context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using Encog.ML.Data.Basic;
using Encog.Neural.Data.Basic;
using Encog.Util.Time;
namespace Encog.ML.Data.Temporal
{
/// <summary>
/// This class implements a temporal neural data set. A temporal neural dataset
/// is designed to use a neural network to predict.
///
/// A temporal dataset is a stream of data over a time range. This time range is
/// broken up into "points". Each point can contain one or more values. These
/// values are either the values that you would like to predict, or use to
/// predict. It is possible for a value to be both predicted and used to predict.
/// For example, if you were trying to predict a trend in a stock's price
/// fluctuations you might very well use the security price for both.
///
/// Each point that we have data for is stored in the TemporalPoint class. Each
/// TemporalPoint will contain one more data values. These data values are
/// described by the TemporalDataDescription class. For example, if you had five
/// TemporalDataDescription objects added to this class, each Temporal point
/// object would contain five values.
///
/// Points are arranged by sequence number. No two points can have the same
/// sequence numbers. Methods are provided to allow you to add points using the
/// Date class. These dates are resolved to sequence number using the level
/// of granularity specified for this class. No two points can occupy the same
/// granularity increment.
/// </summary>
public class TemporalMLDataSet : BasicMLDataSet
{
/// <summary>
/// Error message: adds are not supported.
/// </summary>
public const String AddNotSupported = "Direct adds to the temporal dataset are not supported. "
+ "Add TemporalPoint objects and call generate.";
/// <summary>
/// Descriptions of the data needed.
/// </summary>
private readonly IList<TemporalDataDescription> _descriptions =
new List<TemporalDataDescription>();
/// <summary>
/// The temporal points at which we have data.
/// </summary>
private readonly List<TemporalPoint> _points = new List<TemporalPoint>();
/// <summary>
/// How big would we like the input size to be.
/// </summary>
private int _desiredSetSize;
/// <summary>
/// The highest sequence.
/// </summary>
private int _highSequence;
/// <summary>
/// How many input neurons will be used.
/// </summary>
private int _inputNeuronCount;
/// <summary>
/// The size of the input window, this is the data being used to predict.
/// </summary>
private int _inputWindowSize;
/// <summary>
/// The lowest sequence.
/// </summary>
private int _lowSequence;
/// <summary>
/// How many output neurons will there be.
/// </summary>
private int _outputNeuronCount;
/// <summary>
/// The size of the prediction window.
/// </summary>
private int _predictWindowSize;
/// <summary>
/// What is the granularity of the temporal points? Days, months, years,
/// etc?
/// </summary>
private TimeUnit _sequenceGrandularity;
/// <summary>
/// What is the date for the first temporal point.
/// </summary>
private DateTime _startingPoint = DateTime.MinValue;
/// <summary>
/// Construct a dataset.
/// </summary>
/// <param name="inputWindowSize">What is the input window size.</param>
/// <param name="predictWindowSize">What is the prediction window size.</param>
public TemporalMLDataSet(int inputWindowSize,
int predictWindowSize)
{
_inputWindowSize = inputWindowSize;
_predictWindowSize = predictWindowSize;
_lowSequence = int.MinValue;
_highSequence = int.MaxValue;
_desiredSetSize = int.MaxValue;
_startingPoint = DateTime.MinValue;
_sequenceGrandularity = TimeUnit.Days;
}
/// <summary>
/// The data descriptions.
/// </summary>
public virtual IList<TemporalDataDescription> Descriptions
{
get { return _descriptions; }
}
/// <summary>
/// The points, or time slices to take data from.
/// </summary>
public virtual IList<TemporalPoint> Points
{
get { return _points; }
}
/// <summary>
/// Get the size of the input window.
/// </summary>
public virtual int InputWindowSize
{
get { return _inputWindowSize; }
set { _inputWindowSize = value; }
}
/// <summary>
/// The prediction window size.
/// </summary>
public virtual int PredictWindowSize
{
get { return _predictWindowSize; }
set { _predictWindowSize = value; }
}
/// <summary>
/// The low value for the sequence.
/// </summary>
public virtual int LowSequence
{
get { return _lowSequence; }
set { _lowSequence = value; }
}
/// <summary>
/// The high value for the sequence.
/// </summary>
public virtual int HighSequence
{
get { return _highSequence; }
set { _highSequence = value; }
}
/// <summary>
/// The desired dataset size.
/// </summary>
public virtual int DesiredSetSize
{
get { return _desiredSetSize; }
set { _desiredSetSize = value; }
}
/// <summary>
/// The number of input neurons.
/// </summary>
public virtual int InputNeuronCount
{
get { return _inputNeuronCount; }
set { _inputNeuronCount = value; }
}
/// <summary>
/// The number of output neurons.
/// </summary>
public virtual int OutputNeuronCount
{
get { return _outputNeuronCount; }
set { _outputNeuronCount = value; }
}
/// <summary>
/// The starting point.
/// </summary>
public virtual DateTime StartingPoint
{
get { return _startingPoint; }
set { _startingPoint = value; }
}
/// <summary>
/// The size of the timeslices.
/// </summary>
public virtual TimeUnit SequenceGrandularity
{
get { return _sequenceGrandularity; }
set { _sequenceGrandularity = value; }
}
/// <summary>
/// Add a data description.
/// </summary>
/// <param name="desc">The data description to add.</param>
public virtual void AddDescription(TemporalDataDescription desc)
{
if (_points.Count > 0)
{
throw new TemporalError(
"Can't add anymore descriptions, there are "
+ "already temporal points defined.");
}
int index = _descriptions.Count;
desc.Index = index;
_descriptions.Add(desc);
CalculateNeuronCounts();
}
/// <summary>
/// Clear the entire dataset.
/// </summary>
public virtual void Clear()
{
_descriptions.Clear();
_points.Clear();
Data.Clear();
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="inputData">Not used</param>
/// <param name="idealData">Not used</param>
public sealed override void Add(IMLData inputData, IMLData idealData)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="inputData">Not used.</param>
public sealed override void Add(IMLDataPair inputData)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Adding directly is not supported. Rather, add temporal points and
/// generate the training data.
/// </summary>
/// <param name="data">Not used.</param>
public sealed override void Add(IMLData data)
{
throw new TemporalError(AddNotSupported);
}
/// <summary>
/// Create a temporal data point using a sequence number. They can also be
/// created using time. No two points should have the same sequence number.
/// </summary>
/// <param name="sequence">The sequence number.</param>
/// <returns>A new TemporalPoint object.</returns>
public virtual TemporalPoint CreatePoint(int sequence)
{
var point = new TemporalPoint(_descriptions.Count) {Sequence = sequence};
_points.Add(point);
return point;
}
/// <summary>
/// Create a sequence number from a time. The first date will be zero, and
/// subsequent dates will be increased according to the grandularity
/// specified.
/// </summary>
/// <param name="when">The date to generate the sequence number for.</param>
/// <returns>A sequence number.</returns>
public virtual int GetSequenceFromDate(DateTime when)
{
int sequence;
if (_startingPoint != DateTime.MinValue)
{
var span = new TimeSpanUtil(_startingPoint, when);
sequence = (int) span.GetSpan(_sequenceGrandularity);
}
else
{
_startingPoint = when;
sequence = 0;
}
return sequence;
}
/// <summary>
/// Create a temporal point from a time. Using the grandularity each date is
/// given a unique sequence number. No two dates that fall in the same
/// grandularity should be specified.
/// </summary>
/// <param name="when">The time that this point should be created at.</param>
/// <returns>The point TemporalPoint created.</returns>
public virtual TemporalPoint CreatePoint(DateTime when)
{
int sequence = GetSequenceFromDate(when);
var point = new TemporalPoint(_descriptions.Count) {Sequence = sequence};
_points.Add(point);
return point;
}
/// <summary>
/// Calculate how many points are in the high and low range. These are the
/// points that the training set will be generated on.
/// </summary>
/// <returns>The number of points.</returns>
public virtual int CalculatePointsInRange()
{
return _points.Count(IsPointInRange);
}
/// <summary>
/// Calculate the actual set size, this is the number of training set entries
/// that will be generated.
/// </summary>
/// <returns>The size of the training set.</returns>
public virtual int CalculateActualSetSize()
{
int result = CalculatePointsInRange();
result = Math.Min(_desiredSetSize, result);
return result;
}
/// <summary>
/// Calculate how many input and output neurons will be needed for the
/// current data.
/// </summary>
public virtual void CalculateNeuronCounts()
{
_inputNeuronCount = 0;
_outputNeuronCount = 0;
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsInput)
{
_inputNeuronCount += _inputWindowSize;
}
if (desc.IsPredict)
{
_outputNeuronCount += _predictWindowSize;
}
}
}
/// <summary>
/// Is the specified point within the range. If a point is in the selection
/// range, then the point will be used to generate the training sets.
/// </summary>
/// <param name="point">The point to consider.</param>
/// <returns>True if the point is within the range.</returns>
public virtual bool IsPointInRange(TemporalPoint point)
{
return ((point.Sequence >= LowSequence) && (point.Sequence <= HighSequence));
}
/// <summary>
/// Generate input neural data for the specified index.
/// </summary>
/// <param name="index">The index to generate neural data for.</param>
/// <returns>The input neural data generated.</returns>
public virtual BasicNeuralData GenerateInputNeuralData(int index)
{
if (index + _inputWindowSize > _points.Count)
{
throw new TemporalError("Can't generate input temporal data "
+ "beyond the end of provided data.");
}
var result = new BasicNeuralData(_inputNeuronCount);
int resultIndex = 0;
for (int i = 0; i < _inputWindowSize; i++)
{
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsInput)
{
result[resultIndex++] = FormatData(desc, index
+ i);
}
}
}
return result;
}
/// <summary>
/// Get data between two points in raw form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataRaw(TemporalDataDescription desc,
int index)
{
// Note: The reason that we subtract 1 from the index is because we are always one ahead.
// This allows the DELTA change formatter to work. DELTA change requires two timeslices,
// so we have to be one ahead. RAW only requires one, so we shift backwards.
TemporalPoint point = _points[index-1];
return point[desc.Index];
}
/// <summary>
/// Get data between two points in delta form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataDeltaChange(TemporalDataDescription desc,
int index)
{
if (index == 0)
{
return 0.0;
}
TemporalPoint point = _points[index];
TemporalPoint previousPoint = _points[index - 1];
return point[desc.Index]
- previousPoint[desc.Index];
}
/// <summary>
/// Get data between two points in percent form.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to get data from.</param>
/// <returns>The requested data.</returns>
private double GetDataPercentChange(TemporalDataDescription desc,
int index)
{
if (index == 0)
{
return 0.0;
}
TemporalPoint point = _points[index];
TemporalPoint previousPoint = _points[index - 1];
double currentValue = point[desc.Index];
double previousValue = previousPoint[desc.Index];
return (currentValue - previousValue)/previousValue;
}
/// <summary>
/// Format data according to the type specified in the description.
/// </summary>
/// <param name="desc">The data description.</param>
/// <param name="index">The index to format the data at.</param>
/// <returns>The formatted data.</returns>
private double FormatData(TemporalDataDescription desc,
int index)
{
var result = new double[1];
switch (desc.DescriptionType)
{
case TemporalDataDescription.Type.DeltaChange:
result[0] = GetDataDeltaChange(desc, index);
break;
case TemporalDataDescription.Type.PercentChange:
result[0] = GetDataPercentChange(desc, index);
break;
case TemporalDataDescription.Type.Raw:
result[0] = GetDataRaw(desc, index);
break;
default:
throw new TemporalError("Unsupported data type.");
}
if (desc.ActivationFunction != null)
{
desc.ActivationFunction.ActivationFunction(result, 0, 1);
}
return result[0];
}
/// <summary>
/// Generate neural ideal data for the specified index.
/// </summary>
/// <param name="index">The index to generate for.</param>
/// <returns>The neural data generated.</returns>
public virtual BasicNeuralData GenerateOutputNeuralData(int index)
{
if (index + _predictWindowSize > _points.Count)
{
throw new TemporalError("Can't generate prediction temporal data "
+ "beyond the end of provided data.");
}
var result = new BasicNeuralData(_outputNeuronCount);
int resultIndex = 0;
for (int i = 0; i < _predictWindowSize; i++)
{
foreach (TemporalDataDescription desc in _descriptions)
{
if (desc.IsPredict)
{
result[resultIndex++] = FormatData(desc, index
+ i);
}
}
}
return result;
}
/// <summary>
/// Calculate the index to start at.
/// </summary>
/// <returns>The starting point.</returns>
public virtual int CalculateStartIndex()
{
for (int i = 0; i < _points.Count; i++)
{
TemporalPoint point = _points[i];
if (IsPointInRange(point))
{
return i;
}
}
return -1;
}
/// <summary>
/// Sort the points.
/// </summary>
public virtual void SortPoints()
{
_points.Sort();
}
/// <summary>
/// Generate the training sets.
/// </summary>
public virtual void Generate()
{
SortPoints();
int start = CalculateStartIndex() + 1;
int setSize = CalculateActualSetSize();
int range = start
+ (setSize - _predictWindowSize - _inputWindowSize);
for (int i = start; i < range; i++)
{
BasicNeuralData input = GenerateInputNeuralData(i);
BasicNeuralData ideal = GenerateOutputNeuralData(i
+ _inputWindowSize);
var pair = new BasicNeuralDataPair(input, ideal);
base.Add(pair);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareEqualSByte()
{
var test = new SimpleBinaryOpTest__CompareEqualSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualSByte
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int Op2ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable;
static SimpleBinaryOpTest__CompareEqualSByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareEqual(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareEqual(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualSByte();
var result = Sse2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] == right[0]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections;
using NBM.Plugin;
using System.Text;
using IO = System.IO;
// 15/5/03
public class Message
{
private ArrayList argumentList = new ArrayList();
public static readonly byte[] ArgumentSeperator = new byte[] { 0xC0, 0x80 };
public const int HeaderLength = 20;
public const int Version = 10;
/// <summary>
/// Message header.
/// </summary>
public class MessageHeader
{
private UInt32 packetIdentifier = 0x47534D59; // packet identifier - "YMSG"
private UInt32 version = Message.Version; // Version (little endian)
private UInt16 length = 0; // Length of the packet (big endian)
private UInt16 service = 0; // Service type (big endian)
private UInt32 status = 0; // Status of user (online, invis, etc) (big endian)
private UInt32 sessionIdentifier = 0; // Unique number given to each session.
public YahooService Service
{
get { return (YahooService)Endian.Convert(service); }
set { service = Endian.Convert((UInt16)value); }
}
public YahooStatus Status
{
get { return (YahooStatus)Endian.Convert(status); }
set { status = Endian.Convert((UInt32)value); }
}
public UInt32 SessionID
{
get { return sessionIdentifier; }
}
public UInt16 Length
{
get { return Endian.Convert(length); }
set { length = Endian.Convert(value); }
}
public UInt32 SessionIdentifier
{
get { return sessionIdentifier; }
set { sessionIdentifier = value; }
}
public void Set(byte[] b, int arrayIndex)
{
System.IO.MemoryStream memStream = new System.IO.MemoryStream(b);
memStream.Seek(arrayIndex, IO.SeekOrigin.Begin);
System.IO.BinaryReader br = new System.IO.BinaryReader(memStream);
packetIdentifier = br.ReadUInt32();
version = br.ReadUInt32();
length = br.ReadUInt16();
service = br.ReadUInt16();
status = br.ReadUInt32();
sessionIdentifier = br.ReadUInt32();
br.Close();
memStream.Close();
}
public void Get(IO.BinaryWriter bw)
{
bw.Write(packetIdentifier);
bw.Write(version);
bw.Write(length);
bw.Write(service);
bw.Write(status);
bw.Write(sessionIdentifier);
}
}
private MessageHeader header = new MessageHeader();
public MessageHeader Header
{
get { return header; }
}
#region Constructors
public Message(UInt32 sessionID)
: this(sessionID, YahooService.None)
{
}
public Message(UInt32 sessionID, YahooService service)
: this(sessionID, service, YahooStatus.Available)
{
}
public Message(UInt32 sessionID, YahooService service, YahooStatus status)
{
header.SessionIdentifier = sessionID;
header.Service = service;
header.Status = status;
}
/// <summary>
/// This constructor is for incoming messages
/// </summary>
/// <param name="rawMessage"></param>
public Message(byte[] rawMessage)
{
// copy header
header.Set(rawMessage, 0);
// divide into arguments
bool isKey = true;
byte[] content = new byte[ header.Length ]; // content cant be longer than the message
int contentLength = 0;
int key = 0;
for (int i=Message.HeaderLength; i<header.Length+Message.HeaderLength; ++i)
{
if (rawMessage[i] == Message.ArgumentSeperator[0]
&& rawMessage[i+1] == Message.ArgumentSeperator[1])
{
if (contentLength > 0)
{
// we have hit a boundary
if (isKey)
{
key = int.Parse( ASCIIEncoding.ASCII.GetString( content, 0, contentLength ) );
}
else
{
byte[] temp = new byte[contentLength];
Array.Copy(content, 0, temp, 0, contentLength);
this.argumentList.Add( new Pair(key, temp) );
}
}
contentLength = 0;
++i;
isKey = !isKey;
}
else
{
content[contentLength++] = rawMessage[i];
}
}
}
#endregion
public void AddArgument(int id, byte[] contents)
{
this.argumentList.Add(new Pair(id, contents));
// calculate length of arguments
byte[] idbyte = ASCIIEncoding.ASCII.GetBytes(string.Format("{0}", id));
this.Header.Length += (UInt16)(idbyte.Length + contents.Length + (Message.ArgumentSeperator.Length * 2));
}
public void AddArgument(int id, string contents)
{
AddArgument(id, ASCIIEncoding.ASCII.GetBytes(contents));
}
public ArrayList Arguments
{
get { return this.argumentList; }
}
public byte[] GetArgument(int id)
{
foreach (Pair pair in this.argumentList)
{
if ((int)pair.First == id)
{
return (byte[])pair.Second;
}
}
return null;
}
public string GetArgumentString(int id)
{
byte[] arg = GetArgument(id);
return (arg != null) ? ASCIIEncoding.ASCII.GetString(arg) : null;
}
public byte[] GetRawMessage()
{
IO.MemoryStream stream = new IO.MemoryStream(Message.HeaderLength);
IO.BinaryWriter bw = new IO.BinaryWriter(stream);
// write header
header.Get(bw);
// write arguments
foreach (Pair pair in this.argumentList)
{
int key = (int)pair.First;
byte[] val = (byte[])pair.Second;
bw.Write( ASCIIEncoding.ASCII.GetBytes(string.Format("{0}", key)) );
bw.Write( Message.ArgumentSeperator );
bw.Write( val );
bw.Write( Message.ArgumentSeperator );
}
byte[] final = stream.ToArray();
bw.Close();
stream.Close();
return final;
}
}
| |
//
// HotfixManager.cs
// Created by huailiang.peng on 2016-3-11 17:0:4
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
public enum HotfixMode
{
BEFORE,
AFTER
}
public class HotfixManager : Single<HotfixManager>
{
LuaScriptMgr lua = null;
LuaFunction func_refresh = null;
LuaFunction func_click_b=null;
LuaFunction func_click_a=null;
LuaFunction func_net_b=null;
LuaFunction func_net_a=null;
private const string CLICK_LUA_FILE = "HotfixClick.lua";
private const string NET_LUA_FILE = "HotfixNet.lua";
private const string MSG_LUE_FILE = "HotfixMsglist.lua";
public bool useHotfix=true;
public Dictionary<string,string> hotmsglist=new Dictionary<string, string>();
public List<string> doluafiles=new List<string>();
/// <summary>
/// init load click and refresh type of hot fix files
/// </summary>
public void LoadHotfix(System.Action finish)
{
lua = new LuaScriptMgr();
lua.Start();
Hotfix.Init(()=>
{
TryFixMsglist();
InitClick();
InitNet();
Debug.Log(Localization.Get(10001));
if(finish!=null) finish();
});
}
public void Dispose()
{
doluafiles.Clear();
if(func_click_a!=null) func_click_a.Release();
if(func_click_b!=null) func_click_b.Release();
if(func_net_a!=null) func_net_a.Release();
if(func_net_b!=null) func_net_b.Release();
lua.Destroy();
lua = null;
}
public bool DoLuaFile(string name)
{
if(doluafiles.Contains(name)) return true;
else
{
string path = Application.temporaryCachePath + "/Hotfix/" + name;
if (lua != null)
{
if(LuaStatic.Load(path)==null) return false;
lua.lua.DoFile(path);
doluafiles.Add(name);
return true;
}
}
return false;
}
/// <summary>
/// Used for localization
/// </summary>
public void TryFixMsglist()
{
if(!useHotfix) return;
string path = Application.temporaryCachePath + "/Hotfix/" +MSG_LUE_FILE;
byte[] objs = LuaStatic.Load(path);
if(objs!=null)
{
ByteReader reader=new ByteReader(objs);
hotmsglist = reader.ReadDictionary();
}
}
private void InitClick()
{
if(!useHotfix) return;
bool dofile = DoLuaFile(CLICK_LUA_FILE);
if (dofile)
{
if(func_click_b==null)
{
func_click_b=lua.lua.GetFunction("TABLE.BeforeClick");
}
if(func_click_a==null)
{
func_click_a=lua.lua.GetFunction("TABLE.AfterClick");
}
}
}
/// <summary>
/// Used for All Click Event
/// if lua return false, go on execute c#, else interupt
/// </summary>
public bool TryFixClick(HotfixMode _mode, string _path)
{
if(!useHotfix) return false;
if(_mode==HotfixMode.BEFORE)
{
if(func_click_b!=null)
{
object[] r = func_click_b.Call(_path);
return (bool)r [0];
}
}
else
{
if(func_click_a!=null)
{
object[] r = func_click_a.Call(_path);
return (bool)r [0];
}
}
return false;
}
private void InitNet()
{
if(!useHotfix) return;
bool dofile = DoLuaFile(NET_LUA_FILE);
if (dofile)
{
if(func_net_b==null)
{
func_net_b=lua.lua.GetFunction("TABLE.BeforeNet");
}
if(func_net_a==null)
{
func_net_a=lua.lua.GetFunction("TABLE.AfterNet");
}
}
}
/// <summary>
/// used for network of TCP Protocal
/// if lua return false, go on execute c#, else interupt
/// </summary>
public bool TryFixNet(HotfixMode _mode, uint _udid)
{
if(!useHotfix) return false;
if(_mode==HotfixMode.BEFORE)
{
if(func_net_b!=null)
{
object[] r = func_net_b.Call(_udid);
return (bool)r [0];
}
}
else
{
if(func_net_a!=null)
{
object[] r = func_net_a.Call(_udid);
return (bool)r [0];
}
}
return false;
}
/// <summary>
/// Used for network of HTTP Protocal
/// if lua return false, go on execute c#, else interupt
/// </summary>
public bool TryFixNet(HotfixMode _mode,string _route)
{
if(!useHotfix) return false;
if(_mode==HotfixMode.BEFORE)
{
if(func_net_b!=null)
{
object[] r = func_net_b.Call(_route);
return (bool)r [0];
}
}
else
{
if(func_net_a!=null)
{
object[] r = func_net_a.Call(_route);
return (bool)r [0];
}
}
return false;
}
/// <summary>
/// Used for GamePage Refresh
/// if lua return false, go on execute c#, else interupt
/// </summary>
public bool TryFixRefresh(HotfixMode _mode, string _pageName, GameObject go)
{
if(!useHotfix) return false;
string filename = "Hotfix" + _pageName + ".lua";
bool dolua = DoLuaFile(filename);
if (dolua)
{
func_refresh = lua.lua.GetFunction(_mode == HotfixMode.BEFORE ? "TABLE.BeforeRefresh" : "TABLE.AfterRefresh");
if (func_refresh != null)
{
object[] r = func_refresh.Call(go);
func_refresh.Release();
return (bool)r [0];
}
}
return false;
}
public bool TryCallPBuffer()
{
if(!useHotfix) return false;
string filename = "HotfixPB.lua";
DoLuaFile(filename);
return false;
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Networking;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class RigidbodyFirstPersonController : NetworkBehaviour
{
[Serializable]
public class MovementSettings
{
public float AimMultiplier = 0.5f;
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public KeyCode AimKey = KeyCode.Mouse1;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
public bool m_Running;
public bool m_Aiming;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input.x > 0 || input.x < 0)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
if (input.y < 0)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
if (input.y > 0)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(AimKey))
{
CurrentTargetSpeed *= AimMultiplier;
m_Aiming = true;
}
else
{
m_Aiming = false;
}
if (Input.GetKey(RunKey) && !m_Aiming)
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
if (input == Vector2.zero) return;
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
[Tooltip("set it to 0.1 or more if you get stuck in wall")]
public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
}
// Animation Settings
Animator animator;
bool anim_isJumping = false;
bool anim_isGrounded = false;
float anim_moveSpeedx = 0.0f;
float anim_moveSpeedz = 0.0f;
bool anim_isStationary = false;
[SerializeField]
Transform camNormalLook;
[SerializeField]
Transform camAimLook;
float camFOV = 60.0f;
float dampVelocity = 0.4f;
[SerializeField]
Transform GunPos;
[SerializeField]
Transform GunAimPos;
[SerializeField]
GameObject Gun;
Vector3 targetGunPos;
Vector3 currentGunVel = Vector3.one;
// prefabs
GameObject currentWeapon;
[SerializeField]
Transform leftHand;
[SerializeField]
Transform rightHand;
[SerializeField]
Transform head;
public Camera cam;
private HeadBob headBobScript;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init(transform, cam.transform);
animator = GetComponentInChildren<Animator>();
targetGunPos = GunPos.position;
headBobScript = cam.GetComponent<HeadBob>();
currentWeapon = Instantiate(Gun, GunPos) as GameObject;
currentWeapon.transform.position = GunPos.position;
}
private void LateUpdate()
{
RotateView();
}
private void Update()
{
float newFOV = Mathf.SmoothDamp(cam.fieldOfView, camFOV, ref dampVelocity, 0.1f);
cam.fieldOfView = newFOV;
if (movementSettings.m_Running)
{
headBobScript.enabled = true;
}
else
{
headBobScript.enabled = false;
}
if(movementSettings.m_Aiming)
{
targetGunPos = GunAimPos.position;
camFOV = 30;
}
else
{
targetGunPos = GunPos.position;
camFOV = 60;
}
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
UpdateAnimations();
}
private void UpdateAnimations()
{
animator.SetFloat("moveSpeedx", anim_moveSpeedx);
animator.SetFloat("moveSpeedy", m_RigidBody.velocity.y);
animator.SetFloat("moveSpeedz", anim_moveSpeedz);
animator.SetBool("isJumping", anim_isJumping);
animator.SetBool("isAiming", movementSettings.m_Aiming);
animator.SetBool("isSprinting", movementSettings.m_Running);
animator.SetBool("isStationary", anim_isStationary);
}
private void FixedUpdate()
{
currentWeapon.transform.position = Vector3.SmoothDamp(currentWeapon.transform.position, targetGunPos, ref currentGunVel, 0.1f);
//Vector3.Lerp(currentWeapon.transform.position, targetGunPos, 1 - Mathf.Exp(-20 * Time.deltaTime));
//Vector3.SmoothDamp(currentWeapon.transform.position, targetGunPos, ref currentGunVel, 0.25f);
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward * input.y + cam.transform.right * input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x * movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z * movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y * movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
animator.SetTrigger("startJump");
anim_isJumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height / 2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
if (input == Vector2.zero)
{
anim_isStationary = true;
}
else
{
anim_isStationary = false;
}
anim_moveSpeedx = input.y;
anim_moveSpeedz = input.x;
movementSettings.UpdateDesiredTargetSpeed(input);
if (Input.GetKeyDown(movementSettings.AimKey))
{
animator.SetTrigger("Aim");
}
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
if (movementSettings.m_Aiming)
{
cam.transform.position = camAimLook.position;
//cam.transform.rotation = camAimLook.rotation;
}
else
{
cam.transform.position = camNormalLook.position;
}
mouseLook.LookRotation(transform, cam.transform);
head.rotation = cam.transform.rotation;
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation * m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_IsGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
anim_isJumping = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation test jobs. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
internal partial class TestJobOperations : IServiceOperations<AutomationManagementClient>, ITestJobOperations
{
/// <summary>
/// Initializes a new instance of the TestJobOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TestJobOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a test job of the runbook. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create test job operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create test job operation.
/// </returns>
public async Task<TestJobCreateResponse> CreateAsync(string resourceGroupName, string automationAccount, TestJobCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.RunbookName == null)
{
throw new ArgumentNullException("parameters.RunbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.RunbookName);
url = url + "/draft/testJob";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject testJobCreateParametersValue = new JObject();
requestDoc = testJobCreateParametersValue;
if (parameters.Parameters != null)
{
if (parameters.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Parameters).IsInitialized)
{
JObject parametersDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Parameters)
{
string parametersKey = pair.Key;
string parametersValue = pair.Value;
parametersDictionary[parametersKey] = parametersValue;
}
testJobCreateParametersValue["parameters"] = parametersDictionary;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TestJobCreateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TestJobCreateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TestJob testJobInstance = new TestJob();
result.TestJob = testJobInstance;
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
testJobInstance.CreationTime = creationTimeInstance;
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
testJobInstance.Status = statusInstance;
}
JToken statusDetailsValue = responseDoc["statusDetails"];
if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null)
{
string statusDetailsInstance = ((string)statusDetailsValue);
testJobInstance.StatusDetails = statusDetailsInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
testJobInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = responseDoc["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
testJobInstance.EndTime = endTimeInstance;
}
JToken exceptionValue = responseDoc["exception"];
if (exceptionValue != null && exceptionValue.Type != JTokenType.Null)
{
string exceptionInstance = ((string)exceptionValue);
testJobInstance.Exception = exceptionInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
testJobInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"];
if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue);
testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance;
}
JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]);
if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in parametersSequenceElement)
{
string parametersKey2 = ((string)property.Name);
string parametersValue2 = ((string)property.Value);
testJobInstance.Parameters.Add(parametersKey2, parametersValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the test job for the specified runbook. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get test job operation.
/// </returns>
public async Task<TestJobGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/Runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TestJobGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TestJobGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TestJob testJobInstance = new TestJob();
result.TestJob = testJobInstance;
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
testJobInstance.CreationTime = creationTimeInstance;
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
testJobInstance.Status = statusInstance;
}
JToken statusDetailsValue = responseDoc["statusDetails"];
if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null)
{
string statusDetailsInstance = ((string)statusDetailsValue);
testJobInstance.StatusDetails = statusDetailsInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
testJobInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = responseDoc["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
testJobInstance.EndTime = endTimeInstance;
}
JToken exceptionValue = responseDoc["exception"];
if (exceptionValue != null && exceptionValue.Type != JTokenType.Null)
{
string exceptionInstance = ((string)exceptionValue);
testJobInstance.Exception = exceptionInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
testJobInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"];
if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue);
testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance;
}
JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]);
if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in parametersSequenceElement)
{
string parametersKey = ((string)property.Name);
string parametersValue = ((string)property.Value);
testJobInstance.Parameters.Add(parametersKey, parametersValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Resume the test job. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> ResumeAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "ResumeAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob/resume";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Stop the test job. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> StopAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "StopAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob/stop";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Suspend the test job. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> SuspendAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "SuspendAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob/suspend";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
#pragma warning disable 1591
namespace UnFound.Controls
{
public class DropDownButton : Control
{
public enum Renderers { Default, Native }
public delegate void DropDownItemHandler(object sender, DropDownItemEventArgs e);
/// <summary>
/// Occurs when the button is clicked.
/// </summary>
public new event EventHandler Click;
/// <summary>
/// Occurs when the drop down button is clicked, opening the drop down menu.
/// </summary>
public event EventHandler DropDownClicked;
/// <summary>
/// Occurs when a menu item in the drop down menu is clicked.
/// </summary>
public event DropDownItemHandler DropDownItemClicked;
public DropDownButton()
{
SetStyle(ControlStyles.ResizeRedraw, true);
this.DoubleBuffered = true;
this.Size = new Size(142, 23);
this.TextChanged += DropDownButton_TextChanged;
}
#region Events
private void DropDownMenu_ItemAdded(object sender, ToolStripItemEventArgs e)
{
if ((sender as DropDownMenu).DropDownButton == this)
this.Invalidate();
}
private void DropDownMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if ((sender as DropDownMenu).DropDownButton == this)
{
p_DropDownSelectedItem = p_DropDownMenu.Items.IndexOf(e.ClickedItem);
(sender as DropDownMenu).Close(ToolStripDropDownCloseReason.ItemClicked);
this.Invalidate();
OnDropDownItemClicked(new DropDownItemEventArgs(e.ClickedItem, p_DropDownSelectedItem));
}
}
private void DropDownMenu_ItemRemoved(object sender, ToolStripItemEventArgs e)
{
if ((sender as DropDownMenu).DropDownButton == this)
{
this.Invalidate();
}
}
private void DropDownButton_TextChanged(object sender, EventArgs e)
{
this.Invalidate();
}
#endregion
#region Fields
private DropDownMenu p_DropDownMenu;
private int p_DropDownSelectedItem;
private Renderers p_Renderer = Renderers.Default;
private Rectangle dropDownRect;
private int pushedState = 0;
private PushButtonState buttonState = PushButtonState.Normal;
private ComboBoxState dropDownState = ComboBoxState.Normal;
#endregion
#region Properties
/// <summary>
/// Gets or sets the DropDownMenu to display.
/// </summary>
[DefaultValue(null)]
public DropDownMenu DropDownMenu
{
get { return p_DropDownMenu; }
set
{
if (p_DropDownMenu != null)
{
p_DropDownMenu.DropDownButton = null;
p_DropDownMenu.Renderer = null;
p_DropDownMenu.ItemAdded -= DropDownMenu_ItemAdded;
p_DropDownMenu.ItemClicked -= DropDownMenu_ItemClicked;
p_DropDownMenu.ItemRemoved -= DropDownMenu_ItemRemoved;
}
p_DropDownMenu = value;
if (p_DropDownMenu != null)
{
p_DropDownMenu.DropDownButton = this;
p_DropDownMenu.Renderer = p_Renderer.Equals(Renderers.Default) ?
null : new NativeToolStripRenderer(new ToolbarTheme());
p_DropDownMenu.ItemAdded += DropDownMenu_ItemAdded;
p_DropDownMenu.ItemClicked += DropDownMenu_ItemClicked;
p_DropDownMenu.ItemRemoved += DropDownMenu_ItemRemoved;
}
p_DropDownSelectedItem = 0;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets the DropDownMenu selected item. (Last clicked item)
/// </summary>
[DefaultValue(0)]
public int DropDownSelectedItem
{
get { return p_DropDownSelectedItem; }
set
{
p_DropDownSelectedItem = value;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets the DropDownMenu renderer.
/// </summary>
[DefaultValue(Renderers.Default)]
public Renderers Renderer
{
get { return p_Renderer; }
set
{
if (p_DropDownMenu != null)
{
p_DropDownMenu.Renderer = value == Renderers.Default ?
null : new NativeToolStripRenderer(new ToolbarTheme());
}
p_Renderer = value;
}
}
#endregion
protected override bool IsInputKey(Keys keyData)
{
return keyData.Equals(Keys.Down) || base.IsInputKey(keyData);
}
protected override void OnClick(EventArgs e)
{
// The actual drop down button has it's own event.
if (dropDownState == ComboBoxState.Pressed)
return;
this.Click?.Invoke(this, EventArgs.Empty);
if (p_DropDownMenu == null ||
p_DropDownMenu.Items.Count == 0 ||
this.Text != "")
{
return;
}
if (this.ShowFocusCues)
this.Focus();
p_DropDownMenu.DropDownButton = this;
p_DropDownMenu.Items[p_DropDownSelectedItem].PerformClick();
}
protected virtual void OnDropDownClicked(EventArgs e)
{
DropDownClicked?.Invoke(this, e);
}
protected virtual void OnDropDownItemClicked(DropDownItemEventArgs e)
{
DropDownItemClicked?.Invoke(this, e);
}
protected override void OnGotFocus(EventArgs e)
{
this.Invalidate();
base.OnGotFocus(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
ShowContextMenuStrip(true);
else if (e.KeyCode == Keys.Enter)
{
if (this.Text == "")
OnClick(EventArgs.Empty);
else
ShowContextMenuStrip(true);
}
base.OnKeyDown(e);
}
protected override void OnLostFocus(EventArgs e)
{
this.Invalidate();
base.OnLostFocus(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (dropDownRect.Contains(e.Location))
{
buttonState = PushButtonState.Normal;
dropDownState = ComboBoxState.Pressed;
pushedState = 1;
}
else if (this.DisplayRectangle.Contains(e.Location))
{
buttonState = PushButtonState.Pressed;
dropDownState = ComboBoxState.Normal;
pushedState = 2;
}
this.Invalidate();
}
base.OnMouseDown(e);
}
protected override void OnMouseLeave(EventArgs e)
{
buttonState = PushButtonState.Normal;
dropDownState = ComboBoxState.Normal;
this.Invalidate();
base.OnMouseLeave(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (dropDownRect.Contains(e.Location) && pushedState != 2)
{
if (!(buttonState == PushButtonState.Normal &&
dropDownState == ComboBoxState.Hot))
{
buttonState = PushButtonState.Normal;
dropDownState = ComboBoxState.Hot;
this.Invalidate();
}
}
else if (this.DisplayRectangle.Contains(e.Location) && pushedState != 1)
{
if (!(buttonState == PushButtonState.Hot &&
dropDownState == ComboBoxState.Normal))
{
buttonState = PushButtonState.Hot;
dropDownState = ComboBoxState.Normal;
this.Invalidate();
}
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (dropDownRect.Contains(e.Location))
{
if (pushedState == 1)
ShowContextMenuStrip();
buttonState = PushButtonState.Normal;
dropDownState = ComboBoxState.Hot;
}
else if (this.DisplayRectangle.Contains(e.Location))
{
buttonState = PushButtonState.Hot;
dropDownState = ComboBoxState.Normal;
}
else
{
buttonState = PushButtonState.Normal;
dropDownState = ComboBoxState.Normal;
}
pushedState = 0;
this.Invalidate();
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = this.DisplayRectangle;
Rectangle rectText = this.DisplayRectangle;
StringFormat stringFormat = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
dropDownRect = new Rectangle(this.DisplayRectangle.Width - 20, this.DisplayRectangle.Y + 1, 20, this.DisplayRectangle.Height - 2);
rectText.Width -= 20;
string text;
if (this.Text != string.Empty)
{
text = this.Text;
buttonState = PushButtonState.Normal;
}
else
{
if (!(p_DropDownMenu == null) && p_DropDownMenu.Items.Count > 0)
text = p_DropDownMenu.Items[p_DropDownSelectedItem].Text;
else
text = this.Text;
}
if (Application.RenderWithVisualStyles)
DrawVisualStyle(e.Graphics, rect, dropDownRect);
else
{
ButtonState btnState = ButtonState.Normal;
ButtonState ddbState = ButtonState.Normal;
switch (buttonState)
{
case PushButtonState.Hot:
case PushButtonState.Normal:
btnState = ButtonState.Normal;
break;
case PushButtonState.Pressed:
btnState = ButtonState.Pushed;
break;
}
switch (dropDownState)
{
case ComboBoxState.Hot:
case ComboBoxState.Normal:
ddbState = ButtonState.Normal;
break;
case ComboBoxState.Pressed:
ddbState = ButtonState.Pushed;
break;
}
DrawPreVistaStyle(e.Graphics, rect, btnState, dropDownRect, ddbState);
}
e.Graphics.DrawString(text, this.Font, new SolidBrush(this.ForeColor), rectText, stringFormat);
base.OnPaint(e);
}
private void DrawVisualStyle(Graphics g, Rectangle rect, Rectangle dropDownRect, bool focused = false)
{
bool focus = this.ShowFocusCues && this.Focused;
if (IsWinXP())
{
var sf = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
Rectangle rectNew = dropDownRect; rectNew.Y -= 1; rectNew.Height += 2;
PushButtonState ddState = (PushButtonState)(int)dropDownState;
ButtonRenderer.DrawButton(g, rect, false, buttonState);
ButtonRenderer.DrawButton(g, rectNew, focus, ddState | (focus && ddState == PushButtonState.Normal ? PushButtonState.Default : 0));
g.DrawString("v", this.Font, new SolidBrush(Color.Black), rectNew, sf);
}
else
{
if (this.Text == "")
{
ButtonRenderer.DrawButton(g, rect, focus, buttonState | (focus && buttonState == PushButtonState.Normal ? PushButtonState.Default : 0));
ComboBoxRenderer.DrawDropDownButton(g, dropDownRect, dropDownState);
}
else
{
ButtonRenderer.DrawButton(g, rect, false, buttonState);
ComboBoxRenderer.DrawDropDownButton(g, dropDownRect, dropDownState | (focus ? ComboBoxState.Hot : 0));
if (focus)
{
Rectangle focusBounds = dropDownRect;
focusBounds.Inflate(-2, -2);
ControlPaint.DrawBorder(g, focusBounds, Color.Black, ButtonBorderStyle.Dotted);
}
}
}
}
private void DrawPreVistaStyle(Graphics g, Rectangle rect, ButtonState state, Rectangle dropDownRect, ButtonState dropDownState)
{
Rectangle newDropDownRect = dropDownRect;
newDropDownRect.Y -= 2;
newDropDownRect.Height += 3;
ControlPaint.DrawButton(g, rect, state);
ControlPaint.DrawComboButton(g, newDropDownRect, dropDownState);
if (this.ShowFocusCues && this.Focused)
{
Rectangle focusRect = newDropDownRect; focusRect.Inflate(-3, -3);
newDropDownRect.Y += 1;
newDropDownRect.Height -= 2;
focusRect.X -= 1;
focusRect.Width += 1;
ControlPaint.DrawBorder(g, focusRect, Color.Black, ButtonBorderStyle.Dotted);
ControlPaint.DrawBorder(g, newDropDownRect, Color.Black, ButtonBorderStyle.Solid);
}
}
/// <summary>
/// Shows the DropDownButton at the button.
/// </summary>
/// <param name="selectFirstItem">Selects the first item so arrow keys can be used.</param>
public void ShowContextMenuStrip(bool selectFirstItem = false)
{
if (p_DropDownMenu == null)
return;
int width = p_DropDownMenu.Width;
p_DropDownMenu.DropDownButton = this;
p_DropDownMenu.Show(this, this.DisplayRectangle.Width - width, this.DisplayRectangle.Y + this.Height - 1);
if (selectFirstItem)
p_DropDownMenu.Items[0].Select();
}
private bool IsWinXP()
{
return Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version.Major == 5 &&
Environment.OSVersion.Version.Minor == 1;
}
}
public class DropDownItemEventArgs : EventArgs
{
/// <summary>
/// Gets clicked ToolStripItem,
/// </summary>
public ToolStripItem Item { get; set; }
/// <summary>
/// Gets the index of clicked item.
/// </summary>
public int ItemIndex { get; set; }
public DropDownItemEventArgs(ToolStripItem item, int index)
{
this.Item = item;
this.ItemIndex = index;
}
}
public class DropDownMenu : ContextMenuStrip
{
/// <summary>
/// Gets or sets which DropDownButton is currently interacting with the menu.
/// </summary>
public DropDownButton DropDownButton { get; set; }
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Diagnostics.Trace
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Utility functions for handling correct logging of customer schema data.
/// </summary>
public static class EntityNamePrivacy
{
/// <summary>
/// Gets an entity name representation suitable for logging.
/// </summary>
/// <param name="entityLogicalName">The entity logical name to be logged.</param>
/// <returns>
/// Returns the logical name unchanged if it matches the whitelist of known entities, otherwise returns a
/// hashed representation.
/// </returns>
public static string GetEntityName(string entityLogicalName)
{
if (string.IsNullOrEmpty(entityLogicalName))
{
return entityLogicalName;
}
return PortalEntityAllowedList.Contains(entityLogicalName)
? entityLogicalName
: Convert.ToBase64String(HashPii.ComputeHashPiiSha256(Encoding.UTF8.GetBytes(entityLogicalName)));
}
/// <summary>
/// Determines whether a given entity logical name is allowed to be logged un-hashed.
/// </summary>
/// <param name="entityLogicalName">The entity logical name to be logged.</param>
/// <returns>
/// True if the given entity logical name is not null or empty and can be logged, otherwise false.
/// </returns>
public static bool IsPortalEntityAllowed(string entityLogicalName)
{
return !string.IsNullOrEmpty(entityLogicalName) && PortalEntityAllowedList.Contains(entityLogicalName);
}
#region PortalEntityAllowedList
/// <summary>
/// The list of Microsoft owned CRM and ADX entities which are allowed for logging in feature usage telemetry and other places.
/// </summary>
private static readonly HashSet<string> PortalEntityAllowedList = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
{ "adx_accesscontrolrule_publishingstate" },
{ "adx_ad" },
{ "adx_adplacement" },
{ "adx_adplacement_ad" },
{ "adx_alertsubscription" },
{ "adx_badge" },
{ "adx_badgetype" },
{ "adx_bingmaplookup" },
{ "adx_blog" },
{ "adx_blog_webrole" },
{ "adx_blogpost" },
{ "adx_blogpost_tag" },
{ "adx_communityforum" },
{ "adx_communityforumaccesspermission" },
{ "adx_communityforumaccesspermission_webrole" },
{ "adx_communityforumalert" },
{ "adx_communityforumannouncement" },
{ "adx_communityforumpost" },
{ "adx_communityforumthread" },
{ "adx_communityforumthread_contact" },
{ "adx_communityforumthread_tag" },
{ "adx_contentsnippet" },
{ "adx_entityform" },
{ "adx_entityformmetadata" },
{ "adx_entitylist" },
{ "adx_entitypermission" },
{ "adx_entitypermission_webrole" },
{ "adx_externalidentity" },
{ "adx_forum_activityalert" },
{ "adx_forumnotification" },
{ "adx_forumthreadtype" },
{ "adx_idea" },
{ "adx_ideaforum" },
{ "adx_invitation" },
{ "adx_invitation_invitecontacts" },
{ "adx_invitation_redeemedcontacts" },
{ "adx_invitation_webrole" },
{ "adx_inviteredemption" },
{ "adx_kbarticle_kbarticle" },
{ "adx_knowledgearticle" },
{ "adx_pagealert" },
{ "adx_pagenotification" },
{ "adx_pagetag" },
{ "adx_pagetag_webpage" },
{ "adx_pagetemplate" },
{ "adx_poll" },
{ "adx_polloption" },
{ "adx_pollplacement" },
{ "adx_pollplacement_poll" },
{ "adx_pollsubmission" },
{ "adx_portalcomment" },
{ "adx_publishingstate" },
{ "adx_publishingstatetransitionrule" },
{ "adx_publishingstatetransitionrule_webrole" },
{ "adx_redirect" },
{ "adx_setting" },
{ "adx_shortcut" },
{ "adx_sitemarker" },
{ "adx_sitesetting" },
{ "adx_tag" },
{ "adx_urlhistory" },
{ "adx_webfile" },
{ "adx_webfilelog" },
{ "adx_webform" },
{ "adx_webformmetadata" },
{ "adx_webformsession" },
{ "adx_webformstep" },
{ "adx_weblink" },
{ "adx_weblinkset" },
{ "adx_webnotificationentity" },
{ "adx_webnotificationurl" },
{ "adx_webpage" },
{ "adx_webpage_tag" },
{ "adx_webpageaccesscontrolrule" },
{ "adx_webpageaccesscontrolrule_webrole" },
{ "adx_webpagehistory" },
{ "adx_webpagelog" },
{ "adx_webrole" },
{ "adx_webrole_account" },
{ "adx_webrole_contact" },
{ "adx_webrole_ideaforum_read" },
{ "adx_webrole_ideaforum_write" },
{ "adx_webrole_systemuser" },
{ "adx_website" },
{ "adx_website_list" },
{ "adx_website_sponsor" },
{ "adx_websiteaccess" },
{ "adx_websiteaccess_webrole" },
{ "adx_websitebinding" },
{ "adx_webtemplate" },
{ "session" },
{ "account" },
{ "accountleads" },
{ "aciviewmapper" },
{ "actioncard" },
{ "actioncardusersettings" },
{ "actioncarduserstate" },
{ "activitymimeattachment" },
{ "activityparty" },
{ "activitypointer" },
{ "advancedsimilarityrule" },
{ "annotation" },
{ "annualfiscalcalendar" },
{ "appconfig" },
{ "appconfiginstance" },
{ "appconfigmaster" },
{ "applicationfile" },
{ "appmodule" },
{ "appmodulecomponent" },
{ "appmoduleroles" },
{ "appointment" },
{ "asyncoperation" },
{ "attachment" },
{ "attributemap" },
{ "audit" },
{ "authorizationserver" },
{ "azureserviceconnection" },
{ "bookableresource" },
{ "bookableresourcebooking" },
{ "bookableresourcebookingexchangesyncidmapping" },
{ "bookableresourcebookingheader" },
{ "bookableresourcecategory" },
{ "bookableresourcecategoryassn" },
{ "bookableresourcecharacteristic" },
{ "bookableresourcegroup" },
{ "bookingstatus" },
{ "bulkdeletefailure" },
{ "bulkdeleteoperation" },
{ "bulkoperation" },
{ "bulkoperationlog" },
{ "businessdatalocalizedlabel" },
{ "businessprocessflowinstance" },
{ "businessunit" },
{ "businessunitmap" },
{ "businessunitnewsarticle" },
{ "calendar" },
{ "calendarrule" },
{ "campaign" },
{ "campaignactivity" },
{ "campaignactivityitem" },
{ "campaignitem" },
{ "campaignresponse" },
{ "cardtype" },
{ "category" },
{ "channelaccessprofile" },
{ "channelaccessprofileentityaccesslevel" },
{ "channelaccessprofilerule" },
{ "channelaccessprofileruleitem" },
{ "channelproperty" },
{ "channelpropertygroup" },
{ "characteristic" },
{ "childincidentcount" },
{ "clientupdate" },
{ "columnmapping" },
{ "commitment" },
{ "competitor" },
{ "competitoraddress" },
{ "competitorproduct" },
{ "competitorsalesliterature" },
{ "complexcontrol" },
{ "connection" },
{ "connectionrole" },
{ "connectionroleassociation" },
{ "connectionroleobjecttypecode" },
{ "constraintbasedgroup" },
{ "contact" },
{ "contactinvoices" },
{ "contactleads" },
{ "contactorders" },
{ "contactquotes" },
{ "contract" },
{ "contractdetail" },
{ "contracttemplate" },
{ "convertrule" },
{ "convertruleitem" },
{ "customcontrol" },
{ "customcontroldefaultconfig" },
{ "customcontrolresource" },
{ "customeraddress" },
{ "customeropportunityrole" },
{ "customerrelationship" },
{ "dataperformance" },
{ "dci" },
{ "delveactionhub" },
{ "dependency" },
{ "dependencyfeature" },
{ "dependencynode" },
{ "discount" },
{ "discounttype" },
{ "displaystring" },
{ "displaystringmap" },
{ "documentindex" },
{ "documenttemplate" },
{ "duplicaterecord" },
{ "duplicaterule" },
{ "duplicaterulecondition" },
{ "dynamicproperty" },
{ "dynamicpropertyassociation" },
{ "dynamicpropertyinstance" },
{ "dynamicpropertyoptionsetitem" },
{ "email" },
{ "emailhash" },
{ "emailsearch" },
{ "emailserverprofile" },
{ "emailsignature" },
{ "entitlement" },
{ "entitlementchannel" },
{ "entitlementcontacts" },
{ "entitlementproducts" },
{ "entitlementtemplate" },
{ "entitlementtemplatechannel" },
{ "entitlementtemplateproducts" },
{ "entitydataprovider" },
{ "entitydatasource" },
{ "entitydatasourcemapping" },
{ "entitymap" },
{ "equipment" },
{ "exchangesyncidmapping" },
{ "expiredprocess" },
{ "externalparty" },
{ "externalpartyitem" },
{ "fax" },
{ "feedback" },
{ "fieldpermission" },
{ "fieldsecurityprofile" },
{ "filtertemplate" },
{ "fixedmonthlyfiscalcalendar" },
{ "globalsearchconfiguration" },
{ "goal" },
{ "goalrollupquery" },
{ "hierarchyrule" },
{ "hierarchysecurityconfiguration" },
{ "imagedescriptor" },
{ "import" },
{ "importdata" },
{ "importentitymapping" },
{ "importfile" },
{ "importjob" },
{ "importlog" },
{ "importmap" },
{ "incident" },
{ "incidentknowledgebaserecord" },
{ "incidentresolution" },
{ "integrationstatus" },
{ "interactionforemail" },
{ "internaladdress" },
{ "interprocesslock" },
{ "invaliddependency" },
{ "invoice" },
{ "invoicedetail" },
{ "isvconfig" },
{ "kbarticle" },
{ "kbarticlecomment" },
{ "kbarticletemplate" },
{ "knowledgearticle" },
{ "knowledgearticleincident" },
{ "knowledgearticlescategories" },
{ "knowledgearticleviews" },
{ "knowledgebaserecord" },
{ "knowledgesearchmodel" },
{ "languagelocale" },
{ "lead" },
{ "leadaddress" },
{ "leadcompetitors" },
{ "leadproduct" },
{ "leadtoopportunitysalesprocess" },
{ "letter" },
{ "license" },
{ "list" },
{ "listmember" },
{ "localconfigstore" },
{ "lookupmapping" },
{ "mailbox" },
{ "mailboxstatistics" },
{ "mailboxtrackingfolder" },
{ "mailmergetemplate" },
{ "metadatadifference" },
{ "metric" },
{ "mobileofflineprofile" },
{ "mobileofflineprofileitem" },
{ "mobileofflineprofileitemassociation" },
{ "monthlyfiscalcalendar" },
{ "msdyn_postalbum" },
{ "msdyn_postconfig" },
{ "msdyn_postruleconfig" },
{ "msdyn_wallsavedquery" },
{ "msdyn_wallsavedqueryusersettings" },
{ "multientitysearch" },
{ "multientitysearchentities" },
{ "multiselectattributeoptionvalues" },
{ "navigationsetting" },
{ "newprocess" },
{ "notification" },
{ "officedocument" },
{ "officegraphdocument" },
{ "opportunity" },
{ "opportunityclose" },
{ "opportunitycompetitors" },
{ "opportunityproduct" },
{ "opportunitysalesprocess" },
{ "orderclose" },
{ "organization" },
{ "organizationstatistic" },
{ "organizationui" },
{ "orginsightsmetric" },
{ "owner" },
{ "ownermapping" },
{ "partnerapplication" },
{ "personaldocumenttemplate" },
{ "phonecall" },
{ "phonetocaseprocess" },
{ "picklistmapping" },
{ "pluginassembly" },
{ "plugintracelog" },
{ "plugintype" },
{ "plugintypestatistic" },
{ "position" },
{ "post" },
{ "postcomment" },
{ "postfollow" },
{ "postlike" },
{ "postregarding" },
{ "postrole" },
{ "pricelevel" },
{ "principalattributeaccessmap" },
{ "principalentitymap" },
{ "principalobjectaccess" },
{ "principalobjectaccessreadsnapshot" },
{ "principalobjectattributeaccess" },
{ "principalsyncattributemap" },
{ "privilege" },
{ "privilegeobjecttypecodes" },
{ "processsession" },
{ "processstage" },
{ "processtrigger" },
{ "product" },
{ "productassociation" },
{ "productpricelevel" },
{ "productsalesliterature" },
{ "productsubstitute" },
{ "publisher" },
{ "publisheraddress" },
{ "quarterlyfiscalcalendar" },
{ "queue" },
{ "queueitem" },
{ "queueitemcount" },
{ "queuemembercount" },
{ "queuemembership" },
{ "quote" },
{ "quoteclose" },
{ "quotedetail" },
{ "ratingmodel" },
{ "ratingvalue" },
{ "recommendationcache" },
{ "recommendationmodel" },
{ "recommendationmodelmapping" },
{ "recommendationmodelversion" },
{ "recommendationmodelversionhistory" },
{ "recommendeddocument" },
{ "recordcountsnapshot" },
{ "recurrencerule" },
{ "recurringappointmentmaster" },
{ "relationshiprole" },
{ "relationshiprolemap" },
{ "replicationbacklog" },
{ "report" },
{ "reportcategory" },
{ "reportentity" },
{ "reportlink" },
{ "reportvisibility" },
{ "resource" },
{ "resourcegroup" },
{ "resourcegroupexpansion" },
{ "resourcespec" },
{ "ribboncommand" },
{ "ribboncontextgroup" },
{ "ribboncustomization" },
{ "ribbondiff" },
{ "ribbonrule" },
{ "ribbontabtocommandmap" },
{ "role" },
{ "roleprivileges" },
{ "roletemplate" },
{ "roletemplateprivileges" },
{ "rollupfield" },
{ "rollupjob" },
{ "rollupproperties" },
{ "routingrule" },
{ "routingruleitem" },
{ "runtimedependency" },
{ "salesliterature" },
{ "salesliteratureitem" },
{ "salesorder" },
{ "salesorderdetail" },
{ "salesprocessinstance" },
{ "savedorginsightsconfiguration" },
{ "savedquery" },
{ "savedqueryvisualization" },
{ "sdkmessage" },
{ "sdkmessagefilter" },
{ "sdkmessagepair" },
{ "sdkmessageprocessingstep" },
{ "sdkmessageprocessingstepimage" },
{ "sdkmessageprocessingstepsecureconfig" },
{ "sdkmessagerequest" },
{ "sdkmessagerequestfield" },
{ "sdkmessageresponse" },
{ "sdkmessageresponsefield" },
{ "semiannualfiscalcalendar" },
{ "service" },
{ "serviceappointment" },
{ "servicecontractcontacts" },
{ "serviceendpoint" },
{ "sharedobjectsforread" },
{ "sharepointdata" },
{ "sharepointdocument" },
{ "sharepointdocumentlocation" },
{ "sharepointsite" },
{ "similarityrule" },
{ "site" },
{ "sitemap" },
{ "sla" },
{ "slaitem" },
{ "slakpiinstance" },
{ "socialactivity" },
{ "socialinsightsconfiguration" },
{ "socialprofile" },
{ "solution" },
{ "solutioncomponent" },
{ "sqlencryptionaudit" },
{ "statusmap" },
{ "stringmap" },
{ "subject" },
{ "subscription" },
{ "subscriptionclients" },
{ "subscriptionmanuallytrackedobject" },
{ "subscriptionstatisticsoffline" },
{ "subscriptionstatisticsoutlook" },
{ "subscriptionsyncentryoffline" },
{ "subscriptionsyncentryoutlook" },
{ "subscriptionsyncinfo" },
{ "subscriptiontrackingdeletedobject" },
{ "syncattributemapping" },
{ "syncattributemappingprofile" },
{ "syncerror" },
{ "systemapplicationmetadata" },
{ "systemform" },
{ "systemuser" },
{ "systemuserbusinessunitentitymap" },
{ "systemuserlicenses" },
{ "systemusermanagermap" },
{ "systemuserprincipals" },
{ "systemuserprofiles" },
{ "systemuserroles" },
{ "systemusersyncmappingprofiles" },
{ "task" },
{ "team" },
{ "teammembership" },
{ "teamprofiles" },
{ "teamroles" },
{ "teamsyncattributemappingprofiles" },
{ "teamtemplate" },
{ "template" },
{ "territory" },
{ "textanalyticsentitymapping" },
{ "theme" },
{ "timestampdatemapping" },
{ "timezonedefinition" },
{ "timezonelocalizedname" },
{ "timezonerule" },
{ "topic" },
{ "topichistory" },
{ "topicmodel" },
{ "topicmodelconfiguration" },
{ "topicmodelexecutionhistory" },
{ "traceassociation" },
{ "tracelog" },
{ "traceregarding" },
{ "transactioncurrency" },
{ "transformationmapping" },
{ "transformationparametermapping" },
{ "translationprocess" },
{ "unresolvedaddress" },
{ "untrackedemail" },
{ "uom" },
{ "uomschedule" },
{ "userapplicationmetadata" },
{ "userentityinstancedata" },
{ "userentityuisettings" },
{ "userfiscalcalendar" },
{ "userform" },
{ "usermapping" },
{ "userquery" },
{ "userqueryvisualization" },
{ "usersearchfacet" },
{ "usersettings" },
{ "webresource" },
{ "webwizard" },
{ "wizardaccessprivilege" },
{ "wizardpage" },
{ "workflow" },
{ "workflowdependency" },
{ "workflowlog" },
{ "workflowwaitsubscription" },
};
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Umbraco;
[assembly: PureLiveAssembly]
[assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "73f0b83ef677012f")]
[assembly:System.Reflection.AssemblyVersion("0.0.0.1")]
// FILE: models.generated.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder v3.0.5.96
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Umbraco.Web.PublishedContentModels
{
/// <summary>Website</summary>
[PublishedContentModel("website")]
public partial class Website : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "website";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Website(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Website, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Navn
///</summary>
[ImplementPropertyType("siteName")]
public string SiteName
{
get { return this.GetPropertyValue<string>("siteName"); }
}
///<summary>
/// Startside
///</summary>
[ImplementPropertyType("umbracoInternalRedirectId")]
public IPublishedContent UmbracoInternalRedirectId
{
get { return this.GetPropertyValue<IPublishedContent>("umbracoInternalRedirectId"); }
}
}
/// <summary>Forside</summary>
[PublishedContentModel("FrontPage")]
public partial class FrontPage : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "FrontPage";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public FrontPage(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<FrontPage, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Indholdsside</summary>
[PublishedContentModel("ContentPage")]
public partial class ContentPage : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "ContentPage";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public ContentPage(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ContentPage, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Sektioner
///</summary>
[ImplementPropertyType("sections")]
public IEnumerable<IPublishedContent> Sections
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("sections"); }
}
}
/// <summary>Call To Action</summary>
[PublishedContentModel("Blueprint_CallToAction")]
public partial class Blueprint_CallToAction : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Blueprint_CallToAction";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Blueprint_CallToAction(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Blueprint_CallToAction, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Billede
///</summary>
[ImplementPropertyType("image")]
public IEnumerable<IPublishedContent> Image
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("image"); }
}
///<summary>
/// Titel
///</summary>
[ImplementPropertyType("title")]
public string Title
{
get { return this.GetPropertyValue<string>("title"); }
}
}
/// <summary>Nyheder</summary>
[PublishedContentModel("Blueprint_NewsBand")]
public partial class Blueprint_NewsBand : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Blueprint_NewsBand";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Blueprint_NewsBand(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Blueprint_NewsBand, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Links
///</summary>
[ImplementPropertyType("links")]
public IEnumerable<IPublishedContent> Links
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("links"); }
}
///<summary>
/// Nyhedsoversigter
///</summary>
[ImplementPropertyType("newslists")]
public IPublishedContent Newslists
{
get { return this.GetPropertyValue<IPublishedContent>("newslists"); }
}
}
/// <summary>Kampagner</summary>
[PublishedContentModel("Blueprint_CampaignTeasers")]
public partial class Blueprint_CampaignTeasers : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Blueprint_CampaignTeasers";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Blueprint_CampaignTeasers(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Blueprint_CampaignTeasers, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Kampagner
///</summary>
[ImplementPropertyType("campaigns")]
public string Campaigns
{
get { return this.GetPropertyValue<string>("campaigns"); }
}
}
/// <summary>Folder</summary>
[PublishedContentModel("Folder")]
public partial class Folder : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Folder";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Folder(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Contents:
///</summary>
[ImplementPropertyType("contents")]
public object Contents
{
get { return this.GetPropertyValue("contents"); }
}
}
/// <summary>Image</summary>
[PublishedContentModel("Image")]
public partial class Image : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Image";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Image(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload image
///</summary>
[ImplementPropertyType("umbracoFile")]
public Umbraco.Web.Models.ImageCropDataSet UmbracoFile
{
get { return this.GetPropertyValue<Umbraco.Web.Models.ImageCropDataSet>("umbracoFile"); }
}
///<summary>
/// Height
///</summary>
[ImplementPropertyType("umbracoHeight")]
public string UmbracoHeight
{
get { return this.GetPropertyValue<string>("umbracoHeight"); }
}
///<summary>
/// Width
///</summary>
[ImplementPropertyType("umbracoWidth")]
public string UmbracoWidth
{
get { return this.GetPropertyValue<string>("umbracoWidth"); }
}
}
/// <summary>File</summary>
[PublishedContentModel("File")]
public partial class File : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "File";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public File(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload file
///</summary>
[ImplementPropertyType("umbracoFile")]
public object UmbracoFile
{
get { return this.GetPropertyValue("umbracoFile"); }
}
}
/// <summary>Member</summary>
[PublishedContentModel("Member")]
public partial class Member : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Member";
public new const PublishedItemType ModelItemType = PublishedItemType.Member;
#pragma warning restore 0109
public Member(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Is Approved
///</summary>
[ImplementPropertyType("umbracoMemberApproved")]
public bool UmbracoMemberApproved
{
get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); }
}
///<summary>
/// Comments
///</summary>
[ImplementPropertyType("umbracoMemberComments")]
public string UmbracoMemberComments
{
get { return this.GetPropertyValue<string>("umbracoMemberComments"); }
}
///<summary>
/// Failed Password Attempts
///</summary>
[ImplementPropertyType("umbracoMemberFailedPasswordAttempts")]
public string UmbracoMemberFailedPasswordAttempts
{
get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); }
}
///<summary>
/// Last Lockout Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLockoutDate")]
public string UmbracoMemberLastLockoutDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); }
}
///<summary>
/// Last Login Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLogin")]
public string UmbracoMemberLastLogin
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); }
}
///<summary>
/// Last Password Change Date
///</summary>
[ImplementPropertyType("umbracoMemberLastPasswordChangeDate")]
public string UmbracoMemberLastPasswordChangeDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); }
}
///<summary>
/// Is Locked Out
///</summary>
[ImplementPropertyType("umbracoMemberLockedOut")]
public bool UmbracoMemberLockedOut
{
get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); }
}
///<summary>
/// Password Answer
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")]
public string UmbracoMemberPasswordRetrievalAnswer
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); }
}
///<summary>
/// Password Question
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")]
public string UmbracoMemberPasswordRetrievalQuestion
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); }
}
}
}
// EOF
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Parse.Abstractions.Infrastructure;
using Parse.Abstractions.Infrastructure.Control;
using Parse.Abstractions.Infrastructure.Execution;
using Parse.Abstractions.Platform.Objects;
using Parse.Infrastructure;
using Parse.Infrastructure.Execution;
using Parse.Platform.Objects;
namespace Parse.Tests
{
#warning Finish refactoring.
[TestClass]
public class ObjectControllerTests
{
ParseClient Client { get; set; }
[TestInitialize]
public void SetUp() => Client = new ParseClient(new ServerConnectionData { ApplicationID = "", Key = "", Test = true });
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestFetch()
{
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, new Dictionary<string, object> { ["__type"] = "Object", ["className"] = "Corgi", ["objectId"] = "st4nl3yW", ["doge"] = "isShibaInu", ["createdAt"] = "2015-09-18T18:11:28.943Z" }));
return new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData).FetchAsync(new MutableObjectState { ClassName = "Corgi", ObjectId = "st4nl3yW", ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" } }, default, Client, CancellationToken.None).ContinueWith(task =>
{
Assert.IsFalse(task.IsFaulted);
Assert.IsFalse(task.IsCanceled);
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "classes/Corgi/st4nl3yW"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
IObjectState newState = task.Result;
Assert.AreEqual("isShibaInu", newState["doge"]);
Assert.IsFalse(newState.ContainsKey("corgi"));
Assert.IsNotNull(newState.CreatedAt);
Assert.IsNotNull(newState.UpdatedAt);
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestSave()
{
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, new Dictionary<string, object> { ["__type"] = "Object", ["className"] = "Corgi", ["objectId"] = "st4nl3yW", ["doge"] = "isShibaInu", ["createdAt"] = "2015-09-18T18:11:28.943Z" }));
return new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData).SaveAsync(new MutableObjectState { ClassName = "Corgi", ObjectId = "st4nl3yW", ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" } }, new Dictionary<string, IParseFieldOperation> { ["gogo"] = new Mock<IParseFieldOperation> { }.Object }, default, Client, CancellationToken.None).ContinueWith(task =>
{
Assert.IsFalse(task.IsFaulted);
Assert.IsFalse(task.IsCanceled);
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "classes/Corgi/st4nl3yW"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
IObjectState newState = task.Result;
Assert.AreEqual("isShibaInu", newState["doge"]);
Assert.IsFalse(newState.ContainsKey("corgi"));
Assert.IsFalse(newState.ContainsKey("gogo"));
Assert.IsNotNull(newState.CreatedAt);
Assert.IsNotNull(newState.UpdatedAt);
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestSaveNewObject()
{
MutableObjectState state = new MutableObjectState
{
ClassName = "Corgi",
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
};
Dictionary<string, IParseFieldOperation> operations = new Dictionary<string, IParseFieldOperation> { ["gogo"] = new Mock<IParseFieldOperation> { }.Object };
Dictionary<string, object> responseDict = new Dictionary<string, object>
{
["__type"] = "Object",
["className"] = "Corgi",
["objectId"] = "st4nl3yW",
["doge"] = "isShibaInu",
["createdAt"] = "2015-09-18T18:11:28.943Z"
};
Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Created, responseDict);
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response);
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
return controller.SaveAsync(state, operations, default, Client, CancellationToken.None).ContinueWith(task =>
{
Assert.IsFalse(task.IsFaulted);
Assert.IsFalse(task.IsCanceled);
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "classes/Corgi"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
IObjectState newState = task.Result;
Assert.AreEqual("isShibaInu", newState["doge"]);
Assert.IsFalse(newState.ContainsKey("corgi"));
Assert.IsFalse(newState.ContainsKey("gogo"));
Assert.AreEqual("st4nl3yW", newState.ObjectId);
Assert.IsTrue(newState.IsNew);
Assert.IsNotNull(newState.CreatedAt);
Assert.IsNotNull(newState.UpdatedAt);
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestSaveAll()
{
List<IObjectState> states = new List<IObjectState>();
for (int i = 0; i < 30; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = (i % 2 == 0) ? null : "st4nl3yW" + i,
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
});
}
List<IDictionary<string, IParseFieldOperation>> operationsList = new List<IDictionary<string, IParseFieldOperation>>();
for (int i = 0; i < 30; ++i)
{
operationsList.Add(new Dictionary<string, IParseFieldOperation> { ["gogo"] = new Mock<IParseFieldOperation> { }.Object });
}
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
for (int i = 0; i < 30; ++i)
{
results.Add(new Dictionary<string, object>
{
["success"] = new Dictionary<string, object>
{
["__type"] = "Object",
["className"] = "Corgi",
["objectId"] = "st4nl3yW" + i,
["doge"] = "isShibaInu",
["createdAt"] = "2015-09-18T18:11:28.943Z"
}
});
}
Dictionary<string, object> responseDict = new Dictionary<string, object> { [nameof(results)] = results };
Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict);
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response);
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task<IObjectState>> tasks = controller.SaveAllAsync(states, operationsList, default, Client, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
Assert.IsTrue(tasks.All(task => task.IsCompleted && !task.IsCanceled && !task.IsFaulted));
for (int i = 0; i < 30; ++i)
{
IObjectState serverState = tasks[i].Result;
Assert.AreEqual("st4nl3yW" + i, serverState.ObjectId);
Assert.IsFalse(serverState.ContainsKey("gogo"));
Assert.IsFalse(serverState.ContainsKey("corgi"));
Assert.AreEqual("isShibaInu", serverState["doge"]);
Assert.IsNotNull(serverState.CreatedAt);
Assert.IsNotNull(serverState.UpdatedAt);
}
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestSaveAllManyObjects()
{
List<IObjectState> states = new List<IObjectState>();
for (int i = 0; i < 102; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = "st4nl3yW" + i,
ServerData = new Dictionary<string, object>
{
["corgi"] = "isNotDoge"
}
});
}
List<IDictionary<string, IParseFieldOperation>> operationsList = new List<IDictionary<string, IParseFieldOperation>>();
for (int i = 0; i < 102; ++i)
operationsList.Add(new Dictionary<string, IParseFieldOperation> { ["gogo"] = new Mock<IParseFieldOperation>().Object });
// Make multiple response since the batch will be splitted.
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
for (int i = 0; i < 50; ++i)
{
results.Add(new Dictionary<string, object>
{
["success"] = new Dictionary<string, object>
{
["__type"] = "Object",
["className"] = "Corgi",
["objectId"] = "st4nl3yW" + i,
["doge"] = "isShibaInu",
["createdAt"] = "2015-09-18T18:11:28.943Z"
}
});
}
Dictionary<string, object> responseDict = new Dictionary<string, object> { [nameof(results)] = results };
Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict);
List<IDictionary<string, object>> results2 = new List<IDictionary<string, object>>();
for (int i = 0; i < 2; ++i)
{
results2.Add(new Dictionary<string, object>
{
["success"] = new Dictionary<string, object>
{
["__type"] = "Object",
["className"] = "Corgi",
["objectId"] = "st4nl3yW" + i,
["doge"] = "isShibaInu",
["createdAt"] = "2015-09-18T18:11:28.943Z"
}
});
}
Dictionary<string, object> responseDict2 = new Dictionary<string, object> { [nameof(results)] = results2 };
Tuple<HttpStatusCode, IDictionary<string, object>> response2 = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict2);
Mock<IParseCommandRunner> mockRunner = new Mock<IParseCommandRunner> { };
mockRunner.SetupSequence(obj => obj.RunCommandAsync(It.IsAny<ParseCommand>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response)).Returns(Task.FromResult(response)).Returns(Task.FromResult(response2));
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task<IObjectState>> tasks = controller.SaveAllAsync(states, operationsList, default, Client, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
Assert.IsTrue(tasks.All(task => task.IsCompleted && !task.IsCanceled && !task.IsFaulted));
for (int i = 0; i < 102; ++i)
{
IObjectState serverState = tasks[i].Result;
Assert.AreEqual("st4nl3yW" + i % 50, serverState.ObjectId);
Assert.IsFalse(serverState.ContainsKey("gogo"));
Assert.IsFalse(serverState.ContainsKey("corgi"));
Assert.AreEqual("isShibaInu", serverState["doge"]);
Assert.IsNotNull(serverState.CreatedAt);
Assert.IsNotNull(serverState.UpdatedAt);
}
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(3));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestDelete()
{
MutableObjectState state = new MutableObjectState
{
ClassName = "Corgi",
ObjectId = "st4nl3yW",
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
};
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, new Dictionary<string, object> { }));
return new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData).DeleteAsync(state, default, CancellationToken.None).ContinueWith(task =>
{
Assert.IsFalse(task.IsFaulted);
Assert.IsFalse(task.IsCanceled);
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "classes/Corgi/st4nl3yW"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestDeleteAll()
{
List<IObjectState> states = new List<IObjectState>();
for (int i = 0; i < 30; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = "st4nl3yW" + i,
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
});
}
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
for (int i = 0; i < 30; ++i)
{
results.Add(new Dictionary<string, object> { ["success"] = null });
}
Dictionary<string, object> responseDict = new Dictionary<string, object> { [nameof(results)] = results };
Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict);
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response);
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task> tasks = controller.DeleteAllAsync(states, default, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
Assert.IsTrue(tasks.All(task => task.IsCompleted && !task.IsCanceled && !task.IsFaulted));
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestDeleteAllManyObjects()
{
List<IObjectState> states = new List<IObjectState>();
for (int i = 0; i < 102; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = "st4nl3yW" + i,
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
});
}
// Make multiple response since the batch will be split.
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
for (int i = 0; i < 50; ++i)
{
results.Add(new Dictionary<string, object> { ["success"] = default });
}
Dictionary<string, object> responseDict = new Dictionary<string, object> { [nameof(results)] = results };
Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict);
List<IDictionary<string, object>> results2 = new List<IDictionary<string, object>>();
for (int i = 0; i < 2; ++i)
{
results2.Add(new Dictionary<string, object> { ["success"] = default });
}
Dictionary<string, object> responseDict2 = new Dictionary<string, object> { [nameof(results)] = results2 };
Tuple<HttpStatusCode, IDictionary<string, object>> response2 = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, responseDict2);
Mock<IParseCommandRunner> mockRunner = new Mock<IParseCommandRunner>();
mockRunner.SetupSequence(obj => obj.RunCommandAsync(It.IsAny<ParseCommand>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response)).Returns(Task.FromResult(response)).Returns(Task.FromResult(response2));
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task> tasks = controller.DeleteAllAsync(states, null, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
Assert.IsTrue(tasks.All(task => task.IsCompleted && !task.IsCanceled && !task.IsFaulted));
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(3));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestDeleteAllFailSome()
{
List<IObjectState> states = new List<IObjectState> { };
for (int i = 0; i < 30; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = (i % 2 == 0) ? null : "st4nl3yW" + i,
ServerData = new Dictionary<string, object> { ["corgi"] = "isNotDoge" }
});
}
List<IDictionary<string, object>> results = new List<IDictionary<string, object>> { };
for (int i = 0; i < 15; ++i)
{
if (i % 2 == 0)
{
results.Add(new Dictionary<string, object>
{
["error"] = new Dictionary<string, object>
{
["code"] = (long) ParseFailureException.ErrorCode.ObjectNotFound,
["error"] = "Object not found."
}
});
}
else
{
results.Add(new Dictionary<string, object> { ["success"] = default });
}
}
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, new Dictionary<string, object> { [nameof(results)] = results }));
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task> tasks = controller.DeleteAllAsync(states, null, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
for (int i = 0; i < 15; ++i)
{
if (i % 2 == 0)
{
Assert.IsTrue(tasks[i].IsFaulted);
Assert.IsInstanceOfType(tasks[i].Exception.InnerException, typeof(ParseFailureException));
ParseFailureException exception = tasks[i].Exception.InnerException as ParseFailureException;
Assert.AreEqual(ParseFailureException.ErrorCode.ObjectNotFound, exception.Code);
}
else
{
Assert.IsTrue(tasks[i].IsCompleted);
Assert.IsFalse(tasks[i].IsFaulted || tasks[i].IsCanceled);
}
}
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
});
}
[TestMethod]
[AsyncStateMachine(typeof(ObjectControllerTests))]
public Task TestDeleteAllInconsistent()
{
List<IObjectState> states = new List<IObjectState> { };
for (int i = 0; i < 30; ++i)
{
states.Add(new MutableObjectState
{
ClassName = "Corgi",
ObjectId = "st4nl3yW" + i,
ServerData = new Dictionary<string, object>
{
["corgi"] = "isNotDoge"
}
});
}
List<IDictionary<string, object>> results = new List<IDictionary<string, object>> { };
for (int i = 0; i < 36; ++i)
{
results.Add(new Dictionary<string, object> { ["success"] = default });
}
Mock<IParseCommandRunner> mockRunner = CreateMockRunner(new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.OK, new Dictionary<string, object> { [nameof(results)] = results }));
ParseObjectController controller = new ParseObjectController(mockRunner.Object, Client.Decoder, Client.ServerConnectionData);
IList<Task> tasks = controller.DeleteAllAsync(states, null, CancellationToken.None);
return Task.WhenAll(tasks).ContinueWith(_ =>
{
Assert.IsTrue(tasks.All(task => task.IsFaulted));
Assert.IsInstanceOfType(tasks[0].Exception.InnerException, typeof(InvalidOperationException));
mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Path == "batch"), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>()), Times.Exactly(1));
});
}
private Mock<IParseCommandRunner> CreateMockRunner(Tuple<HttpStatusCode, IDictionary<string, object>> response)
{
Mock<IParseCommandRunner> mockRunner = new Mock<IParseCommandRunner>();
mockRunner.Setup(obj => obj.RunCommandAsync(It.IsAny<ParseCommand>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<IProgress<IDataTransferLevel>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
return mockRunner;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EndpointsOperations.
/// </summary>
public static partial class EndpointsOperationsExtensions
{
/// <summary>
/// Lists existing CDN endpoints within a profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static IEnumerable<Endpoint> ListByProfile(this IEndpointsOperations operations, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).ListByProfileAsync(profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists existing CDN endpoints within a profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Endpoint>> ListByProfileAsync(this IEndpointsOperations operations, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByProfileWithHttpMessagesAsync(profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint Get(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).GetAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> GetAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint Create(this IEndpointsOperations operations, string endpointName, EndpointCreateParameters endpointProperties, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).CreateAsync(endpointName, endpointProperties, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> CreateAsync(this IEndpointsOperations operations, string endpointName, EndpointCreateParameters endpointProperties, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(endpointName, endpointProperties, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint BeginCreate(this IEndpointsOperations operations, string endpointName, EndpointCreateParameters endpointProperties, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginCreateAsync(endpointName, endpointProperties, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginCreateAsync(this IEndpointsOperations operations, string endpointName, EndpointCreateParameters endpointProperties, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(endpointName, endpointProperties, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN endpoint with the specified parameters. Only tags
/// and OriginHostHeader can be updated after creating an endpoint. To update
/// origins, use the Update Origin operation. To update custom domains, use
/// the Update Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint Update(this IEndpointsOperations operations, string endpointName, EndpointUpdateParameters endpointProperties, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).UpdateAsync(endpointName, endpointProperties, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN endpoint with the specified parameters. Only tags
/// and OriginHostHeader can be updated after creating an endpoint. To update
/// origins, use the Update Origin operation. To update custom domains, use
/// the Update Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string endpointName, EndpointUpdateParameters endpointProperties, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(endpointName, endpointProperties, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN endpoint with the specified parameters. Only tags
/// and OriginHostHeader can be updated after creating an endpoint. To update
/// origins, use the Update Origin operation. To update custom domains, use
/// the Update Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint BeginUpdate(this IEndpointsOperations operations, string endpointName, EndpointUpdateParameters endpointProperties, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginUpdateAsync(endpointName, endpointProperties, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN endpoint with the specified parameters. Only tags
/// and OriginHostHeader can be updated after creating an endpoint. To update
/// origins, use the Update Origin operation. To update custom domains, use
/// the Update Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='endpointProperties'>
/// Endpoint properties
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginUpdateAsync(this IEndpointsOperations operations, string endpointName, EndpointUpdateParameters endpointProperties, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(endpointName, endpointProperties, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static void DeleteIfExists(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).DeleteIfExistsAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteIfExistsAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteIfExistsWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static void BeginDeleteIfExists(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginDeleteIfExistsAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteIfExistsAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteIfExistsWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts an existing stopped CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint Start(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).StartAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Starts an existing stopped CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> StartAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StartWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Starts an existing stopped CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint BeginStart(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginStartAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Starts an existing stopped CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginStartAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStartWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint Stop(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).StopAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> StopAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StopWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Endpoint BeginStop(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginStopAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginStopAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStopWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Forcibly purges CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
public static void PurgeContent(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).PurgeContentAsync(endpointName, profileName, resourceGroupName, contentPaths), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Forcibly purges CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PurgeContentAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PurgeContentWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Forcibly purges CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
public static void BeginPurgeContent(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginPurgeContentAsync(endpointName, profileName, resourceGroupName, contentPaths), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Forcibly purges CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPurgeContentAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginPurgeContentWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Forcibly pre-loads CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Should describe a file path.
/// </param>
public static void LoadContent(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).LoadContentAsync(endpointName, profileName, resourceGroupName, contentPaths), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Forcibly pre-loads CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Should describe a file path.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LoadContentAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.LoadContentWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Forcibly pre-loads CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Should describe a file path.
/// </param>
public static void BeginLoadContent(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginLoadContentAsync(endpointName, profileName, resourceGroupName, contentPaths), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Forcibly pre-loads CDN endpoint content.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Should describe a file path.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginLoadContentAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginLoadContentWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Validates a custom domain mapping to ensure it maps to the correct CNAME
/// in DNS.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
public static ValidateCustomDomainOutput ValidateCustomDomain(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, string hostName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).ValidateCustomDomainAsync(endpointName, profileName, resourceGroupName, hostName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Validates a custom domain mapping to ensure it maps to the correct CNAME
/// in DNS.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ValidateCustomDomainOutput> ValidateCustomDomainAsync(this IEndpointsOperations operations, string endpointName, string profileName, string resourceGroupName, string hostName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ValidateCustomDomainWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, hostName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.NodejsTools.Debugger;
using Microsoft.NodejsTools.Debugger.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NodejsTests.Mocks;
namespace NodejsTests.Debugger.Serialization
{
[TestClass]
public class NodeVariablesFactoryTests
{
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateNullEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 5,
Parent = null,
StackFrame = null,
Name = "v_null",
TypeName = "null",
Value = "null",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value.Length, result.StringLength);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(NodeExpressionType.None, result.Type);
Assert.AreEqual(NodeVariableType.Null, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateNumberEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 20,
Parent = null,
StackFrame = null,
Name = "v_number",
TypeName = "number",
Value = "55",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.AreEqual(string.Format("0x{0:x}", int.Parse(variable.Value)), result.HexValue);
Assert.AreEqual(variable.Value.Length, result.StringLength);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(NodeExpressionType.None, result.Type);
Assert.AreEqual(NodeVariableType.Number, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateBooleanEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 21,
Parent = null,
StackFrame = null,
Name = "v_boolean",
TypeName = "boolean",
Value = "false",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value.Length, result.StringLength);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(NodeExpressionType.Boolean, result.Type);
Assert.AreEqual(NodeVariableType.Boolean, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateRegexpEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 22,
Parent = null,
StackFrame = null,
Name = "v_regexp",
TypeName = "regexp",
Value = "55",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value.Length, result.StringLength);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(NodeExpressionType.Expandable, result.Type);
Assert.AreEqual(NodeVariableType.Regexp, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateFunctionWithoutTextEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 23,
Parent = null,
StackFrame = null,
Name = "v_function",
TypeName = "function",
Value = "55",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(string.Format("{{{0}}}", NodeVariableType.Function), result.StringValue);
Assert.AreEqual(NodeExpressionType.Function | NodeExpressionType.Expandable, result.Type);
Assert.AreEqual(NodeVariableType.Function, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateFunctionWithTextEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 23,
Parent = null,
StackFrame = null,
Name = "v_function",
TypeName = "function",
Value = "55",
Class = null,
Text = "function(){...}"
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Text, result.StringValue);
Assert.AreEqual(NodeExpressionType.Function | NodeExpressionType.Expandable, result.Type);
Assert.AreEqual(NodeVariableType.Function, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateStringEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 24,
Parent = null,
StackFrame = null,
Name = "v_string",
TypeName = "string",
Value = "string",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value.Length, result.StringLength);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.String);
Assert.AreEqual(NodeVariableType.String, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateObjectEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 25,
Parent = null,
StackFrame = null,
Name = "v_object",
TypeName = "object",
Value = null,
Class = "Object",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual("{...}", result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.Expandable);
Assert.AreEqual(NodeVariableType.Object, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateDateEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 27,
Parent = null,
StackFrame = null,
Name = "v_date",
TypeName = "object",
Value = null,
Class = "Date",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(string.Format("{{{0}}}", variable.Class), result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.Expandable);
Assert.AreEqual(NodeVariableType.Object, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateArrayEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 19,
Parent = null,
StackFrame = null,
Name = "v_array",
TypeName = "object",
Value = null,
Class = "Array",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(string.Format("{{{0}}}", variable.Class), result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.Expandable);
Assert.AreEqual(NodeVariableType.Object, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateErrorEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 26,
Parent = null,
StackFrame = null,
Name = "v_error",
TypeName = "error",
Value = "Error: dsfdsf",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value.Substring(7), result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.Expandable);
Assert.AreEqual(NodeVariableType.Error, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateUnknownEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 26,
Parent = null,
StackFrame = null,
Name = "v_unknown",
TypeName = "unknown",
Value = "Unknown",
Class = null,
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(NodeExpressionType.None, result.Type);
Assert.AreEqual(NodeVariableType.Unknown, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateUnknownEvaluationResultWithEmptyValue()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 26,
Parent = null,
StackFrame = null,
Name = "v_unknown",
TypeName = "unknown",
Value = null,
Class = null,
Text = "Unknown"
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(variable.Name, result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.IsNull(result.HexValue);
Assert.AreEqual(variable.Text, result.StringValue);
Assert.AreEqual(NodeExpressionType.None, result.Type);
Assert.AreEqual(NodeVariableType.Unknown, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateEvaluationResultFromNullVariable()
{
// Arrange
Exception exception = null;
var factory = new EvaluationResultFactory();
// Act
try
{
factory.Create(null);
}
catch (Exception e)
{
exception = e;
}
// Assert
Assert.IsNotNull(exception);
Assert.IsInstanceOfType(exception, typeof(ArgumentNullException));
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateArrayElementEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 19,
Parent = new NodeEvaluationResult(0, null, null, "Object", "v_array", "v_array", NodeExpressionType.Expandable, null),
StackFrame = null,
Name = "0",
TypeName = "number",
Value = "0",
Class = "Number",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(string.Format("[{0}]", variable.Name), result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(string.Format(@"{0}[{1}]", variable.Parent.Expression, variable.Name), result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.AreEqual(string.Format("0x{0:x}", int.Parse(variable.Value)), result.HexValue);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.None);
Assert.AreEqual(NodeVariableType.Number, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateObjectElementEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 19,
Parent = new NodeEvaluationResult(0, null, null, "Object", "v_object", "v_object", NodeExpressionType.Expandable, null),
StackFrame = null,
Name = "m_number",
TypeName = "number",
Value = "0",
Class = "Number",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(string.Format(@"{0}.{1}", variable.Parent.Expression, variable.Name), result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.AreEqual(string.Format("0x{0:x}", int.Parse(variable.Value)), result.HexValue);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.None);
Assert.AreEqual(NodeVariableType.Number, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateObjectElementWithInvalidIdentifierEvaluationResult()
{
// Arrange
var variable = new MockNodeVariable
{
Id = 19,
Parent = new NodeEvaluationResult(0, null, null, "Object", "v_object", "v_object", NodeExpressionType.Expandable, null),
StackFrame = null,
Name = "123name",
TypeName = "number",
Value = "0",
Class = "Number",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(string.Format(@"{0}[""{1}""]", variable.Parent.Expression, variable.Name), result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.AreEqual(string.Format("0x{0:x}", int.Parse(variable.Value)), result.HexValue);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.None);
Assert.AreEqual(NodeVariableType.Number, result.TypeName);
}
[TestMethod, Priority(0), TestCategory("Debugging")]
public void CreateEvaluationResultForPrototypeChild()
{
// Arrange
const string parentName = "parent";
var variable = new MockNodeVariable
{
Id = 19,
Parent = new NodeEvaluationResult(
0,
null,
null,
"Object",
NodeVariableType.Prototype,
parentName + "." + NodeVariableType.Prototype,
NodeExpressionType.Expandable,
null),
StackFrame = null,
Name = "name",
TypeName = "number",
Value = "0",
Class = "Number",
Text = null
};
var factory = new EvaluationResultFactory();
// Act
NodeEvaluationResult result = factory.Create(variable);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(variable.Name, result.Expression);
Assert.IsNull(result.Frame);
Assert.AreEqual(string.Format(@"{0}.{1}", parentName, variable.Name), result.FullName);
Assert.AreEqual(variable.Id, result.Handle);
Assert.AreEqual(string.Format("0x{0:x}", int.Parse(variable.Value)), result.HexValue);
Assert.AreEqual(variable.Value, result.StringValue);
Assert.AreEqual(result.Type, NodeExpressionType.None);
Assert.AreEqual(NodeVariableType.Number, result.TypeName);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace AssetBundles
{
public class BuildScript
{
public static string overloadedDevelopmentServerURL = "";
static public string CreateAssetBundleDirectory()
{
// Choose the output path according to the build target.
string outputPath = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName());
Debug.Log(outputPath);
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
return outputPath;
}
public static void BuildAssetBundles()
{
BuildAssetBundles(null);
}
public static void BuildAssetBundles(AssetBundleBuild[] builds)
{
// Choose the output path according to the build target.
string outputPath = CreateAssetBundleDirectory();
var options = BuildAssetBundleOptions.None;
bool shouldCheckODR = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS;
#if UNITY_TVOS
shouldCheckODR |= EditorUserBuildSettings.activeBuildTarget == BuildTarget.tvOS;
#endif
if (shouldCheckODR)
{
#if ENABLE_IOS_ON_DEMAND_RESOURCES
if (PlayerSettings.iOS.useOnDemandResources)
options |= BuildAssetBundleOptions.UncompressedAssetBundle;
#endif
#if ENABLE_IOS_APP_SLICING
options |= BuildAssetBundleOptions.UncompressedAssetBundle;
#endif
}
if (builds == null || builds.Length == 0)
{
//@TODO: use append hash... (Make sure pipeline works correctly with it.)
BuildPipeline.BuildAssetBundles(outputPath, options, EditorUserBuildSettings.activeBuildTarget);
}
else
{
BuildPipeline.BuildAssetBundles(outputPath, builds, options, EditorUserBuildSettings.activeBuildTarget);
}
}
public static void WriteServerURL()
{
string downloadURL;
if (string.IsNullOrEmpty(overloadedDevelopmentServerURL) == false)
{
downloadURL = overloadedDevelopmentServerURL;
}
else
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
downloadURL = "http://" + localIP + ":7888/";
}
string assetBundleManagerResourcesDirectory = "Assets/AssetBundleManager/Resources";
string assetBundleUrlPath = Path.Combine(assetBundleManagerResourcesDirectory, "AssetBundleServerURL.bytes");
Directory.CreateDirectory(assetBundleManagerResourcesDirectory);
File.WriteAllText(assetBundleUrlPath, downloadURL);
AssetDatabase.Refresh();
}
public static void BuildPlayer()
{
var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", "");
if (outputPath.Length == 0)
return;
string[] levels = GetLevelsFromBuildSettings();
if (levels.Length == 0)
{
Debug.Log("Nothing to build.");
return;
}
string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget);
if (targetName == null)
return;
// Build and copy AssetBundles.
BuildScript.BuildAssetBundles();
WriteServerURL();
#if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0
BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None;
BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option);
#else
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = levels;
buildPlayerOptions.locationPathName = outputPath + targetName;
buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath();
buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget;
buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None;
BuildPipeline.BuildPlayer(buildPlayerOptions);
#endif
}
public static void BuildStandalonePlayer()
{
var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", "");
if (outputPath.Length == 0)
return;
string[] levels = GetLevelsFromBuildSettings();
if (levels.Length == 0)
{
Debug.Log("Nothing to build.");
return;
}
string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget);
if (targetName == null)
return;
// Build and copy AssetBundles.
BuildScript.BuildAssetBundles();
BuildScript.CopyAssetBundlesTo(Path.Combine(Application.streamingAssetsPath, Utility.AssetBundlesOutputPath));
AssetDatabase.Refresh();
#if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0
BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None;
BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option);
#else
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = levels;
buildPlayerOptions.locationPathName = outputPath + targetName;
buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath();
buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget;
buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None;
BuildPipeline.BuildPlayer(buildPlayerOptions);
#endif
}
public static string GetBuildTargetName(BuildTarget target)
{
switch (target)
{
case BuildTarget.Android:
return "/test.apk";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "/test.exe";
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
case BuildTarget.StandaloneOSXUniversal:
return "/test.app";
case BuildTarget.WebPlayer:
case BuildTarget.WebPlayerStreamed:
case BuildTarget.WebGL:
case BuildTarget.iOS:
return "";
// Add more build targets for your own.
default:
Debug.Log("Target not implemented.");
return null;
}
}
static void CopyAssetBundlesTo(string outputPath)
{
// Clear streaming assets folder.
FileUtil.DeleteFileOrDirectory(Application.streamingAssetsPath);
Directory.CreateDirectory(outputPath);
string outputFolder = Utility.GetPlatformName();
// Setup the source folder for assetbundles.
var source = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, Utility.AssetBundlesOutputPath), outputFolder);
if (!System.IO.Directory.Exists(source))
Debug.Log("No assetBundle output folder, try to build the assetBundles first.");
// Setup the destination folder for assetbundles.
var destination = System.IO.Path.Combine(outputPath, outputFolder);
if (System.IO.Directory.Exists(destination))
FileUtil.DeleteFileOrDirectory(destination);
FileUtil.CopyFileOrDirectory(source, destination);
}
static string[] GetLevelsFromBuildSettings()
{
List<string> levels = new List<string>();
for (int i = 0; i < EditorBuildSettings.scenes.Length; ++i)
{
if (EditorBuildSettings.scenes[i].enabled)
levels.Add(EditorBuildSettings.scenes[i].path);
}
return levels.ToArray();
}
static string GetAssetBundleManifestFilePath()
{
var relativeAssetBundlesOutputPathForPlatform = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName());
return Path.Combine(relativeAssetBundlesOutputPathForPlatform, Utility.GetPlatformName()) + ".manifest";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using CoolNameGenerator.GA.Chromosomes;
using CoolNameGenerator.Properties;
namespace CoolNameGenerator.GA.Populations
{
/// <summary>
/// Represents a population of candidate solutions (chromosomes).
/// </summary>
public class Population : IPopulation
{
#region Events
/// <summary>
/// Occurs when best chromosome changed.
/// </summary>
public event EventHandler BestChromosomeChanged;
#endregion
#region Protected methods
/// <summary>
/// Raises the best chromosome changed event.
/// </summary>
/// <param name="args">The event arguments.</param>
protected virtual void OnBestChromosomeChanged(EventArgs args)
{
BestChromosomeChanged?.Invoke(this, args);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Population" /> class.
/// </summary>
/// <param name="minSize">The minimum size (chromosomes).</param>
/// <param name="maxSize">The maximum size (chromosomes).</param>
/// <param name="adamChromosome">The original chromosome of all population ;).</param>
public Population(int minSize, int maxSize, IChromosome adamChromosome)
{
if (minSize < 2)
{
throw new ArgumentOutOfRangeException(nameof(minSize),
Localization.minimum_size_for_a_population_is_2_chromosomes);
}
if (maxSize < minSize)
{
throw new ArgumentOutOfRangeException(nameof(maxSize),
Localization.maximum_size_for_a_population_should_be_equal_or_greater_than_minimum_size);
}
if (adamChromosome == null) throw new ArgumentNullException(nameof(adamChromosome));
CreationDate = DateTime.Now;
MinSize = minSize;
MaxSize = maxSize;
AdamChromosome = adamChromosome;
Generations = new List<Generation>();
GenerationStrategy = new PerformanceGenerationStrategy(10);
}
/// <summary>
/// Initializes a new instance of the <see cref="Population" /> class.
/// </summary>
/// <param name="minSize">The minimum size (chromosomes).</param>
/// <param name="maxSize">The maximum size (chromosomes).</param>
/// <param name="adamChromosome">The original chromosome of all population ;).</param>
/// <param name="generationStrategy">Generation strategy to some key points of generation behavior inside a population.</param>
public Population(int minSize, int maxSize, IChromosome adamChromosome, IGenerationStrategy generationStrategy)
{
if (minSize < 2)
{
throw new ArgumentOutOfRangeException(nameof(minSize),
Localization.minimum_size_for_a_population_is_2_chromosomes);
}
if (maxSize < minSize)
{
throw new ArgumentOutOfRangeException(nameof(maxSize),
Localization.maximum_size_for_a_population_should_be_equal_or_greater_than_minimum_size);
}
if (adamChromosome == null) throw new ArgumentNullException(nameof(adamChromosome));
if (generationStrategy == null)
{
throw new ArgumentNullException(nameof(generationStrategy));
}
CreationDate = DateTime.Now;
MinSize = minSize;
MaxSize = maxSize;
AdamChromosome = adamChromosome;
Generations = new List<Generation>();
GenerationStrategy = generationStrategy;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the creation date.
/// </summary>
public DateTime CreationDate { get; protected set; }
/// <summary>
/// Gets or sets the generations.
/// <remarks>
/// The information of Generations can vary depending of the IGenerationStrategy used.
/// </remarks>
/// </summary>
/// <value>The generations.</value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",
Justification = "Parent classes need to set it.")]
public IList<Generation> Generations { get; protected set; }
/// <summary>
/// Gets or sets the current generation.
/// </summary>
/// <value>The current generation.</value>
public Generation CurrentGeneration { get; protected set; }
/// <summary>
/// Gets or sets the total number of generations executed.
/// <remarks>
/// Use this information to know how many generations have been executed, because Generations.Count can vary
/// depending of the IGenerationStrategy used.
/// </remarks>
/// </summary>
public int GenerationsNumber { get; protected set; }
/// <summary>
/// Gets or sets the minimum size.
/// </summary>
/// <value>The minimum size.</value>
public int MinSize { get; set; }
/// <summary>
/// Gets or sets the size of the max.
/// </summary>
/// <value>The size of the max.</value>
public int MaxSize { get; set; }
/// <summary>
/// Gets or sets the best chromosome.
/// </summary>
/// <value>The best chromosome.</value>
public IChromosome BestChromosome { get; protected set; }
/// <summary>
/// Gets or sets the generation strategy.
/// </summary>
public IGenerationStrategy GenerationStrategy { get; set; }
/// <summary>
/// Gets or sets the original chromosome of all population.
/// </summary>
/// <value>The adam chromosome.</value>
protected IChromosome AdamChromosome { get; set; }
#endregion
#region Public methods
/// <summary>
/// Creates the initial generation.
/// </summary>
public virtual void CreateInitialGeneration()
{
Generations = new List<Generation>();
GenerationsNumber = 0;
var chromosomes = new List<IChromosome>();
for (var i = 0; i < MinSize; i++)
{
var c = AdamChromosome.CreateNew();
if (c == null)
{
throw new InvalidOperationException(
"The Adam chromosome's 'CreateNew' method generated a null chromosome. This is a invalid behavior, please, check your chromosome code.");
}
c.ValidateGenes();
chromosomes.Add(c);
}
CreateNewGeneration(chromosomes);
}
/// <summary>
/// Creates a new generation.
/// </summary>
/// <param name="chromosomes">The chromosomes for new generation.</param>
public virtual void CreateNewGeneration(IList<IChromosome> chromosomes)
{
if (chromosomes == null) throw new ArgumentNullException(nameof(chromosomes));
chromosomes.ValidateGenes();
CurrentGeneration = new Generation(++GenerationsNumber, chromosomes);
Generations.Add(CurrentGeneration);
GenerationStrategy.RegisterNewGeneration(this);
}
/// <summary>
/// Ends the current generation.
/// </summary>
public virtual void EndCurrentGeneration()
{
CurrentGeneration.End(MaxSize);
if (BestChromosome != CurrentGeneration.BestChromosome)
{
BestChromosome = CurrentGeneration.BestChromosome;
OnBestChromosomeChanged(EventArgs.Empty);
}
}
#endregion
}
}
| |
/*
* MindTouch DekiScript - embeddable web-oriented scripting runtime
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using MindTouch.Deki.Script.Expr;
using MindTouch.Dream;
using MindTouch.Extensions;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.Script.Runtime.TargetInvocation {
public class DekiScriptNativeInvocationTarget : ADekiScriptInvocationTarget {
//--- Types ---
public class Parameter {
//--- Class Fields ---
public static readonly Parameter Default = new Parameter(null, false);
//--- Fields ---
public readonly string Hint;
public readonly bool Optional;
//--- Constructor ---
public Parameter(string hint, bool optional) {
this.Hint = hint;
this.Optional = optional;
}
}
//--- Fields ---
private readonly Func<DekiScriptRuntime, object[], object> _invoke;
//--- Constructors ---
public DekiScriptNativeInvocationTarget(object subject, MethodInfo method, Parameter[] parameters) {
this.Method = method;
// check if method is a coroutine
Type nativeReturnType;
ConstructorInfo resultTypeConstructor = null;
ParameterInfo[] methodParams = method.GetParameters();
bool isCoroutine = (method.ReturnType == typeof(IEnumerator<IYield>));
if(isCoroutine) {
// check if enough parameters are present
if(methodParams.Length == 0) {
throw new ArgumentException("handler is missing Result<T> parameter");
}
// check that the last parameter is of type Result<T>
Type lastParam = methodParams[methodParams.Length - 1].ParameterType;
if(!lastParam.IsGenericType || (lastParam.GetGenericTypeDefinition() != typeof(Result<>))) {
throw new ArgumentException(string.Format("handler last parameter must be generic type Result<T>, but is {0}", lastParam.FullName));
}
resultTypeConstructor = lastParam.GetConstructor(Type.EmptyTypes);
nativeReturnType = lastParam.GetGenericArguments()[0];
// remove last parameter from array since it represents the return type
methodParams = ArrayUtil.Resize(methodParams, methodParams.Length - 1);
} else {
nativeReturnType = method.ReturnType;
}
ReturnType = DekiScriptLiteral.AsScriptType(nativeReturnType);
// check if first parameter is a DekiScriptRuntime
bool usesRuntime = false;
if((methodParams.Length > 0) && (methodParams[methodParams.Length - 1].ParameterType.IsA<DekiScriptRuntime>())) {
usesRuntime = true;
methodParams = ArrayUtil.Resize(methodParams, methodParams.Length - 1);
}
// retrieve method parameters and their attributes
Parameters = new DekiScriptParameter[methodParams.Length];
for(int i = 0; i < methodParams.Length; ++i) {
ParameterInfo param = methodParams[i];
Parameter details = parameters[i] ?? Parameter.Default;
// add hint parameter
Parameters[i] = new DekiScriptParameter(param.Name, DekiScriptLiteral.AsScriptType(param.ParameterType), details.Optional, details.Hint, param.ParameterType, DekiScriptNil.Value);
}
// determine access rights
if(method.IsPrivate || method.IsFamily) {
this.Access = DreamAccess.Private;
} else if(method.IsAssembly) {
this.Access = DreamAccess.Internal;
} else {
this.Access = DreamAccess.Public;
}
// create invocation callback
if(resultTypeConstructor != null) {
if(usesRuntime) {
// invoke coroutine with runtime
_invoke = (runtime, args) => {
var arguments = new object[args.Length + 2];
AResult result = (AResult)resultTypeConstructor.Invoke(null);
arguments[arguments.Length - 1] = result;
arguments[arguments.Length - 2] = runtime;
Array.Copy(args, arguments, args.Length);
new Coroutine(method, result).Invoke(() => (IEnumerator<IYield>)method.InvokeWithRethrow(subject, arguments));
result.Block();
return result.UntypedValue;
};
} else {
// invoke coroutine without runtime
_invoke = (runtime, args) => {
var arguments = new object[args.Length + 1];
AResult result = (AResult)resultTypeConstructor.Invoke(null);
arguments[arguments.Length - 1] = result;
Array.Copy(args, arguments, args.Length);
new Coroutine(method, result).Invoke(() => (IEnumerator<IYield>)method.InvokeWithRethrow(subject, arguments));
result.Block();
return result.UntypedValue;
};
}
} else {
if(usesRuntime) {
// invoke method with runtime
_invoke = (runtime, args) => {
var arguments = new object[args.Length + 1];
arguments[arguments.Length - 1] = runtime;
Array.Copy(args, arguments, args.Length);
return method.InvokeWithRethrow(subject, arguments);
};
} else {
// invoke method without runtime
_invoke = (runtime, args) => method.InvokeWithRethrow(subject, args);
}
}
}
//--- Properties ---
public DreamAccess Access { get; private set; }
public DekiScriptParameter[] Parameters { get; private set; }
public MethodInfo Method { get; private set; }
public DekiScriptType ReturnType { get; private set; }
//--- Methods ---
public override DekiScriptLiteral InvokeList(DekiScriptRuntime runtime, DekiScriptList args) {
return InvokeHelper(runtime, DekiScriptParameter.ValidateToList(Parameters, args));
}
public override DekiScriptLiteral InvokeMap(DekiScriptRuntime runtime, DekiScriptMap args) {
return InvokeHelper(runtime, DekiScriptParameter.ValidateToList(Parameters, args));
}
private DekiScriptLiteral InvokeHelper(DekiScriptRuntime runtime, DekiScriptList args) {
// convert passed in arguments
object[] arguments = new object[Parameters.Length];
int i = 0;
try {
for(; i < Parameters.Length; ++i) {
var value = args[i].NativeValue;
// check if we need to convert the value
if((value != null) && (Parameters[i].NativeType != typeof(object))) {
// check for the special case where we cast from XML to STR
if((value is XDoc) && (Parameters[i].NativeType == typeof(string))) {
XDoc xml = (XDoc)value;
if(xml.HasName("html")) {
value = xml["body[not(@target)]"].Contents;
} else {
value = xml.ToString();
}
} else {
// rely on the default type conversion rules
value = SysUtil.ChangeType(value, Parameters[i].NativeType);
}
}
arguments[i] = value;
}
} catch {
throw new ArgumentException(string.Format("could not convert parameter '{0}' (index {1}) from {2} to {3}", Parameters[i].Name, i, args[i].ScriptTypeName, DekiScriptLiteral.AsScriptTypeName(Parameters[i].ScriptType)));
}
// invoke method
var result = _invoke(runtime, arguments);
// check if result is a URI
if(result is XUri) {
// normalize URI if possible
DreamContext context = DreamContext.CurrentOrNull;
if(context != null) {
result = context.AsPublicUri((XUri)result);
}
}
var literal = DekiScriptLiteral.FromNativeValue(result);
try {
return literal.Convert(ReturnType);
} catch(DekiScriptInvalidCastException) {
throw new DekiScriptInvalidReturnCastException(Location.None, literal.ScriptType, ReturnType);
}
}
}
}
| |
using System;
using System.Data.SqlTypes;
using BLToolkit.Reflection;
namespace BLToolkit.Mapping
{
[CLSCompliant(false)]
public static class MapSetData<T>
{
public abstract class MB<V>
{
public abstract void To(IMapDataDestination d, object o, int i, V v);
}
public static void To(IMapDataDestination d, object o, int i, T v)
{
I.To(d, o, i, v);
}
public static MB<T> I = GetSetter();
private static MB<T> GetSetter()
{
Type t = typeof(T);
// Scalar Types.
//
if (t == typeof(SByte)) return (MB<T>)(object)(new I8());
if (t == typeof(Int16)) return (MB<T>)(object)(new I16());
if (t == typeof(Int32)) return (MB<T>)(object)(new I32());
if (t == typeof(Int64)) return (MB<T>)(object)(new I64());
if (t == typeof(Byte)) return (MB<T>)(object)(new U8());
if (t == typeof(UInt16)) return (MB<T>)(object)(new U16());
if (t == typeof(UInt32)) return (MB<T>)(object)(new U32());
if (t == typeof(UInt64)) return (MB<T>)(object)(new U64());
if (t == typeof(Single)) return (MB<T>)(object)(new R4());
if (t == typeof(Double)) return (MB<T>)(object)(new R8());
if (t == typeof(Boolean)) return (MB<T>)(object)(new B());
if (t == typeof(Decimal)) return (MB<T>)(object)(new D());
if (t == typeof(Char)) return (MB<T>)(object)(new C());
if (t == typeof(Guid)) return (MB<T>)(object)(new G());
if (t == typeof(DateTime)) return (MB<T>)(object)(new DT());
#if FW3
if (t == typeof(DateTimeOffset)) return (MB<T>)(object)(new DTO());
#endif
// Enums.
//
if (t.IsEnum)
{
t = Enum.GetUnderlyingType(t);
if (t == typeof(SByte)) return new EI8<T>();
if (t == typeof(Int16)) return new EI16<T>();
if (t == typeof(Int32)) return new EI32<T>();
if (t == typeof(Int64)) return new EI64<T>();
if (t == typeof(Byte)) return new EU8<T>();
if (t == typeof(UInt16)) return new EU16<T>();
if (t == typeof(UInt32)) return new EU32<T>();
if (t == typeof(UInt64)) return new EU64<T>();
}
// Nullable Types.
//
if (t == typeof(SByte?)) return (MB<T>)(object)(new NI8());
if (t == typeof(Int16?)) return (MB<T>)(object)(new NI16());
if (t == typeof(Int32?)) return (MB<T>)(object)(new NI32());
if (t == typeof(Int64?)) return (MB<T>)(object)(new NI64());
if (t == typeof(Byte?)) return (MB<T>)(object)(new NU8());
if (t == typeof(UInt16?)) return (MB<T>)(object)(new NU16());
if (t == typeof(UInt32?)) return (MB<T>)(object)(new NU32());
if (t == typeof(UInt64?)) return (MB<T>)(object)(new NU64());
if (t == typeof(Single?)) return (MB<T>)(object)(new NR4());
if (t == typeof(Double?)) return (MB<T>)(object)(new NR8());
if (t == typeof(Boolean?)) return (MB<T>)(object)(new NB());
if (t == typeof(Decimal?)) return (MB<T>)(object)(new ND());
if (t == typeof(Char?)) return (MB<T>)(object)(new NC());
if (t == typeof(Guid?)) return (MB<T>)(object)(new NG());
if (t == typeof(DateTime?)) return (MB<T>)(object)(new NDT());
#if FW3
if (t == typeof(DateTimeOffset?)) return (MB<T>)(object)(new NDTO());
#endif
// Nullable Enums.
//
if (TypeHelper.IsNullable(t) && Nullable.GetUnderlyingType(t).IsEnum)
{
Type enumType = Nullable.GetUnderlyingType(t);
t = Enum.GetUnderlyingType(enumType);
if (t == typeof(SByte)) return (MB<T>)Activator.CreateInstance(typeof(NEI8<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(Int16)) return (MB<T>)Activator.CreateInstance(typeof(NEI16<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(Int32)) return (MB<T>)Activator.CreateInstance(typeof(NEI32<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(Int64)) return (MB<T>)Activator.CreateInstance(typeof(NEI64<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(Byte)) return (MB<T>)Activator.CreateInstance(typeof(NEU8<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(UInt16)) return (MB<T>)Activator.CreateInstance(typeof(NEU16<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(UInt32)) return (MB<T>)Activator.CreateInstance(typeof(NEU32<>).MakeGenericType(typeof(T), enumType));
if (t == typeof(UInt64)) return (MB<T>)Activator.CreateInstance(typeof(NEU64<>).MakeGenericType(typeof(T), enumType));
}
// SqlTypes.
//
if (t == typeof(SqlString)) return (MB<T>)(object)(new dbS());
if (t == typeof(SqlByte)) return (MB<T>)(object)(new dbU8());
if (t == typeof(SqlInt16)) return (MB<T>)(object)(new dbI16());
if (t == typeof(SqlInt32)) return (MB<T>)(object)(new dbI32());
if (t == typeof(SqlInt64)) return (MB<T>)(object)(new dbI64());
if (t == typeof(SqlSingle)) return (MB<T>)(object)(new dbR4());
if (t == typeof(SqlDouble)) return (MB<T>)(object)(new dbR8());
if (t == typeof(SqlDecimal)) return (MB<T>)(object)(new dbD());
if (t == typeof(SqlMoney)) return (MB<T>)(object)(new dbM());
if (t == typeof(SqlBoolean)) return (MB<T>)(object)(new dbB());
if (t == typeof(SqlGuid)) return (MB<T>)(object)(new dbG());
if (t == typeof(SqlDateTime)) return (MB<T>)(object)(new dbDT());
return new Default<T>();
}
// Default setter.
//
public sealed class Default<V> : MB<V> { public override void To(IMapDataDestination d, object o, int i, V v) { d.SetValue (o, i, v); } }
// Scalar Types.
//
sealed class I8 : MB<SByte> { public override void To(IMapDataDestination d, object o, int i, SByte v) { d.SetSByte (o, i, v); } }
sealed class I16 : MB<Int16> { public override void To(IMapDataDestination d, object o, int i, Int16 v) { d.SetInt16 (o, i, v); } }
sealed class I32 : MB<Int32> { public override void To(IMapDataDestination d, object o, int i, Int32 v) { d.SetInt32 (o, i, v); } }
sealed class I64 : MB<Int64> { public override void To(IMapDataDestination d, object o, int i, Int64 v) { d.SetInt64 (o, i, v); } }
sealed class U8 : MB<Byte> { public override void To(IMapDataDestination d, object o, int i, Byte v) { d.SetByte (o, i, v); } }
sealed class U16 : MB<UInt16> { public override void To(IMapDataDestination d, object o, int i, UInt16 v) { d.SetUInt16 (o, i, v); } }
sealed class U32 : MB<UInt32> { public override void To(IMapDataDestination d, object o, int i, UInt32 v) { d.SetUInt32 (o, i, v); } }
sealed class U64 : MB<UInt64> { public override void To(IMapDataDestination d, object o, int i, UInt64 v) { d.SetUInt64 (o, i, v); } }
sealed class R4 : MB<Single> { public override void To(IMapDataDestination d, object o, int i, Single v) { d.SetSingle (o, i, v); } }
sealed class R8 : MB<Double> { public override void To(IMapDataDestination d, object o, int i, Double v) { d.SetDouble (o, i, v); } }
sealed class B : MB<Boolean> { public override void To(IMapDataDestination d, object o, int i, Boolean v) { d.SetBoolean (o, i, v); } }
sealed class D : MB<Decimal> { public override void To(IMapDataDestination d, object o, int i, Decimal v) { d.SetDecimal (o, i, v); } }
sealed class C : MB<Char> { public override void To(IMapDataDestination d, object o, int i, Char v) { d.SetChar (o, i, v); } }
sealed class G : MB<Guid> { public override void To(IMapDataDestination d, object o, int i, Guid v) { d.SetGuid (o, i, v); } }
sealed class DT : MB<DateTime> { public override void To(IMapDataDestination d, object o, int i, DateTime v) { d.SetDateTime (o, i, v); } }
#if FW3
sealed class DTO : MB<DateTimeOffset>{ public override void To(IMapDataDestination d, object o, int i, DateTimeOffset v) { d.SetDateTimeOffset (o, i, v); } }
#endif
// Enums.
//
sealed class EI8<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetSByte (o, i, (SByte)(object)v); } }
sealed class EI16<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetInt16 (o, i, (Int16)(object)v); } }
sealed class EI32<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetInt32 (o, i, (Int32)(object)v); } }
sealed class EI64<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetInt64 (o, i, (Int64)(object)v); } }
sealed class EU8<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetByte (o, i, (Byte)(object)v); } }
sealed class EU16<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetUInt16 (o, i, (UInt16)(object)v); } }
sealed class EU32<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetUInt32 (o, i, (UInt32)(object)v); } }
sealed class EU64<E> : MB<E> { public override void To(IMapDataDestination d, object o, int i, E v) { d.SetUInt64 (o, i, (UInt64)(object)v); } }
// Nullable Types.
//
sealed class NI8 : MB<SByte?> { public override void To(IMapDataDestination d, object o, int i, SByte? v) { d.SetNullableSByte (o, i, v); } }
sealed class NI16 : MB<Int16?> { public override void To(IMapDataDestination d, object o, int i, Int16? v) { d.SetNullableInt16 (o, i, v); } }
sealed class NI32 : MB<Int32?> { public override void To(IMapDataDestination d, object o, int i, Int32? v) { d.SetNullableInt32 (o, i, v); } }
sealed class NI64 : MB<Int64?> { public override void To(IMapDataDestination d, object o, int i, Int64? v) { d.SetNullableInt64 (o, i, v); } }
sealed class NU8 : MB<Byte?> { public override void To(IMapDataDestination d, object o, int i, Byte? v) { d.SetNullableByte (o, i, v); } }
sealed class NU16 : MB<UInt16?> { public override void To(IMapDataDestination d, object o, int i, UInt16? v) { d.SetNullableUInt16 (o, i, v); } }
sealed class NU32 : MB<UInt32?> { public override void To(IMapDataDestination d, object o, int i, UInt32? v) { d.SetNullableUInt32 (o, i, v); } }
sealed class NU64 : MB<UInt64?> { public override void To(IMapDataDestination d, object o, int i, UInt64? v) { d.SetNullableUInt64 (o, i, v); } }
sealed class NR4 : MB<Single?> { public override void To(IMapDataDestination d, object o, int i, Single? v) { d.SetNullableSingle (o, i, v); } }
sealed class NR8 : MB<Double?> { public override void To(IMapDataDestination d, object o, int i, Double? v) { d.SetNullableDouble (o, i, v); } }
sealed class NB : MB<Boolean?> { public override void To(IMapDataDestination d, object o, int i, Boolean? v) { d.SetNullableBoolean (o, i, v); } }
sealed class ND : MB<Decimal?> { public override void To(IMapDataDestination d, object o, int i, Decimal? v) { d.SetNullableDecimal (o, i, v); } }
sealed class NC : MB<Char?> { public override void To(IMapDataDestination d, object o, int i, Char? v) { d.SetNullableChar (o, i, v); } }
sealed class NG : MB<Guid?> { public override void To(IMapDataDestination d, object o, int i, Guid? v) { d.SetNullableGuid (o, i, v); } }
sealed class NDT : MB<DateTime?> { public override void To(IMapDataDestination d, object o, int i, DateTime? v) { d.SetNullableDateTime (o, i, v); } }
#if FW3
sealed class NDTO : MB<DateTimeOffset?>{ public override void To(IMapDataDestination d, object o, int i, DateTimeOffset? v) { d.SetNullableDateTimeOffset (o, i, v); } }
#endif
// Nullable Enums.
//
sealed class NEI8<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetSByte (o, i, (SByte)(object)v.Value); } }
sealed class NEI16<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetInt16 (o, i, (Int16)(object)v.Value); } }
sealed class NEI32<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetInt32 (o, i, (Int32)(object)v.Value); } }
sealed class NEI64<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetInt64 (o, i, (Int64)(object)v.Value); } }
sealed class NEU8<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetByte (o, i, (Byte)(object)v.Value); } }
sealed class NEU16<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetUInt16(o, i, (UInt16)(object)v.Value); } }
sealed class NEU32<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetUInt32(o, i, (UInt32)(object)v.Value); } }
sealed class NEU64<E> : MB<E?> where E : struct { public override void To(IMapDataDestination d, object o, int i, E? v) { /*if (null == v) d.SetNull(o, i); else*/ d.SetUInt64(o, i, (UInt64)(object)v.Value); } }
// SqlTypes.
//
sealed class dbS : MB<SqlString> { public override void To(IMapDataDestination d, object o, int i, SqlString v) { d.SetSqlString (o, i, v); } }
sealed class dbU8 : MB<SqlByte> { public override void To(IMapDataDestination d, object o, int i, SqlByte v) { d.SetSqlByte (o, i, v); } }
sealed class dbI16 : MB<SqlInt16> { public override void To(IMapDataDestination d, object o, int i, SqlInt16 v) { d.SetSqlInt16 (o, i, v); } }
sealed class dbI32 : MB<SqlInt32> { public override void To(IMapDataDestination d, object o, int i, SqlInt32 v) { d.SetSqlInt32 (o, i, v); } }
sealed class dbI64 : MB<SqlInt64> { public override void To(IMapDataDestination d, object o, int i, SqlInt64 v) { d.SetSqlInt64 (o, i, v); } }
sealed class dbR4 : MB<SqlSingle> { public override void To(IMapDataDestination d, object o, int i, SqlSingle v) { d.SetSqlSingle (o, i, v); } }
sealed class dbR8 : MB<SqlDouble> { public override void To(IMapDataDestination d, object o, int i, SqlDouble v) { d.SetSqlDouble (o, i, v); } }
sealed class dbD : MB<SqlDecimal> { public override void To(IMapDataDestination d, object o, int i, SqlDecimal v) { d.SetSqlDecimal (o, i, v); } }
sealed class dbM : MB<SqlMoney> { public override void To(IMapDataDestination d, object o, int i, SqlMoney v) { d.SetSqlMoney (o, i, v); } }
sealed class dbB : MB<SqlBoolean> { public override void To(IMapDataDestination d, object o, int i, SqlBoolean v) { d.SetSqlBoolean (o, i, v); } }
sealed class dbG : MB<SqlGuid> { public override void To(IMapDataDestination d, object o, int i, SqlGuid v) { d.SetSqlGuid (o, i, v); } }
sealed class dbDT : MB<SqlDateTime> { public override void To(IMapDataDestination d, object o, int i, SqlDateTime v) { d.SetSqlDateTime (o, i, v); } }
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding;
/** Handles path calls for a single unit.
* \ingroup relevant
* This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle it's pathfinding calls.
* It also handles post-processing of paths using modifiers.
* \see \ref calling-pathfinding
*/
[AddComponentMenu("Pathfinding/Seeker")]
[HelpURL("http://arongranberg.com/astar/docs/class_seeker.php")]
public class Seeker : MonoBehaviour, ISerializationCallbackReceiver {
//====== SETTINGS ======
/** Enables drawing of the last calculated path using Gizmos.
* The path will show up in green.
*
* \see OnDrawGizmos
*/
public bool drawGizmos = true;
/** Enables drawing of the non-postprocessed path using Gizmos.
* The path will show up in orange.
*
* Requires that #drawGizmos is true.
*
* This will show the path before any post processing such as smoothing is applied.
*
* \see drawGizmos
* \see OnDrawGizmos
*/
public bool detailedGizmos;
/** Path modifier which tweaks the start and end points of a path */
public StartEndModifier startEndModifier = new StartEndModifier();
/** The tags which the Seeker can traverse.
*
* \note This field is a bitmask.
* \see https://en.wikipedia.org/wiki/Mask_(computing)
*/
[HideInInspector]
public int traversableTags = -1;
/** Required for serialization backwards compatibility.
* \since 3.6.8
*/
[UnityEngine.Serialization.FormerlySerializedAs("traversableTags")]
[SerializeField]
[HideInInspector]
protected TagMask traversableTagsCompatibility = new TagMask(-1, -1);
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
*
* \note This array should always have a length of 32 otherwise the system will ignore it.
*
* \see Pathfinding.Path.tagPenalties
*/
[HideInInspector]
public int[] tagPenalties = new int[32];
//====== SETTINGS ======
/** Callback for when a path is completed.
* Movement scripts should register to this delegate.\n
* A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path
*/
public OnPathDelegate pathCallback;
/** Called before pathfinding is started */
public OnPathDelegate preProcessPath;
/** Called after a path has been calculated, right before modifiers are executed.
* Can be anything which only modifies the positions (Vector3[]).
*/
public OnPathDelegate postProcessPath;
/** Used for drawing gizmos */
[System.NonSerialized]
List<Vector3> lastCompletedVectorPath;
/** Used for drawing gizmos */
[System.NonSerialized]
List<GraphNode> lastCompletedNodePath;
/** The current path */
[System.NonSerialized]
protected Path path;
/** Previous path. Used to draw gizmos */
[System.NonSerialized]
private Path prevPath;
/** Cached delegate to avoid allocating one every time a path is started */
private readonly OnPathDelegate onPathDelegate;
/** Cached delegate to avoid allocating one every time a path is started */
private readonly OnPathDelegate onPartialPathDelegate;
/** Temporary callback only called for the current path. This value is set by the StartPath functions */
private OnPathDelegate tmpPathCallback;
/** The path ID of the last path queried */
protected uint lastPathID;
/** Internal list of all modifiers */
readonly List<IPathModifier> modifiers = new List<IPathModifier>();
public enum ModifierPass {
PreProcess,
// An obsolete item occupied index 1 previously
PostProcess = 2,
}
public Seeker () {
onPathDelegate = OnPathComplete;
onPartialPathDelegate = OnPartialPathComplete;
}
/** Initializes a few variables */
void Awake () {
startEndModifier.Awake(this);
}
/** Path that is currently being calculated or was last calculated.
* You should rarely have to use this. Instead get the path when the path callback is called.
*
* \see pathCallback
*/
public Path GetCurrentPath () {
return path;
}
/** Cleans up some variables.
* Releases any eventually claimed paths.
* Calls OnDestroy on the #startEndModifier.
*
* \see ReleaseClaimedPath
* \see startEndModifier
*/
public void OnDestroy () {
ReleaseClaimedPath();
startEndModifier.OnDestroy(this);
}
/** Releases the path used for gizmos (if any).
* The seeker keeps the latest path claimed so it can draw gizmos.
* In some cases this might not be desireable and you want it released.
* In that case, you can call this method to release it (not that path gizmos will then not be drawn).
*
* If you didn't understand anything from the description above, you probably don't need to use this method.
*
* \see \ref pooling
*/
public void ReleaseClaimedPath () {
if (prevPath != null) {
prevPath.Release(this, true);
prevPath = null;
}
}
/** Called by modifiers to register themselves */
public void RegisterModifier (IPathModifier mod) {
modifiers.Add(mod);
// Sort the modifiers based on their specified order
modifiers.Sort((a, b) => a.Order.CompareTo(b.Order));
}
/** Called by modifiers when they are disabled or destroyed */
public void DeregisterModifier (IPathModifier mod) {
modifiers.Remove(mod);
}
/** Post Processes the path.
* This will run any modifiers attached to this GameObject on the path.
* This is identical to calling RunModifiers(ModifierPass.PostProcess, path)
* \see RunModifiers
* \since Added in 3.2
*/
public void PostProcess (Path p) {
RunModifiers(ModifierPass.PostProcess, p);
}
/** Runs modifiers on path \a p */
public void RunModifiers (ModifierPass pass, Path p) {
// Call delegates if they exist
if (pass == ModifierPass.PreProcess && preProcessPath != null) {
preProcessPath(p);
} else if (pass == ModifierPass.PostProcess && postProcessPath != null) {
postProcessPath(p);
}
// Loop through all modifiers and apply post processing
for (int i = 0; i < modifiers.Count; i++) {
// Cast to MonoModifier, i.e modifiers attached as scripts to the game object
var mMod = modifiers[i] as MonoModifier;
// Ignore modifiers which are not enabled
if (mMod != null && !mMod.enabled) continue;
if (pass == ModifierPass.PreProcess) {
modifiers[i].PreProcess(p);
} else if (pass == ModifierPass.PostProcess) {
modifiers[i].Apply(p);
}
}
}
/** Is the current path done calculating.
* Returns true if the current #path has been returned or if the #path is null.
*
* \note Do not confuse this with Pathfinding.Path.IsDone. They usually return the same value, but not always
* since the path might be completely calculated, but it has not yet been processed by the Seeker.
*
* \since Added in 3.0.8
* \version Behaviour changed in 3.2
*/
public bool IsDone () {
return path == null || path.GetState() >= PathState.Returned;
}
/** Called when a path has completed.
* This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones)
* \see OnPathComplete(Path,bool,bool)
*/
void OnPathComplete (Path p) {
OnPathComplete(p, true, true);
}
/** Called when a path has completed.
* Will post process it and return it by calling #tmpPathCallback and #pathCallback
*/
void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) {
if (p != null && p != path && sendCallbacks) {
return;
}
if (this == null || p == null || p != path)
return;
if (!path.error && runModifiers) {
// This will send the path for post processing to modifiers attached to this Seeker
RunModifiers(ModifierPass.PostProcess, path);
}
if (sendCallbacks) {
p.Claim(this);
lastCompletedNodePath = p.path;
lastCompletedVectorPath = p.vectorPath;
// This will send the path to the callback (if any) specified when calling StartPath
if (tmpPathCallback != null) {
tmpPathCallback(p);
}
// This will send the path to any script which has registered to the callback
if (pathCallback != null) {
pathCallback(p);
}
// Recycle the previous path to reduce the load on the GC
if (prevPath != null) {
prevPath.Release(this, true);
}
prevPath = p;
// If not drawing gizmos, then storing prevPath is quite unecessary
// So clear it and set prevPath to null
if (!drawGizmos) ReleaseClaimedPath();
}
}
/** Called for each path in a MultiTargetPath.
* Only post processes the path, does not return it.
* \astarpro */
void OnPartialPathComplete (Path p) {
OnPathComplete(p, true, false);
}
/** Called once for a MultiTargetPath. Only returns the path, does not post process.
* \astarpro */
void OnMultiPathComplete (Path p) {
OnPathComplete(p, false, true);
}
/** Returns a new path instance.
* The path will be taken from the path pool if path recycling is turned on.\n
* This path can be sent to #StartPath(Path,OnPathDelegate,int) with no change, but if no change is required #StartPath(Vector3,Vector3,OnPathDelegate) does just that.
* \code var seeker = GetComponent<Seeker>();
* Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100);
* // Disable heuristics on just this path for example
* p.heuristic = Heuristic.None;
* seeker.StartPath (p, OnPathComplete);
* \endcode
*/
public ABPath GetNewPath (Vector3 start, Vector3 end) {
// Construct a path with start and end points
return ABPath.Construct(start, end, null);
}
/** Call this function to start calculating a path.
* \param start The start point of the path
* \param end The end point of the path
*/
public Path StartPath (Vector3 start, Vector3 end) {
return StartPath(start, end, null, -1);
}
/** Call this function to start calculating a path.
*
* \param start The start point of the path
* \param end The end point of the path
* \param callback The function to call when the path has been calculated
*
* \a callback will be called when the path has completed.
* \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) {
return StartPath(start, end, callback, -1);
}
/** Call this function to start calculating a path.
*
* \param start The start point of the path
* \param end The end point of the path
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.
*
* \a callback will be called when the path has completed.
* \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, int graphMask) {
return StartPath(GetNewPath(start, end), callback, graphMask);
}
/** Call this function to start calculating a path.
*
* \param p The path to start calculating
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.
*
* \a callback will be called when the path has completed.
* \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
*/
public Path StartPath (Path p, OnPathDelegate callback = null, int graphMask = -1) {
p.enabledTags = traversableTags;
p.tagPenalties = tagPenalties;
p.callback += onPathDelegate;
p.nnConstraint.graphMask = graphMask;
StartPathInternal(p, callback);
return path;
}
/** Internal method to start a path and mark it as the currently active path */
void StartPathInternal (Path p, OnPathDelegate callback) {
// Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else
if (path != null && path.GetState() <= PathState.Processing && lastPathID == path.pathID) {
path.Error();
path.LogError("Canceled path because a new one was requested.\n"+
"This happens when a new path is requested from the seeker when one was already being calculated.\n" +
"For example if a unit got a new order, you might request a new path directly instead of waiting for the now" +
" invalid path to be calculated. Which is probably what you want.\n" +
"If you are getting this a lot, you might want to consider how you are scheduling path requests.");
// No callback will be sent for the canceled path
}
// Set p as the active path
path = p;
tmpPathCallback = callback;
// Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet.
lastPathID = path.pathID;
// Pre process the path
RunModifiers(ModifierPass.PreProcess, path);
// Send the request to the pathfinder
AstarPath.StartPath(path);
}
/** Starts a Multi Target Path from one start point to multiple end points.
* A Multi Target Path will search for all the end points in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n
*
* \param start The start point of the path
* \param endPoints The end points of the path
* \param pathsForAll Indicates whether or not a path to all end points should be searched for or only to the closest one
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.
*
* \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
* \astarpro
* \see Pathfinding.MultiTargetPath
* \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths"
*/
public MultiTargetPath StartMultiTargetPath (Vector3 start, Vector3[] endPoints, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) {
MultiTargetPath p = MultiTargetPath.Construct(start, endPoints, null, null);
p.pathsForAll = pathsForAll;
return StartMultiTargetPath(p, callback, graphMask);
}
/** Starts a Multi Target Path from multiple start points to a single target point.
* A Multi Target Path will search from all start points to the target point in one search and will return all paths if \a pathsForAll is true, or only the shortest one if \a pathsForAll is false.\n
*
* \param startPoints The start points of the path
* \param end The end point of the path
* \param pathsForAll Indicates whether or not a path from all start points should be searched for or only to the closest one
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.
*
* \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
* \astarpro
* \see Pathfinding.MultiTargetPath
* \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths"
*/
public MultiTargetPath StartMultiTargetPath (Vector3[] startPoints, Vector3 end, bool pathsForAll, OnPathDelegate callback = null, int graphMask = -1) {
MultiTargetPath p = MultiTargetPath.Construct(startPoints, end, null, null);
p.pathsForAll = pathsForAll;
return StartMultiTargetPath(p, callback, graphMask);
}
/** Starts a Multi Target Path.
* Takes a MultiTargetPath and wires everything up for it to send callbacks to the seeker for post-processing.\n
*
* \param p The path to start calculating
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.
*
* \a callback and #pathCallback will be called when the path has completed. \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed)
* \astarpro
* \see Pathfinding.MultiTargetPath
* \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths"
*/
public MultiTargetPath StartMultiTargetPath (MultiTargetPath p, OnPathDelegate callback = null, int graphMask = -1) {
// TODO: Allocation, cache
var callbacks = new OnPathDelegate[p.targetPoints.Length];
for (int i = 0; i < callbacks.Length; i++) {
callbacks[i] = onPartialPathDelegate;
}
// TODO: This method does not set the enabledTags or tagPenalties
// as the StartPath method does... should this be changed?
// Hard to do since the API has existed for a long time...
p.callbacks = callbacks;
p.callback += OnMultiPathComplete;
p.nnConstraint.graphMask = graphMask;
StartPathInternal(p, callback);
return p;
}
/** Draws gizmos for the Seeker */
public void OnDrawGizmos () {
if (lastCompletedNodePath == null || !drawGizmos) {
return;
}
if (detailedGizmos) {
Gizmos.color = new Color(0.7F, 0.5F, 0.1F, 0.5F);
if (lastCompletedNodePath != null) {
for (int i = 0; i < lastCompletedNodePath.Count-1; i++) {
Gizmos.DrawLine((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position);
}
}
}
Gizmos.color = new Color(0, 1F, 0, 1F);
if (lastCompletedVectorPath != null) {
for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) {
Gizmos.DrawLine(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]);
}
}
}
/** Handle serialization backwards compatibility */
void ISerializationCallbackReceiver.OnBeforeSerialize () {
}
/** Handle serialization backwards compatibility */
void ISerializationCallbackReceiver.OnAfterDeserialize () {
if (traversableTagsCompatibility != null && traversableTagsCompatibility.tagsChange != -1) {
traversableTags = traversableTagsCompatibility.tagsChange;
traversableTagsCompatibility = new TagMask(-1, -1);
}
}
}
| |
using System;
using Quartz.Impl.Triggers;
using Quartz.Spi;
namespace Quartz
{
/// <summary>
/// CalendarIntervalScheduleBuilder is a <see cref="IScheduleBuilder" />
/// that defines calendar time (day, week, month, year) interval-based
/// schedules for Triggers.
/// </summary>
/// <remarks>
/// <para>
/// Quartz provides a builder-style API for constructing scheduling-related
/// entities via a Domain-Specific Language (DSL). The DSL can best be
/// utilized through the usage of static imports of the methods on the classes
/// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />,
/// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" />
/// and the various <see cref="IScheduleBuilder" /> implementations.
/// </para>
/// <para>Client code can then use the DSL to write code such as this:</para>
/// <code>
/// JobDetail job = JobBuilder.Create<MyJob>()
/// .WithIdentity("myJob")
/// .Build();
/// Trigger trigger = TriggerBuilder.Create()
/// .WithIdentity("myTrigger", "myTriggerGroup")
/// .WithSimpleSchedule(x => x
/// .WithIntervalInHours(1)
/// .RepeatForever())
/// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute))
/// .Build();
/// scheduler.scheduleJob(job, trigger);
/// </code>
/// </remarks>
/// <seealso cref="ICalendarIntervalTrigger" />
/// <seealso cref="CronScheduleBuilder" />
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="SimpleScheduleBuilder" />
/// <seealso cref="TriggerBuilder" />
public class CalendarIntervalScheduleBuilder : ScheduleBuilder<ICalendarIntervalTrigger>
{
private int interval = 1;
private IntervalUnit intervalUnit = IntervalUnit.Day;
private int misfireInstruction = MisfireInstruction.SmartPolicy;
private TimeZoneInfo timeZone;
private bool preserveHourOfDayAcrossDaylightSavings;
private bool skipDayIfHourDoesNotExist;
protected CalendarIntervalScheduleBuilder()
{
}
/// <summary>
/// Create a CalendarIntervalScheduleBuilder.
/// </summary>
/// <returns></returns>
public static CalendarIntervalScheduleBuilder Create()
{
return new CalendarIntervalScheduleBuilder();
}
/// <summary>
/// Build the actual Trigger -- NOT intended to be invoked by end users,
/// but will rather be invoked by a TriggerBuilder which this
/// ScheduleBuilder is given to.
/// </summary>
/// <returns></returns>
public override IMutableTrigger Build()
{
CalendarIntervalTriggerImpl st = new CalendarIntervalTriggerImpl();
st.RepeatInterval = interval;
st.RepeatIntervalUnit = intervalUnit;
st.MisfireInstruction = misfireInstruction;
st.TimeZone = timeZone;
st.PreserveHourOfDayAcrossDaylightSavings = preserveHourOfDayAcrossDaylightSavings;
st.SkipDayIfHourDoesNotExist = skipDayIfHourDoesNotExist;
return st;
}
/// <summary>
/// Specify the time unit and interval for the Trigger to be produced.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="interval">the interval at which the trigger should repeat.</param>
/// <param name="unit"> the time unit (IntervalUnit) of the interval.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithInterval(int interval, IntervalUnit unit)
{
ValidateInterval(interval);
this.interval = interval;
this.intervalUnit = unit;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.SECOND that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInSeconds">the number of seconds at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInSeconds(int intervalInSeconds)
{
ValidateInterval(intervalInSeconds);
this.interval = intervalInSeconds;
this.intervalUnit = IntervalUnit.Second;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.MINUTE that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInMinutes">the number of minutes at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInMinutes(int intervalInMinutes)
{
ValidateInterval(intervalInMinutes);
this.interval = intervalInMinutes;
this.intervalUnit = IntervalUnit.Minute;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.HOUR that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInHours">the number of hours at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInHours(int intervalInHours)
{
ValidateInterval(intervalInHours);
this.interval = intervalInHours;
this.intervalUnit = IntervalUnit.Hour;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.DAY that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInDays">the number of days at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInDays(int intervalInDays)
{
ValidateInterval(intervalInDays);
this.interval = intervalInDays;
this.intervalUnit = IntervalUnit.Day;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.WEEK that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInWeeks">the number of weeks at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInWeeks(int intervalInWeeks)
{
ValidateInterval(intervalInWeeks);
this.interval = intervalInWeeks;
this.intervalUnit = IntervalUnit.Week;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.MONTH that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInMonths">the number of months at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInMonths(int intervalInMonths)
{
ValidateInterval(intervalInMonths);
this.interval = intervalInMonths;
this.intervalUnit = IntervalUnit.Month;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.YEAR that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInYears">the number of years at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInYears(int intervalInYears)
{
ValidateInterval(intervalInYears);
this.interval = intervalInYears;
this.intervalUnit = IntervalUnit.Year;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.IgnoreMisfirePolicy" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CronScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.IgnoreMisfirePolicy" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionIgnoreMisfires()
{
misfireInstruction = MisfireInstruction.IgnoreMisfirePolicy;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.CalendarIntervalTrigger.DoNothing" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.CalendarIntervalTrigger.DoNothing" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionDoNothing()
{
misfireInstruction = MisfireInstruction.CalendarIntervalTrigger.DoNothing;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionFireAndProceed()
{
misfireInstruction = MisfireInstruction.CalendarIntervalTrigger.FireOnceNow;
return this;
}
/// <summary>
/// TimeZone in which to base the schedule.
/// </summary>
/// <param name="timezone">the time-zone for the schedule</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.TimeZone" />
public CalendarIntervalScheduleBuilder InTimeZone(TimeZoneInfo timezone)
{
this.timeZone = timezone;
return this;
}
///<summary>
/// If intervals are a day or greater, this property (set to true) will
/// cause the firing of the trigger to always occur at the same time of day,
/// (the time of day of the startTime) regardless of daylight saving time
/// transitions. Default value is false.
/// </summary>
/// <remarks>
/// <para>
/// For example, without the property set, your trigger may have a start
/// time of 9:00 am on March 1st, and a repeat interval of 2 days. But
/// after the daylight saving transition occurs, the trigger may start
/// firing at 8:00 am every other day.
/// </para>
/// <para>
/// If however, the time of day does not exist on a given day to fire
/// (e.g. 2:00 am in the United States on the days of daylight saving
/// transition), the trigger will go ahead and fire one hour off on
/// that day, and then resume the normal hour on other days. If
/// you wish for the trigger to never fire at the "wrong" hour, then
/// you should set the property skipDayIfHourDoesNotExist.
/// </para>
///</remarks>
/// <seealso cref="SkipDayIfHourDoesNotExist"/>
/// <seealso cref="TimeZone"/>
/// <seealso cref="InTimeZone"/>
/// <seealso cref="TriggerBuilder.StartAt"/>
public CalendarIntervalScheduleBuilder PreserveHourOfDayAcrossDaylightSavings(bool preserveHourOfDay)
{
preserveHourOfDayAcrossDaylightSavings = preserveHourOfDay;
return this;
}
/// <summary>
/// If intervals are a day or greater, and
/// preserveHourOfDayAcrossDaylightSavings property is set to true, and the
/// hour of the day does not exist on a given day for which the trigger
/// would fire, the day will be skipped and the trigger advanced a second
/// interval if this property is set to true. Defaults to false.
/// </summary>
/// <remarks>
/// <b>CAUTION!</b> If you enable this property, and your hour of day happens
/// to be that of daylight savings transition (e.g. 2:00 am in the United
/// States) and the trigger's interval would have had the trigger fire on
/// that day, then you may actually completely miss a firing on the day of
/// transition if that hour of day does not exist on that day! In such a
/// case the next fire time of the trigger will be computed as double (if
/// the interval is 2 days, then a span of 4 days between firings will
/// occur).
/// </remarks>
/// <seealso cref="PreserveHourOfDayAcrossDaylightSavings"/>
public CalendarIntervalScheduleBuilder SkipDayIfHourDoesNotExist(bool skipDay)
{
skipDayIfHourDoesNotExist = skipDay;
return this;
}
private static void ValidateInterval(int interval)
{
if (interval <= 0)
{
throw new ArgumentException("Interval must be a positive value.");
}
}
internal CalendarIntervalScheduleBuilder WithMisfireHandlingInstruction(int readMisfireInstructionFromString)
{
misfireInstruction = readMisfireInstructionFromString;
return this;
}
}
/// <summary>
/// Extension methods that attach <see cref="CalendarIntervalScheduleBuilder" /> to <see cref="TriggerBuilder" />.
/// </summary>
public static class CalendarIntervalTriggerBuilderExtensions
{
public static TriggerBuilder WithCalendarIntervalSchedule(this TriggerBuilder triggerBuilder)
{
CalendarIntervalScheduleBuilder builder = CalendarIntervalScheduleBuilder.Create();
return triggerBuilder.WithSchedule(builder);
}
public static TriggerBuilder WithCalendarIntervalSchedule(this TriggerBuilder triggerBuilder, Action<CalendarIntervalScheduleBuilder> action)
{
CalendarIntervalScheduleBuilder builder = CalendarIntervalScheduleBuilder.Create();
action(builder);
return triggerBuilder.WithSchedule(builder);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmGlobalFilter : System.Windows.Forms.Form
{
int gID;
string gFilter;
string gFilterSQL;
short gSection;
ADODB.Recordset gRS;
int gSect;
int g_UpdateID;
string g_SectString;
//Update Sequence...
bool gAll;
bool gLoad;
bool c_Scale;
bool c_Barcode;
bool c_cmbUpPrint;
bool c_PosOveride;
bool c_NonWeighted;
bool c_chkDisabled;
bool c_chkDisconti;
bool c_cmbUpPricing;
bool c_cmbSupplier;
bool c_AllowFraction;
bool c_SerialTracing;
bool c_ReportGroups;
bool c_UndoPosOveride;
List<RadioButton> OprBarcode = new List<RadioButton>();
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2431;
//Global Update|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2432;
//Global Cost|Checked
if (modRecordSet.rsLang.RecordCount){Command1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Command1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){Frame1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Frame1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblHeading = No Code [Using the "Stock Item Selector".....]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblHeading.Caption = rsLang("LanguageLayoutLnk_Description"): lblHeading.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){Command3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Command3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2499;
//Field(s) to Update|Checked
if (modRecordSet.rsLang.RecordCount){Frame2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Frame2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1032;
//This is a scale product|Checked
if (modRecordSet.rsLang.RecordCount){chkScale.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkScale.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1033;
//This is a scale item non-weight|Checked
if (modRecordSet.rsLang.RecordCount){chkNonWeigted.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkNonWeigted.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1034;
//Allow fractions|Checked
if (modRecordSet.rsLang.RecordCount){chkAllowFractions.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkAllowFractions.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2453;
//POS Price Override (SQ)|Checked
if (modRecordSet.rsLang.RecordCount){chkPosOveride.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkPosOveride.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1037;
//Serial Tracking|Checked
if (modRecordSet.rsLang.RecordCount){chkSerialTracking.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkSerialTracking.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//NOTE: BD Entry 2455 needs a "&&" for correct display!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2455;
//Shelf & Barcode Printing|
if (modRecordSet.rsLang.RecordCount){Label4.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label4.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2456;
//Shelf|Checked
if (modRecordSet.rsLang.RecordCount){OprBarcode[0].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;OprBarcode[0].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1838;
//Barcode|Checked
if (modRecordSet.rsLang.RecordCount){OprBarcode[1].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;OprBarcode[1].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2458;
//None|Checked
if (modRecordSet.rsLang.RecordCount){OprBarcode[2].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;OprBarcode[2].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2459;
//New Supplier|Checked
if (modRecordSet.rsLang.RecordCount){Label6.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label6.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2460;
//New Pricing group|Checked
if (modRecordSet.rsLang.RecordCount){Label5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2461;
//New Printing Location|Checked
if (modRecordSet.rsLang.RecordCount){Label3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//Label1 = No Code [Report Groups]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2463;
//Disabled|Checked
if (modRecordSet.rsLang.RecordCount){chkDisable.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkDisable.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2464;
//Update|Checked
if (modRecordSet.rsLang.RecordCount){cmdUpdate.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdUpdate.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2465;
//Discontinued|Checked
if (modRecordSet.rsLang.RecordCount){chkDiscontinued.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkDiscontinued.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2466;
//Undo changes|Checked
if (modRecordSet.rsLang.RecordCount){Frame3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Frame3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2467;
//Undo POS Price Overide|Checked
if (modRecordSet.rsLang.RecordCount){chkUndoPosOveride.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkUndoPosOveride.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2468;
//Undo Update|Checked
if (modRecordSet.rsLang.RecordCount){cmdUndo.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdUndo.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmGlobalFilter.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void chkAllowFractions_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkAllowFractions.CheckState == 1)
c_AllowFraction = true;
}
private void chkNonWeigted_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkNonWeigted.CheckState == 1)
c_NonWeighted = true;
}
private void chkPosOveride_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkPosOveride.CheckState == 1)
c_PosOveride = true;
}
private void chkUndoPosOveride_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkUndoPosOveride.CheckState == 1)
c_UndoPosOveride = true;
}
private void chkScale_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkScale.CheckState == 1)
c_Scale = true;
}
private void chkSerialTracking_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (chkSerialTracking.CheckState == 1)
c_SerialTracing = true;
}
private void cmbReportGroups_Change(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(cmbReportGroups.BoundText))
c_ReportGroups = true;
}
private void cmbUpPricing_Change(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(cmbUpPricing.BoundText))
c_cmbUpPricing = true;
}
private void cmbUpPrinting_Change(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(cmbUpPrinting.Text))
c_cmbUpPrint = true;
}
private void cmdUndo_Click(System.Object eventSender, System.EventArgs eventArgs)
{
if (c_UndoPosOveride == true) {
modRecordSet.cnnDB.Execute("Delete StockitemOverwrite.* From StockitemOverwrite ");
} else {
Interaction.MsgBox("Check the Undo POS Price Overide ", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Global Update");
return;
}
Interaction.MsgBox("Update Completed Succesfully", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Global Update");
}
private void cmdUpdate_Click(System.Object eventSender, System.EventArgs eventArgs)
{
string stString = null;
ADODB.Recordset rj = default(ADODB.Recordset);
if (c_Scale == true)
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_VariablePrice = " + this.chkScale.CheckState + ";");
if (c_NonWeighted == true)
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_NonWeighted = " + this.chkNonWeigted.CheckState + ";");
if (c_AllowFraction == true)
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_Fractions = " + this.chkAllowFractions.CheckState + ";");
if (c_SerialTracing == true)
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SerialTracker = " + this.chkSerialTracking.CheckState + ";");
if (c_ReportGroups == true)
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_ReportID = " + Conversion.Val(this.cmbReportGroups.BoundText) + ";");
if (c_cmbUpPrint == true) {
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_PrintLocationID = " + this.cmbUpPrinting.BoundText + ";");
cmbUpPrinting.BoundText = "";
}
if (c_cmbUpPricing == true) {
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_PricingGroupID = " + Conversion.Val(this.cmbUpPricing.BoundText) + ";");
cmbUpPricing.BoundText = "";
}
if (c_cmbSupplier == true) {
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SupplierID = " + this.cmpUpSupplier.BoundText + ";");
this.cmpUpSupplier.BoundText = "";
}
if (c_Barcode == true) {
if (OprBarcode[0].Checked == true) {
stString = "Shelf";
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SShelf = True;");
//cnnDB.Execute "UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SBarcode = 'Shelf';"
} else if (OprBarcode[1].Checked == true) {
stString = "Barcode";
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SBarcode = True;");
//cnnDB.Execute "UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SBarcode = 'Barcode';"
} else if (OprBarcode[2].Checked == true) {
stString = "";
modRecordSet.cnnDB.Execute("UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem.StockItem_SShelf=False, StockItem.StockItem_SBarcode=False ;");
//cnnDB.Execute "UPDATE StockItem INNER JOIN gGlobalUpdate ON StockItem.StockItemID = gGlobalUpdate.gStockItemID SET StockItem_SBarcode = Null;"
}
}
if (c_PosOveride == true) {
rj = modRecordSet.getRS(ref "SELECT * FROM gGlobalUpdate;");
if (rj.RecordCount) {
rj.MoveFirst();
while (rj.EOF == false) {
modRecordSet.cnnDB.Execute("Delete StockitemOverwrite.* From StockitemOverwrite WHERE (((StockitemOverwrite.StockitemOverwriteID)=" + rj.Fields("gStockItemID").Value + "));");
modRecordSet.cnnDB.Execute("INSERT INTO StockitemOverwrite ( StockitemOverwriteID ) SELECT " + rj.Fields("gStockItemID").Value + ";");
rj.MoveNext();
}
}
}
c_Scale = false;
c_Barcode = false;
c_cmbUpPrint = false;
c_PosOveride = false;
c_UndoPosOveride = false;
//As Boolean
c_chkDisabled = false;
c_chkDisconti = false;
c_NonWeighted = false;
c_cmbUpPricing = false;
c_AllowFraction = false;
c_SerialTracing = false;
c_ReportGroups = false;
Interaction.MsgBox("Update Completed Succesfully", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Global Update");
Frame2.Enabled = false;
}
private void cmpUpSupplier_Change(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(this.cmpUpSupplier.BoundText)) {
c_cmbSupplier = true;
}
}
private void Command1_Click(System.Object eventSender, System.EventArgs eventArgs)
{
My.MyProject.Forms.frmGlobalCost.ShowDialog();
}
private void Command2_Click(System.Object eventSender, System.EventArgs eventArgs)
{
modRecordSet.cnnDB.Execute("DELETE * FROM gGlobalUpdate;");
this.Close();
}
private void Command3_Click(System.Object eventSender, System.EventArgs eventArgs)
{
modBResolutions.g_Updatep = true;
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
gLoad = true;
getNamespace();
}
private void Command4_Click()
{
}
private void frmGlobalFilter_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
this.Close();
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void buildDataControls()
{
//4 Updating purposes...
doDataControl(ref (this.cmbUpPricing), ref "SELECT PricingGroupID, PricingGroup_Name FROM PricingGroup ORDER BY PricingGroup_Name", ref "StockItem_PricingGroupID", ref "PricingGroupID", ref "PricingGroup_Name");
doDataControl(ref (this.cmpUpSupplier), ref "SELECT SupplierID, Supplier_Name FROM Supplier WHERE Supplier_Disabled=False ORDER BY Supplier_Name", ref "StockItem_SupplierID", ref "SupplierID", ref "Supplier_Name");
doDataControl(ref (this.cmbUpPrinting), ref "SELECT PrintLocation.* From PrintLocation WHERE (((PrintLocation.PrintLocation_Disabled)=False));", ref "StockItem_PrintLocationID", ref "PrintLocationID", ref "PrintLocation_Name");
//New Report ID
doDataControl(ref (this.cmbReportGroups), ref "SELECT ReportGroup.* From ReportGroup WHERE (((ReportGroup.ReportGroup_Disabled)=False));", ref "StockItem_ReportID", ref "ReportID", ref "ReportGroup_Name");
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
ADODB.Recordset rs = default(ADODB.Recordset);
rs = modRecordSet.getRS(ref sql);
dataControl.DataSource = rs;
dataControl.boundColumn = boundColumn;
dataControl.listField = listField;
}
//Handles OprBarcode.CheckedChanged
private void OprBarcode_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs)
{
if (eventSender.Checked) {
RadioButton rb = new RadioButton();
rb = (RadioButton)eventSender;
int Index = GetIndex.GetIndexer(ref rb, ref OprBarcode);
c_Barcode = true;
}
}
private void doSearch()
{
ADODB.Recordset rj = default(ADODB.Recordset);
string sql = null;
string lString = null;
lString = gFilterSQL;
if (gAll) {
} else {
if (string.IsNullOrEmpty(lString)) {
lString = " WHERE StockItem.StockItem_Disabled = 0 Or StockItem.StockItem_Discontinued = 0 ";
} else {
lString = lString + " AND (StockItem.StockItem_Disabled = 0 Or StockItem.StockItem_Discontinued = 0) ";
}
}
g_SectString = lString;
gRS = modRecordSet.getRS(ref "SELECT DISTINCT StockItemID, StockItem_Name FROM StockItem " + lString + " ORDER BY StockItem_Name");
if (gRS.RecordCount > 0 & gLoad == true) {
My.MyProject.Forms.frmStockItemByGroup.loadItem(ref "SELECT DISTINCT StockItemID, StockItem_Name FROM StockItem " + lString + " ORDER BY StockItem_Name");
Frame2.Enabled = true;
}
}
private void getNamespace()
{
if (string.IsNullOrEmpty(gFilter)) {
this.lblHeading.Text = "";
} else {
My.MyProject.Forms.frmFilter.buildCriteria(ref gFilter);
this.lblHeading.Text = My.MyProject.Forms.frmFilter.gHeading;
}
gFilterSQL = My.MyProject.Forms.frmFilter.gCriteria;
doSearch();
}
public void editItem(ref short lSection)
{
modRecordSet.cnnDB.Execute("DELETE ftData.* From ftData");
modRecordSet.cnnDB.Execute("DELETE ftDataItem.* From ftDataItem");
buildDataControls();
gSection = lSection;
gFilter = "StockItem";
gLoad = false;
getNamespace();
loadLanguage();
ShowDialog();
}
private void frmGlobalFilter_Load(object sender, System.EventArgs e)
{
OprBarcode.AddRange(new RadioButton[] {
_OprBarcode_0,
_OprBarcode_1,
_OprBarcode_2
});
RadioButton rb = new RadioButton();
foreach (RadioButton rb_loopVariable in OprBarcode) {
rb = rb_loopVariable;
rb.CheckedChanged += OprBarcode_CheckedChanged;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using NUnit.Compatibility;
using NUnit.Framework.Api;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.ActionAttributeTests;
namespace NUnit.Framework.Tests
{
[TestFixture, NonParallelizable]
public class ActionAttributeTests
{
// NOTE: An earlier version of this fixture attempted to test
// the exact order of all actions. However, the order of execution
// of the individual tests cannot be predicted reliably across
// different runtimes, so we now look only at the relative position
// of before and after actions with respect to the test.
private static readonly string ASSEMBLY_PATH = AssemblyHelper.GetAssemblyPath(typeof(ActionAttributeFixture).GetTypeInfo().Assembly);
private static readonly string ASSEMBLY_NAME = System.IO.Path.GetFileName(ASSEMBLY_PATH);
private ITestResult _result = null;
private int _numEvents = -1;
[OneTimeSetUp]
public void Setup()
{
var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
ActionAttributeFixture.ClearResults();
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { "NUnit.TestData.ActionAttributeTests" };
// No need for the overhead of parallel execution here
options["NumberOfTestWorkers"] = 0;
Assert.NotNull(runner.Load(ASSEMBLY_PATH, options), "Assembly not loaded");
Assert.That(runner.LoadedTest.RunState, Is.EqualTo(RunState.Runnable));
_result = runner.Run(TestListener.NULL, TestFilter.Empty);
_numEvents = ActionAttributeFixture.Events.Count;
}
[Test]
public void TestsRunSuccessfully()
{
Assert.That(_result.ResultState, Is.EqualTo(ResultState.Success));
//foreach(string message in ActionAttributeFixture.Events)
// Console.WriteLine(message);
}
[Test]
public void ExpectedOutput_InCorrectOrder()
{
var notFound = new List<string>();
var notExpected = new List<string>();
foreach (var item in ExpectedEvents)
if (!ActionAttributeFixture.Events.Contains(item))
notFound.Add(item);
foreach (var item in ActionAttributeFixture.Events)
if (!ExpectedEvents.Contains(item))
notExpected.Add(item);
if (notFound.Count > 0 || notExpected.Count > 0)
{
var sb = new StringBuilder("Expected and actual events do not match.");
if (notFound.Count > 0)
{
sb.Append(Environment.NewLine + " Missing:");
foreach (var item in notFound)
sb.Append(Environment.NewLine + " " + item);
}
if (notExpected.Count > 0)
{
sb.Append(Environment.NewLine + " Extra:");
foreach (var item in notExpected)
sb.Append(Environment.NewLine + " " + item);
}
Assert.Fail(sb.ToString());
}
}
[Test]
public void ActionsWrappingAssembly()
{
CheckActionsOnSuite(ASSEMBLY_NAME, 0, _numEvents - 1, ExpectedAssemblyActions);
}
[Test]
public void ActionsWrappingSetUpFixture()
{
int firstAction = NumAssemblyActions;
int lastAction = _numEvents - firstAction - 1;
CheckActionsOnSuite("ActionAttributeTests", firstAction, lastAction, ExpectedSetUpFixtureActions);
}
[Test]
public void ActionsWrappingTestFixture()
{
int firstAction = NumAssemblyActions + NumSetUpFixtureActions;
int lastAction = _numEvents - firstAction - 1;
CheckActionsOnSuite("ActionAttributeFixture", firstAction, lastAction, ExpectedTestFixtureActions);
}
[Test]
public void ActionsWrappingParameterizedMethodSuite()
{
int case1 = ActionAttributeFixture.Events.IndexOf("CaseOne");
int case2 = ActionAttributeFixture.Events.IndexOf("CaseTwo");
Assume.That(case1, Is.GreaterThanOrEqualTo(0));
Assume.That(case2, Is.GreaterThanOrEqualTo(0));
int firstAction = Math.Min(case1, case2) - NumTestCaseActions - NumParameterizedTestActions;
int lastAction = Math.Max(case1, case2) + NumTestCaseActions + NumParameterizedTestActions;
CheckActionsOnSuite("ParameterizedTest", firstAction, lastAction, "OnMethod", "OnMethod");
}
[Test]
public void CorrectNumberOfEventsReceived()
{
Assert.That(ActionAttributeFixture.Events.Count, Is.EqualTo(
NumTestCaseEvents + 2 * (NumParameterizedTestActions + NumTestFixtureActions + NumSetUpFixtureActions + NumAssemblyActions)));
}
[TestCase("CaseOne")]
[TestCase("CaseTwo")]
[TestCase("SimpleTest")]
public void ActionsWrappingTestMethod(string testName)
{
CheckActionsOnTestCase(testName);
}
#region Helper Methods
private void CheckActionsOnSuite(string suiteName, int firstEvent, int lastEvent, params string[] tags)
{
for (int i = 0; i < tags.Length; i++)
CheckBeforeAfterActionPair(firstEvent + i, lastEvent - i, suiteName, tags[i]);
if (firstEvent > 0)
{
var beforeEvent = ActionAttributeFixture.Events[firstEvent - 1];
Assert.That(beforeEvent, Does.Not.StartWith(suiteName), "Extra ActionAttribute Before: {0}", beforeEvent);
}
if (lastEvent < ActionAttributeFixture.Events.Count - 1)
{
var afterEvent = ActionAttributeFixture.Events[lastEvent + 1];
Assert.That(afterEvent, Does.Not.StartWith(suiteName), "Extra ActionAttribute After: {0}", afterEvent);
}
}
private void CheckActionsOnTestCase(string testName)
{
var index = ActionAttributeFixture.Events.IndexOf(testName);
Assert.That(index, Is.GreaterThanOrEqualTo(0), "{0} did not execute", testName);
var numActions = ExpectedTestCaseActions.Length;
for (int i = 0; i < numActions; i++)
CheckBeforeAfterActionPair(index - i - 1, index + i + 1, testName, ExpectedTestCaseActions[i]);
Assert.That(ActionAttributeFixture.Events[index - numActions - 1], Does.Not.StartWith(testName), "Extra ActionAttribute Before");
Assert.That(ActionAttributeFixture.Events[index + numActions + 1], Does.Not.StartWith(testName), "Extra ActionAttribute After");
}
private void CheckBeforeAfterActionPair(int index1, int index2, string testName, string tag)
{
var event1 = ActionAttributeFixture.Events[index1];
var event2 = ActionAttributeFixture.Events[index2];
Assert.That(event1, Does.StartWith(testName + "." + tag + ".Before"));
Assert.That(event2, Does.StartWith(testName + "." + tag + ".After"));
int index = event1.LastIndexOf('.');
var target1 = event1.Substring(index); // Target is last in string
Assert.That(event2, Does.EndWith(target1), "Event mismatch");
}
#endregion
#region Expected Attributes and Events
private static readonly string[] ExpectedAssemblyActions = new string[] {
"OnAssembly", "OnAssembly", "OnAssembly" };
private static readonly string[] ExpectedSetUpFixtureActions = new string[] {
"OnBaseSetupFixture", "OnBaseSetupFixture", "OnBaseSetupFixture",
"OnSetupFixture", "OnSetupFixture", "OnSetupFixture"
};
private static readonly string[] ExpectedTestFixtureActions = new string[] {
"OnBaseInterface", "OnBaseInterface", "OnBaseInterface",
"OnBaseFixture", "OnBaseFixture", "OnBaseFixture",
"OnInterface", "OnInterface", "OnInterface",
"OnFixture", "OnFixture", "OnFixture"
};
private static readonly string[] ExpectedParameterizedTestActions = new string[] {
"OnMethod", "OnMethod"
};
private static readonly string[] ExpectedTestCaseActions = new string[] {
"OnMethod", "OnMethod", "OnMethod",
"SetUpTearDown",
"OnFixture", "OnFixture",
"OnInterface", "OnInterface",
"OnBaseFixture", "OnBaseFixture",
"OnBaseInterface", "OnBaseInterface",
"OnSetupFixture", "OnSetupFixture",
"OnBaseSetupFixture", "OnBaseSetupFixture",
"OnAssembly", "OnAssembly"
};
// The exact order of events may vary, depending on the runtime framework
// in use. Consequently, we test heuristically. The following list is
// only one possible ordering of events.
private static readonly List<string> ExpectedEvents = new List<string>(new string[] {
ASSEMBLY_NAME + ".OnAssembly.Before.Test, Suite",
ASSEMBLY_NAME + ".OnAssembly.Before.Suite",
ASSEMBLY_NAME + ".OnAssembly.Before.Default",
"ActionAttributeTests.OnBaseSetupFixture.Before.Test, Suite",
"ActionAttributeTests.OnBaseSetupFixture.Before.Suite",
"ActionAttributeTests.OnBaseSetupFixture.Before.Default",
"ActionAttributeTests.OnSetupFixture.Before.Test, Suite",
"ActionAttributeTests.OnSetupFixture.Before.Suite",
"ActionAttributeTests.OnSetupFixture.Before.Default",
"ActionAttributeFixture.OnBaseInterface.Before.Test, Suite",
"ActionAttributeFixture.OnBaseInterface.Before.Suite",
"ActionAttributeFixture.OnBaseInterface.Before.Default",
"ActionAttributeFixture.OnBaseFixture.Before.Test, Suite",
"ActionAttributeFixture.OnBaseFixture.Before.Suite",
"ActionAttributeFixture.OnBaseFixture.Before.Default",
"ActionAttributeFixture.OnInterface.Before.Test, Suite",
"ActionAttributeFixture.OnInterface.Before.Suite",
"ActionAttributeFixture.OnInterface.Before.Default",
"ActionAttributeFixture.OnFixture.Before.Test, Suite",
"ActionAttributeFixture.OnFixture.Before.Suite",
"ActionAttributeFixture.OnFixture.Before.Default",
"ParameterizedTest.OnMethod.Before.Test, Suite",
"ParameterizedTest.OnMethod.Before.Suite",
"CaseOne.OnAssembly.Before.Test, Suite",
"CaseOne.OnAssembly.Before.Test",
"CaseOne.OnBaseSetupFixture.Before.Test, Suite",
"CaseOne.OnBaseSetupFixture.Before.Test",
"CaseOne.OnSetupFixture.Before.Test, Suite",
"CaseOne.OnSetupFixture.Before.Test",
"CaseOne.OnBaseInterface.Before.Test, Suite",
"CaseOne.OnBaseInterface.Before.Test",
"CaseOne.OnBaseFixture.Before.Test, Suite",
"CaseOne.OnBaseFixture.Before.Test",
"CaseOne.OnInterface.Before.Test, Suite",
"CaseOne.OnInterface.Before.Test",
"CaseOne.OnFixture.Before.Test, Suite",
"CaseOne.OnFixture.Before.Test",
"CaseOne.SetUpTearDown.Before.Test",
"CaseOne.OnMethod.Before.Test, Suite",
"CaseOne.OnMethod.Before.Test",
"CaseOne.OnMethod.Before.Default",
"CaseOne",
"CaseOne.OnMethod.After.Default",
"CaseOne.OnMethod.After.Test",
"CaseOne.OnMethod.After.Test, Suite",
"CaseOne.SetUpTearDown.After.Test",
"CaseOne.OnFixture.After.Test",
"CaseOne.OnFixture.After.Test, Suite",
"CaseOne.OnInterface.After.Test",
"CaseOne.OnInterface.After.Test, Suite",
"CaseOne.OnBaseFixture.After.Test",
"CaseOne.OnBaseFixture.After.Test, Suite",
"CaseOne.OnBaseInterface.After.Test",
"CaseOne.OnBaseInterface.After.Test, Suite",
"CaseOne.OnSetupFixture.After.Test",
"CaseOne.OnSetupFixture.After.Test, Suite",
"CaseOne.OnBaseSetupFixture.After.Test",
"CaseOne.OnBaseSetupFixture.After.Test, Suite",
"CaseOne.OnAssembly.After.Test",
"CaseOne.OnAssembly.After.Test, Suite",
"CaseTwo.OnAssembly.Before.Test, Suite",
"CaseTwo.OnAssembly.Before.Test",
"CaseTwo.OnBaseSetupFixture.Before.Test, Suite",
"CaseTwo.OnBaseSetupFixture.Before.Test",
"CaseTwo.OnSetupFixture.Before.Test, Suite",
"CaseTwo.OnSetupFixture.Before.Test",
"CaseTwo.OnBaseInterface.Before.Test, Suite",
"CaseTwo.OnBaseInterface.Before.Test",
"CaseTwo.OnBaseFixture.Before.Test",
"CaseTwo.OnBaseFixture.Before.Test, Suite",
"CaseTwo.OnInterface.Before.Test, Suite",
"CaseTwo.OnInterface.Before.Test",
"CaseTwo.OnFixture.Before.Test, Suite",
"CaseTwo.OnFixture.Before.Test",
"CaseTwo.SetUpTearDown.Before.Test",
"CaseTwo.OnMethod.Before.Test, Suite",
"CaseTwo.OnMethod.Before.Test",
"CaseTwo.OnMethod.Before.Default",
"CaseTwo",
"CaseTwo.OnMethod.After.Default",
"CaseTwo.OnMethod.After.Test",
"CaseTwo.OnMethod.After.Test, Suite",
"CaseTwo.SetUpTearDown.After.Test",
"CaseTwo.OnFixture.After.Test",
"CaseTwo.OnFixture.After.Test, Suite",
"CaseTwo.OnInterface.After.Test",
"CaseTwo.OnInterface.After.Test, Suite",
"CaseTwo.OnBaseFixture.After.Test",
"CaseTwo.OnBaseFixture.After.Test, Suite",
"CaseTwo.OnBaseInterface.After.Test",
"CaseTwo.OnBaseInterface.After.Test, Suite",
"CaseTwo.OnSetupFixture.After.Test",
"CaseTwo.OnSetupFixture.After.Test, Suite",
"CaseTwo.OnBaseSetupFixture.After.Test",
"CaseTwo.OnBaseSetupFixture.After.Test, Suite",
"CaseTwo.OnAssembly.After.Test",
"CaseTwo.OnAssembly.After.Test, Suite",
"ParameterizedTest.OnMethod.After.Suite",
"ParameterizedTest.OnMethod.After.Test, Suite",
"SimpleTest.OnAssembly.Before.Test, Suite",
"SimpleTest.OnAssembly.Before.Test",
"SimpleTest.OnBaseSetupFixture.Before.Test, Suite",
"SimpleTest.OnBaseSetupFixture.Before.Test",
"SimpleTest.OnSetupFixture.Before.Test, Suite",
"SimpleTest.OnSetupFixture.Before.Test",
"SimpleTest.OnBaseInterface.Before.Test, Suite",
"SimpleTest.OnBaseInterface.Before.Test",
"SimpleTest.OnBaseFixture.Before.Test, Suite",
"SimpleTest.OnBaseFixture.Before.Test",
"SimpleTest.OnInterface.Before.Test, Suite",
"SimpleTest.OnInterface.Before.Test",
"SimpleTest.OnFixture.Before.Test, Suite",
"SimpleTest.OnFixture.Before.Test",
"SimpleTest.SetUpTearDown.Before.Test",
"SimpleTest.OnMethod.Before.Test, Suite",
"SimpleTest.OnMethod.Before.Test",
"SimpleTest.OnMethod.Before.Default",
"SimpleTest",
"SimpleTest.OnMethod.After.Default",
"SimpleTest.OnMethod.After.Test",
"SimpleTest.OnMethod.After.Test, Suite",
"SimpleTest.SetUpTearDown.After.Test",
"SimpleTest.OnFixture.After.Test",
"SimpleTest.OnFixture.After.Test, Suite",
"SimpleTest.OnInterface.After.Test",
"SimpleTest.OnInterface.After.Test, Suite",
"SimpleTest.OnBaseFixture.After.Test",
"SimpleTest.OnBaseFixture.After.Test, Suite",
"SimpleTest.OnBaseInterface.After.Test",
"SimpleTest.OnBaseInterface.After.Test, Suite",
"SimpleTest.OnSetupFixture.After.Test",
"SimpleTest.OnSetupFixture.After.Test, Suite",
"SimpleTest.OnBaseSetupFixture.After.Test",
"SimpleTest.OnBaseSetupFixture.After.Test, Suite",
"SimpleTest.OnAssembly.After.Test",
"SimpleTest.OnAssembly.After.Test, Suite",
"ActionAttributeFixture.OnFixture.After.Default",
"ActionAttributeFixture.OnFixture.After.Suite",
"ActionAttributeFixture.OnFixture.After.Test, Suite",
"ActionAttributeFixture.OnInterface.After.Default",
"ActionAttributeFixture.OnInterface.After.Suite",
"ActionAttributeFixture.OnInterface.After.Test, Suite",
"ActionAttributeFixture.OnBaseFixture.After.Default",
"ActionAttributeFixture.OnBaseFixture.After.Suite",
"ActionAttributeFixture.OnBaseFixture.After.Test, Suite",
"ActionAttributeFixture.OnBaseInterface.After.Default",
"ActionAttributeFixture.OnBaseInterface.After.Suite",
"ActionAttributeFixture.OnBaseInterface.After.Test, Suite",
"ActionAttributeTests.OnSetupFixture.After.Default",
"ActionAttributeTests.OnSetupFixture.After.Suite",
"ActionAttributeTests.OnSetupFixture.After.Test, Suite",
"ActionAttributeTests.OnBaseSetupFixture.After.Default",
"ActionAttributeTests.OnBaseSetupFixture.After.Suite",
"ActionAttributeTests.OnBaseSetupFixture.After.Test, Suite",
ASSEMBLY_NAME + ".OnAssembly.After.Default",
ASSEMBLY_NAME + ".OnAssembly.After.Suite",
ASSEMBLY_NAME + ".OnAssembly.After.Test, Suite"
});
private static readonly int NumTestCaseActions = ExpectedTestCaseActions.Length;
private static readonly int EventsPerTestCase = 2 * NumTestCaseActions + 1;
private static readonly int NumTestCaseEvents = 3 * EventsPerTestCase;
private static readonly int NumParameterizedTestActions = ExpectedParameterizedTestActions.Length;
private static readonly int NumTestFixtureActions = ExpectedTestFixtureActions.Length;
private static readonly int NumSetUpFixtureActions = ExpectedSetUpFixtureActions.Length;
private static readonly int NumAssemblyActions = ExpectedAssemblyActions.Length;
#endregion
}
}
#endif
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
namespace Lucene.Net.Misc
{
[SuppressCodecs("Lucene3x")]
public class TestHighFreqTerms : LuceneTestCase
{
private static IndexWriter writer = null;
private static Directory dir = null;
private static IndexReader reader = null;
[OneTimeSetUp]
public override void BeforeClass() // LUCENENET specific - renamed from SetUpClass() to ensure calling order vs base class
{
base.BeforeClass();
dir = NewDirectory();
writer = new IndexWriter(dir, NewIndexWriterConfig(Random,
TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false))
.SetMaxBufferedDocs(2));
IndexDocs(writer);
reader = DirectoryReader.Open(dir);
TestUtil.CheckIndex(dir);
}
[OneTimeTearDown]
public override void AfterClass() // LUCENENET specific - renamed from TearDownClass() to ensure calling order vs base class
{
reader.Dispose();
dir.Dispose();
dir = null;
reader = null;
writer = null;
base.AfterClass();
}
/******************** Tests for getHighFreqTerms **********************************/
// test without specifying field (i.e. if we pass in field=null it should examine all fields)
// the term "diff" in the field "different_field" occurs 20 times and is the highest df term
[Test]
public void TestFirstTermHighestDocFreqAllFields()
{
int numTerms = 12;
string field = null;
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.DocFreqComparer());
assertEquals("Term with highest docfreq is first", 20, terms[0].DocFreq);
}
[Test]
public void TestFirstTermHighestDocFreq()
{
int numTerms = 12;
string field = "FIELD_1";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.DocFreqComparer());
assertEquals("Term with highest docfreq is first", 10, terms[0].DocFreq);
}
[Test]
public void TestOrderedByDocFreqDescending()
{
int numTerms = 12;
string field = "FIELD_1";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.DocFreqComparer());
for (int i = 0; i < terms.Length; i++)
{
if (i > 0)
{
assertTrue("out of order " + terms[i - 1].DocFreq + "should be >= " + terms[i].DocFreq, terms[i - 1].DocFreq >= terms[i].DocFreq);
}
}
}
[Test]
public void TestNumTerms()
{
int numTerms = 12;
string field = null;
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.DocFreqComparer());
assertEquals("length of terms array equals numTerms :" + numTerms, numTerms, terms.Length);
}
[Test]
public void TestGetHighFreqTerms()
{
int numTerms = 12;
string field = "FIELD_1";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.DocFreqComparer());
for (int i = 0; i < terms.Length; i++)
{
string termtext = terms[i].termtext.Utf8ToString();
// hardcoded highTF or highTFmedDF
if (termtext.Contains("highTF"))
{
if (termtext.Contains("medDF"))
{
assertEquals("doc freq is not as expected", 5, terms[i].DocFreq);
}
else
{
assertEquals("doc freq is not as expected", 1, terms[i].DocFreq);
}
}
else
{
int n = Convert.ToInt32(termtext);
assertEquals("doc freq is not as expected", GetExpecteddocFreq(n),
terms[i].DocFreq);
}
}
}
/********************Test sortByTotalTermFreq**********************************/
[Test]
public void TestFirstTermHighestTotalTermFreq()
{
int numTerms = 20;
string field = null;
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.TotalTermFreqComparer());
assertEquals("Term with highest totalTermFreq is first", 200, terms[0].TotalTermFreq);
}
[Test]
public void TestFirstTermHighestTotalTermFreqDifferentField()
{
int numTerms = 20;
string field = "different_field";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.TotalTermFreqComparer());
assertEquals("Term with highest totalTermFreq is first" + terms[0].GetTermText(), 150, terms[0].TotalTermFreq);
}
[Test]
public void TestOrderedByTermFreqDescending()
{
int numTerms = 12;
string field = "FIELD_1";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.TotalTermFreqComparer());
for (int i = 0; i < terms.Length; i++)
{
// check that they are sorted by descending termfreq
// order
if (i > 0)
{
assertTrue("out of order" + terms[i - 1] + " > " + terms[i], terms[i - 1].TotalTermFreq >= terms[i].TotalTermFreq);
}
}
}
[Test]
public void TestGetTermFreqOrdered()
{
int numTerms = 12;
string field = "FIELD_1";
TermStats[]
terms = HighFreqTerms.GetHighFreqTerms(reader, numTerms, field, new HighFreqTerms.TotalTermFreqComparer());
for (int i = 0; i < terms.Length; i++)
{
string text = terms[i].termtext.Utf8ToString();
if (text.Contains("highTF"))
{
if (text.Contains("medDF"))
{
assertEquals("total term freq is expected", 125,
terms[i].TotalTermFreq);
}
else
{
assertEquals("total term freq is expected", 200,
terms[i].TotalTermFreq);
}
}
else
{
int n = Convert.ToInt32(text);
assertEquals("doc freq is expected", GetExpecteddocFreq(n),
terms[i].DocFreq);
assertEquals("total term freq is expected", GetExpectedtotalTermFreq(n),
terms[i].TotalTermFreq);
}
}
}
/********************Testing Utils**********************************/
/// <summary>
/// LUCENENET NOTE: Made non-static because it depends on NewIndexField that is also non-static
/// </summary>
private void IndexDocs(IndexWriter writer)
{
Random rnd = Random;
/**
* Generate 10 documents where term n has a docFreq of n and a totalTermFreq of n*2 (squared).
*/
for (int i = 1; i <= 10; i++)
{
Document doc = new Document();
string content = GetContent(i);
doc.Add(NewTextField(rnd, "FIELD_1", content, Field.Store.YES));
//add a different field
doc.Add(NewTextField(rnd, "different_field", "diff", Field.Store.YES));
writer.AddDocument(doc);
}
//add 10 more docs with the term "diff" this will make it have the highest docFreq if we don't ask for the
//highest freq terms for a specific field.
for (int i = 1; i <= 10; i++)
{
Document doc = new Document();
doc.Add(NewTextField(rnd, "different_field", "diff", Field.Store.YES));
writer.AddDocument(doc);
}
// add some docs where tf < df so we can see if sorting works
// highTF low df
int highTF = 200;
Document doc2 = new Document();
string content2 = "";
for (int i = 0; i < highTF; i++)
{
content2 += "highTF ";
}
doc2.Add(NewTextField(rnd, "FIELD_1", content2, Field.Store.YES));
writer.AddDocument(doc2);
// highTF medium df =5
int medium_df = 5;
for (int i = 0; i < medium_df; i++)
{
int tf = 25;
Document newdoc = new Document();
string newcontent = "";
for (int j = 0; j < tf; j++)
{
newcontent += "highTFmedDF ";
}
newdoc.Add(NewTextField(rnd, "FIELD_1", newcontent, Field.Store.YES));
writer.AddDocument(newdoc);
}
// add a doc with high tf in field different_field
int targetTF = 150;
doc2 = new Document();
content2 = "";
for (int i = 0; i < targetTF; i++)
{
content2 += "TF150 ";
}
doc2.Add(NewTextField(rnd, "different_field", content2, Field.Store.YES));
writer.AddDocument(doc2);
writer.Dispose();
}
/**
* getContent
* return string containing numbers 1 to i with each number n occurring n times.
* i.e. for input of 3 return string "3 3 3 2 2 1"
*/
private static string GetContent(int i)
{
string s = "";
for (int j = 10; j >= i; j--)
{
for (int k = 0; k < j; k++)
{
// if j is 3 we return "3 3 3"
s += j.ToString() + " ";
}
}
return s;
}
private static int GetExpectedtotalTermFreq(int i)
{
return GetExpecteddocFreq(i) * i;
}
private static int GetExpecteddocFreq(int i)
{
return i;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//------------------------------------------------------------------------------
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
// To get up to date fundamental definition files for your hedgefund contact sales@quantconnect.com
using System;
using System.IO;
using Newtonsoft.Json;
namespace QuantConnect.Data.Fundamental
{
/// <summary>
/// Definition of the OperationRatios class
/// </summary>
public class OperationRatios : BaseData
{
/// <summary>
/// The growth in the company's revenue on a percentage basis. Morningstar calculates the growth percentage based on the
/// underlying revenue data reported in the Income Statement within the company filings or reports.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10001
/// </remarks>
[JsonProperty("10001")]
public RevenueGrowth RevenueGrowth { get; set; }
/// <summary>
/// The growth in the company's operating income on a percentage basis. Morningstar calculates the growth percentage based on the
/// underlying operating income data reported in the Income Statement within the company filings or reports.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10002
/// </remarks>
[JsonProperty("10002")]
public OperationIncomeGrowth OperationIncomeGrowth { get; set; }
/// <summary>
/// The growth in the company's net income on a percentage basis. Morningstar calculates the growth percentage based on the
/// underlying net income data reported in the Income Statement within the company filings or reports.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10003
/// </remarks>
[JsonProperty("10003")]
public NetIncomeGrowth NetIncomeGrowth { get; set; }
/// <summary>
/// The growth in the company's net income from continuing operati
/// </summary>
/// <remarks>
/// Morningstar DataId: 10004
/// </remarks>
[JsonProperty("10004")]
public NetIncomeContOpsGrowth NetIncomeContOpsGrowth { get; set; }
/// <summary>
/// The growth in the company's cash flow from operations on a percentage basis. Morningstar calculates the growth percentage
/// based on the underlying cash flow from operations data reported in the Cash Flow Statement within the company filings or reports.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10005
/// </remarks>
[JsonProperty("10005")]
public CFOGrowth CFOGrowth { get; set; }
/// <summary>
/// The growth in the company's free cash flow on a percentage basis. Morningstar calculates the growth percentage based on the
/// underlying cash flow from operations and capital expenditures data reported in the Cash Flow Statement within the company filings
/// or reports: Free Cash Flow = Cash flow from operations - Capital Expenditures.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10006
/// </remarks>
[JsonProperty("10006")]
public FCFGrowth FCFGrowth { get; set; }
/// <summary>
/// The growth in the company's operating revenue on a percentage basis. Morningstar calculates the growth percentage based on
/// the underlying operating revenue data reported in the Income Statement within the company filings or reports.
/// </summary>
/// <remarks>
/// Morningstar DataId: 10007
/// </remarks>
[JsonProperty("10007")]
public OperationRevenueGrowth3MonthAvg OperationRevenueGrowth3MonthAvg { get; set; }
/// <summary>
/// Refers to the ratio of gross profit to revenue. Morningstar calculates the ratio by using the underlying data reported in the company
/// filings or reports: (Revenue - Cost of Goods Sold) / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11001
/// </remarks>
[JsonProperty("11001")]
public GrossMargin GrossMargin { get; set; }
/// <summary>
/// Refers to the ratio of operating income to revenue. Morningstar calculates the ratio by using the underlying data reported in the
/// company filings or reports: Operating Income / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11002
/// </remarks>
[JsonProperty("11002")]
public OperationMargin OperationMargin { get; set; }
/// <summary>
/// Refers to the ratio of pretax income to revenue. Morningstar calculates the ratio by using the underlying data reported in the
/// company filings or reports: Pretax Income / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11003
/// </remarks>
[JsonProperty("11003")]
public PretaxMargin PretaxMargin { get; set; }
/// <summary>
/// Refers to the ratio of net income to revenue. Morningstar calculates the ratio by using the underlying data reported in the company
/// filings or reports: Net Income / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11004
/// </remarks>
[JsonProperty("11004")]
public NetMargin NetMargin { get; set; }
/// <summary>
/// Refers to the ratio of tax provision to pretax income. Morningstar calculates the ratio by using the underlying data reported in the
/// company filings or reports: Tax Provision / Pretax Income.
/// [Note: Valid only when positive pretax income, and positive tax expense (not tax benefit)]
/// </summary>
/// <remarks>
/// Morningstar DataId: 11005
/// </remarks>
[JsonProperty("11005")]
public TaxRate TaxRate { get; set; }
/// <summary>
/// Refers to the ratio of earnings before interest and taxes to revenue. Morningstar calculates the ratio by using the underlying data
/// reported in the company filings or reports: EBIT / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11006
/// </remarks>
[JsonProperty("11006")]
public EBITMargin EBITMargin { get; set; }
/// <summary>
/// Refers to the ratio of earnings before interest, taxes and depreciation and amortization to revenue. Morningstar calculates the ratio
/// by using the underlying data reported in the company filings or reports: EBITDA / Revenue.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11007
/// </remarks>
[JsonProperty("11007")]
public EBITDAMargin EBITDAMargin { get; set; }
/// <summary>
/// Refers to the ratio of Revenue to Employees. Morningstar calculates the ratio by using the underlying data reported in the company
/// filings or reports: Revenue / Employee Number.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11008
/// </remarks>
[JsonProperty("11008")]
public SalesPerEmployee SalesPerEmployee { get; set; }
/// <summary>
/// Refers to the ratio of Current Assets to Current Liabilities. Morningstar calculates the ratio by using the underlying data reported in
/// the Balance Sheet within the company filings or reports: Current Assets / Current Liabilities.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11009
/// </remarks>
[JsonProperty("11009")]
public CurrentRatio CurrentRatio { get; set; }
/// <summary>
/// Refers to the ratio of liquid assets to Current Liabilities. Morningstar calculates the ratio by using the underlying data reported in the
/// Balance Sheet within the company filings or reports: ( Cash, Cash Equivalents, and ShortTerm Investments + Receivables ) /
/// Current Liabilities.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11010
/// </remarks>
[JsonProperty("11010")]
public QuickRatio QuickRatio { get; set; }
/// <summary>
/// Refers to the ratio of Long Term Debt to Total Capital. Morningstar calculates the ratio by using the underlying data reported in the
/// Balance Sheet within the company filings or reports: Long-Term Debt And Capital Lease Obligation / (Long-Term Debt And Capital
/// Lease Obligation + Total Shareholder's Equity)
/// </summary>
/// <remarks>
/// Morningstar DataId: 11011
/// </remarks>
[JsonProperty("11011")]
public LongTermDebtTotalCapitalRatio LongTermDebtTotalCapitalRatio { get; set; }
/// <summary>
/// Refers to the ratio of EBIT to Interest Expense. Morningstar calculates the ratio by using the underlying data reported in the Income
/// Statement within the company filings or reports: EBIT / Interest Expense.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11012
/// </remarks>
[JsonProperty("11012")]
public InterestCoverage InterestCoverage { get; set; }
/// <summary>
/// Refers to the ratio of Long Term Debt to Common Equity. Morningstar calculates the ratio by using the underlying data reported in
/// the Balance Sheet within the company filings or reports: Long-Term Debt And Capital Lease Obligation / Common Equity.
/// [Note: Common Equity = Total Shareholder's Equity - Preferred Stock]
/// </summary>
/// <remarks>
/// Morningstar DataId: 11013
/// </remarks>
[JsonProperty("11013")]
public LongTermDebtEquityRatio LongTermDebtEquityRatio { get; set; }
/// <summary>
/// Refers to the ratio of Total Assets to Common Equity. Morningstar calculates the ratio by using the underlying data reported in the
/// Balance Sheet within the company filings or reports: Total Assets / Common Equity. [Note: Common Equity = Total
/// Shareholder's Equity - Preferred Stock]
/// </summary>
/// <remarks>
/// Morningstar DataId: 11014
/// </remarks>
[JsonProperty("11014")]
public FinancialLeverage FinancialLeverage { get; set; }
/// <summary>
/// Refers to the ratio of Current Debt and Long Term Debt to Common Equity. Morningstar calculates the ratio by using the underlying
/// data reported in the Balance Sheet within the company filings or reports: (Current Debt And Current Capital Lease Obligation +
/// Long-Term Debt And Long-Term Capital Lease Obligation / Common Equity. [Note: Common Equity = Total Shareholder's Equity -
/// Preferred Stock]
/// </summary>
/// <remarks>
/// Morningstar DataId: 11015
/// </remarks>
[JsonProperty("11015")]
public TotalDebtEquityRatio TotalDebtEquityRatio { get; set; }
/// <summary>
/// Normalized Income / Total Revenue. A measure of profitability of the company calculated by finding Normalized Net Profit as a
/// percentage of Total Revenues.
/// </summary>
/// <remarks>
/// Morningstar DataId: 11016
/// </remarks>
[JsonProperty("11016")]
public NormalizedNetProfitMargin NormalizedNetProfitMargin { get; set; }
/// <summary>
/// 365 / Receivable Turnover
/// </summary>
/// <remarks>
/// Morningstar DataId: 12001
/// </remarks>
[JsonProperty("12001")]
public DaysInSales DaysInSales { get; set; }
/// <summary>
/// 365 / Inventory turnover
/// </summary>
/// <remarks>
/// Morningstar DataId: 12002
/// </remarks>
[JsonProperty("12002")]
public DaysInInventory DaysInInventory { get; set; }
/// <summary>
/// 365 / Payable turnover
/// </summary>
/// <remarks>
/// Morningstar DataId: 12003
/// </remarks>
[JsonProperty("12003")]
public DaysInPayment DaysInPayment { get; set; }
/// <summary>
/// Days In Inventory + Days In Sales - Days In Payment
/// </summary>
/// <remarks>
/// Morningstar DataId: 12004
/// </remarks>
[JsonProperty("12004")]
public CashConversionCycle CashConversionCycle { get; set; }
/// <summary>
/// Revenue / Average Accounts Receivables
/// </summary>
/// <remarks>
/// Morningstar DataId: 12005
/// </remarks>
[JsonProperty("12005")]
public ReceivableTurnover ReceivableTurnover { get; set; }
/// <summary>
/// Cost Of Goods Sold / Average Inventory
/// </summary>
/// <remarks>
/// Morningstar DataId: 12006
/// </remarks>
[JsonProperty("12006")]
public InventoryTurnover InventoryTurnover { get; set; }
/// <summary>
/// Cost of Goods Sold / Average Accounts Payables
/// </summary>
/// <remarks>
/// Morningstar DataId: 12007
/// </remarks>
[JsonProperty("12007")]
public PaymentTurnover PaymentTurnover { get; set; }
/// <summary>
/// Revenue / Average PP&E
/// </summary>
/// <remarks>
/// Morningstar DataId: 12008
/// </remarks>
[JsonProperty("12008")]
public FixAssetsTuronver FixAssetsTuronver { get; set; }
/// <summary>
/// Revenue / Average Total Assets
/// </summary>
/// <remarks>
/// Morningstar DataId: 12009
/// </remarks>
[JsonProperty("12009")]
public AssetsTurnover AssetsTurnover { get; set; }
/// <summary>
/// Net Income / Average Total Common Equity
/// </summary>
/// <remarks>
/// Morningstar DataId: 12010
/// </remarks>
[JsonProperty("12010")]
public ROE ROE { get; set; }
/// <summary>
/// Net Income / Average Total Assets
/// </summary>
/// <remarks>
/// Morningstar DataId: 12011
/// </remarks>
[JsonProperty("12011")]
public ROA ROA { get; set; }
/// <summary>
/// Net Income / (Total Equity + Long-term Debt and Capital Lease Obligation + Short-term Debt and Capital Lease Obligation)
/// </summary>
/// <remarks>
/// Morningstar DataId: 12012
/// </remarks>
[JsonProperty("12012")]
public ROIC ROIC { get; set; }
/// <summary>
/// Free Cash flow / Revenue
/// </summary>
/// <remarks>
/// Morningstar DataId: 12013
/// </remarks>
[JsonProperty("12013")]
public FCFSalesRatio FCFSalesRatio { get; set; }
/// <summary>
/// Free Cash Flow / Net Income
/// </summary>
/// <remarks>
/// Morningstar DataId: 12014
/// </remarks>
[JsonProperty("12014")]
public FCFNetIncomeRatio FCFNetIncomeRatio { get; set; }
/// <summary>
/// Capital Expenditure / Revenue
/// </summary>
/// <remarks>
/// Morningstar DataId: 12015
/// </remarks>
[JsonProperty("12015")]
public CapExSalesRatio CapExSalesRatio { get; set; }
/// <summary>
/// This is a leverage ratio used to determine how much debt (a sum of long term and current portion of debt) a company has on its
/// balance sheet relative to total assets. This ratio examines the percent of the company that is financed by debt.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12016
/// </remarks>
[JsonProperty("12016")]
public DebttoAssets DebttoAssets { get; set; }
/// <summary>
/// This is a financial ratio of common stock equity to total assets that indicates the relative proportion of equity used to finance a
/// company's assets.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12017
/// </remarks>
[JsonProperty("12017")]
public CommonEquityToAssets CommonEquityToAssets { get; set; }
/// <summary>
/// This is the compound annual growth rate of the company's capital spending over the last 5 years. Capital Spending is the sum of
/// the Capital Expenditure items found in the Statement of Cash Flows.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12018
/// </remarks>
[JsonProperty("12018")]
public CapitalExpenditureAnnual5YrGrowth CapitalExpenditureAnnual5YrGrowth { get; set; }
/// <summary>
/// This is the compound annual growth rate of the company's Gross Profit over the last 5 years.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12019
/// </remarks>
[JsonProperty("12019")]
public GrossProfitAnnual5YrGrowth GrossProfitAnnual5YrGrowth { get; set; }
/// <summary>
/// This is the simple average of the company's Annual Gross Margin over the last 5 years. Gross Margin is Total Revenue minus Cost
/// of Goods Sold divided by Total Revenue and is expressed as a percentage.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12020
/// </remarks>
[JsonProperty("12020")]
public GrossMargin5YrAvg GrossMargin5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's Annual Post Tax Margin over the last 5 years. Post tax margin is Post tax divided by
/// total revenue for the same period.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12021
/// </remarks>
[JsonProperty("12021")]
public PostTaxMargin5YrAvg PostTaxMargin5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's Annual Pre Tax Margin over the last 5 years. Pre tax margin is Pre tax divided by total
/// revenue for the same period.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12022
/// </remarks>
[JsonProperty("12022")]
public PreTaxMargin5YrAvg PreTaxMargin5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's Annual Net Profit Margin over the last 5 years. Net profit margin is post tax income
/// divided by total revenue for the same period.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12023
/// </remarks>
[JsonProperty("12023")]
public ProfitMargin5YrAvg ProfitMargin5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's ROE over the last 5 years. Return on equity reveals how much profit a company has
/// earned in comparison to the total amount of shareholder equity found on the balance sheet.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12024
/// </remarks>
[JsonProperty("12024")]
public ROE5YrAvg ROE5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's ROA over the last 5 years. Return on asset is calculated by dividing a company's annual
/// earnings by its average total assets.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12025
/// </remarks>
[JsonProperty("12025")]
public ROA5YrAvg ROA5YrAvg { get; set; }
/// <summary>
/// This is the simple average of the company's ROIC over the last 5 years. Return on invested capital is calculated by taking net
/// operating profit after taxes and dividends and dividing by the total amount of capital invested and expressing the result as a
/// percentage.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12026
/// </remarks>
[JsonProperty("12026")]
public AVG5YrsROIC AVG5YrsROIC { get; set; }
/// <summary>
/// [Normalized Income + (Interest Expense * (1-Tax Rate))] / Invested Capital
/// </summary>
/// <remarks>
/// Morningstar DataId: 12027
/// </remarks>
[JsonProperty("12027")]
public NormalizedROIC NormalizedROIC { get; set; }
/// <summary>
/// The five-year growth rate of operating revenue, calculated using regression analysis.
/// </summary>
/// <remarks>
/// Morningstar DataId: 12028
/// </remarks>
[JsonProperty("12028")]
public RegressionGrowthOperatingRevenue5Years RegressionGrowthOperatingRevenue5Years { get; set; }
/// <summary>
/// Creates an instance of the OperationRatios class
/// </summary>
public OperationRatios()
{
RevenueGrowth = new RevenueGrowth();
OperationIncomeGrowth = new OperationIncomeGrowth();
NetIncomeGrowth = new NetIncomeGrowth();
NetIncomeContOpsGrowth = new NetIncomeContOpsGrowth();
CFOGrowth = new CFOGrowth();
FCFGrowth = new FCFGrowth();
OperationRevenueGrowth3MonthAvg = new OperationRevenueGrowth3MonthAvg();
GrossMargin = new GrossMargin();
OperationMargin = new OperationMargin();
PretaxMargin = new PretaxMargin();
NetMargin = new NetMargin();
TaxRate = new TaxRate();
EBITMargin = new EBITMargin();
EBITDAMargin = new EBITDAMargin();
SalesPerEmployee = new SalesPerEmployee();
CurrentRatio = new CurrentRatio();
QuickRatio = new QuickRatio();
LongTermDebtTotalCapitalRatio = new LongTermDebtTotalCapitalRatio();
InterestCoverage = new InterestCoverage();
LongTermDebtEquityRatio = new LongTermDebtEquityRatio();
FinancialLeverage = new FinancialLeverage();
TotalDebtEquityRatio = new TotalDebtEquityRatio();
NormalizedNetProfitMargin = new NormalizedNetProfitMargin();
DaysInSales = new DaysInSales();
DaysInInventory = new DaysInInventory();
DaysInPayment = new DaysInPayment();
CashConversionCycle = new CashConversionCycle();
ReceivableTurnover = new ReceivableTurnover();
InventoryTurnover = new InventoryTurnover();
PaymentTurnover = new PaymentTurnover();
FixAssetsTuronver = new FixAssetsTuronver();
AssetsTurnover = new AssetsTurnover();
ROE = new ROE();
ROA = new ROA();
ROIC = new ROIC();
FCFSalesRatio = new FCFSalesRatio();
FCFNetIncomeRatio = new FCFNetIncomeRatio();
CapExSalesRatio = new CapExSalesRatio();
DebttoAssets = new DebttoAssets();
CommonEquityToAssets = new CommonEquityToAssets();
CapitalExpenditureAnnual5YrGrowth = new CapitalExpenditureAnnual5YrGrowth();
GrossProfitAnnual5YrGrowth = new GrossProfitAnnual5YrGrowth();
GrossMargin5YrAvg = new GrossMargin5YrAvg();
PostTaxMargin5YrAvg = new PostTaxMargin5YrAvg();
PreTaxMargin5YrAvg = new PreTaxMargin5YrAvg();
ProfitMargin5YrAvg = new ProfitMargin5YrAvg();
ROE5YrAvg = new ROE5YrAvg();
ROA5YrAvg = new ROA5YrAvg();
AVG5YrsROIC = new AVG5YrsROIC();
NormalizedROIC = new NormalizedROIC();
RegressionGrowthOperatingRevenue5Years = new RegressionGrowthOperatingRevenue5Years();
}
/// <summary>
/// Sets values for non existing periods from a previous instance
/// </summary>
/// <remarks>Used to fill-forward values from previous dates</remarks>
/// <param name="previous">The previous instance</param>
public void UpdateValues(OperationRatios previous)
{
RevenueGrowth.UpdateValues(previous.RevenueGrowth);
OperationIncomeGrowth.UpdateValues(previous.OperationIncomeGrowth);
NetIncomeGrowth.UpdateValues(previous.NetIncomeGrowth);
NetIncomeContOpsGrowth.UpdateValues(previous.NetIncomeContOpsGrowth);
CFOGrowth.UpdateValues(previous.CFOGrowth);
FCFGrowth.UpdateValues(previous.FCFGrowth);
OperationRevenueGrowth3MonthAvg.UpdateValues(previous.OperationRevenueGrowth3MonthAvg);
GrossMargin.UpdateValues(previous.GrossMargin);
OperationMargin.UpdateValues(previous.OperationMargin);
PretaxMargin.UpdateValues(previous.PretaxMargin);
NetMargin.UpdateValues(previous.NetMargin);
TaxRate.UpdateValues(previous.TaxRate);
EBITMargin.UpdateValues(previous.EBITMargin);
EBITDAMargin.UpdateValues(previous.EBITDAMargin);
SalesPerEmployee.UpdateValues(previous.SalesPerEmployee);
CurrentRatio.UpdateValues(previous.CurrentRatio);
QuickRatio.UpdateValues(previous.QuickRatio);
LongTermDebtTotalCapitalRatio.UpdateValues(previous.LongTermDebtTotalCapitalRatio);
InterestCoverage.UpdateValues(previous.InterestCoverage);
LongTermDebtEquityRatio.UpdateValues(previous.LongTermDebtEquityRatio);
FinancialLeverage.UpdateValues(previous.FinancialLeverage);
TotalDebtEquityRatio.UpdateValues(previous.TotalDebtEquityRatio);
NormalizedNetProfitMargin.UpdateValues(previous.NormalizedNetProfitMargin);
DaysInSales.UpdateValues(previous.DaysInSales);
DaysInInventory.UpdateValues(previous.DaysInInventory);
DaysInPayment.UpdateValues(previous.DaysInPayment);
CashConversionCycle.UpdateValues(previous.CashConversionCycle);
ReceivableTurnover.UpdateValues(previous.ReceivableTurnover);
InventoryTurnover.UpdateValues(previous.InventoryTurnover);
PaymentTurnover.UpdateValues(previous.PaymentTurnover);
FixAssetsTuronver.UpdateValues(previous.FixAssetsTuronver);
AssetsTurnover.UpdateValues(previous.AssetsTurnover);
ROE.UpdateValues(previous.ROE);
ROA.UpdateValues(previous.ROA);
ROIC.UpdateValues(previous.ROIC);
FCFSalesRatio.UpdateValues(previous.FCFSalesRatio);
FCFNetIncomeRatio.UpdateValues(previous.FCFNetIncomeRatio);
CapExSalesRatio.UpdateValues(previous.CapExSalesRatio);
DebttoAssets.UpdateValues(previous.DebttoAssets);
CommonEquityToAssets.UpdateValues(previous.CommonEquityToAssets);
CapitalExpenditureAnnual5YrGrowth.UpdateValues(previous.CapitalExpenditureAnnual5YrGrowth);
GrossProfitAnnual5YrGrowth.UpdateValues(previous.GrossProfitAnnual5YrGrowth);
GrossMargin5YrAvg.UpdateValues(previous.GrossMargin5YrAvg);
PostTaxMargin5YrAvg.UpdateValues(previous.PostTaxMargin5YrAvg);
PreTaxMargin5YrAvg.UpdateValues(previous.PreTaxMargin5YrAvg);
ProfitMargin5YrAvg.UpdateValues(previous.ProfitMargin5YrAvg);
ROE5YrAvg.UpdateValues(previous.ROE5YrAvg);
ROA5YrAvg.UpdateValues(previous.ROA5YrAvg);
AVG5YrsROIC.UpdateValues(previous.AVG5YrsROIC);
NormalizedROIC.UpdateValues(previous.NormalizedROIC);
RegressionGrowthOperatingRevenue5Years.UpdateValues(previous.RegressionGrowthOperatingRevenue5Years);
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecT409FieldElement
: ECFieldElement
{
protected ulong[] x;
public SecT409FieldElement(BigInteger x)
{
if (x == null || x.SignValue < 0)
throw new ArgumentException("value invalid for SecT409FieldElement", "x");
this.x = SecT409Field.FromBigInteger(x);
}
public SecT409FieldElement()
{
this.x = Nat448.Create64();
}
protected internal SecT409FieldElement(ulong[] x)
{
this.x = x;
}
public override bool IsOne
{
get { return Nat448.IsOne64(x); }
}
public override bool IsZero
{
get { return Nat448.IsZero64(x); }
}
public override bool TestBitZero()
{
return (x[0] & 1UL) != 0UL;
}
public override BigInteger ToBigInteger()
{
return Nat448.ToBigInteger64(x);
}
public override string FieldName
{
get { return "SecT409Field"; }
}
public override int FieldSize
{
get { return 409; }
}
public override ECFieldElement Add(ECFieldElement b)
{
ulong[] z = Nat448.Create64();
SecT409Field.Add(x, ((SecT409FieldElement)b).x, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement AddOne()
{
ulong[] z = Nat448.Create64();
SecT409Field.AddOne(x, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return Add(b);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
ulong[] z = Nat448.Create64();
SecT409Field.Multiply(x, ((SecT409FieldElement)b).x, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return MultiplyPlusProduct(b, x, y);
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
ulong[] ax = this.x, bx = ((SecT409FieldElement)b).x;
ulong[] xx = ((SecT409FieldElement)x).x, yx = ((SecT409FieldElement)y).x;
ulong[] tt = Nat.Create64(13);
SecT409Field.MultiplyAddToExt(ax, bx, tt);
SecT409Field.MultiplyAddToExt(xx, yx, tt);
ulong[] z = Nat448.Create64();
SecT409Field.Reduce(tt, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement Divide(ECFieldElement b)
{
return Multiply(b.Invert());
}
public override ECFieldElement Negate()
{
return this;
}
public override ECFieldElement Square()
{
ulong[] z = Nat448.Create64();
SecT409Field.Square(x, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return SquarePlusProduct(x, y);
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
ulong[] ax = this.x;
ulong[] xx = ((SecT409FieldElement)x).x, yx = ((SecT409FieldElement)y).x;
ulong[] tt = Nat.Create64(13);
SecT409Field.SquareAddToExt(ax, tt);
SecT409Field.MultiplyAddToExt(xx, yx, tt);
ulong[] z = Nat448.Create64();
SecT409Field.Reduce(tt, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement SquarePow(int pow)
{
if (pow < 1)
return this;
ulong[] z = Nat448.Create64();
SecT409Field.SquareN(x, pow, z);
return new SecT409FieldElement(z);
}
public override ECFieldElement Invert()
{
return new SecT409FieldElement(
AbstractF2mCurve.Inverse(409, new int[] { 87 }, ToBigInteger()));
}
public override ECFieldElement Sqrt()
{
return SquarePow(M - 1);
}
public virtual int Representation
{
get { return F2mFieldElement.Tpb; }
}
public virtual int M
{
get { return 409; }
}
public virtual int K1
{
get { return 87; }
}
public virtual int K2
{
get { return 0; }
}
public virtual int K3
{
get { return 0; }
}
public override bool Equals(object obj)
{
return Equals(obj as SecT409FieldElement);
}
public override bool Equals(ECFieldElement other)
{
return Equals(other as SecT409FieldElement);
}
public virtual bool Equals(SecT409FieldElement other)
{
if (this == other)
return true;
if (null == other)
return false;
return Nat448.Eq64(x, other.x);
}
public override int GetHashCode()
{
return 4090087 ^ Arrays.GetHashCode(x, 0, 7);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Keen.Core;
using Keen.Query;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Keen.Test
{
/// <summary>
/// Integration tests for Queries. These will exercise more than unit tests, like the
/// integration between KeenClient, Queries and KeenHttpClient.
/// </summary>
class QueryTests_Integration : TestBase
{
[Test]
public async Task QueryFilter_NotContains_Success()
{
var queriesUrl = HttpTests.GetUriForResource(SettingsEnv,
KeenConstants.QueriesResource);
var handler = new FuncHandler()
{
PreProcess = (req, ct) =>
{
var queryStr = req.RequestUri.Query;
// Make sure our filter properties are in the query string
Assert.IsTrue(queryStr.Contains("propertyName") &&
queryStr.Contains("four") &&
queryStr.Contains(QueryFilter.FilterOperator.NotContains()));
},
ProduceResultAsync = (req, ct) =>
{
return HttpTests.CreateJsonStringResponseAsync(new { result = 2 });
},
DeferToDefault = false
};
// NOTE : This example shows use of UrlToMessageHandler, but since we only make one
// request to a single endpoint, we could just directly use the FuncHandler here.
var urlHandler = new UrlToMessageHandler(
new Dictionary<Uri, IHttpMessageHandler>
{
{ queriesUrl, handler }
})
{ DeferToDefault = false };
var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
{
ProvideKeenHttpClient =
(url) => KeenHttpClientFactory.Create(url,
new HttpClientCache(),
null,
new DelegatingHandlerMock(urlHandler))
});
var filters = new List<QueryFilter>
{
new QueryFilter("propertyName", QueryFilter.FilterOperator.NotContains(), "four")
};
var count = await client.QueryAsync(
QueryType.Count(),
"testCollection",
"",
QueryRelativeTimeframe.ThisMonth(),
filters);
Assert.IsNotNull(count);
Assert.AreEqual("2", count);
}
[Test]
public async Task QueryFilter_NullPropertyValue_Success()
{
// TODO : Consolidate this FuncHandler/KeenClient setup into a helper method.
var handler = new FuncHandler()
{
PreProcess = (req, ct) =>
{
var queryStr = req.RequestUri.Query;
// Make sure our filter properties are in the query string
Assert.IsTrue(queryStr.Contains("propertyName") &&
queryStr.Contains("null") &&
queryStr.Contains(QueryFilter.FilterOperator.Equals()));
},
ProduceResultAsync = (req, ct) =>
{
return HttpTests.CreateJsonStringResponseAsync(new { result = 2 });
},
DeferToDefault = false
};
var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
{
ProvideKeenHttpClient =
(url) => KeenHttpClientFactory.Create(url,
new HttpClientCache(),
null,
new DelegatingHandlerMock(handler))
});
var filters = new List<QueryFilter>
{
new QueryFilter("propertyName", QueryFilter.FilterOperator.Equals(), null)
};
var count = await client.QueryAsync(
QueryType.Count(),
"testCollection",
"",
QueryRelativeTimeframe.ThisMonth(),
filters);
Assert.IsNotNull(count);
Assert.AreEqual("2", count);
}
[Test]
public async Task Query_AvailableQueries_Success()
{
var queriesResource = HttpTests.GetUriForResource(SettingsEnv, KeenConstants.QueriesResource);
var expectedQueries = new Dictionary<string, string>()
{
{ "select_unique_url", $"{queriesResource.AbsolutePath}/select_unique"},
{ "minimum", $"{queriesResource.AbsolutePath}/minimum" },
{ "extraction_url", $"{queriesResource.AbsolutePath}/extraction" },
{ "percentile", $"{queriesResource.AbsolutePath}/percentile" },
{ "funnel_url", $"{queriesResource.AbsolutePath}/funnel" },
{ "average", $"{queriesResource.AbsolutePath}/average" },
{ "median", $"{queriesResource.AbsolutePath}/median" },
{ "maximum", $"{queriesResource.AbsolutePath}/maximum" },
{ "count_url", $"{queriesResource.AbsolutePath}/count" },
{ "count_unique_url", $"{queriesResource.AbsolutePath}/count_unique" },
{ "sum", $"{queriesResource.AbsolutePath}/sum"}
};
FuncHandler handler = new FuncHandler()
{
ProduceResultAsync = (request, ct) =>
{
return HttpTests.CreateJsonStringResponseAsync(expectedQueries);
}
};
var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
{
ProvideKeenHttpClient =
(url) => KeenHttpClientFactory.Create(url,
new HttpClientCache(),
null,
new DelegatingHandlerMock(handler))
});
var actualQueries = await client.GetQueriesAsync();
Assert.That(actualQueries, Is.EquivalentTo(expectedQueries));
}
class QueryParameters
{
internal string EventCollection = "myEvents";
internal QueryType Analysis = QueryType.Count();
internal string TargetProperty;
internal String GroupBy;
internal QueryRelativeTimeframe Timeframe;
internal QueryInterval Interval;
internal virtual string GetResourceName() => Analysis;
internal virtual Dictionary<string, string> GetQueryParameters()
{
var queryParameters = new Dictionary<string, string>();
if (null != EventCollection) { queryParameters[KeenConstants.QueryParmEventCollection] = EventCollection; }
if (null != TargetProperty) { queryParameters[KeenConstants.QueryParmTargetProperty] = TargetProperty; }
if (null != GroupBy) { queryParameters[KeenConstants.QueryParmGroupBy] = GroupBy; }
if (null != Timeframe) { queryParameters[KeenConstants.QueryParmTimeframe] = Timeframe.ToString(); }
if (null != Interval) { queryParameters[KeenConstants.QueryParmInterval] = Interval; }
return queryParameters;
}
internal MultiAnalysisParam GetMultiAnalysisParameter(string label)
{
return new MultiAnalysisParam(
label,
String.IsNullOrEmpty(TargetProperty) ?
new MultiAnalysisParam.Metric(Analysis) :
new MultiAnalysisParam.Metric(Analysis, TargetProperty));
}
}
class ExtractionParameters : QueryParameters
{
internal ExtractionParameters()
{
Analysis = null;
}
internal override string GetResourceName() => KeenConstants.QueryExtraction;
}
class FunnelParameters : QueryParameters
{
internal IEnumerable<FunnelStep> Steps;
internal FunnelParameters()
{
EventCollection = null;
Analysis = null;
}
internal override string GetResourceName() => KeenConstants.QueryFunnel;
internal override Dictionary<string, string> GetQueryParameters()
{
var parameters = base.GetQueryParameters();
parameters[KeenConstants.QueryParmSteps] = JArray.FromObject(Steps).ToString(Newtonsoft.Json.Formatting.None);
return parameters;
}
}
class MultiAnalysisParameters : QueryParameters
{
internal IEnumerable<QueryParameters> Analyses;
internal IList<string> Labels;
internal MultiAnalysisParameters()
{
Analysis = null;
}
internal override string GetResourceName() => KeenConstants.QueryMultiAnalysis;
internal override Dictionary<string, string> GetQueryParameters()
{
var parameters = base.GetQueryParameters();
var multiAnalysisParameters = GetMultiAnalysisParameters();
var jObjects = multiAnalysisParameters.Select(x =>
new JProperty(x.Label, JObject.FromObject(
string.IsNullOrEmpty(x.TargetProperty) ?
(object)new { analysis_type = x.Analysis } :
new { analysis_type = x.Analysis, target_property = x.TargetProperty })));
var analysesJson = JsonConvert.SerializeObject(
new JObject(jObjects),
Formatting.None,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
parameters[KeenConstants.QueryParmAnalyses] = analysesJson;
return parameters;
}
internal IEnumerable<MultiAnalysisParam> GetMultiAnalysisParameters()
{
return Analyses.Zip(Labels, (parameters, label) => parameters.GetMultiAnalysisParameter(label));
}
}
FuncHandler CreateQueryRequestHandler(QueryParameters queryParameters, object response)
{
// Create a NameValueCollection with all expected query string parameters
var expectedQueryStringCollection = new NameValueCollection();
foreach (var parameter in queryParameters.GetQueryParameters())
{
if (null != parameter.Value)
{
expectedQueryStringCollection[parameter.Key] = parameter.Value;
}
}
return new FuncHandler()
{
ProduceResultAsync = (request, ct) =>
{
var expectedPath =
$"{HttpTests.GetUriForResource(SettingsEnv, KeenConstants.QueriesResource)}/" +
$"{queryParameters.GetResourceName()}";
string actualPath =
$"{request.RequestUri.Scheme}{Uri.SchemeDelimiter}" +
$"{request.RequestUri.Authority}{request.RequestUri.AbsolutePath}";
Assert.AreEqual(expectedPath, actualPath);
var actualQueryStringCollection = HttpUtility.ParseQueryString(request.RequestUri.Query);
Assert.That(actualQueryStringCollection, Is.EquivalentTo(expectedQueryStringCollection));
return HttpTests.CreateJsonStringResponseAsync(response);
}
};
}
KeenClient CreateQueryTestKeenClient(QueryParameters queryParameters, object response)
{
var handler = CreateQueryRequestHandler(queryParameters, response);
return new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
{
ProvideKeenHttpClient =
(url) => KeenHttpClientFactory.Create(url,
new HttpClientCache(),
null,
new DelegatingHandlerMock(handler))
});
}
[Test]
public async Task Query_SimpleCount_Success()
{
var queryParameters = new QueryParameters();
string expectedResult = "10";
var expectedResponse = new Dictionary<string, string>()
{
{ "result", expectedResult},
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
null);
Assert.AreEqual(expectedResult, actualResult);
}
[Test]
public async Task Query_SimpleSelectUnique_Success()
{
var queryParameters = new QueryParameters()
{
Analysis = QueryType.SelectUnique(),
TargetProperty = "targetProperty"
};
string[] results =
{
"this",
"that",
"theOtherThing"
};
var expectedResponse = new
{
result = results,
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty);
string expectedResultString = string.Join(',', results);
Assert.AreEqual(expectedResultString, actualResult);
}
[Test]
public async Task Query_SimpleAverage_Success()
{
var queryParameters = new QueryParameters()
{
Analysis = QueryType.Average(),
TargetProperty = "someProperty"
};
string expectedResult = "10";
var expectedResponse = new Dictionary<string, string>()
{
{ "result", expectedResult},
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty);
Assert.AreEqual(expectedResult, actualResult);
}
[Test]
public async Task Query_SimpleCountGroupBy_Success()
{
var queryParameters = new QueryParameters()
{
GroupBy = "someGroupProperty"
};
var expectedResults = new List<string>() { "10", "20" };
var expectedGroups = new List<string>() { "group1", "group2" };
var expectedGroupResults = expectedResults.Zip(
expectedGroups,
(result, group) => new Dictionary<string, string>()
{
{ queryParameters.GroupBy, group },
{ "result", result }
});
var expectedResponse = new
{
result = expectedGroupResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
null,
queryParameters.GroupBy);
var expectedSdkResult = expectedGroupResults.Select((result) =>
{
return new QueryGroupValue<string>(
result["result"],
result[queryParameters.GroupBy]);
});
Assert.That(actualResult, Is.EquivalentTo(expectedSdkResult));
}
[Test]
public async Task Query_SimpleSelectUniqueGroupBy_Success()
{
var queryParameters = new QueryParameters()
{
Analysis = QueryType.SelectUnique(),
TargetProperty = "someProperty",
GroupBy = "someGroupProperty"
};
var expectedResults = new List<string[]>() { new string[] { "10", "20" }, new string[] { "30", "40" } };
var expectedGroups = new List<string>() { "group1", "group2" };
var expectedGroupResults = expectedResults.Zip(
expectedGroups,
(result, group) => new
{
someGroupProperty = group,
result = result
});
var expectedResponse = new
{
result = expectedGroupResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty,
queryParameters.GroupBy);
var expectedSdkResult = expectedGroupResults.Select((result) =>
{
return new QueryGroupValue<string>(
string.Join(',', result.result),
result.someGroupProperty);
});
Assert.That(actualResult, Is.EquivalentTo(expectedSdkResult));
}
[Test]
public async Task Query_SimpleCountInterval_Success()
{
var queryParameters = new QueryParameters()
{
TargetProperty = "someProperty",
Timeframe = QueryRelativeTimeframe.ThisNHours(2),
Interval = QueryInterval.EveryNHours(1)
};
var expectedCounts = new List<string>() { "10", "20" };
var expectedTimeframes = new List<QueryAbsoluteTimeframe>()
{
new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-2), DateTime.Now.AddHours(-1)),
new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-1), DateTime.Now)
};
var expectedResults = expectedCounts.Zip(
expectedTimeframes,
(count, time) => new { timeframe = time, value = count });
var expectedResponse = new
{
result = expectedResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty,
queryParameters.Timeframe,
queryParameters.Interval);
var expectedSdkResult = expectedResults.Select((result) =>
{
return new QueryIntervalValue<string>(
string.Join(',', result.value),
result.timeframe.Start,
result.timeframe.End);
});
Assert.That(actualResult, Is.EquivalentTo(expectedSdkResult));
}
[Test]
public async Task Query_SimpleSelectUniqueInterval_Success()
{
var queryParameters = new QueryParameters()
{
Analysis = QueryType.SelectUnique(),
TargetProperty = "someProperty",
Timeframe = QueryRelativeTimeframe.ThisNHours(2),
Interval = QueryInterval.EveryNHours(1)
};
var expectedCounts = new List<string[]>() { new string[] { "10", "20" }, new string[] { "30", "40" } };
var expectedTimeframes = new List<QueryAbsoluteTimeframe>()
{
new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-2), DateTime.Now.AddHours(-1)),
new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-1), DateTime.Now)
};
var expectedResults = expectedCounts.Zip(
expectedTimeframes,
(count, time) => new { timeframe = time, value = count });
var expectedResponse = new
{
result = expectedResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty,
queryParameters.Timeframe,
queryParameters.Interval);
var expectedSdkResult = expectedResults.Select((result) =>
{
return new QueryIntervalValue<string>(
string.Join(',', result.value),
result.timeframe.Start,
result.timeframe.End);
});
Assert.That(actualResult, Is.EquivalentTo(expectedSdkResult));
}
[Test]
public async Task Query_SimpleCountGroupByInterval_Success()
{
var queryParameters = new QueryParameters()
{
TargetProperty = "someProperty",
Timeframe = QueryRelativeTimeframe.ThisNHours(2),
Interval = QueryInterval.EveryNHours(1),
GroupBy = "someGroupProperty"
};
var expectedResults = new[]
{
new
{
timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-2), DateTime.Now.AddHours(-1)),
value = new List<Dictionary<string, string>>
{
new Dictionary<string, string>{ { queryParameters.GroupBy, "group1" }, { "result", "10" } },
new Dictionary<string, string>{ { queryParameters.GroupBy, "group2" }, { "result", "20" } },
}
},
new
{
timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddHours(-1), DateTime.Now),
value = new List<Dictionary<string, string>>
{
new Dictionary<string, string>{ { queryParameters.GroupBy, "group1" }, { "result", "30" } },
new Dictionary<string, string>{ { queryParameters.GroupBy, "group2" }, { "result", "40" } },
}
}
};
var expectedResponse = new
{
result = expectedResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = (await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty,
queryParameters.GroupBy,
queryParameters.Timeframe,
queryParameters.Interval));
var expectedSdkResult = expectedResults.Select((intervals) =>
{
return new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
intervals.value.Select((group) => new QueryGroupValue<string>(
group["result"],
group[queryParameters.GroupBy])),
intervals.timeframe.Start,
intervals.timeframe.End
);
});
// Use JArray objects as a way to normalize types here, since the
// concrete types won't match for the QueryInternalValue IEnumerable implementation.
Assert.That(JArray.FromObject(actualResult), Is.EquivalentTo(JArray.FromObject(expectedSdkResult)));
}
[Test]
public async Task Query_SimpleSelectUniqueGroupByInterval_Success()
{
var queryParameters = new QueryParameters()
{
Analysis = QueryType.SelectUnique(),
TargetProperty = "someProperty",
Timeframe = QueryRelativeTimeframe.ThisNHours(2),
Interval = QueryInterval.EveryNHours(1),
GroupBy = "someGroupProperty"
};
string resultsJson = @"[
{
""timeframe"": {
""start"": ""2017-10-14T00:00:00.000Z"",
""end"": ""2017-10-15T00:00:00.000Z""
},
""value"": [
{
""someGroupProperty"": ""group1"",
""result"": [
""10"",
""20""
]
},
{
""someGroupProperty"": ""group2"",
""result"": [
""30"",
""40""
]
}
]
},
{
""timeframe"": {
""start"": ""2017-10-15T00:00:00.000Z"",
""end"": ""2017-10-16T00:00:00.000Z""
},
""value"": [
{
""someGroupProperty"": ""group1"",
""result"": [
""50"",
""60""
]
},
{
""someGroupProperty"": ""group2"",
""result"": [
""70"",
""80""
]
}
]
}
]";
var expectedResults = JArray.Parse(resultsJson);
var expectedResponse = new
{
result = expectedResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResult = await client.Queries.Metric(
queryParameters.Analysis,
queryParameters.EventCollection,
queryParameters.TargetProperty,
queryParameters.GroupBy,
queryParameters.Timeframe,
queryParameters.Interval);
var expectedSdkResult = expectedResults.Select((intervalToken) =>
{
return new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
intervalToken["value"].Select((groupToken) =>
{
return new QueryGroupValue<string>(
string.Join(',', groupToken["result"]),
groupToken[queryParameters.GroupBy].Value<string>());
}),
intervalToken["timeframe"]["start"].Value<DateTime>(),
intervalToken["timeframe"]["end"].Value<DateTime>());
});
// Use JArray objects as a way to normalize types here, since the
// concrete types won't match for the QueryInternalValue IEnumerable implementation.
Assert.That(JArray.FromObject(actualResult), Is.EquivalentTo(JArray.FromObject(expectedSdkResult)));
}
[Test]
public async Task Query_SimpleExtraction_Success()
{
var queryParameters = new ExtractionParameters()
{
Timeframe = QueryRelativeTimeframe.ThisNHours(2),
};
string resultsJson = @"[
{
""keen"": {
""created_at"": ""2012-07-30T21:21:46.566000+00:00"",
""timestamp"": ""2012-07-30T21:21:46.566000+00:00"",
""id"": """"
},
""user"": {
""email"": ""dan@keen.io"",
""id"": ""4f4db6c7777d66ffff000000""
},
""user_agent"": {
""browser"": ""chrome"",
""browser_version"": ""20.0.1132.57"",
""platform"": ""macos""
}
},
{
""keen"": {
""created_at"": ""2012-07-30T21:40:05.386000+00:00"",
""timestamp"": ""2012-07-30T21:40:05.386000+00:00"",
""id"": """"
},
""user"": {
""email"": ""michelle@keen.io"",
""id"": ""4fa2cccccf546ffff000006""
},
""user_agent"": {
""browser"": ""chrome"",
""browser_version"": ""20.0.1132.57"",
""platform"": ""macos""
}
}
]";
var expectedResults = JArray.Parse(resultsJson);
var expectedResponse = new
{
result = expectedResults
};
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.Extract(
queryParameters.EventCollection,
queryParameters.Timeframe);
Assert.That(actualResults, Is.EquivalentTo(expectedResults));
}
[Test]
public async Task Query_SimpleFunnel_Success()
{
var queryParameters = new FunnelParameters()
{
Steps = new FunnelStep[]
{
new FunnelStep() {EventCollection = "signed up", ActorProperty = "visitor.guid", Timeframe = QueryRelativeTimeframe.ThisNDays(7)},
new FunnelStep() {EventCollection = "completed profile", ActorProperty = "user.guid", Timeframe = QueryRelativeTimeframe.ThisNDays(7)},
new FunnelStep() {EventCollection = "referred user", ActorProperty = "user.guid", Timeframe = QueryRelativeTimeframe.ThisNDays(7)},
}
};
string responseJson = @"{
""result"": [
3,
1,
0
],
""steps"": [
{
""actor_property"": ""visitor.guid"",
""event_collection"": ""signed up"",
""timeframe"": ""this_7_days""
},
{
""actor_property"": ""user.guid"",
""event_collection"": ""completed profile"",
""timeframe"": ""this_7_days""
},
{
""actor_property"": ""user.guid"",
""event_collection"": ""referred user"",
""timeframe"": ""this_7_days""
}
]
}";
var expectedResponse = JObject.Parse(responseJson);
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.Funnel(
queryParameters.Steps);
var expectedResults = expectedResponse["result"].Values<int>();
Assert.That(actualResults.Result, Is.EquivalentTo(expectedResults));
var expectedSteps = queryParameters.Steps.Select((step) => new FunnelResultStep() { EventCollection = step.EventCollection, ActorProperty = step.ActorProperty, Timeframe = step.Timeframe });
Assert.That(actualResults.Steps, Is.EquivalentTo(expectedSteps));
}
[Test]
public async Task Query_SimpleMultiAnalysis_Success()
{
var queryParameters = new MultiAnalysisParameters()
{
Labels = new string[]
{
"first analysis",
"second analysis"
},
Analyses = new QueryParameters[]
{
new QueryParameters(),
new QueryParameters()
{
Analysis = QueryType.Average(),
TargetProperty = "targetProperty"
}
}
};
string responseJson = $"{{\"result\":{{ \"{queryParameters.Labels[0]}\" : 12345, \"{queryParameters.Labels[1]}\" : 54321 }} }}";
var expectedResponse = JObject.Parse(responseJson);
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.MultiAnalysis(
queryParameters.EventCollection,
queryParameters.GetMultiAnalysisParameters(),
timeframe: null,
filters: null,
timezone: null);
var expectedResults = expectedResponse["result"];
var transformedResults = JObject.FromObject(actualResults.ToDictionary((pair) => pair.Key, (pair) => int.Parse(pair.Value)));
Assert.That(transformedResults, Is.EquivalentTo(expectedResults));
}
[Test]
public async Task Query_SimpleMultiAnalysisGroupBy_Success()
{
var queryParameters = new MultiAnalysisParameters()
{
Labels = new string[]
{
"first analysis",
"second analysis"
},
Analyses = new QueryParameters[]
{
new QueryParameters(),
new QueryParameters()
{
Analysis = QueryType.Average(),
TargetProperty = "targetProperty"
}
},
GroupBy = "groupByProperty"
};
string responseJson = $"{{\"result\":[" +
$"{{\"{queryParameters.GroupBy}\":\"group1\",\"{queryParameters.Labels[0]}\":12345,\"{queryParameters.Labels[1]}\":54321}}," +
$"{{\"{queryParameters.GroupBy}\":\"group2\",\"{queryParameters.Labels[0]}\":67890,\"{queryParameters.Labels[1]}\":9876}}" +
$"]}}";
var expectedResponse = JObject.Parse(responseJson);
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.MultiAnalysis(
queryParameters.EventCollection,
queryParameters.GetMultiAnalysisParameters(),
null,
null,
queryParameters.GroupBy,
null);
var expectedResults = expectedResponse["result"];
Assert.AreEqual(expectedResults.Count(), actualResults.Count());
foreach (var group in new string[] { "group1", "group2" })
{
var actualGroupResult = actualResults.Where((result) => result.Group == group).First();
var expectedGroupResult = expectedResults.Where((result) => result[queryParameters.GroupBy].Value<string>() == group).First();
foreach (var label in queryParameters.Labels)
{
// Validate the result is correct
Assert.AreEqual(expectedGroupResult[label].Value<int>(), int.Parse(actualGroupResult.Value[label]));
}
}
}
[Test]
public async Task Query_SimpleMultiAnalysisInterval_Success()
{
var queryParameters = new MultiAnalysisParameters()
{
Labels = new string[]
{
"first analysis",
"second analysis"
},
Analyses = new QueryParameters[]
{
new QueryParameters(),
new QueryParameters()
{
Analysis = QueryType.Average(),
TargetProperty = "targetProperty"
}
},
Interval = QueryInterval.Daily()
};
string responseJson = "{\"result\":[" +
"{\"timeframe\":{\"start\":\"2017-10-14T00:00:00.000Z\",\"end\":\"2017-10-15T00:00:00.000Z\"}," +
"\"value\":{" +
$"\"{queryParameters.Labels[0]}\":12345,\"{queryParameters.Labels[1]}\":54321}}" +
"}," +
"{\"timeframe\":{\"start\":\"2017-10-15T00:00:00.000Z\",\"end\":\"2017-10-16T00:00:00.000Z\"}," +
"\"value\":{" +
$"\"{queryParameters.Labels[0]}\":123,\"{queryParameters.Labels[1]}\":321}}" +
"}" +
"]}";
var expectedResponse = JObject.Parse(responseJson);
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.MultiAnalysis(
queryParameters.EventCollection,
queryParameters.GetMultiAnalysisParameters(),
timeframe: null,
interval: queryParameters.Interval,
filters: null,
timezone: null);
var expectedResults = expectedResponse["result"];
Assert.AreEqual(expectedResults.Count(), actualResults.Count());
var results = expectedResults.Zip(actualResults, (expected, actual) => new { Expected = expected, Actual = actual });
foreach (var result in results)
{
Assert.AreEqual(DateTime.Parse(result.Expected["timeframe"]["start"].Value<string>()), result.Actual.Start);
Assert.AreEqual(DateTime.Parse(result.Expected["timeframe"]["end"].Value<string>()), result.Actual.End);
foreach (var label in queryParameters.Labels)
{
// Validate the result is correct
Assert.AreEqual(result.Expected["value"][label].Value<int>(), int.Parse(result.Actual.Value[label]));
}
}
}
[Test]
public async Task Query_SimpleMultiAnalysisIntervalGroupBy_Success()
{
var queryParameters = new MultiAnalysisParameters()
{
Labels = new string[]
{
"first analysis",
"second analysis"
},
Analyses = new QueryParameters[]
{
new QueryParameters(),
new QueryParameters()
{
Analysis = QueryType.Average(),
TargetProperty = "targetProperty"
}
},
GroupBy = "groupByProperty",
Interval = QueryInterval.Daily()
};
string responseJson = "{\"result\":[" +
"{\"timeframe\":{\"start\":\"2017-10-14T00:00:00.000Z\",\"end\":\"2017-10-15T00:00:00.000Z\"}," +
"\"value\":[" +
$"{{\"{queryParameters.GroupBy}\":\"group1\",\"{queryParameters.Labels[0]}\":12345,\"{queryParameters.Labels[1]}\":54321}}," +
$"{{\"{queryParameters.GroupBy}\":\"group2\",\"{queryParameters.Labels[0]}\":67890,\"{queryParameters.Labels[1]}\":9876}}" +
"]}," +
"{\"timeframe\":{\"start\":\"2017-10-15T00:00:00.000Z\",\"end\":\"2017-10-16T00:00:00.000Z\"}," +
"\"value\":[" +
$"{{\"{queryParameters.GroupBy}\":\"group1\",\"{queryParameters.Labels[0]}\":123,\"{queryParameters.Labels[1]}\":321}}," +
$"{{\"{queryParameters.GroupBy}\":\"group2\",\"{queryParameters.Labels[0]}\":456,\"{queryParameters.Labels[1]}\":654}}" +
"]}" +
"]}";
var expectedResponse = JObject.Parse(responseJson);
var client = CreateQueryTestKeenClient(queryParameters, expectedResponse);
var actualResults = await client.Queries.MultiAnalysis(
queryParameters.EventCollection,
queryParameters.GetMultiAnalysisParameters(),
groupby: queryParameters.GroupBy,
interval: queryParameters.Interval);
var expectedResults = expectedResponse["result"];
Assert.AreEqual(expectedResults.Count(), actualResults.Count());
var results = expectedResults.Zip(actualResults, (expected, actual) => new { Expected = expected, Actual = actual });
foreach (var result in results)
{
Assert.AreEqual(DateTime.Parse(result.Expected["timeframe"]["start"].Value<string>()), result.Actual.Start);
Assert.AreEqual(DateTime.Parse(result.Expected["timeframe"]["end"].Value<string>()), result.Actual.End);
foreach (var group in new string[] { "group1", "group2" })
{
var expectedGroupResult = result.Expected["value"].Where((groupResult) => groupResult[queryParameters.GroupBy].Value<string>() == group).First();
var actualGroupResult = result.Actual.Value.Where((groupResult) => groupResult.Group == group).First();
foreach (var label in queryParameters.Labels)
{
Assert.AreEqual(expectedGroupResult[label].Value<int>(), int.Parse(actualGroupResult.Value[label]));
}
}
}
}
}
}
| |
// Copyright Bastian Eicher
// Licensed under the MIT License
using System.Globalization;
using NanoByte.Common.Native;
#if NET45 || NET461 || NET472
using TaskDialog;
#endif
namespace NanoByte.Common.Controls;
/// <summary>
/// Provides easier access to typical <see cref="MessageBox"/> configurations and automatically upgrades to TaskDialogs when available.
/// </summary>
public static class Msg
{
/// <summary>
/// Displays a message to the user using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
public static void Inform(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity)
{
if (ShowTaskDialog(owner, text, severity) == null)
ShowMessageBox(owner, text, severity, MessageBoxButtons.OK);
}
/// <summary>
/// Asks the user a OK/Cancel-question using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <param name="okCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.OK"/> option.</param>
/// <param name="cancelCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.Cancel"/> option; can be <c>null</c>.</param>
/// <returns><c>true</c> if <paramref name="okCaption"/> was selected, <c>false</c> if <paramref name="cancelCaption"/> was selected.</returns>
/// <remarks>If a <see cref="MessageBox"/> is used, <paramref name="okCaption"/> and <paramref name="cancelCaption"/> are not display to the user, so don't rely on them!</remarks>
public static bool OkCancel(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity, [Localizable(true)] string okCaption, [Localizable(true)] string? cancelCaption = null)
{
#region Sanity checks
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException(nameof(text));
if (string.IsNullOrEmpty(okCaption)) throw new ArgumentNullException(nameof(okCaption));
#endregion
var result = ShowTaskDialog(owner, text, severity, ok: okCaption, cancel: cancelCaption, canCancel: true)
?? ShowMessageBox(owner, text, severity, MessageBoxButtons.OKCancel);
return result == DialogResult.OK;
}
/// <summary>
/// Asks the user a OK/Cancel-question using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <returns><c>true</c> if OK was selected, <c>false</c> if Cancel was selected.</returns>
/// <remarks>If a <see cref="MessageBox"/> is used, OK and Cancel are not display to the user, so don't rely on them!</remarks>
public static bool OkCancel(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity)
=> OkCancel(owner, text, severity, "OK", Resources.Cancel);
/// <summary>
/// Asks the user to choose between two options (yes/no) using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <param name="yesCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.Yes"/> option.</param>
/// <param name="noCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.No"/> option.</param>
/// <returns><c>true</c> if <paramref name="yesCaption"/> was chosen, <c>false</c> if <paramref name="noCaption"/> was chosen.</returns>
/// <remarks>If a <see cref="MessageBox"/> is used, <paramref name="yesCaption"/> and <paramref name="noCaption"/> are not display to the user, so don't rely on them!</remarks>
public static bool YesNo(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity, [Localizable(true)] string yesCaption, [Localizable(true)] string noCaption)
{
#region Sanity checks
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException(nameof(text));
if (string.IsNullOrEmpty(yesCaption)) throw new ArgumentNullException(nameof(yesCaption));
if (string.IsNullOrEmpty(noCaption)) throw new ArgumentNullException(nameof(noCaption));
#endregion
var result = ShowTaskDialog(owner, text, severity, yes: yesCaption, no: noCaption)
?? ShowMessageBox(owner, text, severity, MessageBoxButtons.YesNo);
return result == DialogResult.Yes;
}
/// <summary>
/// Asks the user to choose between two options (yes/no) using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
public static bool YesNo(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity)
=> YesNo(owner, text, severity, Resources.Yes, Resources.No);
/// <summary>
/// Asks the user to choose between three options (yes/no/cancel) using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <param name="yesCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.Yes"/> option.</param>
/// <param name="noCaption">The title and a short description (separated by a linebreak) of the <see cref="DialogResult.No"/> option.</param>
/// <returns><see cref="DialogResult.Yes"/> if <paramref name="yesCaption"/> was chosen,
/// <see cref="DialogResult.No"/> if <paramref name="noCaption"/> was chosen,
/// <see cref="DialogResult.Cancel"/> otherwise.</returns>
/// <remarks>If a <see cref="MessageBox"/> is used, <paramref name="yesCaption"/> and <paramref name="noCaption"/> are not display to the user, so don't rely on them!</remarks>
public static DialogResult YesNoCancel(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity, [Localizable(true)] string yesCaption, [Localizable(true)] string noCaption)
{
#region Sanity checks
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException(nameof(text));
if (string.IsNullOrEmpty(yesCaption)) throw new ArgumentNullException(nameof(yesCaption));
if (string.IsNullOrEmpty(noCaption)) throw new ArgumentNullException(nameof(noCaption));
#endregion
return ShowTaskDialog(owner, text, severity, yes: yesCaption, no: noCaption, canCancel: true)
?? ShowMessageBox(owner, text, severity, MessageBoxButtons.YesNoCancel);
}
/// <summary>
/// Asks the user to choose between three options (yes/no/cancel) using a message box or task dialog.
/// </summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <returns><see cref="DialogResult.Yes"/> if Yes was chosen,
/// <see cref="DialogResult.No"/> if No was chosen,
/// <see cref="DialogResult.Cancel"/> otherwise.</returns>
public static DialogResult YesNoCancel(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity)
=> YesNoCancel(owner, text, severity, Resources.Yes, Resources.No);
/// <summary>Displays a message using a <see cref="MessageBox"/>.</summary>
/// <param name="owner">The parent window the displayed window is modal to; can be <c>null</c>.</param>
/// <param name="text">The message to be displayed.</param>
/// <param name="severity">How severe/important the message is.</param>
/// <param name="buttons">The buttons the user can click.</param>
private static DialogResult ShowMessageBox(IWin32Window? owner, [Localizable(true)] string text, MsgSeverity severity, MessageBoxButtons buttons)
{
// Handle RTL systems
MessageBoxOptions localizedOptions;
if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft) localizedOptions = MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign;
else localizedOptions = 0;
// Select icon based on message severity
var icon = severity switch
{
MsgSeverity.Warn => MessageBoxIcon.Warning,
MsgSeverity.Error => MessageBoxIcon.Error,
MsgSeverity.Info => MessageBoxIcon.Information,
_ => MessageBoxIcon.Information
};
// Display MessageDialog
return MessageBox.Show(owner, text, Application.ProductName, buttons, icon, MessageBoxDefaultButton.Button1, localizedOptions);
}
private static DialogResult? ShowTaskDialog(IWin32Window? owner, string text, MsgSeverity severity, string? yes = null, string? no = null, string? ok = null, string? cancel = null, bool canCancel = false)
{
#if NET20 || NET40
return null;
#else
if (!WindowsUtils.IsWindowsVista) return null;
var icon = severity switch
{
MsgSeverity.Warn => TaskDialogIcon.Warning,
MsgSeverity.Error => TaskDialogIcon.Error,
MsgSeverity.Info => TaskDialogIcon.Information,
_ => TaskDialogIcon.Information
};
string[] splitText = text.Replace("\r\n", "\n").Split(new[] {'\n'}, 2);
string heading = splitText[0];
string? details = (splitText.Length == 2) ? splitText[1] : null;
var buttons = new List<TaskDialogButton>();
void TryAddButton(DialogResult result, string? caption)
{
#if NET
if (string.IsNullOrEmpty(caption)) return;
string[] captionSplit = caption.Replace("\r\n", "\n").Split(new[] {'\n'}, 2);
buttons.Add(new TaskDialogCommandLinkButton(captionSplit[0], (captionSplit.Length == 2) ? captionSplit[1] : null) {Tag = result});
#else
if (!string.IsNullOrEmpty(caption))
buttons.Add(new TaskDialogButton((int)result, caption.Replace("\r\n", "\n")));
#endif
}
TryAddButton(DialogResult.Yes, yes);
TryAddButton(DialogResult.No, no);
TryAddButton(DialogResult.OK, ok);
#if NET
var taskDialog = new TaskDialogPage
{
Caption = Application.ProductName,
Icon = icon,
Heading = heading,
Text = details
};
taskDialog.Buttons.AddRange(buttons);
if (canCancel)
{
taskDialog.AllowCancel = true;
if (string.IsNullOrEmpty(ok)) buttons.Add(TaskDialogButton.Cancel);
else TryAddButton(DialogResult.Cancel, cancel);
}
if (severity >= MsgSeverity.Warn)
taskDialog.DefaultButton = buttons.Skip(1).FirstOrDefault(); // "No" or "Cancel"
var pushedButton = (owner == null)
? TaskDialog.ShowDialog(taskDialog)
: TaskDialog.ShowDialog(owner, taskDialog);
return pushedButton.Tag is DialogResult tag ? tag : DialogResult.Cancel;
#else
var taskDialog = new TaskDialog.TaskDialog
{
PositionRelativeToWindow = true,
WindowTitle = Application.ProductName,
MainIcon = icon,
MainInstruction = heading,
Content = details
};
if (buttons.Count != 0)
{
taskDialog.UseCommandLinks = true;
taskDialog.Buttons = buttons.ToArray();
}
if (canCancel)
{
taskDialog.AllowDialogCancellation = true;
if (string.IsNullOrEmpty(cancel))
taskDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
else
TryAddButton(DialogResult.Cancel, cancel);
}
if (severity >= MsgSeverity.Warn)
taskDialog.DefaultButton = (int)(string.IsNullOrEmpty(no) ? DialogResult.No : DialogResult.Cancel);
try
{
int result = owner == null ? taskDialog.Show() : taskDialog.Show(owner);
return (DialogResult)result;
}
catch (BadImageFormatException)
{
return null;
}
catch (EntryPointNotFoundException)
{
return null;
}
#endif
#endif
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ElementAccessExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WorkItem(636117)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnExpression()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
C[] c = new C[1];
c[0][$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingBracketWithParameters()
{
var markup =
@"class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingBracketWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[22, $$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[b: false, a: $$42|]];
}
}";
VerifyCurrentParameterName(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerBracket()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[42,$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
var x = [|c[42, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '[' };
char[] unexpectedCharacters = { ' ', '(', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_PropertyAlways()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_PropertyNever()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_PropertyAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
public int this[double d]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0),
};
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_GetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_SetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Foo()[$$
}
}";
var referencedCode = @"
public class Foo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region Indexed Property tests
[WorkItem(530811)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void IndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.IndexProp[$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var metadataItems = new List<SignatureHelpTestItem>();
metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0));
var projectReferenceItems = new List<SignatureHelpTestItem>();
projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: metadataItems,
expectedOrderedItemsSameSolution: projectReferenceItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
void foo()
{
var x = this[$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
#if BAR
void foo()
{
var x = this[$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ElementAccessExpressionSignatureHelpProvider();
}
[WorkItem(636117)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocation()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Foo()
{
var c = new C();
c[$$]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WorkItem(939417)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ConditionalIndexer()
{
var markup = @"
public class P
{
public int this[int z]
{
get
{
return 0;
}
}
public void foo()
{
P p = null;
p?[$$]
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void NonIdentifierConditionalIndexer()
{
var expected = new[] { new SignatureHelpTestItem("char string[int index]") };
Test(@"class C { void M() { """"?[$$ } }", expected); // inline with a string literal
Test(@"class C { void M() { """"?[/**/$$ } }", expected); // inline with a string literal and multiline comment
Test(@"class C { void M() { ("""")?[$$ } }", expected); // parenthesized expression
Test(@"class C { void M() { new System.String(' ', 1)?[$$ } }", expected); // new object expression
// more complicated parenthesized expression
Test(@"class C { void M() { (null as System.Collections.Generic.List<int>)?[$$ } }", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") });
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo[$$";
Test(markup);
}
}
}
}
| |
//
// TextEntryBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
namespace Xwt.Mac
{
public class TextEntryBackend: ViewBackend<NSView,ITextBoxEventSink>, ITextEntryBackend, ITextAreaBackend
{
int cacheSelectionStart, cacheSelectionLength;
bool checkMouseSelection;
public TextEntryBackend ()
{
}
internal TextEntryBackend (MacComboBox field)
{
ViewObject = field;
}
public override void Initialize ()
{
base.Initialize ();
if (ViewObject is MacComboBox) {
((MacComboBox)ViewObject).SetEntryEventSink (EventSink);
} else {
var view = new CustomTextField (EventSink, ApplicationContext);
ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view);
if (Frontend is Xwt.TextArea)
MultiLine = true;
else
MultiLine = false;
Wrap = WrapMode.None;
}
Frontend.MouseEntered += delegate {
checkMouseSelection = true;
};
Frontend.MouseExited += delegate {
checkMouseSelection = false;
HandleSelectionChanged ();
};
Frontend.MouseMoved += delegate {
if (checkMouseSelection)
HandleSelectionChanged ();
};
}
protected override void OnSizeToFit ()
{
Container.SizeToFit ();
}
CustomAlignedContainer Container {
get { return base.Widget as CustomAlignedContainer; }
}
public new NSTextField Widget {
get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; }
}
protected override Size GetNaturalSize ()
{
var s = base.GetNaturalSize ();
return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height);
}
#region ITextEntryBackend implementation
public string Text {
get {
return Widget.StringValue;
}
set {
Widget.StringValue = value ?? string.Empty;
}
}
public Alignment TextAlignment {
get {
return Widget.Alignment.ToAlignment ();
}
set {
Widget.Alignment = value.ToNSTextAlignment ();
}
}
public bool ReadOnly {
get {
return !Widget.Editable;
}
set {
Widget.Editable = !value;
}
}
public bool ShowFrame {
get {
return Widget.Bordered;
}
set {
Widget.Bordered = value;
}
}
public string PlaceholderText {
get {
return ((NSTextFieldCell) Widget.Cell).PlaceholderString;
}
set {
((NSTextFieldCell) Widget.Cell).PlaceholderString = value;
}
}
public bool MultiLine {
get {
if (Widget is MacComboBox)
return false;
return Widget.Cell.UsesSingleLineMode;
}
set {
if (Widget is MacComboBox)
return;
if (value) {
Widget.Cell.UsesSingleLineMode = false;
Widget.Cell.Scrollable = false;
} else {
Widget.Cell.UsesSingleLineMode = true;
Widget.Cell.Scrollable = true;
}
Container.ExpandVertically = value;
}
}
public WrapMode Wrap {
get {
if (!Widget.Cell.Wraps)
return WrapMode.None;
switch (Widget.Cell.LineBreakMode) {
case NSLineBreakMode.ByWordWrapping:
return WrapMode.Word;
case NSLineBreakMode.CharWrapping:
return WrapMode.Character;
default:
return WrapMode.None;
}
}
set {
if (value == WrapMode.None) {
Widget.Cell.Wraps = false;
} else {
Widget.Cell.Wraps = true;
switch (value) {
case WrapMode.Word:
case WrapMode.WordAndCharacter:
Widget.Cell.LineBreakMode = NSLineBreakMode.ByWordWrapping;
break;
case WrapMode.Character:
Widget.Cell.LineBreakMode = NSLineBreakMode.CharWrapping;
break;
}
}
}
}
public int CursorPosition {
get {
if (Widget.CurrentEditor == null)
return 0;
return Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new MonoMac.Foundation.NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionStart {
get {
if (Widget.CurrentEditor == null)
return 0;
return Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new MonoMac.Foundation.NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionLength {
get {
if (Widget.CurrentEditor == null)
return 0;
return Widget.CurrentEditor.SelectedRange.Length;
}
set {
Widget.CurrentEditor.SelectedRange = new MonoMac.Foundation.NSRange (SelectionStart, value);
HandleSelectionChanged ();
}
}
public string SelectedText {
get {
if (Widget.CurrentEditor == null)
return String.Empty;
int start = SelectionStart;
int end = start + SelectionLength;
if (start == end) return String.Empty;
try {
return Text.Substring (start, end - start);
} catch {
return String.Empty;
}
}
set {
int cacheSelStart = SelectionStart;
int pos = cacheSelStart;
if (SelectionLength > 0) {
Text = Text.Remove (pos, SelectionLength).Insert (pos, value);
}
SelectionStart = pos;
SelectionLength = value.Length;
HandleSelectionChanged ();
}
}
void HandleSelectionChanged ()
{
if (cacheSelectionStart != SelectionStart ||
cacheSelectionLength != SelectionLength) {
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
}
public override void SetFocus ()
{
Widget.BecomeFirstResponder ();
}
#endregion
}
class CustomTextField: NSTextField, IViewObject
{
ITextBoxEventSink eventSink;
ApplicationContext context;
public CustomTextField (ITextBoxEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
}
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
public override void DidChange (MonoMac.Foundation.NSNotification notification)
{
base.DidChange (notification);
context.InvokeUserCode (delegate {
eventSink.OnChanged ();
eventSink.OnSelectionChanged ();
});
}
int cachedCursorPosition;
public override void KeyUp (NSEvent theEvent)
{
base.KeyUp (theEvent);
if (cachedCursorPosition != CurrentEditor.SelectedRange.Location)
context.InvokeUserCode (delegate {
eventSink.OnSelectionChanged ();
});
cachedCursorPosition = CurrentEditor.SelectedRange.Location;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="AdGroupCriterionLabelServiceClient"/> instances.</summary>
public sealed partial class AdGroupCriterionLabelServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupCriterionLabelServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupCriterionLabelServiceSettings"/>.</returns>
public static AdGroupCriterionLabelServiceSettings GetDefault() => new AdGroupCriterionLabelServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupCriterionLabelServiceSettings"/> object with default settings.
/// </summary>
public AdGroupCriterionLabelServiceSettings()
{
}
private AdGroupCriterionLabelServiceSettings(AdGroupCriterionLabelServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupCriterionLabelSettings = existing.GetAdGroupCriterionLabelSettings;
MutateAdGroupCriterionLabelsSettings = existing.MutateAdGroupCriterionLabelsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupCriterionLabelServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionLabelServiceClient.GetAdGroupCriterionLabel</c> and
/// <c>AdGroupCriterionLabelServiceClient.GetAdGroupCriterionLabelAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupCriterionLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionLabelServiceClient.MutateAdGroupCriterionLabels</c> and
/// <c>AdGroupCriterionLabelServiceClient.MutateAdGroupCriterionLabelsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupCriterionLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupCriterionLabelServiceSettings"/> object.</returns>
public AdGroupCriterionLabelServiceSettings Clone() => new AdGroupCriterionLabelServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupCriterionLabelServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class AdGroupCriterionLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionLabelServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupCriterionLabelServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupCriterionLabelServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupCriterionLabelServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupCriterionLabelServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionLabelServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupCriterionLabelServiceClient Build()
{
AdGroupCriterionLabelServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupCriterionLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupCriterionLabelServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupCriterionLabelServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupCriterionLabelServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupCriterionLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupCriterionLabelServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupCriterionLabelServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionLabelServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionLabelServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupCriterionLabelService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group criteria.
/// </remarks>
public abstract partial class AdGroupCriterionLabelServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupCriterionLabelService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupCriterionLabelService scopes.</summary>
/// <remarks>
/// The default AdGroupCriterionLabelService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupCriterionLabelServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionLabelServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
public static stt::Task<AdGroupCriterionLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupCriterionLabelServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupCriterionLabelServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionLabelServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
public static AdGroupCriterionLabelServiceClient Create() => new AdGroupCriterionLabelServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupCriterionLabelServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupCriterionLabelServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
internal static AdGroupCriterionLabelServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionLabelServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient = new AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient(callInvoker);
return new AdGroupCriterionLabelServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupCriterionLabelService client</summary>
public virtual AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabel(new GetAdGroupCriterionLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabelAsync(new GetAdGroupCriterionLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(gagvr::AdGroupCriterionLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabel(new GetAdGroupCriterionLabelRequest
{
ResourceNameAsAdGroupCriterionLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(gagvr::AdGroupCriterionLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabelAsync(new GetAdGroupCriterionLabelRequest
{
ResourceNameAsAdGroupCriterionLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(gagvr::AdGroupCriterionLabelName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupCriterionLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriterionLabels(new MutateAdGroupCriterionLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriterionLabelsAsync(new MutateAdGroupCriterionLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupCriterionLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupCriterionLabelService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group criteria.
/// </remarks>
public sealed partial class AdGroupCriterionLabelServiceClientImpl : AdGroupCriterionLabelServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel> _callGetAdGroupCriterionLabel;
private readonly gaxgrpc::ApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse> _callMutateAdGroupCriterionLabels;
/// <summary>
/// Constructs a client wrapper for the AdGroupCriterionLabelService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupCriterionLabelServiceSettings"/> used within this client.
/// </param>
public AdGroupCriterionLabelServiceClientImpl(AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient, AdGroupCriterionLabelServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupCriterionLabelServiceSettings effectiveSettings = settings ?? AdGroupCriterionLabelServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupCriterionLabel = clientHelper.BuildApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel>(grpcClient.GetAdGroupCriterionLabelAsync, grpcClient.GetAdGroupCriterionLabel, effectiveSettings.GetAdGroupCriterionLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupCriterionLabel);
Modify_GetAdGroupCriterionLabelApiCall(ref _callGetAdGroupCriterionLabel);
_callMutateAdGroupCriterionLabels = clientHelper.BuildApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse>(grpcClient.MutateAdGroupCriterionLabelsAsync, grpcClient.MutateAdGroupCriterionLabels, effectiveSettings.MutateAdGroupCriterionLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupCriterionLabels);
Modify_MutateAdGroupCriterionLabelsApiCall(ref _callMutateAdGroupCriterionLabels);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupCriterionLabelApiCall(ref gaxgrpc::ApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel> call);
partial void Modify_MutateAdGroupCriterionLabelsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse> call);
partial void OnConstruction(AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient, AdGroupCriterionLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupCriterionLabelService client</summary>
public override AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupCriterionLabelRequest(ref GetAdGroupCriterionLabelRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupCriterionLabelsRequest(ref MutateAdGroupCriterionLabelsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionLabelRequest(ref request, ref callSettings);
return _callGetAdGroupCriterionLabel.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionLabelRequest(ref request, ref callSettings);
return _callGetAdGroupCriterionLabel.Async(request, callSettings);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriterionLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupCriterionLabels.Sync(request, callSettings);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriterionLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupCriterionLabels.Async(request, callSettings);
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using Amazon.S3.Util;
using Amazon.Util;
namespace Amazon.S3.Model
{
/// <summary>
/// The GetObjectMetadataResponse contains any headers returned by S3.
/// </summary>
public class GetObjectMetadataResponse : S3Response
{
private DateTime? lastModified;
private string etag;
private long contentLength;
private string contentType;
private string versionId;
private ServerSideEncryptionMethod serverSideEncryptionMethod;
private Expiration expiration;
private string websiteRedirectLocation;
private DateTime? restoreExpiration;
private bool restoreInProgress;
/// <summary>
/// Gets and sets the lastModified property.
/// </summary>
public DateTime LastModified
{
get { return this.lastModified.GetValueOrDefault(); }
set { this.lastModified = value; }
}
/// <summary>
/// Gets and sets the ETag property.
/// </summary>
public string ETag
{
get { return this.etag; }
set { this.etag = value; }
}
/// <summary>
/// Gets and sets the ContentType property.
/// </summary>
public string ContentType
{
get { return this.contentType; }
set { this.contentType = value; }
}
/// <summary>
/// Gets and sets the ContentLength property.
/// </summary>
public long ContentLength
{
get { return this.contentLength; }
set { this.contentLength = value; }
}
/// <summary>
/// Gets and sets the VersionId property.
/// This is the version-id of the S3 object
/// </summary>
public string VersionId
{
get { return this.versionId; }
set { this.versionId = value; }
}
/// <summary>
/// Gets and sets the ServerSideEncryptionMethod property.
/// Specifies the encryption used on the server to
/// store the content.
/// Default is None.
/// </summary>
public ServerSideEncryptionMethod ServerSideEncryptionMethod
{
get { return this.serverSideEncryptionMethod; }
set { this.serverSideEncryptionMethod = value; }
}
/// <summary>
/// Gets and sets the Expiration property.
/// Specifies the expiration date for the object and the
/// rule governing the expiration.
/// Is null if expiration is not applicable.
/// </summary>
public Expiration Expiration
{
get { return this.expiration; }
set { this.expiration = value; }
}
/// <summary>
/// Gets and sets the WebsiteRedirectLocation property.
/// If this is set then when a GET request is made from the S3 website endpoint a 301 HTTP status code
/// will be returned indicating a redirect with this value as the redirect location.
/// </summary>
public string WebsiteRedirectLocation
{
get { return this.websiteRedirectLocation; }
set { this.websiteRedirectLocation = value; }
}
/// <summary>
/// Gets and sets the RestoreExpiration property.
/// RestoreExpiration will be set for objects that have been restored from Amazon Glacier.
/// It indiciates for those objects how long the restored object will exist.
/// </summary>
public DateTime? RestoreExpiration
{
get { return this.restoreExpiration; }
set { this.restoreExpiration = value; }
}
/// <summary>
/// Gets and sets the RestoreInProgress
/// Will be true when the object is in the process of being restored from Amazon Glacier.
/// </summary>
public bool RestoreInProgress
{
get { return this.restoreInProgress; }
set { this.restoreInProgress = value; }
}
/// <summary>
/// Gets and sets the Headers property.
/// </summary>
public override System.Net.WebHeaderCollection Headers
{
set
{
base.Headers = value;
string hdr = null;
if (!String.IsNullOrEmpty(hdr = value.Get("Last-Modified")))
{
this.LastModified = DateTime.SpecifyKind(DateTime.ParseExact(hdr,
AWSSDKUtils.GMTDateFormat,
System.Globalization.CultureInfo.InvariantCulture),
DateTimeKind.Utc);
}
if (!String.IsNullOrEmpty(hdr = value.Get(AWSSDKUtils.ETagHeader)))
{
this.ETag = hdr;
}
if (!String.IsNullOrEmpty(hdr = value.Get(AWSSDKUtils.ContentTypeHeader)))
{
this.ContentType = hdr;
}
if (!String.IsNullOrEmpty(hdr = value.Get(AWSSDKUtils.ContentLengthHeader)))
{
this.ContentLength = System.Convert.ToInt64(hdr);
}
if (!System.String.IsNullOrEmpty(hdr = value.Get(Util.S3Constants.AmzVersionIdHeader)))
{
this.VersionId = hdr;
}
if (!System.String.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzExpirationHeader)))
{
this.Expiration = new Expiration(hdr);
}
if (!System.String.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzWebsiteRedirectLocationHeader)))
{
this.WebsiteRedirectLocation = hdr;
}
ServerSideEncryptionMethod = ServerSideEncryptionMethod.None;
if (!System.String.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzServerSideEncryptionHeader)))
{
this.ServerSideEncryptionMethod = (ServerSideEncryptionMethod)Enum.Parse(typeof(ServerSideEncryptionMethod), hdr);
}
if (!string.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzRestoreHeader)))
{
AmazonS3Util.ParseAmzRestoreHeader(hdr, out this.restoreInProgress, out this.restoreExpiration);
}
}
}
}
}
| |
--- /dev/null 2016-07-30 10:22:00.000000000 -0400
+++ src/Compilers/Core/Portable/PEWriter/MetadataSizes.cs 2016-07-30 10:29:27.534763000 -0400
@@ -0,0 +1,476 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Immutable;
+using System.Diagnostics;
+using System.Reflection.Metadata.Ecma335;
+using Roslyn.Utilities;
+
+namespace Microsoft.Cci
+{
+ internal sealed class MetadataSizes
+ {
+ private const int StreamAlignment = 4;
+
+ public const ulong DebugMetadataTablesMask =
+ 1UL << (int)TableIndex.Document |
+ 1UL << (int)TableIndex.MethodDebugInformation |
+ 1UL << (int)TableIndex.LocalScope |
+ 1UL << (int)TableIndex.LocalVariable |
+ 1UL << (int)TableIndex.LocalConstant |
+ 1UL << (int)TableIndex.ImportScope |
+ 1UL << (int)TableIndex.StateMachineMethod |
+ 1UL << (int)TableIndex.CustomDebugInformation;
+
+ public const ulong SortedDebugTables =
+ 1UL << (int)TableIndex.LocalScope |
+ 1UL << (int)TableIndex.StateMachineMethod |
+ 1UL << (int)TableIndex.CustomDebugInformation;
+
+ public readonly bool IsMinimalDelta;
+
+ // EnC delta tables are stored as uncompressed metadata table stream
+ public bool IsMetadataTableStreamCompressed => !IsMinimalDelta;
+
+ public readonly byte BlobIndexSize;
+ public readonly byte StringIndexSize;
+ public readonly byte GuidIndexSize;
+ public readonly byte CustomAttributeTypeCodedIndexSize;
+ public readonly byte DeclSecurityCodedIndexSize;
+ public readonly byte EventDefIndexSize;
+ public readonly byte FieldDefIndexSize;
+ public readonly byte GenericParamIndexSize;
+ public readonly byte HasConstantCodedIndexSize;
+ public readonly byte HasCustomAttributeCodedIndexSize;
+ public readonly byte HasFieldMarshalCodedIndexSize;
+ public readonly byte HasSemanticsCodedIndexSize;
+ public readonly byte ImplementationCodedIndexSize;
+ public readonly byte MemberForwardedCodedIndexSize;
+ public readonly byte MemberRefParentCodedIndexSize;
+ public readonly byte MethodDefIndexSize;
+ public readonly byte MethodDefOrRefCodedIndexSize;
+ public readonly byte ModuleRefIndexSize;
+ public readonly byte ParameterIndexSize;
+ public readonly byte PropertyDefIndexSize;
+ public readonly byte ResolutionScopeCodedIndexSize;
+ public readonly byte TypeDefIndexSize;
+ public readonly byte TypeDefOrRefCodedIndexSize;
+ public readonly byte TypeOrMethodDefCodedIndexSize;
+
+ public readonly byte DocumentIndexSize;
+ public readonly byte LocalVariableIndexSize;
+ public readonly byte LocalConstantIndexSize;
+ public readonly byte ImportScopeIndexSize;
+ public readonly byte HasCustomDebugInformationSize;
+
+ /// <summary>
+ /// Table row counts.
+ /// </summary>
+ public readonly ImmutableArray<int> RowCounts;
+
+ /// <summary>
+ /// Non-empty tables that are emitted into the metadata table stream.
+ /// </summary>
+ public readonly ulong PresentTablesMask;
+
+ /// <summary>
+ /// Non-empty tables stored in an external metadata table stream that might be referenced from the metadata table stream being emitted.
+ /// </summary>
+ public readonly ulong ExternalTablesMask;
+
+ /// <summary>
+ /// Exact (unaligned) heap sizes.
+ /// </summary>
+ public readonly ImmutableArray<int> HeapSizes;
+
+ /// <summary>
+ /// Overall size of metadata stream storage (stream headers, table stream, heaps, additional streams).
+ /// Aligned to <see cref="StreamAlignment"/>.
+ /// </summary>
+ public readonly int MetadataStreamStorageSize;
+
+ /// <summary>
+ /// The size of metadata stream (#- or #~). Aligned.
+ /// Aligned to <see cref="StreamAlignment"/>.
+ /// </summary>
+ public readonly int MetadataTableStreamSize;
+
+ /// <summary>
+ /// The size of #Pdb stream. Aligned.
+ /// </summary>
+ public readonly int StandalonePdbStreamSize;
+
+ /// <summary>
+ /// The size of IL stream.
+ /// </summary>
+ public readonly int ILStreamSize;
+
+ /// <summary>
+ /// The size of mapped field data stream.
+ /// Aligned to <see cref="MetadataWriter.MappedFieldDataAlignment"/>.
+ /// </summary>
+ public readonly int MappedFieldDataSize;
+
+ /// <summary>
+ /// The size of managed resource data stream.
+ /// Aligned to <see cref="MetadataWriter.ManagedResourcesDataAlignment"/>.
+ /// </summary>
+ public readonly int ResourceDataSize;
+
+ /// <summary>
+ /// Size of strong name hash.
+ /// </summary>
+ public readonly int StrongNameSignatureSize;
+
+ public MetadataSizes(
+ ImmutableArray<int> rowCounts,
+ ImmutableArray<int> heapSizes,
+ int ilStreamSize,
+ int mappedFieldDataSize,
+ int resourceDataSize,
+ int strongNameSignatureSize,
+ bool isMinimalDelta,
+ bool emitStandaloneDebugMetadata,
+ bool isStandaloneDebugMetadata)
+ {
+ Debug.Assert(rowCounts.Length == MetadataTokens.TableCount);
+ Debug.Assert(heapSizes.Length == MetadataTokens.HeapCount);
+ Debug.Assert(!isStandaloneDebugMetadata || emitStandaloneDebugMetadata);
+
+ const byte large = 4;
+ const byte small = 2;
+
+ this.RowCounts = rowCounts;
+ this.HeapSizes = heapSizes;
+ this.ResourceDataSize = resourceDataSize;
+ this.ILStreamSize = ilStreamSize;
+ this.MappedFieldDataSize = mappedFieldDataSize;
+ this.StrongNameSignatureSize = strongNameSignatureSize;
+ this.IsMinimalDelta = isMinimalDelta;
+
+ this.BlobIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.Blob] > ushort.MaxValue) ? large : small;
+ this.StringIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.String] > ushort.MaxValue) ? large : small;
+ this.GuidIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.Guid] > ushort.MaxValue) ? large : small;
+
+ ulong allTables = ComputeNonEmptyTableMask(rowCounts);
+ if (!emitStandaloneDebugMetadata)
+ {
+ // all tables
+ PresentTablesMask = allTables;
+ ExternalTablesMask = 0;
+ }
+ else if (isStandaloneDebugMetadata)
+ {
+ // debug tables:
+ PresentTablesMask = allTables & DebugMetadataTablesMask;
+ ExternalTablesMask = allTables & ~DebugMetadataTablesMask;
+ }
+ else
+ {
+ // type-system tables only:
+ PresentTablesMask = allTables & ~DebugMetadataTablesMask;
+ ExternalTablesMask = 0;
+ }
+
+ this.CustomAttributeTypeCodedIndexSize = this.GetReferenceByteSize(3, TableIndex.MethodDef, TableIndex.MemberRef);
+ this.DeclSecurityCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.MethodDef, TableIndex.TypeDef);
+ this.EventDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Event);
+ this.FieldDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Field);
+ this.GenericParamIndexSize = this.GetReferenceByteSize(0, TableIndex.GenericParam);
+ this.HasConstantCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.Field, TableIndex.Param, TableIndex.Property);
+
+ this.HasCustomAttributeCodedIndexSize = this.GetReferenceByteSize(5,
+ TableIndex.MethodDef,
+ TableIndex.Field,
+ TableIndex.TypeRef,
+ TableIndex.TypeDef,
+ TableIndex.Param,
+ TableIndex.InterfaceImpl,
+ TableIndex.MemberRef,
+ TableIndex.Module,
+ TableIndex.DeclSecurity,
+ TableIndex.Property,
+ TableIndex.Event,
+ TableIndex.StandAloneSig,
+ TableIndex.ModuleRef,
+ TableIndex.TypeSpec,
+ TableIndex.Assembly,
+ TableIndex.AssemblyRef,
+ TableIndex.File,
+ TableIndex.ExportedType,
+ TableIndex.ManifestResource,
+ TableIndex.GenericParam,
+ TableIndex.GenericParamConstraint,
+ TableIndex.MethodSpec);
+
+ this.HasFieldMarshalCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Field, TableIndex.Param);
+ this.HasSemanticsCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Event, TableIndex.Property);
+ this.ImplementationCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.File, TableIndex.AssemblyRef, TableIndex.ExportedType);
+ this.MemberForwardedCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Field, TableIndex.MethodDef);
+ this.MemberRefParentCodedIndexSize = this.GetReferenceByteSize(3, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.ModuleRef, TableIndex.MethodDef, TableIndex.TypeSpec);
+ this.MethodDefIndexSize = this.GetReferenceByteSize(0, TableIndex.MethodDef);
+ this.MethodDefOrRefCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.MethodDef, TableIndex.MemberRef);
+ this.ModuleRefIndexSize = this.GetReferenceByteSize(0, TableIndex.ModuleRef);
+ this.ParameterIndexSize = this.GetReferenceByteSize(0, TableIndex.Param);
+ this.PropertyDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Property);
+ this.ResolutionScopeCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.Module, TableIndex.ModuleRef, TableIndex.AssemblyRef, TableIndex.TypeRef);
+ this.TypeDefIndexSize = this.GetReferenceByteSize(0, TableIndex.TypeDef);
+ this.TypeDefOrRefCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.TypeSpec);
+ this.TypeOrMethodDefCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.TypeDef, TableIndex.MethodDef);
+
+ this.DocumentIndexSize = this.GetReferenceByteSize(0, TableIndex.Document);
+ this.LocalVariableIndexSize = this.GetReferenceByteSize(0, TableIndex.LocalVariable);
+ this.LocalConstantIndexSize = this.GetReferenceByteSize(0, TableIndex.LocalConstant);
+ this.ImportScopeIndexSize = this.GetReferenceByteSize(0, TableIndex.ImportScope);
+
+ this.HasCustomDebugInformationSize = this.GetReferenceByteSize(5,
+ TableIndex.MethodDef,
+ TableIndex.Field,
+ TableIndex.TypeRef,
+ TableIndex.TypeDef,
+ TableIndex.Param,
+ TableIndex.InterfaceImpl,
+ TableIndex.MemberRef,
+ TableIndex.Module,
+ TableIndex.DeclSecurity,
+ TableIndex.Property,
+ TableIndex.Event,
+ TableIndex.StandAloneSig,
+ TableIndex.ModuleRef,
+ TableIndex.TypeSpec,
+ TableIndex.Assembly,
+ TableIndex.AssemblyRef,
+ TableIndex.File,
+ TableIndex.ExportedType,
+ TableIndex.ManifestResource,
+ TableIndex.GenericParam,
+ TableIndex.GenericParamConstraint,
+ TableIndex.MethodSpec,
+ TableIndex.Document,
+ TableIndex.LocalScope,
+ TableIndex.LocalVariable,
+ TableIndex.LocalConstant,
+ TableIndex.ImportScope);
+
+ int size = this.CalculateTableStreamHeaderSize();
+
+ size += GetTableSize(TableIndex.Module, 2 + 3 * this.GuidIndexSize + this.StringIndexSize);
+ size += GetTableSize(TableIndex.TypeRef, this.ResolutionScopeCodedIndexSize + this.StringIndexSize + this.StringIndexSize);
+ size += GetTableSize(TableIndex.TypeDef, 4 + this.StringIndexSize + this.StringIndexSize + this.TypeDefOrRefCodedIndexSize + this.FieldDefIndexSize + this.MethodDefIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.FieldPtr] == 0);
+ size += GetTableSize(TableIndex.Field, 2 + this.StringIndexSize + this.BlobIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.MethodPtr] == 0);
+ size += GetTableSize(TableIndex.MethodDef, 8 + this.StringIndexSize + this.BlobIndexSize + this.ParameterIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.ParamPtr] == 0);
+ size += GetTableSize(TableIndex.Param, 4 + this.StringIndexSize);
+ size += GetTableSize(TableIndex.InterfaceImpl, this.TypeDefIndexSize + this.TypeDefOrRefCodedIndexSize);
+ size += GetTableSize(TableIndex.MemberRef, this.MemberRefParentCodedIndexSize + this.StringIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.Constant, 2 + this.HasConstantCodedIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.CustomAttribute, this.HasCustomAttributeCodedIndexSize + this.CustomAttributeTypeCodedIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.FieldMarshal, this.HasFieldMarshalCodedIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.DeclSecurity, 2 + this.DeclSecurityCodedIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.ClassLayout, 6 + this.TypeDefIndexSize);
+ size += GetTableSize(TableIndex.FieldLayout, 4 + this.FieldDefIndexSize);
+ size += GetTableSize(TableIndex.StandAloneSig, this.BlobIndexSize);
+ size += GetTableSize(TableIndex.EventMap, this.TypeDefIndexSize + this.EventDefIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.EventPtr] == 0);
+ size += GetTableSize(TableIndex.Event, 2 + this.StringIndexSize + this.TypeDefOrRefCodedIndexSize);
+ size += GetTableSize(TableIndex.PropertyMap, this.TypeDefIndexSize + this.PropertyDefIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.PropertyPtr] == 0);
+ size += GetTableSize(TableIndex.Property, 2 + this.StringIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.MethodSemantics, 2 + this.MethodDefIndexSize + this.HasSemanticsCodedIndexSize);
+ size += GetTableSize(TableIndex.MethodImpl, 0 + this.TypeDefIndexSize + this.MethodDefOrRefCodedIndexSize + this.MethodDefOrRefCodedIndexSize);
+ size += GetTableSize(TableIndex.ModuleRef, 0 + this.StringIndexSize);
+ size += GetTableSize(TableIndex.TypeSpec, 0 + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.ImplMap, 2 + this.MemberForwardedCodedIndexSize + this.StringIndexSize + this.ModuleRefIndexSize);
+ size += GetTableSize(TableIndex.FieldRva, 4 + this.FieldDefIndexSize);
+ size += GetTableSize(TableIndex.EncLog, 8);
+ size += GetTableSize(TableIndex.EncMap, 4);
+ size += GetTableSize(TableIndex.Assembly, 16 + this.BlobIndexSize + this.StringIndexSize + this.StringIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.AssemblyProcessor] == 0);
+ Debug.Assert(rowCounts[(int)TableIndex.AssemblyOS] == 0);
+ size += GetTableSize(TableIndex.AssemblyRef, 12 + this.BlobIndexSize + this.StringIndexSize + this.StringIndexSize + this.BlobIndexSize);
+ Debug.Assert(rowCounts[(int)TableIndex.AssemblyRefProcessor] == 0);
+ Debug.Assert(rowCounts[(int)TableIndex.AssemblyRefOS] == 0);
+ size += GetTableSize(TableIndex.File, 4 + this.StringIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.ExportedType, 8 + this.StringIndexSize + this.StringIndexSize + this.ImplementationCodedIndexSize);
+ size += GetTableSize(TableIndex.ManifestResource, 8 + this.StringIndexSize + this.ImplementationCodedIndexSize);
+ size += GetTableSize(TableIndex.NestedClass, this.TypeDefIndexSize + this.TypeDefIndexSize);
+ size += GetTableSize(TableIndex.GenericParam, 4 + this.TypeOrMethodDefCodedIndexSize + this.StringIndexSize);
+ size += GetTableSize(TableIndex.MethodSpec, this.MethodDefOrRefCodedIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.GenericParamConstraint, this.GenericParamIndexSize + this.TypeDefOrRefCodedIndexSize);
+
+ size += GetTableSize(TableIndex.Document, this.BlobIndexSize + this.GuidIndexSize + this.BlobIndexSize + this.GuidIndexSize);
+ size += GetTableSize(TableIndex.MethodDebugInformation, this.DocumentIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.LocalScope, this.MethodDefIndexSize + this.ImportScopeIndexSize + this.LocalVariableIndexSize + this.LocalConstantIndexSize + 4 + 4);
+ size += GetTableSize(TableIndex.LocalVariable, 2 + 2 + this.StringIndexSize);
+ size += GetTableSize(TableIndex.LocalConstant, this.StringIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.ImportScope, this.ImportScopeIndexSize + this.BlobIndexSize);
+ size += GetTableSize(TableIndex.StateMachineMethod, this.MethodDefIndexSize + this.MethodDefIndexSize);
+ size += GetTableSize(TableIndex.CustomDebugInformation, this.HasCustomDebugInformationSize + this.GuidIndexSize + this.BlobIndexSize);
+
+ // +1 for terminating 0 byte
+ size = BitArithmeticUtilities.Align(size + 1, StreamAlignment);
+
+ this.MetadataTableStreamSize = size;
+
+ size += GetAlignedHeapSize(HeapIndex.String);
+ size += GetAlignedHeapSize(HeapIndex.UserString);
+ size += GetAlignedHeapSize(HeapIndex.Guid);
+ size += GetAlignedHeapSize(HeapIndex.Blob);
+
+ this.StandalonePdbStreamSize = isStandaloneDebugMetadata ? CalculateStandalonePdbStreamSize() : 0;
+ size += this.StandalonePdbStreamSize;
+
+ this.MetadataStreamStorageSize = size;
+ }
+
+ public bool IsStandaloneDebugMetadata => StandalonePdbStreamSize > 0;
+
+ public bool IsPresent(TableIndex table) => (PresentTablesMask & (1UL << (int)table)) != 0;
+
+ /// <summary>
+ /// Metadata header size.
+ /// Includes:
+ /// - metadata storage signature
+ /// - storage header
+ /// - stream headers
+ /// </summary>
+ public int MetadataHeaderSize
+ {
+ get
+ {
+ const int RegularStreamHeaderSizes = 76;
+ const int MinimalDeltaMarkerStreamHeaderSize = 16;
+ const int StandalonePdbStreamHeaderSize = 16;
+
+ Debug.Assert(RegularStreamHeaderSizes ==
+ GetMetadataStreamHeaderSize("#~") +
+ GetMetadataStreamHeaderSize("#Strings") +
+ GetMetadataStreamHeaderSize("#US") +
+ GetMetadataStreamHeaderSize("#GUID") +
+ GetMetadataStreamHeaderSize("#Blob"));
+
+ Debug.Assert(MinimalDeltaMarkerStreamHeaderSize == GetMetadataStreamHeaderSize("#JTD"));
+ Debug.Assert(StandalonePdbStreamHeaderSize == GetMetadataStreamHeaderSize("#Pdb"));
+
+ return
+ sizeof(uint) + // signature
+ sizeof(ushort) + // major version
+ sizeof(ushort) + // minor version
+ sizeof(uint) + // reserved
+ sizeof(uint) + // padded metadata version length
+ MetadataVersionPaddedLength + // metadata version
+ sizeof(ushort) + // storage header: reserved
+ sizeof(ushort) + // stream count
+ (IsStandaloneDebugMetadata ? StandalonePdbStreamHeaderSize : 0) +
+ RegularStreamHeaderSizes +
+ (IsMinimalDelta ? MinimalDeltaMarkerStreamHeaderSize : 0);
+ }
+ }
+
+ // version must be 12 chars long, this observation is not supported by the standard
+ public const int MetadataVersionPaddedLength = 12;
+
+ public static int GetMetadataStreamHeaderSize(string streamName)
+ {
+ return
+ sizeof(int) + // offset
+ sizeof(int) + // size
+ BitArithmeticUtilities.Align(streamName.Length + 1, 4); // zero-terminated name, padding
+ }
+
+ /// <summary>
+ /// Total size of metadata (header and all streams).
+ /// </summary>
+ public int MetadataSize => MetadataHeaderSize + MetadataStreamStorageSize;
+
+ public int GetAlignedHeapSize(HeapIndex index)
+ {
+ return BitArithmeticUtilities.Align(HeapSizes[(int)index], StreamAlignment);
+ }
+
+ internal int CalculateTableStreamHeaderSize()
+ {
+ int result = sizeof(int) + // Reserved
+ sizeof(short) + // Version (major, minor)
+ sizeof(byte) + // Heap index sizes
+ sizeof(byte) + // Bit width of RowId
+ sizeof(long) + // Valid table mask
+ sizeof(long); // Sorted table mask
+
+ // present table row counts
+ for (int i = 0; i < RowCounts.Length; i++)
+ {
+ if (((1UL << i) & PresentTablesMask) != 0)
+ {
+ result += sizeof(int);
+ }
+ }
+
+ return result;
+ }
+
+ internal const int PdbIdSize = 20;
+
+ internal int CalculateStandalonePdbStreamSize()
+ {
+ int result = PdbIdSize + // PDB ID
+ sizeof(int) + // EntryPoint
+ sizeof(long); // ReferencedTypeSystemTables
+
+ // external table row counts
+ for (int i = 0; i < RowCounts.Length; i++)
+ {
+ if (((1UL << i) & ExternalTablesMask) != 0)
+ {
+ result += sizeof(int);
+ }
+ }
+
+ Debug.Assert(result % StreamAlignment == 0);
+ return result;
+ }
+
+ private static ulong ComputeNonEmptyTableMask(ImmutableArray<int> rowCounts)
+ {
+ ulong mask = 0;
+ for (int i = 0; i < rowCounts.Length; i++)
+ {
+ if (rowCounts[i] > 0)
+ {
+ mask |= (1UL << i);
+ }
+ }
+
+ return mask;
+ }
+
+ private int GetTableSize(TableIndex index, int rowSize)
+ {
+ return (PresentTablesMask & (1UL << (int)index)) != 0 ? RowCounts[(int)index] * rowSize : 0;
+ }
+
+ private byte GetReferenceByteSize(int tagBitSize, params TableIndex[] tables)
+ {
+ const byte large = 4;
+ const byte small = 2;
+ const int smallBitCount = 16;
+
+ return (!IsMetadataTableStreamCompressed || !ReferenceFits(smallBitCount - tagBitSize, tables)) ? large : small;
+ }
+
+ private bool ReferenceFits(int bitCount, TableIndex[] tables)
+ {
+ int maxIndex = (1 << bitCount) - 1;
+ foreach (TableIndex table in tables)
+ {
+ if (RowCounts[(int)table] > maxIndex)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Runtime.InteropServices
{
internal class InternalTypes
{
internal static RuntimeTypeHandle IUnknown = typeof(System.Runtime.InteropServices.__com_IUnknown).TypeHandle;
internal static RuntimeTypeHandle ICCW = typeof(System.Runtime.InteropServices.__com_ICCW).TypeHandle;
internal static RuntimeTypeHandle IMarshal = typeof(System.Runtime.InteropServices.__com_IMarshal).TypeHandle;
internal static RuntimeTypeHandle IDispatch = typeof(System.Runtime.InteropServices.__com_IDispatch).TypeHandle;
internal static RuntimeTypeHandle IInspectable = typeof(System.Runtime.InteropServices.__com_IInspectable).TypeHandle;
#if ENABLE_MIN_WINRT
internal static RuntimeTypeHandle IActivationFactoryInternal = typeof(System.Runtime.InteropServices.WindowsRuntime.IActivationFactoryInternal).TypeHandle;
#endif
#if ENABLE_WINRT
internal static RuntimeTypeHandle ICustomPropertyProvider = typeof(System.Runtime.InteropServices.__com_ICustomPropertyProvider).TypeHandle;
internal static RuntimeTypeHandle IWeakReferenceSource = typeof(System.Runtime.InteropServices.__com_IWeakReferenceSource).TypeHandle;
internal static RuntimeTypeHandle IWeakReference = typeof(System.Runtime.InteropServices.__com_IWeakReference).TypeHandle;
internal static RuntimeTypeHandle IJupiterObject = typeof(System.Runtime.InteropServices.__com_IJupiterObject).TypeHandle;
internal static RuntimeTypeHandle IStringable = typeof(System.Runtime.InteropServices.__com_IStringable).TypeHandle;
internal static RuntimeTypeHandle IManagedActivationFactory = typeof(System.Runtime.InteropServices.WindowsRuntime.IManagedActivationFactory).TypeHandle;
internal static RuntimeTypeHandle IRestrictedErrorInfo = typeof(System.Runtime.InteropServices.ExceptionHelpers.__com_IRestrictedErrorInfo).TypeHandle;
internal static RuntimeTypeHandle HSTRING = typeof(System.Runtime.InteropServices.HSTRING).TypeHandle;
#endif
}
/// <summary>
/// Singleton module that managed types implemented internally, rather than in MCG-generated code.
/// This works together with interface implementations in StandardInterfaces.cs
/// NOTE: Interfaces defined here are implemented by CCWs, but user might be able to override them
/// depending on the interface
/// </summary>
internal class InternalModule : McgModule
{
// The internal module is always lower priority than all other modules.
private const int PriorityForInternalModule = -1;
unsafe internal InternalModule()
: base(
PriorityForInternalModule,
s_interfaceData,
null, // CCWTemplateData
null, // CCWTemplateInterfaceList
null, // classData,
null, // boxingData,
null, // additionalClassData,
null, // collectionData,
null, // DelegateData
null, // CCWFactories
null, // structMarshalData
null, // unsafeStructFieldOffsetData
null, // interfaceMarshalData
null, // hashcodeVerify
null, // interfaceTypeInfo_Hashtable
null, // ccwTemplateData_Hashtable
null, // classData_Hashtable
null, // collectionData_Hashtable
null // boxingData_Hashtable
)
{
// Following code is disabled due to lazy static constructor dependency from McgModule which is
// static eager constructor. Undo this when McgCurrentModule is using ModuleConstructorAttribute
#if EAGER_CTOR_WORKAROUND
for (int i = 0; i < s_interfaceData.Length; i++)
{
Debug.Assert((s_interfaceData[i].Flags & McgInterfaceFlags.useSharedCCW) == 0);
}
#endif
}
// IUnknown
static internal McgInterfaceData s_IUnknown = new McgInterfaceData
{
ItfType = InternalTypes.IUnknown,
ItfGuid = Interop.COM.IID_IUnknown,
CcwVtable = __vtable_IUnknown.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
// IInspectable
static internal McgInterfaceData s_IInspectable = new McgInterfaceData
{
ItfType = InternalTypes.IInspectable,
ItfGuid = Interop.COM.IID_IInspectable,
CcwVtable = __vtable_IInspectable.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal | McgInterfaceFlags.isIInspectable,
};
#if ENABLE_MIN_WINRT
// IActivationFactoryInternal
static internal McgInterfaceData s_IActivationFactoryInternal = new McgInterfaceData
{
ItfType = InternalTypes.IActivationFactoryInternal,
ItfGuid = Interop.COM.IID_IActivationFactoryInternal,
CcwVtable = __vtable_IActivationFactoryInternal.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
#endif
#if ENABLE_WINRT
// ICustomPropertyProvider
static internal McgInterfaceData s_ICustomPropertyProvider = new McgInterfaceData
{
ItfType = InternalTypes.ICustomPropertyProvider,
ItfGuid = Interop.COM.IID_ICustomPropertyProvider,
CcwVtable = __vtable_ICustomPropertyProvider.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal | McgInterfaceFlags.isIInspectable,
};
// IWeakReferenceSource
static internal McgInterfaceData s_IWeakReferenceSource = new McgInterfaceData
{
ItfType = InternalTypes.IWeakReferenceSource,
ItfGuid = Interop.COM.IID_IWeakReferenceSource,
CcwVtable = __vtable_IWeakReferenceSource.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
// IWeakReference
static internal McgInterfaceData s_IWeakReference = new McgInterfaceData
{
ItfType = InternalTypes.IWeakReference,
ItfGuid = Interop.COM.IID_IWeakReference,
CcwVtable = __vtable_IWeakReference.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
#endif
// ICCW
static internal McgInterfaceData s_ICCW = new McgInterfaceData
{
ItfType = InternalTypes.ICCW,
ItfGuid = Interop.COM.IID_ICCW,
CcwVtable = __vtable_ICCW.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
#if ENABLE_WINRT
// IJupiterObject
static internal McgInterfaceData s_IJupiterObject = new McgInterfaceData
{
ItfType = InternalTypes.IJupiterObject,
ItfGuid = Interop.COM.IID_IJupiterObject,
Flags = McgInterfaceFlags.isInternal,
};
// IStringable
static internal McgInterfaceData s_IStringable = new McgInterfaceData
{
ItfType = InternalTypes.IStringable,
ItfGuid = Interop.COM.IID_IStringable,
CcwVtable = __vtable_IStringable.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
// IManagedActivationFactory
static internal McgInterfaceData s_IManagedActivationFactory = new McgInterfaceData
{
ItfType = InternalTypes.IManagedActivationFactory,
ItfGuid = Interop.COM.IID_IManagedActivationFactory,
CcwVtable = __vtable_IManagedActivationFactory.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
// IRestrictedErrorInfo
static internal McgInterfaceData s_IRestrictedErrorInfo = new McgInterfaceData
{
ItfType = InternalTypes.IRestrictedErrorInfo,
ItfGuid = Interop.COM.IID_IRestrictedErrorInfo,
Flags = McgInterfaceFlags.isInternal,
};
#endif
// IMarshal
static internal McgInterfaceData s_IMarshal = new McgInterfaceData
{
ItfType = InternalTypes.IMarshal,
ItfGuid = Interop.COM.IID_IMarshal,
CcwVtable = __vtable_IMarshal.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
// IDispatch
static internal McgInterfaceData s_IDispatch = new McgInterfaceData
{
ItfType = InternalTypes.IDispatch,
ItfGuid = Interop.COM.IID_IDispatch,
CcwVtable = __vtable_IDispatch.GetVtableFuncPtr(),
Flags = McgInterfaceFlags.isInternal,
};
#if ENABLE_WINRT
// HSTRING, just needed for TypeHandle comparison
static internal McgInterfaceData s_HSTRING = new McgInterfaceData
{
ItfType = InternalTypes.HSTRING
};
#endif
static readonly McgInterfaceData[] s_interfaceData = new McgInterfaceData[] {
s_IUnknown,
s_IInspectable,
#if ENABLE_WINRT
s_ICustomPropertyProvider,
s_IWeakReferenceSource,
s_IWeakReference,
#endif
s_ICCW,
#if ENABLE_MIN_WINRT
s_IActivationFactoryInternal,
#endif
#if ENABLE_WINRT
s_IJupiterObject,
s_IStringable,
s_IManagedActivationFactory,
s_IRestrictedErrorInfo,
#endif
s_IMarshal,
s_IDispatch,
#if ENABLE_WINRT
s_HSTRING
#endif
};
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.Format
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using NUnit.Framework;
using NPOI.HSSF.UserModel;
using NPOI.SS.Format;
using NPOI.SS.UserModel;
using NPOI.Util;
using TestCases.SS;
using System.Diagnostics;
/**
* This class is a base class for spreadsheet-based tests, such as are used for
* cell formatting. This Reads tests from the spreadsheet, as well as Reading
* flags that can be used to paramterize these tests.
* <p/>
* Each test has four parts: The expected result (column A), the format string
* (column B), the value to format (column C), and a comma-Separated list of
* categores that this test falls in1. Normally all tests are Run, but if the
* flag "Categories" is not empty, only tests that have at least one category
* listed in "Categories" are Run.
*/
//[TestFixture]
public class CellFormatTestBase
{
private static POILogger logger = POILogFactory.GetLogger(typeof(CellFormatTestBase));
private ITestDataProvider _testDataProvider;
protected IWorkbook workbook;
private String testFile;
private Dictionary<String, String> testFlags;
private bool tryAllColors;
//private Label label;
private static String[] COLOR_NAMES =
{"Black", "Red", "Green", "Blue", "Yellow", "Cyan", "Magenta",
"White"};
private static Color[] COLORS = { Color.Black, Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Cyan, Color.Magenta, Color.Wheat };
public static Color TEST_COLOR = Color.Orange; //Darker();
protected CellFormatTestBase(ITestDataProvider testDataProvider)
{
_testDataProvider = testDataProvider;
}
public abstract class CellValue
{
public abstract Object GetValue(ICell cell);
public Color GetColor(ICell cell)
{
return TEST_COLOR;
}
public virtual void Equivalent(String expected, String actual, CellFormatPart format)
{
Assert.AreEqual('"' + expected + '"',
'"' + actual + '"', "format \"" + format.ToString() + "\"");
}
}
protected void RunFormatTests(String workbookName, CellValue valueGetter)
{
OpenWorkbook(workbookName);
ReadFlags(workbook);
SortedList<string, object> runCategories = new SortedList<string, object>(StringComparer.InvariantCultureIgnoreCase);
String RunCategoryList = flagString("Categories", "");
Regex regex = new Regex("\\s*,\\s*");
if (RunCategoryList != null)
{
foreach (string s in regex.Split(RunCategoryList))
if (!runCategories.ContainsKey(s))
runCategories.Add(s, null);
runCategories.Remove(""); // this can be found and means nothing
}
ISheet sheet = workbook.GetSheet("Tests");
int end = sheet.LastRowNum;
// Skip the header row, therefore "+ 1"
for (int r = sheet.FirstRowNum + 1; r <= end; r++)
{
IRow row = sheet.GetRow(r);
if (row == null)
continue;
int cellnum = 0;
String expectedText = row.GetCell(cellnum).StringCellValue;
String format = row.GetCell(1).StringCellValue;
String testCategoryList = row.GetCell(3).StringCellValue;
bool byCategory = RunByCategory(runCategories, testCategoryList);
if ((expectedText.Length > 0 || format.Length > 0) && byCategory)
{
ICell cell = row.GetCell(2);
Debug.WriteLine(string.Format("expectedText: {0}, format:{1}", expectedText, format));
if (format == "hh:mm:ss a/p")
expectedText = expectedText.ToUpper();
else if (format == "H:M:S.00 a/p")
expectedText = expectedText.ToUpper();
tryFormat(r, expectedText, format, valueGetter, cell);
}
}
}
/**
* Open a given workbook.
*
* @param workbookName The workbook name. This is presumed to live in the
* "spreadsheets" directory under the directory named in
* the Java property "POI.testdata.path".
*
* @throws IOException
*/
protected void OpenWorkbook(String workbookName)
{
workbook = _testDataProvider.OpenSampleWorkbook(workbookName);
workbook.MissingCellPolicy = MissingCellPolicy.CREATE_NULL_AS_BLANK;//Row.CREATE_NULL_AS_BLANK);
testFile = workbookName;
}
/**
* Read the flags from the workbook. Flags are on the sheet named "Flags",
* and consist of names in column A and values in column B. These are Put
* into a map that can be queried later.
*
* @param wb The workbook to look in1.
*/
private void ReadFlags(IWorkbook wb)
{
ISheet flagSheet = wb.GetSheet("Flags");
testFlags = new Dictionary<String, String>();
if (flagSheet != null)
{
int end = flagSheet.LastRowNum;
// Skip the header row, therefore "+ 1"
for (int r = flagSheet.FirstRowNum + 1; r <= end; r++)
{
IRow row = flagSheet.GetRow(r);
if (row == null)
continue;
String flagName = row.GetCell(0).StringCellValue;
String flagValue = row.GetCell(1).StringCellValue;
if (flagName.Length > 0)
{
testFlags.Add(flagName, flagValue);
}
}
}
tryAllColors = flagBoolean("AllColors", true);
}
/**
* Returns <tt>true</tt> if any of the categories for this run are Contained
* in the test's listed categories.
*
* @param categories The categories of tests to be Run. If this is
* empty, then all tests will be Run.
* @param testCategories The categories that this test is in1. This is a
* comma-Separated list. If <em>any</em> tests in
* this list are in <tt>categories</tt>, the test will
* be Run.
*
* @return <tt>true</tt> if the test should be Run.
*/
private bool RunByCategory(SortedList<string, object> categories,
String testCategories)
{
if (categories.Count == 0)
return true;
// If there are specified categories, find out if this has one of them
Regex regex = new Regex("\\s*,\\s*");
foreach (String category in regex.Split(testCategories))//.Split("\\s*,\\s*"))
{
if (categories.ContainsKey(category))
{
return true;
}
}
return false;
}
Color labelForeColor;
string labelText;
private void tryFormat(int row, String expectedText, String desc,
CellValue getter, ICell cell)
{
Object value = getter.GetValue(cell);
Color testColor = getter.GetColor(cell);
if (testColor == null)
testColor = TEST_COLOR;
labelForeColor = testColor;
labelText = "xyzzy";
logger.Log(POILogger.INFO, String.Format("Row %d: \"%s\" -> \"%s\": expected \"%s\"", row + 1,
value.ToString(), desc, expectedText));
String actualText = tryColor(desc, null, getter, value, expectedText,
testColor);
logger.Log(POILogger.INFO, String.Format(", actual \"%s\")%n", actualText));
if (tryAllColors && testColor != TEST_COLOR)
{
for (int i = 0; i < COLOR_NAMES.Length; i++)
{
String cname = COLOR_NAMES[i];
tryColor(desc, cname, getter, value, expectedText, COLORS[i]);
}
}
}
private String tryColor(String desc, String cname, CellValue getter,
Object value, String expectedText, Color expectedColor)
{
if (cname != null)
desc = "[" + cname + "]" + desc;
Color origColor = labelForeColor;
CellFormatPart format = new CellFormatPart(desc);
CellFormatResult result = format.Apply(value);
if (!result.Applies)
{
// If this doesn't Apply, no color change is expected
expectedColor = origColor;
}
String actualText = result.Text;
Color actualColor = labelForeColor;
getter.Equivalent(expectedText, actualText, format);
Assert.AreEqual(
expectedColor, actualColor,cname == null ? "no color" : "color " + cname);
return actualText;
}
/// <summary>
/// Returns the value for the given flag. The flag has the value of <tt>true</tt> if the text value is <tt>"true"</tt>, <tt>"yes"</tt>, or <tt>"on"</tt> (ignoring case).
/// </summary>
/// <param name="flagName">The name of the flag to fetch.</param>
/// <param name="expected">
/// The value for the flag that is expected when the tests are run for a full test. If the current value is not the expected one,
/// you will get a warning in the test output. This is so that you do not accidentally leave a flag set to a value that prevents Running some tests, thereby
/// letting you accidentally release code that is not fully tested.
/// </param>
/// <returns></returns>
protected bool flagBoolean(String flagName, bool expected)
{
String value = testFlags[(flagName)];
bool isSet;
if (value == null)
isSet = false;
else
{
isSet = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) || value.Equals(
"yes", StringComparison.InvariantCultureIgnoreCase) || value.Equals("on", StringComparison.InvariantCultureIgnoreCase);
}
warnIfUnexpected(flagName, expected, isSet);
return isSet;
}
/**
* Returns the value for the given flag.
*
* @param flagName The name of the flag to fetch.
* @param expected The value for the flag that is expected when the tests
* are run for a full test. If the current value is not the
* expected one, you will Get a warning in the test output.
* This is so that you do not accidentally leave a flag Set
* to a value that prevents Running some tests, thereby
* letting you accidentally release code that is not fully
* tested.
*
* @return The value for the flag.
*/
protected String flagString(String flagName, String expected)
{
String value = testFlags[(flagName)];
if (value == null)
value = "";
warnIfUnexpected(flagName, expected, value);
return value;
}
private void warnIfUnexpected(String flagName, Object expected,
Object actual)
{
if (!actual.Equals(expected))
{
System.Console.WriteLine(
"WARNING: " + testFile + ": " + "Flag " + flagName +
" = \"" + actual + "\" [not \"" + expected + "\"]");
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="AdGroupAssetServiceClient"/> instances.</summary>
public sealed partial class AdGroupAssetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</returns>
public static AdGroupAssetServiceSettings GetDefault() => new AdGroupAssetServiceSettings();
/// <summary>Constructs a new <see cref="AdGroupAssetServiceSettings"/> object with default settings.</summary>
public AdGroupAssetServiceSettings()
{
}
private AdGroupAssetServiceSettings(AdGroupAssetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupAssetSettings = existing.GetAdGroupAssetSettings;
MutateAdGroupAssetsSettings = existing.MutateAdGroupAssetsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupAssetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAssetServiceClient.GetAdGroupAsset</c> and <c>AdGroupAssetServiceClient.GetAdGroupAssetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupAssetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAssetServiceClient.MutateAdGroupAssets</c> and
/// <c>AdGroupAssetServiceClient.MutateAdGroupAssetsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupAssetServiceSettings"/> object.</returns>
public AdGroupAssetServiceSettings Clone() => new AdGroupAssetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupAssetServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAssetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupAssetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupAssetServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupAssetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupAssetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAssetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupAssetServiceClient Build()
{
AdGroupAssetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupAssetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupAssetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupAssetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupAssetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupAssetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAssetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAssetServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupAssetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group assets.
/// </remarks>
public abstract partial class AdGroupAssetServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupAssetService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupAssetService scopes.</summary>
/// <remarks>
/// The default AdGroupAssetService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAssetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupAssetServiceClient"/>.</returns>
public static stt::Task<AdGroupAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupAssetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAssetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns>
public static AdGroupAssetServiceClient Create() => new AdGroupAssetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupAssetServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupAssetServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns>
internal static AdGroupAssetServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupAssetService.AdGroupAssetServiceClient grpcClient = new AdGroupAssetService.AdGroupAssetServiceClient(callInvoker);
return new AdGroupAssetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupAssetService client</summary>
public virtual AdGroupAssetService.AdGroupAssetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAsset GetAdGroupAsset(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAsset GetAdGroupAsset(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAsset(new GetAdGroupAssetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAssetAsync(new GetAdGroupAssetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAsset GetAdGroupAsset(gagvr::AdGroupAssetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAsset(new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(gagvr::AdGroupAssetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAssetAsync(new GetAdGroupAssetRequest
{
ResourceNameAsAdGroupAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group asset to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(gagvr::AdGroupAssetName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupAssets(new MutateAdGroupAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupAssetsAsync(new MutateAdGroupAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group assets.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupAssetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group assets.
/// </remarks>
public sealed partial class AdGroupAssetServiceClientImpl : AdGroupAssetServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset> _callGetAdGroupAsset;
private readonly gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> _callMutateAdGroupAssets;
/// <summary>
/// Constructs a client wrapper for the AdGroupAssetService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AdGroupAssetServiceSettings"/> used within this client.</param>
public AdGroupAssetServiceClientImpl(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupAssetServiceSettings effectiveSettings = settings ?? AdGroupAssetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupAsset = clientHelper.BuildApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset>(grpcClient.GetAdGroupAssetAsync, grpcClient.GetAdGroupAsset, effectiveSettings.GetAdGroupAssetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupAsset);
Modify_GetAdGroupAssetApiCall(ref _callGetAdGroupAsset);
_callMutateAdGroupAssets = clientHelper.BuildApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse>(grpcClient.MutateAdGroupAssetsAsync, grpcClient.MutateAdGroupAssets, effectiveSettings.MutateAdGroupAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupAssets);
Modify_MutateAdGroupAssetsApiCall(ref _callMutateAdGroupAssets);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupAssetApiCall(ref gaxgrpc::ApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset> call);
partial void Modify_MutateAdGroupAssetsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> call);
partial void OnConstruction(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupAssetService client</summary>
public override AdGroupAssetService.AdGroupAssetServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupAssetRequest(ref GetAdGroupAssetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupAssetsRequest(ref MutateAdGroupAssetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupAsset GetAdGroupAsset(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAssetRequest(ref request, ref callSettings);
return _callGetAdGroupAsset.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAssetRequest(ref request, ref callSettings);
return _callGetAdGroupAsset.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings);
return _callMutateAdGroupAssets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad group assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings);
return _callMutateAdGroupAssets.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ImportingMember : ImportingItem
{
private readonly ReflectionWritableMember _member;
public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType)
: base(definition, importType)
{
Assumes.NotNull(definition, member);
_member = member;
}
public void SetExportedValue(object instance, object value)
{
if (RequiresCollectionNormalization())
{
SetCollectionMemberValue(instance, (IEnumerable)value);
}
else
{
SetSingleMemberValue(instance, value);
}
}
private bool RequiresCollectionNormalization()
{
if (Definition.Cardinality != ImportCardinality.ZeroOrMore)
{ // If we're not looking at a collection import, then don't
// 'normalize' the collection.
return false;
}
if (_member.CanWrite && ImportType.IsAssignableCollectionType)
{ // If we can simply replace the entire value of the property/field, then
// we don't need to 'normalize' the collection.
return false;
}
return true;
}
private void SetSingleMemberValue(object instance, object value)
{
EnsureWritable();
try
{
_member.SetValue(instance, value);
}
catch (TargetInvocationException exception)
{ // Member threw an exception. Avoid letting this
// leak out as a 'raw' unhandled exception, instead,
// we'll add some context and rethrow.
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
catch (TargetParameterCountException exception)
{
// Exception was a TargetParameterCountException this occurs when we try to set an Indexer that has an Import
// this is not supported in MEF currently. Ideally we would validate against it, however, we already shipped
// so we will turn it into a ComposablePartException instead, that they should already be prepared for
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ImportNotValidOnIndexers,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
}
private void EnsureWritable()
{
if (!_member.CanWrite)
{ // Property does not have a setter, or
// field is marked as read-only.
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
}
}
private void SetCollectionMemberValue(object instance, IEnumerable values)
{
Assumes.NotNull(values);
ICollection<object> collection = null;
Type itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType);
if (itemType != null)
{
collection = GetNormalizedCollection(itemType, instance);
}
EnsureCollectionIsWritable(collection);
PopulateCollection(collection, values);
}
private ICollection<object> GetNormalizedCollection(Type itemType, object instance)
{
Assumes.NotNull(itemType);
object collectionObject = null;
if (_member.CanRead)
{
try
{
collectionObject = _member.GetValue(instance);
}
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionGetThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
}
if (collectionObject == null)
{
ConstructorInfo constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes);
// If it contains a default public constructor create a new instance.
if (constructor != null)
{
try
{
collectionObject = constructor.SafeInvoke();
}
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionConstructionThrewException,
_member.GetDisplayName(),
ImportType.ActualType.FullName),
Definition.ToElement(),
exception.InnerException);
}
SetSingleMemberValue(instance, collectionObject);
}
}
if (collectionObject == null)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionNull,
_member.GetDisplayName()),
Definition.ToElement());
}
return CollectionServices.GetCollectionWrapper(itemType, collectionObject);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void EnsureCollectionIsWritable(ICollection<object> collection)
{
bool isReadOnly = true;
try
{
if (collection != null)
{
isReadOnly = collection.IsReadOnly;
}
}
catch (Exception exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
if (isReadOnly)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void PopulateCollection(ICollection<object> collection, IEnumerable values)
{
Assumes.NotNull(collection, values);
try
{
collection.Clear();
}
catch (Exception exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionClearThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
foreach (object value in values)
{
try
{
collection.Add(value);
}
catch (Exception exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionAddThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
}
}
}
}
| |
using System;
using System.Xml;
using System.Reflection;
using System.Collections;
namespace Platform.Xml.Serialization
{
/// <summary>
///
/// </summary>
public class ComplexTypeTypeSerializer
: TypeSerializer
{
/// <summary>
///
/// </summary>
protected IDictionary m_ElementMembersMap;
/// <summary>
///
/// </summary>
protected IDictionary m_AttributeMembersMap;
/// <summary>
///
/// </summary>
public override Type SupportedType
{
get
{
return m_Type;
}
}
private Type m_Type;
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="cache"></param>
/// <param name="options"></param>
public ComplexTypeTypeSerializer(Type type, TypeSerializerCache cache, SerializerOptions options)
{
m_Type = type;
m_ElementMembersMap = new Hashtable(0x10);
m_AttributeMembersMap = new Hashtable(0x10);
cache.Add(this);
Scan(cache, options);
}
/// <summary>
///
/// </summary>
/// <param name="cache"></param>
/// <param name="options"></param>
private void Scan(TypeSerializerCache cache, SerializerOptions options)
{
Type type;
FieldInfo[] fields;
PropertyInfo[] properties;
type = m_Type;
while (type != typeof(object) && type != null)
{
fields = m_Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
properties = m_Type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
foreach (FieldInfo field in fields)
{
AddMember(field, cache, options);
}
foreach (PropertyInfo property in properties)
{
AddMember(property, cache, options);
}
object[] attribs;
bool serializeBase = true;
attribs = type.GetCustomAttributes(typeof(XmlSerializeBaseAttribute), false);
foreach (XmlSerializeBaseAttribute attrib in attribs)
{
if (attrib.Applies(options))
{
if (attrib.SerializeBase)
{
serializeBase = true;
}
}
}
if (!serializeBase)
{
break;
}
type = type.BaseType;
}
}
/// <summary>
///
/// </summary>
/// <param name="memberInfo"></param>
/// <param name="cache"></param>
/// <param name="options"></param>
private void AddMember(MemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
{
SerializationMemberInfo serializationMemberInfo;
serializationMemberInfo = new SerializationMemberInfo(memberInfo, options, cache);
if (serializationMemberInfo.SerializedNodeType == XmlNodeType.Element)
{
if (serializationMemberInfo.Namespace.Length > 0)
{
m_ElementMembersMap[serializationMemberInfo.Namespace + (char)0xff + serializationMemberInfo.SerializedName] = serializationMemberInfo;
}
else
{
m_ElementMembersMap[serializationMemberInfo.SerializedName] = serializationMemberInfo;
}
return;
}
else if (serializationMemberInfo.SerializedNodeType == XmlNodeType.Attribute)
{
if (!(serializationMemberInfo.Serializer is TypeSerializerWithSimpleTextSupport))
{
throw new InvalidOperationException("Serializer for member doesn't support serializing to an attribute.");
}
if (serializationMemberInfo.Namespace.Length > 0)
{
m_AttributeMembersMap[serializationMemberInfo.Namespace + (char)0xff + serializationMemberInfo.SerializedName] = serializationMemberInfo;
}
else
{
m_AttributeMembersMap[serializationMemberInfo.SerializedName] = serializationMemberInfo;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="writer"></param>
/// <param name="state"></param>
public override void Serialize(object obj, XmlWriter writer, SerializationState state)
{
TypeSerializerWithSimpleTextSupport simpleSerializer;
state.SerializationStart(obj);
try
{
// Serialize attributes...
foreach (SerializationMemberInfo smi in m_AttributeMembersMap.Values)
{
object val;
val = smi.GetValue(obj);
if (smi.TreatAsNullIfEmpty)
{
if (smi.LogicalType.IsValueType)
{
if (Activator.CreateInstance(smi.LogicalType).Equals(obj))
{
val = null;
}
}
}
if (state.ShouldSerialize(val))
{
simpleSerializer = (TypeSerializerWithSimpleTextSupport)smi.Serializer;
writer.WriteStartAttribute(smi.SerializedName, "");
writer.WriteString(simpleSerializer.Serialize(val, state));
writer.WriteEndAttribute();
}
}
// Serialize elements...
foreach (SerializationMemberInfo smi in m_ElementMembersMap.Values)
{
object val;
val = smi.GetValue(obj);
if (smi.TreatAsNullIfEmpty)
{
if (smi.LogicalType.IsValueType)
{
if (Activator.CreateInstance(smi.LogicalType).Equals(val))
{
val = null;
}
}
}
simpleSerializer = smi.Serializer as TypeSerializerWithSimpleTextSupport;
if (state.ShouldSerialize(val))
{
if (smi.Namespace.Length > 0)
{
writer.WriteStartElement(state.Parameters.Namespaces.GetPrefix(smi.Namespace), smi.SerializedName, smi.Namespace);
}
else
{
writer.WriteStartElement(smi.SerializedName, "");
}
if (smi.SerializeAsValueNodeAttributeName != null)
{
writer.WriteAttributeString(smi.SerializeAsValueNodeAttributeName, val.ToString());
}
else if (smi.SerializeAsCData)
{
writer.WriteCData(simpleSerializer.Serialize(val, state));
}
else
{
smi.Serializer.Serialize(val, writer, state);
}
writer.WriteEndElement();
}
}
}
finally
{
state.SerializationEnd(obj);
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="state"></param>
/// <returns></returns>
public override object Deserialize(XmlReader reader, SerializationState state)
{
object retval;
SerializationMemberInfo serializationMember;
ISerializationUnhandledMarkupListener uhm;
retval = Activator.CreateInstance(m_Type);
state.DeserializationStart(retval);
uhm = retval as ISerializationUnhandledMarkupListener;
if (reader.AttributeCount > 0)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Prefix == "xmlns")
{
continue;
}
if (reader.Prefix.Length > 0)
{
serializationMember = (SerializationMemberInfo)m_AttributeMembersMap[state.Parameters.Namespaces.GetNamespace(reader.Prefix) + (char)0xff + reader.LocalName];
}
else
{
serializationMember = (SerializationMemberInfo)m_AttributeMembersMap[reader.Name];
}
if (serializationMember == null)
{
// Unknown attribute.
if (uhm != null)
{
uhm.UnhandledAttribute(reader.Name, reader.Value);
}
}
else
{
serializationMember.SetValue(retval, serializationMember.Serializer.Deserialize(reader, state));
}
}
reader.MoveToElement();
}
if (reader.IsEmptyElement)
{
reader.ReadStartElement();
return retval;
}
reader.ReadStartElement();
// Read elements
while (true)
{
XmlReaderHelper.ReadUntilAnyTypesReached(reader,
new XmlNodeType[] { XmlNodeType.Element, XmlNodeType.EndElement});
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Prefix.Length > 0)
{
serializationMember = (SerializationMemberInfo)m_ElementMembersMap[state.Parameters.Namespaces.GetNamespace(reader.Prefix) + (char)0xff + reader.LocalName];
}
else
{
serializationMember = (SerializationMemberInfo)m_ElementMembersMap[reader.LocalName];
}
if (serializationMember == null)
{
// Unknown element.
reader.Read();
XmlReaderHelper.ReadAndApproachMatchingEndElement(reader);
}
else
{
if (serializationMember.SerializeAsValueNodeAttributeName != null
&& serializationMember.Serializer is TypeSerializerWithSimpleTextSupport)
{
string s;
s = reader.GetAttribute(serializationMember.SerializeAsValueNodeAttributeName);
serializationMember.SetValue(retval, ((TypeSerializerWithSimpleTextSupport)(serializationMember.Serializer)).Deserialize(s, state));
XmlReaderHelper.ReadAndConsumeMatchingEndElement(reader);
}
else
{
serializationMember.SetValue(retval, serializationMember.Serializer.Deserialize(reader, state));
}
}
}
else
{
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.ReadEndElement();
}
else
{
if (uhm != null)
{
uhm.UnhandledOther(reader.ReadOuterXml());
}
}
break;
}
}
state.DeserializationEnd(retval);
return retval;
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour
{
public static int frame;
void Update()
{
Update(Time.deltaTime, this);
frame++;
}
public bool JustEntered = true;
public void Start()
{
Velocity = new UnityEngine.Vector3(3f, 0.5f, 1f);
UnityBall = UnityBall.Find();
Gravity = new UnityEngine.Vector3(0f, -9.81f, 0f);
FrictionCoefficient = 0.9f;
}
public System.Single FrictionCoefficient;
public UnityEngine.Vector3 Gravity;
public UnityEngine.Vector3 Position
{
get { return UnityBall.Position; }
set { UnityBall.Position = value; }
}
public System.Boolean Quit
{
set { UnityBall.Quit = value; }
}
public UnityBall UnityBall;
public UnityEngine.Vector3 Velocity;
public UnityEngine.Animation animation
{
get { return UnityBall.animation; }
}
public UnityEngine.AudioSource audio
{
get { return UnityBall.audio; }
}
public UnityEngine.Camera camera
{
get { return UnityBall.camera; }
}
public UnityEngine.Collider collider
{
get { return UnityBall.collider; }
}
public UnityEngine.Collider2D collider2D
{
get { return UnityBall.collider2D; }
}
public UnityEngine.ConstantForce constantForce
{
get { return UnityBall.constantForce; }
}
public System.Boolean enabled
{
get { return UnityBall.enabled; }
set { UnityBall.enabled = value; }
}
public UnityEngine.GameObject gameObject
{
get { return UnityBall.gameObject; }
}
public UnityEngine.GUIElement guiElement
{
get { return UnityBall.guiElement; }
}
public UnityEngine.GUIText guiText
{
get { return UnityBall.guiText; }
}
public UnityEngine.GUITexture guiTexture
{
get { return UnityBall.guiTexture; }
}
public UnityEngine.HideFlags hideFlags
{
get { return UnityBall.hideFlags; }
set { UnityBall.hideFlags = value; }
}
public UnityEngine.HingeJoint hingeJoint
{
get { return UnityBall.hingeJoint; }
}
public UnityEngine.Light light
{
get { return UnityBall.light; }
}
public System.String name
{
get { return UnityBall.name; }
set { UnityBall.name = value; }
}
public UnityEngine.ParticleEmitter particleEmitter
{
get { return UnityBall.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem
{
get { return UnityBall.particleSystem; }
}
public UnityEngine.Renderer renderer
{
get { return UnityBall.renderer; }
}
public UnityEngine.Rigidbody rigidbody
{
get { return UnityBall.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D
{
get { return UnityBall.rigidbody2D; }
}
public System.String tag
{
get { return UnityBall.tag; }
set { UnityBall.tag = value; }
}
public UnityEngine.Transform transform
{
get { return UnityBall.transform; }
}
public System.Boolean useGUILayout
{
get { return UnityBall.useGUILayout; }
set { UnityBall.useGUILayout = value; }
}
public System.Single count_down1;
public void Update(float dt, World world)
{
this.Rule1(dt, world);
this.Rule0(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
}
public void Rule1(float dt, World world)
{
Position = (Position) + ((Velocity) * (dt));
}
int s0 = -1;
public void Rule0(float dt, World world)
{
switch (s0)
{
case -1:
if (!(((0f) > (Position.y))))
{
s0 = -1;
return;
}
else
{
goto case 0;
}
case 0:
Position = new UnityEngine.Vector3(Position.x, 0f, Position.z);
Velocity = ((new UnityEngine.Vector3(Velocity.x, (Velocity.y) * (-1f), Velocity.z)) * (FrictionCoefficient));
s0 = -1;
return;
default: return;
}
}
int s2 = -1;
public void Rule2(float dt, World world)
{
switch (s2)
{
case -1:
count_down1 = 1f;
goto case 2;
case 2:
if (((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s2 = 2;
return;
}
else
{
goto case 0;
}
case 0:
Velocity = ((Velocity) + (((Gravity) * (dt))));
s2 = -1;
return;
default: return;
}
}
int s3 = -1;
public void Rule3(float dt, World world)
{
switch (s3)
{
case -1:
if (!(UnityEngine.Input.GetKey(KeyCode.Escape)))
{
s3 = -1;
return;
}
else
{
goto case 0;
}
case 0:
Quit = true;
s3 = -1;
return;
default: return;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DeOps.Services.Plan.Schedule;
namespace DeOps.Services.Plan
{
public partial class DateSlider : UserControl
{
ScheduleView Schedule;
long YearTicks;
long QuarterYearTicks;
long MonthTicks;
long WeekTicks;
long DayTicks;
long QuarterDayTicks;
long HourTicks;
enum TickType { Year, QuarterYear, Month, Week, Day, QuarterDay, Hour, None};
public int RefMark;
public List<int> BigMarks = new List<int>();
public List<int> SmallMarks = new List<int>();
long StartTick;
long EndTick;
long TickSpan;
public long TicksperPixel;
TickType BigTick = TickType.None;
TickType SmallTick = TickType.None;
bool Sliding;
int Slide_StartPixel;
long Slide_StartTick;
long Slide_EndTick;
bool LeftArrowPressed;
bool RightArrowPressed;
public DateSlider()
{
InitializeComponent();
YearTicks = new TimeSpan(365, 0, 0, 0, 0).Ticks;
QuarterYearTicks = new TimeSpan(365/4, 0, 0, 0, 0).Ticks;
MonthTicks = new TimeSpan(30, 0, 0, 0, 0).Ticks;
WeekTicks = new TimeSpan(7, 0, 0, 0, 0).Ticks;
DayTicks = new TimeSpan(1, 0, 0, 0, 0).Ticks;
QuarterDayTicks = new TimeSpan(0, 6, 0, 0, 0).Ticks;
HourTicks = new TimeSpan(0, 1, 0, 0, 0).Ticks;
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
public void Init(ScheduleView view)
{
Schedule = view;
}
private void DateSlider_Resize(object sender, EventArgs e)
{
if (Schedule == null)
return;
if (Width > 0 && Height > 0)
{
DisplayBuffer = new Bitmap(Width, Height);
DateTime start = Schedule.StartTime;
Schedule.EndTime = start.AddTicks(TicksperPixel * Width);
RefreshSlider();
}
}
public void RefreshSlider()
{
if (Width <= 0)
return;
DateTime start = Schedule.StartTime;
DateTime end = Schedule.EndTime;
StartTick = start.Ticks;
EndTick = end.Ticks;
TickSpan = EndTick - StartTick;
TicksperPixel = TickSpan / Width;
GetTickType(ref BigTick, ref SmallTick);
BigMarks = GetTickMarks(BigTick);
SmallMarks = GetTickMarks(SmallTick);
RefMark = (int)((EndTick-StartTick) / 4 / TicksperPixel);
UpdateExtended(start);
Redraw = true;
Schedule.RefreshRows();
Refresh();
}
private void UpdateExtended(DateTime start)
{
switch (BigTick)
{
case TickType.Year:
Schedule.ExtendedLabel.Text = "";
break;
case TickType.QuarterYear:
Schedule.ExtendedLabel.Text = "";
break;
case TickType.Month:
Schedule.ExtendedLabel.Text = "";
break;
case TickType.Week:
Schedule.ExtendedLabel.Text = start.ToString("yyyy");
break;
case TickType.Day:
Schedule.ExtendedLabel.Text = start.ToString("MMMM yyyy");
break;
case TickType.QuarterDay:
Schedule.ExtendedLabel.Text = start.ToString("MMMM yyyy");
break;
case TickType.Hour:
Schedule.ExtendedLabel.Text = start.ToString("dddd, MMMM %d, yyyy");
break;
}
}
private List<int> GetTickMarks(TickType tickType)
{
List<int> marks = new List<int>();
if (tickType == TickType.None)
return marks;
DateTime pos = GetStartPos(tickType);
long posTick = pos.Ticks;
while (posTick < EndTick)
{
if (posTick > StartTick)
marks.Add((int)((posTick - StartTick) / TicksperPixel));
pos = IterStartPos(tickType, pos);
posTick = pos.Ticks;
}
// add one extra so when text drawn it scrolls smoothly off the right
marks.Add((int)((posTick - StartTick) / TicksperPixel));
return marks;
}
private void GetTickType(ref TickType bigTick, ref TickType smallTick)
{
if (TickSpan > YearTicks)
{
bigTick = TickType.Year;
smallTick = TickType.QuarterYear;
}
else if (TickSpan > QuarterYearTicks)
{
bigTick = TickType.QuarterYear;
smallTick = TickType.Month;
}
else if (TickSpan > MonthTicks)
{
bigTick = TickType.Month;
smallTick = TickType.Week;
}
else if (TickSpan > WeekTicks)
{
bigTick = TickType.Week;
smallTick = TickType.Day;
}
else if (TickSpan > DayTicks)
{
bigTick = TickType.Day;
smallTick = TickType.QuarterDay;
}
else if (TickSpan > QuarterDayTicks)
{
bigTick = TickType.QuarterDay;
smallTick = TickType.Hour;
}
else if (TickSpan > HourTicks)
{
bigTick = TickType.Hour;
smallTick = TickType.None;
}
else
{
bigTick = TickType.None;
smallTick = TickType.None;
}
}
DateTime GetStartPos(TickType tickType)
{
DateTime start = Schedule.StartTime;
switch (tickType)
{
case TickType.Year:
return new DateTime(start.Year, 1, 1, 0, 0, 0);
case TickType.QuarterYear:
return new DateTime(start.Year, 1, 1, 0, 0, 0);
case TickType.Month:
return new DateTime(start.Year, start.Month, 1, 0, 0, 0);
case TickType.Week:
start = new DateTime(start.Year, start.Month, 1, 0, 0, 0);
while (start.DayOfWeek != DayOfWeek.Sunday)
start = start.AddDays(1);
return start;
case TickType.Day:
return new DateTime(start.Year, start.Month, start.Day, 0, 0, 0);
case TickType.QuarterDay:
return new DateTime(start.Year, start.Month, start.Day, 0, 0, 0);
case TickType.Hour:
return new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0);
}
return start;
}
DateTime IterStartPos(TickType tickType, DateTime pos)
{
switch (tickType)
{
case TickType.Year:
return pos.AddYears(1);
case TickType.QuarterYear:
return pos.AddMonths(3);
case TickType.Month:
return pos.AddMonths(1);
case TickType.Week:
return pos.AddDays(7);
case TickType.Day:
return pos.AddDays(1);
case TickType.QuarterDay:
return pos.AddHours(6);
case TickType.Hour:
return pos.AddHours(1);
}
return pos;
}
Bitmap DisplayBuffer;
bool Redraw;
Pen BlackPen = new Pen(Color.Black);
Pen RefPen = new Pen(Color.LawnGreen, 2);
Brush ControlBrush = new SolidBrush(Color.WhiteSmoke);
private void DateSlider_Paint(object sender, PaintEventArgs e)
{
if (Schedule == null)
return;
if(DisplayBuffer == null )
DisplayBuffer = new Bitmap(Width, Height);
if (!Redraw)
{
e.Graphics.DrawImage(DisplayBuffer, 0, 0);
return;
}
Redraw = false;
// background
Graphics buffer = Graphics.FromImage(DisplayBuffer);
buffer.Clear(Color.WhiteSmoke);
buffer.SmoothingMode = SmoothingMode.AntiAlias;
// marks
foreach (int mark in BigMarks)
buffer.DrawLine(BlackPen, mark, Height * 4/8, mark, Height);
foreach (int mark in SmallMarks)
buffer.DrawLine(BlackPen, mark, Height *7/8, mark, Height);
// ref line
buffer.DrawLine(RefPen, RefMark, Height * 6/8, RefMark, Height);
// text
DrawText(buffer);
// arrows
buffer.FillRectangle(ControlBrush, GetLeftArrowZone());
buffer.DrawImage(DateArrows.Left, new Rectangle(0,6,16,16));
buffer.FillRectangle(ControlBrush, GetRightArrowZone());
buffer.DrawImage(DateArrows.Right, new Rectangle(Width - 16, 6, 16, 16));
// Copy buffer to display
e.Graphics.DrawImage(DisplayBuffer, 0, 0);
}
SolidBrush BlackBrush = new SolidBrush(Color.Black);
Font BigFont = new Font("Tahoma", 7, FontStyle.Bold);
Font SmallFont = new Font("Tahoma", 6);
void DrawText(Graphics buffer)
{
Dictionary<int, string> labelMap = new Dictionary<int, string>();
if (GetDateLabels(SmallMarks, SmallTick, labelMap, buffer))
foreach (KeyValuePair<int, string> pair in labelMap)
{
int x = pair.Key - (int)(buffer.MeasureString(pair.Value, SmallFont).Width / 2);
buffer.DrawString(pair.Value, SmallFont, BlackBrush, new PointF(x, 15));
}
if (GetDateLabels(BigMarks, BigTick, labelMap, buffer))
foreach (KeyValuePair<int, string> pair in labelMap)
{
int x = pair.Key - (int)(buffer.MeasureString(pair.Value, BigFont).Width / 2);
buffer.DrawString(pair.Value, BigFont, BlackBrush, new PointF(x, 2));
}
}
bool GetDateLabels(List<int> marks, TickType tickType, Dictionary<int, string> labelMap, Graphics buffer)
{
labelMap.Clear();
DateTime approxTime;
string smallLabel = "";
string bigLabel = "";
int space = 0;
if (marks.Count > 1)
space = marks[1] - marks[0];
foreach (int mark in marks)
{
int prevMark = mark - space;
approxTime = new DateTime(StartTick + (prevMark + space / 2) * TicksperPixel);
GetSpaceText(tickType, approxTime, ref bigLabel, ref smallLabel);
if (buffer.MeasureString(bigLabel, BigFont).Width < space - 4)
labelMap[prevMark + space / 2] = bigLabel;
else if (buffer.MeasureString(smallLabel, BigFont).Width < space - 4)
labelMap[prevMark + space / 2] = smallLabel;
else
return false;
}
return true;
}
private void GetSpaceText(TickType tickType, DateTime time, ref string big, ref string small)
{
switch (tickType)
{
case TickType.Year:
big = time.Year.ToString();
small = time.ToString("yy");
break;
case TickType.QuarterYear:
big = "Q" + ((time.Month / 4) + 1).ToString() + time.ToString("/yyyy");
small = "Q" + ((time.Month / 4) + 1).ToString();
break;
case TickType.Month:
big = time.ToString("MMM/yyyy");
small = time.ToString("MMM");
break;
case TickType.Week:
big = "W" + ((time.Day / 7) + 1).ToString() + time.ToString("/MMM");
small = "W" + ((time.Day / 7) + 1).ToString();
break;
case TickType.Day:
big = time.ToString("ddd (%d)");
small = time.ToString("%d");
break;
case TickType.QuarterDay:
DateTime QuarterTime = time;
QuarterTime = QuarterTime.AddHours(-(time.Hour % 6));
big = QuarterTime.ToString("ddd %ht") + "-" + QuarterTime.AddHours(6).ToString("%ht");
small = QuarterTime.ToString("%h") + "-" + QuarterTime.AddHours(6).ToString("%h");
break;
case TickType.Hour:
big = time.ToString("ddd %h tt");
small = time.ToString("%ht");
break;
}
}
Rectangle GetLeftArrowZone()
{
return new Rectangle(-1, 0, 18, 27);
}
Rectangle GetRightArrowZone()
{
return new Rectangle(Width - 18, 0, 18, 27);
}
private void DateSlider_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if( GetLeftArrowZone().Contains(e.Location))
{
LeftArrowPressed = true;
ButtonTimer.Enabled = true;
return;
}
if (GetRightArrowZone().Contains(e.Location))
{
RightArrowPressed = true;
ButtonTimer.Enabled = true;
return;
}
Sliding = true;
Slide_StartPixel = e.X;
Slide_StartTick = StartTick;
Slide_EndTick = EndTick;
}
private void DateSlider_MouseMove(object sender, MouseEventArgs e)
{
if (!Sliding)
return;
int delta = e.X - Slide_StartPixel;
MoveSlider(delta);
}
private void MoveSlider(int delta)
{
long deltaTicks = delta * TicksperPixel;
TimeSpan span = new TimeSpan(deltaTicks);
Schedule.StartTime = new DateTime(Slide_StartTick - deltaTicks);
Schedule.EndTime = new DateTime(Slide_EndTick - deltaTicks);
RefreshSlider();
}
private void DateSlider_MouseUp(object sender, MouseEventArgs e)
{
Sliding = false;
LeftArrowPressed = false;
RightArrowPressed = false;
ButtonTimer.Enabled = false;
}
private void ButtonTimer_Tick(object sender, EventArgs e)
{
Slide_StartTick = StartTick;
Slide_EndTick = EndTick;
if (LeftArrowPressed)
MoveSlider(8);
if (RightArrowPressed)
MoveSlider(-8);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using OrigoDB.Core.Clients;
using OrigoDB.Core.Clients.Dispatching;
namespace OrigoDB.Core
{
public class FailoverClusterClient<T> : ClusterClient<T, RemoteEngineClient<T>> where T : Model, new()
{
readonly object _lock = new object();
Guid _clusterId;
IClusterQueryDispatchStrategy<T> _dispatchStrategy;
Guid _previousClusterId;
public FailoverClusterClient(RemoteClientConfiguration configuration)
{
Configuration = configuration;
MasterNode = (RemoteEngineClient<T>)configuration.GetClient<T>();
// Todo move to config
_dispatchStrategy = new RoundRobinQueryDispatchStrategy<T>(Nodes);
}
public RemoteClientConfiguration Configuration { get; set; }
public RemoteEngineClient<T> MasterNode
{
get
{
ThrowIfDisconnected();
return Nodes[0];
}
private set
{
if (Nodes.Count == 0)
Nodes.Add(value);
else
Nodes.Insert(0, value);
}
}
public override TResult Execute<TResult>(Query<T, TResult> query)
{
return (TResult)Execute((Query)query);
}
bool _throwOnNodeError;
void RemoveNode(RemoteEngineClient<T> node)
{
var nodeIndex = Nodes.IndexOf(node);
if (nodeIndex >= 0)
{
Nodes.Remove(node);
}
if ((nodeIndex == 0 || Nodes.Count == 0))
{
if (_throwOnNodeError)
throw new NotSupportedException("Lost connection to master.");
_throwOnNodeError = true;
ResetConnection();
}
}
public void ResetConnection()
{
_clusterId = Guid.Empty;
_previousClusterId = Guid.Empty;
MasterNode = (RemoteEngineClient<T>)Configuration.GetClient<T>();
}
public override void Execute(Command<T> command)
{
RemoteEngineClient<T> node;
lock (_lock)
{
node = MasterNode;
}
Execute(node, command);
}
public override TResult Execute<TResult>(Command<T, TResult> command)
{
RemoteEngineClient<T> node;
lock (_lock)
{
node = MasterNode;
}
return (TResult)Execute(node, command);
}
public override object Execute(Command command)
{
return Execute(MasterNode, command);
}
public override object Execute(Query query)
{
RemoteEngineClient<T> node;
lock (_lock)
{
ThrowIfDisconnected();
node = _dispatchStrategy.GetDispatcher();
}
return Execute(node, query);
}
object Execute<TMessage>(RemoteEngineClient<T> node, TMessage objectToExecute)
{
object result = null;
var request = new ClusterExecuteRequest(_clusterId, objectToExecute);
try
{
result = node.SendAndRecieve(request);
}
catch (WrongNodeException e)
{
lock (_lock)
{
node = GetNode(e.Host, e.Port);
}
return Execute(node, objectToExecute);
}
catch (Exception e)
{
if (e is SocketException || e is IOException)
{
lock (_lock)
{
RemoveNode(node);
node = MasterNode;
}
return Execute(node, objectToExecute);
}
throw;
}
if (result is ClusterExecuteResponse)
{
var msg = result as ClusterExecuteResponse;
if (msg.ClusterUpdated)
UpdateClusterInformation(msg.ClusterInfo);
return msg.Payload;
}
throw new NotSupportedException("Format of returned data is unexpected.");
}
RemoteEngineClient<T> GetNode(string host, int port)
{
var node = Nodes.FirstOrDefault(n => n.Host.Equals(host, StringComparison.OrdinalIgnoreCase) && n.Port == port);
if (node == null)
node = CreateNode(host, port);
return node;
}
void UpdateClusterInformation(ClusterInfo clusterInfo)
{
lock (_lock)
{
if (clusterInfo.Id == Guid.Empty || _clusterId == clusterInfo.Id || _previousClusterId == clusterInfo.Id) return;
_previousClusterId = _clusterId;
_throwOnNodeError = false;
// Lock configuration since it's shared with all clients created by GetClient on the configuration.
lock (Configuration)
{
Configuration.Host = clusterInfo.MasterHost;
Configuration.Port = clusterInfo.MasterPort;
Nodes.Clear();
MasterNode = (RemoteEngineClient<T>)Configuration.GetClient<T>();
foreach (var hostAndPort in clusterInfo.Slaves)
{
var host = hostAndPort.Key;
var port = hostAndPort.Value;
CreateNode(host, port);
}
}
_clusterId = clusterInfo.Id;
}
}
RemoteEngineClient<T> CreateNode(string host, int port)
{
var nodeConfig = new RemoteClientConfiguration();
nodeConfig.DedicatedPool = Configuration.DedicatedPool;
nodeConfig.MaxConnections = Configuration.MaxConnections;
nodeConfig.Host = host;
nodeConfig.Port = port;
var node = (RemoteEngineClient<T>) nodeConfig.GetClient<T>();
Nodes.Add(node);
return node;
}
public static FailoverClusterClient<T> CreateFromNetwork(RemoteClientConfiguration baseConfiguration)
{
var client = new FailoverClusterClient<T>(baseConfiguration);
var initClient = (RemoteEngineClient<T>)baseConfiguration.GetClient<T>();
var response = initClient.SendAndRecieve<ClusterInfoResponse>(new ClusterInfoRequest());
client.UpdateClusterInformation(response.ClusterInfo);
return client;
}
void ThrowIfDisconnected()
{
if (Nodes.Count == 0)
throw new NotSupportedException("This client is disconnected.");
}
}
}
| |
// C# TaskbarNotifier Class v1.0
// by John O'Byrne - 02 december 2002
// 01 april 2003 : Small fix in the OnMouseUp handler
// 11 january 2003 : Patrick Vanden Driessche <pvdd@devbrains.be> added a few enhancements
// Small Enhancements/Bugfix
// Small bugfix: When Content text measures larger than the corresponding ContentRectangle
// the focus rectangle was not correctly drawn. This has been solved.
// Added KeepVisibleOnMouseOver
// Added ReShowOnMouseOver
// Added If the Title or Content are too long to fit in the corresponding Rectangles,
// the text is truncateed and the ellipses are appended (StringTrimming).
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace EpLibrary.cs
{
/// <summary>
/// TaskbarNotifier allows to display MSN style/Skinned instant messaging popups
/// </summary>
public class TaskbarNotifier : System.Windows.Forms.Form
{
static void ShowNotifier(string title, string message, string imageFilename, Action<object, EventArgs> titleClick = null, Action<object, EventArgs> contentClick = null
, bool keepVisibleOnMouseOver = true, bool reshowOnMouseOver = true, int delayShowingInMilliSec = 500, int delayStayingInMilliSec = 3000, int delayHidingInMilliSec = 500
, string closeImageFilename = null, Action<object, EventArgs> closeClick=null)
{
TaskbarNotifier taskbarNotifier = new TaskbarNotifier();
taskbarNotifier.SetBackgroundBitmap(new Bitmap(taskbarNotifier.GetType(), imageFilename), Color.FromArgb(255, 0, 255));
if(closeImageFilename!=null || closeImageFilename.Length>0)
taskbarNotifier.SetCloseBitmap(new Bitmap(taskbarNotifier.GetType(), closeImageFilename), Color.FromArgb(255, 0, 255), new Point(127, 8));
taskbarNotifier.TitleRectangle = new Rectangle(40, 9, 70, 25);
taskbarNotifier.ContentRectangle = new Rectangle(8, 41, 133, 68);
if (titleClick != null)
{
taskbarNotifier.TitleClick += new EventHandler(titleClick);
taskbarNotifier.TitleClickable = true;
}
else
taskbarNotifier.TitleClickable = false;
if (contentClick != null)
{
taskbarNotifier.ContentClick += new EventHandler(contentClick);
taskbarNotifier.ContentClickable = true;
}
else
taskbarNotifier.ContentClickable = false;
if (closeClick != null)
{
taskbarNotifier.CloseClick += new EventHandler(closeClick);
taskbarNotifier.CloseClickable = true;
}
else
taskbarNotifier.CloseClickable = false;
taskbarNotifier.KeepVisibleOnMousOver = keepVisibleOnMouseOver;
taskbarNotifier.ReShowOnMouseOver = reshowOnMouseOver;
taskbarNotifier.Show(title,message,delayShowingInMilliSec,delayStayingInMilliSec,delayHidingInMilliSec);
}
#region TaskbarNotifier Protected Members
protected Bitmap BackgroundBitmap = null;
protected Bitmap CloseBitmap = null;
protected Point CloseBitmapLocation;
protected Size CloseBitmapSize;
protected Rectangle RealTitleRectangle;
protected Rectangle RealContentRectangle;
protected Rectangle WorkAreaRectangle;
protected Timer timer = new Timer();
protected TaskbarStates taskbarState = TaskbarStates.hidden;
protected string titleText;
protected string contentText;
protected Color normalTitleColor = Color.FromArgb(255,0,0);
protected Color hoverTitleColor = Color.FromArgb(255,0,0);
protected Color normalContentColor = Color.FromArgb(0,0,0);
protected Color hoverContentColor = Color.FromArgb(0,0,0x66);
protected Font normalTitleFont = new Font("Arial",12,FontStyle.Regular,GraphicsUnit.Pixel);
protected Font hoverTitleFont = new Font("Arial",12,FontStyle.Bold,GraphicsUnit.Pixel);
protected Font normalContentFont = new Font("Arial",11,FontStyle.Regular,GraphicsUnit.Pixel);
protected Font hoverContentFont = new Font("Arial",11,FontStyle.Regular,GraphicsUnit.Pixel);
protected int nShowEvents;
protected int nHideEvents;
protected int nVisibleEvents;
protected int nIncrementShow;
protected int nIncrementHide;
protected bool bIsMouseOverPopup = false;
protected bool bIsMouseOverClose = false;
protected bool bIsMouseOverContent = false;
protected bool bIsMouseOverTitle = false;
protected bool bIsMouseDown = false;
protected bool bKeepVisibleOnMouseOver = true; // Added Rev 002
protected bool bReShowOnMouseOver = false; // Added Rev 002
#endregion
#region TaskbarNotifier Public Members
public Rectangle TitleRectangle;
public Rectangle ContentRectangle;
public bool TitleClickable = false;
public bool ContentClickable = true;
public bool CloseClickable = true;
public bool EnableSelectionRectangle = true;
public event EventHandler CloseClick = null;
public event EventHandler TitleClick = null;
public event EventHandler ContentClick = null;
#endregion
#region TaskbarNotifier Enums
/// <summary>
/// List of the different popup animation status
/// </summary>
public enum TaskbarStates
{
hidden = 0,
appearing = 1,
visible = 2,
disappearing = 3
}
#endregion
#region TaskbarNotifier Constructor
/// <summary>
/// The Constructor for TaskbarNotifier
/// </summary>
public TaskbarNotifier()
{
// Window Style
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Minimized;
base.Show();
base.Hide();
WindowState = FormWindowState.Normal;
ShowInTaskbar = false;
TopMost = true;
MaximizeBox = false;
MinimizeBox = false;
ControlBox = false;
timer.Enabled = true;
timer.Tick += new EventHandler(OnTimer);
}
#endregion
#region TaskbarNotifier Properties
/// <summary>
/// Get the current TaskbarState (hidden, showing, visible, hiding)
/// </summary>
public TaskbarStates TaskbarState
{
get
{
return taskbarState;
}
}
/// <summary>
/// Get/Set the popup Title Text
/// </summary>
public string TitleText
{
get
{
return titleText;
}
set
{
titleText=value;
Refresh();
}
}
/// <summary>
/// Get/Set the popup Content Text
/// </summary>
public string ContentText
{
get
{
return contentText;
}
set
{
contentText=value;
Refresh();
}
}
/// <summary>
/// Get/Set the Normal Title Color
/// </summary>
public Color NormalTitleColor
{
get
{
return normalTitleColor;
}
set
{
normalTitleColor = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Hover Title Color
/// </summary>
public Color HoverTitleColor
{
get
{
return hoverTitleColor;
}
set
{
hoverTitleColor = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Normal Content Color
/// </summary>
public Color NormalContentColor
{
get
{
return normalContentColor;
}
set
{
normalContentColor = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Hover Content Color
/// </summary>
public Color HoverContentColor
{
get
{
return hoverContentColor;
}
set
{
hoverContentColor = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Normal Title Font
/// </summary>
public Font NormalTitleFont
{
get
{
return normalTitleFont;
}
set
{
normalTitleFont = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Hover Title Font
/// </summary>
public Font HoverTitleFont
{
get
{
return hoverTitleFont;
}
set
{
hoverTitleFont = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Normal Content Font
/// </summary>
public Font NormalContentFont
{
get
{
return normalContentFont;
}
set
{
normalContentFont = value;
Refresh();
}
}
/// <summary>
/// Get/Set the Hover Content Font
/// </summary>
public Font HoverContentFont
{
get
{
return hoverContentFont;
}
set
{
hoverContentFont = value;
Refresh();
}
}
/// <summary>
/// Indicates if the popup should remain visible when the mouse pointer is over it.
/// Added Rev 002
/// </summary>
public bool KeepVisibleOnMousOver
{
get
{
return bKeepVisibleOnMouseOver;
}
set
{
bKeepVisibleOnMouseOver=value;
}
}
/// <summary>
/// Indicates if the popup should appear again when mouse moves over it while it's disappearing.
/// Added Rev 002
/// </summary>
public bool ReShowOnMouseOver
{
get
{
return bReShowOnMouseOver;
}
set
{
bReShowOnMouseOver=value;
}
}
#endregion
#region TaskbarNotifier Public Methods
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd,Int32 nCmdShow);
/// <summary>
/// Displays the popup for a certain amount of time
/// </summary>
/// <param name="strTitle">The string which will be shown as the title of the popup</param>
/// <param name="strContent">The string which will be shown as the content of the popup</param>
/// <param name="nTimeToShow">Duration of the showing animation (in milliseconds)</param>
/// <param name="nTimeToStay">Duration of the visible state before collapsing (in milliseconds)</param>
/// <param name="nTimeToHide">Duration of the hiding animation (in milliseconds)</param>
/// <returns>Nothing</returns>
public void Show(string strTitle, string strContent, int nTimeToShow, int nTimeToStay, int nTimeToHide)
{
WorkAreaRectangle = Screen.GetWorkingArea(WorkAreaRectangle);
titleText = strTitle;
contentText = strContent;
nVisibleEvents = nTimeToStay;
CalculateMouseRectangles();
// We calculate the pixel increment and the timer value for the showing animation
int nEvents;
if (nTimeToShow > 10)
{
nEvents = Math.Min((nTimeToShow / 10), BackgroundBitmap.Height);
nShowEvents = nTimeToShow / nEvents;
nIncrementShow = BackgroundBitmap.Height / nEvents;
}
else
{
nShowEvents = 10;
nIncrementShow = BackgroundBitmap.Height;
}
// We calculate the pixel increment and the timer value for the hiding animation
if( nTimeToHide > 10)
{
nEvents = Math.Min((nTimeToHide / 10), BackgroundBitmap.Height);
nHideEvents = nTimeToHide / nEvents;
nIncrementHide = BackgroundBitmap.Height / nEvents;
}
else
{
nHideEvents = 10;
nIncrementHide = BackgroundBitmap.Height;
}
switch (taskbarState)
{
case TaskbarStates.hidden:
taskbarState = TaskbarStates.appearing;
SetBounds(WorkAreaRectangle.Right-BackgroundBitmap.Width-17, WorkAreaRectangle.Bottom-1, BackgroundBitmap.Width, 0);
timer.Interval = nShowEvents;
timer.Start();
// We Show the popup without stealing focus
ShowWindow(this.Handle, 4);
break;
case TaskbarStates.appearing:
Refresh();
break;
case TaskbarStates.visible:
timer.Stop();
timer.Interval = nVisibleEvents;
timer.Start();
Refresh();
break;
case TaskbarStates.disappearing:
timer.Stop();
taskbarState = TaskbarStates.visible;
SetBounds(WorkAreaRectangle.Right-BackgroundBitmap.Width-17, WorkAreaRectangle.Bottom-BackgroundBitmap.Height-1, BackgroundBitmap.Width, BackgroundBitmap.Height);
timer.Interval = nVisibleEvents;
timer.Start();
Refresh();
break;
}
}
/// <summary>
/// Hides the popup
/// </summary>
/// <returns>Nothing</returns>
public new void Hide()
{
if (taskbarState != TaskbarStates.hidden)
{
timer.Stop();
taskbarState = TaskbarStates.hidden;
base.Hide();
}
}
/// <summary>
/// Sets the background bitmap and its transparency color
/// </summary>
/// <param name="strFilename">Path of the Background Bitmap on the disk</param>
/// <param name="transparencyColor">Color of the Bitmap which won't be visible</param>
/// <returns>Nothing</returns>
public void SetBackgroundBitmap(string strFilename, Color transparencyColor)
{
BackgroundBitmap = new Bitmap(strFilename);
Width = BackgroundBitmap.Width;
Height = BackgroundBitmap.Height;
Region = BitmapToRegion(BackgroundBitmap, transparencyColor);
}
/// <summary>
/// Sets the background bitmap and its transparency color
/// </summary>
/// <param name="image">Image/Bitmap object which represents the Background Bitmap</param>
/// <param name="transparencyColor">Color of the Bitmap which won't be visible</param>
/// <returns>Nothing</returns>
public void SetBackgroundBitmap(Image image, Color transparencyColor)
{
BackgroundBitmap = new Bitmap(image);
Width = BackgroundBitmap.Width;
Height = BackgroundBitmap.Height;
Region = BitmapToRegion(BackgroundBitmap, transparencyColor);
}
/// <summary>
/// Sets the 3-State Close Button bitmap, its transparency color and its coordinates
/// </summary>
/// <param name="strFilename">Path of the 3-state Close button Bitmap on the disk (width must a multiple of 3)</param>
/// <param name="transparencyColor">Color of the Bitmap which won't be visible</param>
/// <param name="position">Location of the close button on the popup</param>
/// <returns>Nothing</returns>
public void SetCloseBitmap(string strFilename, Color transparencyColor, Point position)
{
CloseBitmap = new Bitmap(strFilename);
CloseBitmap.MakeTransparent(transparencyColor);
CloseBitmapSize = new Size(CloseBitmap.Width/3, CloseBitmap.Height);
CloseBitmapLocation = position;
}
/// <summary>
/// Sets the 3-State Close Button bitmap, its transparency color and its coordinates
/// </summary>
/// <param name="image">Image/Bitmap object which represents the 3-state Close button Bitmap (width must be a multiple of 3)</param>
/// <param name="transparencyColor">Color of the Bitmap which won't be visible</param>
/// /// <param name="position">Location of the close button on the popup</param>
/// <returns>Nothing</returns>
public void SetCloseBitmap(Image image, Color transparencyColor, Point position)
{
CloseBitmap = new Bitmap(image);
CloseBitmap.MakeTransparent(transparencyColor);
CloseBitmapSize = new Size(CloseBitmap.Width/3, CloseBitmap.Height);
CloseBitmapLocation = position;
}
#endregion
#region TaskbarNotifier Protected Methods
protected void DrawCloseButton(Graphics grfx)
{
if (CloseBitmap != null)
{
Rectangle rectDest = new Rectangle(CloseBitmapLocation, CloseBitmapSize);
Rectangle rectSrc;
if (bIsMouseOverClose)
{
if (bIsMouseDown)
rectSrc = new Rectangle(new Point(CloseBitmapSize.Width*2, 0), CloseBitmapSize);
else
rectSrc = new Rectangle(new Point(CloseBitmapSize.Width, 0), CloseBitmapSize);
}
else
rectSrc = new Rectangle(new Point(0, 0), CloseBitmapSize);
grfx.DrawImage(CloseBitmap, rectDest, rectSrc, GraphicsUnit.Pixel);
}
}
protected void DrawText(Graphics grfx)
{
if (titleText != null && titleText.Length != 0)
{
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.NoWrap;
sf.Trimming = StringTrimming.EllipsisCharacter; // Added Rev 002
if (bIsMouseOverTitle)
grfx.DrawString(titleText, hoverTitleFont, new SolidBrush(hoverTitleColor), TitleRectangle, sf);
else
grfx.DrawString(titleText, normalTitleFont, new SolidBrush(normalTitleColor), TitleRectangle, sf);
}
if (contentText != null && contentText.Length != 0)
{
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
sf.Trimming = StringTrimming.Word; // Added Rev 002
if (bIsMouseOverContent)
{
grfx.DrawString(contentText, hoverContentFont, new SolidBrush(hoverContentColor), ContentRectangle, sf);
if (EnableSelectionRectangle)
ControlPaint.DrawBorder3D(grfx, RealContentRectangle, Border3DStyle.Etched, Border3DSide.Top | Border3DSide.Bottom | Border3DSide.Left | Border3DSide.Right);
}
else
grfx.DrawString(contentText, normalContentFont, new SolidBrush(normalContentColor), ContentRectangle, sf);
}
}
protected void CalculateMouseRectangles()
{
Graphics grfx = CreateGraphics();
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
SizeF sizefTitle = grfx.MeasureString(titleText, hoverTitleFont, TitleRectangle.Width, sf);
SizeF sizefContent = grfx.MeasureString(contentText, hoverContentFont, ContentRectangle.Width, sf);
grfx.Dispose();
// Added Rev 002
//We should check if the title size really fits inside the pre-defined title rectangle
if (sizefTitle.Height > TitleRectangle.Height)
{
RealTitleRectangle = new Rectangle(TitleRectangle.Left, TitleRectangle.Top, TitleRectangle.Width , TitleRectangle.Height );
}
else
{
RealTitleRectangle = new Rectangle(TitleRectangle.Left, TitleRectangle.Top, (int)sizefTitle.Width, (int)sizefTitle.Height);
}
RealTitleRectangle.Inflate(0,2);
// Added Rev 002
//We should check if the Content size really fits inside the pre-defined Content rectangle
if (sizefContent.Height > ContentRectangle.Height)
{
RealContentRectangle = new Rectangle((ContentRectangle.Width-(int)sizefContent.Width)/2+ContentRectangle.Left, ContentRectangle.Top, (int)sizefContent.Width, ContentRectangle.Height );
}
else
{
RealContentRectangle = new Rectangle((ContentRectangle.Width-(int)sizefContent.Width)/2+ContentRectangle.Left, (ContentRectangle.Height-(int)sizefContent.Height)/2+ContentRectangle.Top, (int)sizefContent.Width, (int)sizefContent.Height);
}
RealContentRectangle.Inflate(0,2);
}
protected Region BitmapToRegion(Bitmap bitmap, Color transparencyColor)
{
if (bitmap == null)
throw new ArgumentNullException("Bitmap", "Bitmap cannot be null!");
int height = bitmap.Height;
int width = bitmap.Width;
GraphicsPath path = new GraphicsPath();
for (int j=0; j<height; j++ )
for (int i=0; i<width; i++)
{
if (bitmap.GetPixel(i, j) == transparencyColor)
continue;
int x0 = i;
while ((i < width) && (bitmap.GetPixel(i, j) != transparencyColor))
i++;
path.AddRectangle(new Rectangle(x0, j, i-x0, 1));
}
Region region = new Region(path);
path.Dispose();
return region;
}
#endregion
#region TaskbarNotifier Events Overrides
protected void OnTimer(Object obj, EventArgs ea)
{
switch (taskbarState)
{
case TaskbarStates.appearing:
if (Height < BackgroundBitmap.Height)
SetBounds(Left, Top-nIncrementShow ,Width, Height + nIncrementShow);
else
{
timer.Stop();
Height = BackgroundBitmap.Height;
timer.Interval = nVisibleEvents;
taskbarState = TaskbarStates.visible;
timer.Start();
}
break;
case TaskbarStates.visible:
timer.Stop();
timer.Interval = nHideEvents;
// Added Rev 002
if ((bKeepVisibleOnMouseOver && !bIsMouseOverPopup ) || (!bKeepVisibleOnMouseOver))
{
taskbarState = TaskbarStates.disappearing;
}
//taskbarState = TaskbarStates.disappearing; // Rev 002
timer.Start();
break;
case TaskbarStates.disappearing:
// Added Rev 002
if (bReShowOnMouseOver && bIsMouseOverPopup)
{
taskbarState = TaskbarStates.appearing;
}
else
{
if (Top < WorkAreaRectangle.Bottom)
SetBounds(Left, Top + nIncrementHide, Width, Height - nIncrementHide);
else
Hide();
}
break;
}
}
protected override void OnMouseEnter(EventArgs ea)
{
base.OnMouseEnter(ea);
bIsMouseOverPopup = true;
Refresh();
}
protected override void OnMouseLeave(EventArgs ea)
{
base.OnMouseLeave(ea);
bIsMouseOverPopup = false;
bIsMouseOverClose = false;
bIsMouseOverTitle = false;
bIsMouseOverContent = false;
Refresh();
}
protected override void OnMouseMove(MouseEventArgs mea)
{
base.OnMouseMove(mea);
bool bContentModified = false;
if ( (mea.X > CloseBitmapLocation.X) && (mea.X < CloseBitmapLocation.X + CloseBitmapSize.Width) && (mea.Y > CloseBitmapLocation.Y) && (mea.Y < CloseBitmapLocation.Y + CloseBitmapSize.Height) && CloseClickable )
{
if (!bIsMouseOverClose)
{
bIsMouseOverClose = true;
bIsMouseOverTitle = false;
bIsMouseOverContent = false;
Cursor = Cursors.Hand;
bContentModified = true;
}
}
else if (RealContentRectangle.Contains(new Point(mea.X, mea.Y)) && ContentClickable)
{
if (!bIsMouseOverContent)
{
bIsMouseOverClose = false;
bIsMouseOverTitle = false;
bIsMouseOverContent = true;
Cursor = Cursors.Hand;
bContentModified = true;
}
}
else if (RealTitleRectangle.Contains(new Point(mea.X, mea.Y)) && TitleClickable)
{
if (!bIsMouseOverTitle)
{
bIsMouseOverClose = false;
bIsMouseOverTitle = true;
bIsMouseOverContent = false;
Cursor = Cursors.Hand;
bContentModified = true;
}
}
else
{
if (bIsMouseOverClose || bIsMouseOverTitle || bIsMouseOverContent)
bContentModified = true;
bIsMouseOverClose = false;
bIsMouseOverTitle = false;
bIsMouseOverContent = false;
Cursor = Cursors.Default;
}
if (bContentModified)
Refresh();
}
protected override void OnMouseDown(MouseEventArgs mea)
{
base.OnMouseDown(mea);
bIsMouseDown = true;
if (bIsMouseOverClose)
Refresh();
}
protected override void OnMouseUp(MouseEventArgs mea)
{
base.OnMouseUp(mea);
bIsMouseDown = false;
if (bIsMouseOverClose)
{
Hide();
if (CloseClick != null)
CloseClick(this, new EventArgs());
}
else if (bIsMouseOverTitle)
{
if (TitleClick != null)
TitleClick(this, new EventArgs());
}
else if (bIsMouseOverContent)
{
if (ContentClick != null)
ContentClick(this, new EventArgs());
}
}
protected override void OnPaintBackground(PaintEventArgs pea)
{
Graphics grfx = pea.Graphics;
grfx.PageUnit = GraphicsUnit.Pixel;
Graphics offScreenGraphics;
Bitmap offscreenBitmap;
offscreenBitmap = new Bitmap(BackgroundBitmap.Width, BackgroundBitmap.Height);
offScreenGraphics = Graphics.FromImage(offscreenBitmap);
if (BackgroundBitmap != null)
{
offScreenGraphics.DrawImage(BackgroundBitmap, 0, 0, BackgroundBitmap.Width, BackgroundBitmap.Height);
}
DrawCloseButton(offScreenGraphics);
DrawText(offScreenGraphics);
grfx.DrawImage(offscreenBitmap, 0, 0);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !UNIX
using System.Collections.Generic;
using System.Diagnostics.Eventing;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation.Tracing
{
/// <summary>
/// Attribute to represent an EtwEvent.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public sealed class EtwEvent : Attribute
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="eventId"></param>
public EtwEvent(long eventId)
{
this.EventId = eventId;
}
/// <summary>
/// EventId.
/// </summary>
public long EventId { get; }
}
/// <summary>
/// Delegates that defines a call back with no parameter.
/// </summary>
public delegate void CallbackNoParameter();
/// <summary>
/// Delegates that defines a call back with one parameter (state)
/// </summary>
public delegate void CallbackWithState(object state);
/// <summary>
/// Delegates that defines a call back with two parameters; state and ElapsedEventArgs.
/// It will be used in System.Timers.Timer scenarios.
/// </summary>
public delegate void CallbackWithStateAndArgs(object state, System.Timers.ElapsedEventArgs args);
/// <summary>
/// ETW events argument class.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public class EtwEventArgs : EventArgs
{
/// <summary> Gets Event descriptor </summary>
public EventDescriptor Descriptor
{
get;
private set;
}
/// <summary> Gets whether the event is successfully written </summary>
public bool Success { get; }
/// <summary> Gets payload in the event </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] Payload { get; }
/// <summary>
/// Creates a new instance of EtwEventArgs class.
/// </summary>
/// <param name="descriptor">Event descriptor.</param>
/// <param name="success">Indicate whether the event is successfully written.</param>
/// <param name="payload">Event payload.</param>
public EtwEventArgs(EventDescriptor descriptor, bool success, object[] payload)
{
this.Descriptor = descriptor;
this.Payload = payload;
this.Success = success;
}
}
/// <summary>
/// This the abstract base class of all activity classes that represent an end-to-end scenario.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public abstract class EtwActivity
{
/// <summary>
/// This is a helper class that is used to wrap many multi-threading scenarios
/// and makes correlation event to be logged easily.
/// </summary>
private sealed class CorrelatedCallback
{
private readonly CallbackNoParameter callbackNoParam;
private readonly CallbackWithState callbackWithState;
private readonly AsyncCallback asyncCallback;
/// <summary>
/// ParentActivityId.
/// </summary>
private readonly Guid parentActivityId;
private readonly EtwActivity tracer;
/// <summary>
/// EtwCorrelator Constructor.
/// </summary>
/// <param name="tracer"></param>
/// <param name="callback"></param>
public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
if (tracer == null)
{
throw new ArgumentNullException(nameof(tracer));
}
this.tracer = tracer;
this.parentActivityId = EtwActivity.GetActivityId();
this.callbackNoParam = callback;
}
/// <summary>
/// EtwCorrelator Constructor.
/// </summary>
/// <param name="tracer"></param>
/// <param name="callback"></param>
public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
if (tracer == null)
{
throw new ArgumentNullException(nameof(tracer));
}
this.tracer = tracer;
this.parentActivityId = EtwActivity.GetActivityId();
this.callbackWithState = callback;
}
/// <summary>
/// EtwCorrelator Constructor.
/// </summary>
/// <param name="tracer"></param>
/// <param name="callback"></param>
public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
if (tracer == null)
{
throw new ArgumentNullException(nameof(tracer));
}
this.tracer = tracer;
this.parentActivityId = EtwActivity.GetActivityId();
this.asyncCallback = callback;
}
/// <summary>
/// It is to be used in System.Timers.Timer scenarios.
/// </summary>
private readonly CallbackWithStateAndArgs callbackWithStateAndArgs;
/// <summary>
/// EtwCorrelator Constructor.
/// </summary>
/// <param name="tracer"></param>
/// <param name="callback"></param>
public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
if (tracer == null)
{
throw new ArgumentNullException(nameof(tracer));
}
this.tracer = tracer;
this.parentActivityId = EtwActivity.GetActivityId();
this.callbackWithStateAndArgs = callback;
}
/// <summary>
/// This is the wrapper on the actual callback.
/// </summary>
public void Callback(object state, System.Timers.ElapsedEventArgs args)
{
Debug.Assert(callbackWithStateAndArgs != null, "callback is NULL. There MUST always ba a valid callback!");
Correlate();
this.callbackWithStateAndArgs(state, args);
}
/// <summary>
/// Correlate.
/// </summary>
private void Correlate()
{
tracer.CorrelateWithActivity(this.parentActivityId);
}
/// <summary>
/// This is the wrapper on the actual callback.
/// </summary>
public void Callback()
{
Debug.Assert(callbackNoParam != null, "callback is NULL. There MUST always ba a valid callback");
Correlate();
this.callbackNoParam();
}
/// <summary>
/// This is the wrapper on the actual callback.
/// </summary>
public void Callback(object state)
{
Debug.Assert(callbackWithState != null, "callback is NULL. There MUST always ba a valid callback!");
Correlate();
this.callbackWithState(state);
}
/// <summary>
/// This is the wrapper on the actual callback.
/// </summary>
public void Callback(IAsyncResult asyncResult)
{
Debug.Assert(asyncCallback != null, "callback is NULL. There MUST always ba a valid callback!");
Correlate();
this.asyncCallback(asyncResult);
}
}
private static readonly Dictionary<Guid, EventProvider> providers = new Dictionary<Guid, EventProvider>();
private static readonly object syncLock = new object();
private static readonly EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000);
private EventProvider currentProvider;
/// <summary>
/// Event handler for the class.
/// </summary>
public static event EventHandler<EtwEventArgs> EventWritten;
/// <summary>
/// Sets the activityId provided in the current thread.
/// If current thread already has the same activityId it does
/// nothing.
/// </summary>
/// <param name="activityId"></param>
/// <returns>True when provided activity was set, false if current activity
/// was found to be same and set was not needed.</returns>
public static bool SetActivityId(Guid activityId)
{
if (GetActivityId() != activityId)
{
EventProvider.SetActivityId(ref activityId);
return true;
}
return false;
}
/// <summary>
/// Creates a new ActivityId that can be used to set in the thread's context.
/// </summary>
/// <returns></returns>
public static Guid CreateActivityId()
{
return EventProvider.CreateActivityId();
}
/// <summary>
/// Returns the ActivityId set in current thread.
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")]
public static Guid GetActivityId()
{
Guid activityId = Guid.Empty;
uint hresult = UnsafeNativeMethods.EventActivityIdControl(UnsafeNativeMethods.ActivityControlCode.Get, ref activityId);
return activityId;
}
/// <summary>
/// Constructor.
/// </summary>
protected EtwActivity()
{
}
/// <summary>
/// CorrelateWithActivity (EventId: 0x1f05/7941)
/// This method also sets a new activity id in current thread.
/// And then correlates the new id with parentActivityId.
/// </summary>
public void CorrelateWithActivity(Guid parentActivityId)
{
EventProvider provider = GetProvider();
if (!provider.IsEnabled())
return;
Guid activityId = CreateActivityId();
SetActivityId(activityId);
if (parentActivityId != Guid.Empty)
{
EventDescriptor transferEvent = TransferEvent;
provider.WriteTransferEvent(in transferEvent, parentActivityId, activityId, parentActivityId);
}
}
/// <summary>
/// IsEnabled.
/// </summary>
public bool IsEnabled
{
get
{
return GetProvider().IsEnabled();
}
}
/// <summary>
/// Checks whether a provider matching certain levels and keyword is enabled.
/// </summary>
/// <param name="levels">Levels to check.</param>
/// <param name="keywords">Keywords to check.</param>
/// <returns>True, if any ETW listener is enabled else false.</returns>
public bool IsProviderEnabled(byte levels, long keywords)
{
return GetProvider().IsEnabled(levels, keywords);
}
/// <summary>
/// Correlates parent activity id set in the thread with a new activity id
/// If parent activity id is not, it just sets a new activity in the current thread. And does not write the Transfer event.
/// </summary>
public void Correlate()
{
Guid parentActivity = GetActivityId();
CorrelateWithActivity(parentActivity);
}
/// <summary>
/// Wraps a callback with no params.
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public CallbackNoParameter Correlate(CallbackNoParameter callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
return new CorrelatedCallback(this, callback).Callback;
}
/// <summary>
/// Wraps a callback with one object param.
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public CallbackWithState Correlate(CallbackWithState callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
return new CorrelatedCallback(this, callback).Callback;
}
/// <summary>
/// Wraps a AsyncCallback with IAsyncResult param.
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public AsyncCallback Correlate(AsyncCallback callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
return new CorrelatedCallback(this, callback).Callback;
}
/// <summary>
/// Wraps a callback with one object param and one ElapsedEventArgs object
/// This is menat to be used in System.Timers.Timer scenarios.
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
return new CorrelatedCallback(this, callback).Callback;
}
/// <summary>
/// The provider where the tracing messages will be written to.
/// </summary>
protected virtual Guid ProviderId
{
get
{
return PSEtwLogProvider.ProviderGuid;
}
}
/// <summary>
/// The event that is defined to be used to log transfer event.
/// The derived class must override this property if they don't
/// want to use the PowerShell's transfer event.
/// </summary>
protected virtual EventDescriptor TransferEvent
{
get
{
return _WriteTransferEvent;
}
}
/// <summary>
/// This is the main method that write the messages to the trace.
/// All derived classes must use this method to write to the provider log.
/// </summary>
/// <param name="ed">EventDescriptor.</param>
/// <param name="payload">Payload.</param>
protected void WriteEvent(EventDescriptor ed, params object[] payload)
{
EventProvider provider = GetProvider();
if (!provider.IsEnabled())
return;
if (payload != null)
{
for (int i = 0; i < payload.Length; i++)
{
if (payload[i] == null)
{
payload[i] = string.Empty;
}
}
}
bool success = provider.WriteEvent(in ed, payload);
if (EventWritten != null)
{
EventWritten.Invoke(this, new EtwEventArgs(ed, success, payload));
}
}
private EventProvider GetProvider()
{
if (currentProvider != null)
return currentProvider;
lock (syncLock)
{
if (currentProvider != null)
return currentProvider;
if (!providers.TryGetValue(ProviderId, out currentProvider))
{
currentProvider = new EventProvider(ProviderId);
providers[ProviderId] = currentProvider;
}
}
return currentProvider;
}
private static class UnsafeNativeMethods
{
internal enum ActivityControlCode : uint
{
/// <summary>
/// Gets the ActivityId from thread local storage.
/// </summary>
Get = 1,
/// <summary>
/// Sets the ActivityId in the thread local storage.
/// </summary>
Set = 2,
/// <summary>
/// Creates a new activity id.
/// </summary>
Create = 3,
/// <summary>
/// Sets the activity id in thread local storage and returns the previous value.
/// </summary>
GetSet = 4,
/// <summary>
/// Creates a new activity id, sets thread local storage, and returns the previous value.
/// </summary>
CreateSet = 5
}
/// <summary>
/// Provides interop access to creating, querying and setting the current activity identifier.
/// </summary>
/// <param name="controlCode">The <see cref="ActivityControlCode"/> indicating the type of operation to perform.</param>
/// <param name="activityId">The activity id to set or retrieve.</param>
/// <returns>Zero on success.</returns>
[DllImport(PinvokeDllNames.EventActivityIdControlDllName, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = CharSet.Unicode)]
internal static extern unsafe uint EventActivityIdControl([In] ActivityControlCode controlCode, [In][Out] ref Guid activityId);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
namespace System.Transactions
{
internal class CheapUnfairReaderWriterLock
{
private object _writerFinishedEvent;
private int _readersIn;
private int _readersOut;
private bool _writerPresent;
private object _syncRoot;
// Spin lock params
private const int MAX_SPIN_COUNT = 100;
private const int SLEEP_TIME = 500;
public CheapUnfairReaderWriterLock()
{
}
private object SyncRoot
{
get
{
if (_syncRoot == null)
{
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
private bool ReadersPresent => _readersIn != _readersOut;
private ManualResetEvent WriterFinishedEvent
{
get
{
if (_writerFinishedEvent == null)
{
Interlocked.CompareExchange(ref _writerFinishedEvent, new ManualResetEvent(true), null);
}
return (ManualResetEvent)_writerFinishedEvent;
}
}
public int EnterReadLock()
{
int readerIndex = 0;
do
{
if (_writerPresent)
{
WriterFinishedEvent.WaitOne();
}
readerIndex = Interlocked.Increment(ref _readersIn);
if (!_writerPresent)
{
break;
}
Interlocked.Decrement(ref _readersIn);
}
while (true);
return readerIndex;
}
public void EnterWriteLock()
{
Monitor.Enter(SyncRoot);
_writerPresent = true;
WriterFinishedEvent.Reset();
do
{
int i = 0;
while (ReadersPresent && i < MAX_SPIN_COUNT)
{
Thread.Sleep(0);
i++;
}
if (ReadersPresent)
{
Thread.Sleep(SLEEP_TIME);
}
}
while (ReadersPresent);
}
public void ExitReadLock()
{
Interlocked.Increment(ref _readersOut);
}
public void ExitWriteLock()
{
try
{
_writerPresent = false;
WriterFinishedEvent.Set();
}
finally
{
Monitor.Exit(SyncRoot);
}
}
}
// This transaction table implementation uses an array of lists to avoid contention. The list for a
// transaction is decided by its hashcode.
internal class TransactionTable
{
// Use a timer to initiate looking for transactions that have timed out.
private Timer _timer;
// Private storage noting if the timer is enabled.
private bool _timerEnabled;
// Store the timer interval
private const int timerInternalExponent = 9;
private int _timerInterval;
// Store the number of ticks. A tick is a mark of 1 timer interval. By counting ticks
// we can avoid expensive calls to get the current time for every transaction creation.
private const long TicksPerMillisecond = 10000;
private long _ticks;
private long _lastTimerTime;
// Sets of arrays of transactions.
private BucketSet _headBucketSet;
// Synchronize adding transactions with shutting off the timer and started events.
private CheapUnfairReaderWriterLock _rwLock;
internal TransactionTable()
{
// Create a timer that is initially disabled by specifing an Infinite time to the first interval
_timer = new Timer(new TimerCallback(ThreadTimer), null, Timeout.Infinite, _timerInterval);
// Note that the timer is disabled
_timerEnabled = false;
// Store the timer interval
_timerInterval = 1 << TransactionTable.timerInternalExponent;
// Ticks start off at zero.
_ticks = 0;
// The head of the list is long.MaxValue. It contains all of the transactions that for
// some reason or other don't have a timeout.
_headBucketSet = new BucketSet(this, long.MaxValue);
// Allocate the lock
_rwLock = new CheapUnfairReaderWriterLock();
}
// Calculate the maximum number of ticks for which this transaction should live
internal long TimeoutTicks(TimeSpan timeout)
{
if (timeout != TimeSpan.Zero)
{
// Note: At the current setting of approximately 2 ticks per second this timer will
// wrap in approximately 2^64/2/60/60/24/365=292,471,208,677.5360162195585996
// (nearly 300 billion) years.
long timeoutTicks = ((timeout.Ticks / TimeSpan.TicksPerMillisecond) >>
TransactionTable.timerInternalExponent) + _ticks;
return timeoutTicks;
}
else
{
return long.MaxValue;
}
}
// Absolute timeout
internal TimeSpan RecalcTimeout(InternalTransaction tx)
{
return TimeSpan.FromMilliseconds((tx.AbsoluteTimeout - _ticks) * _timerInterval);
}
// Creation time
private long CurrentTime
{
get
{
if (_timerEnabled)
{
return _lastTimerTime;
}
else
{
return DateTime.UtcNow.Ticks;
}
}
}
// Add a transaction to the table. Transactions are added to the end of the list in sorted order based on their
// absolute timeout.
internal int Add(InternalTransaction txNew)
{
// Tell the runtime that we are modifying global state.
int readerIndex = 0;
readerIndex = _rwLock.EnterReadLock();
try
{
// Start the timer if needed before checking the current time since the current
// time can be more efficient with a running timer.
if (txNew.AbsoluteTimeout != long.MaxValue)
{
if (!_timerEnabled)
{
if (!_timer.Change(_timerInterval, _timerInterval))
{
throw TransactionException.CreateInvalidOperationException(
SR.TraceSourceLtm,
SR.UnexpectedTimerFailure,
null
);
}
_lastTimerTime = DateTime.UtcNow.Ticks;
_timerEnabled = true;
}
}
txNew.CreationTime = CurrentTime;
AddIter(txNew);
}
finally
{
_rwLock.ExitReadLock();
}
return readerIndex;
}
private void AddIter(InternalTransaction txNew)
{
//
// Theory of operation.
//
// Note that the head bucket contains any transaction with essentially infinite
// timeout (long.MaxValue). The list is sorted in decending order. To add
// a node the code must walk down the list looking for a set of bucket that matches
// the absolute timeout value for the transaction. When it is found it passes
// the insert down to that set.
//
// An importent thing to note about the list is that forward links are all weak
// references and reverse links are all strong references. This allows the GC
// to clean up old links in the list so that they don't need to be removed manually.
// However if there is still a rooted strong reference to an old link in the
// chain that link wont fall off the list because there is a strong reference held
// forward.
//
BucketSet currentBucketSet = _headBucketSet;
while (currentBucketSet.AbsoluteTimeout != txNew.AbsoluteTimeout)
{
BucketSet lastBucketSet = null;
do
{
WeakReference nextSetWeak = (WeakReference)currentBucketSet.nextSetWeak;
BucketSet nextBucketSet = null;
if (nextSetWeak != null)
{
nextBucketSet = (BucketSet)nextSetWeak.Target;
}
if (nextBucketSet == null)
{
//
// We've reached the end of the list either because nextSetWeak was null or
// because its reference was collected. This code doesn't care. Make a new
// set, attempt to attach it and move on.
//
BucketSet newBucketSet = new BucketSet(this, txNew.AbsoluteTimeout);
WeakReference newSetWeak = new WeakReference(newBucketSet);
WeakReference oldNextSetWeak = (WeakReference)Interlocked.CompareExchange(
ref currentBucketSet.nextSetWeak, newSetWeak, nextSetWeak);
if (oldNextSetWeak == nextSetWeak)
{
// Ladies and Gentlemen we have a winner.
newBucketSet.prevSet = currentBucketSet;
}
// Note that at this point we don't update currentBucketSet. On the next loop
// iteration we should be able to pick up where we left off.
}
else
{
lastBucketSet = currentBucketSet;
currentBucketSet = nextBucketSet;
}
}
while (currentBucketSet.AbsoluteTimeout > txNew.AbsoluteTimeout);
if (currentBucketSet.AbsoluteTimeout != txNew.AbsoluteTimeout)
{
//
// Getting to here means that we've found a slot in the list where this bucket set should go.
//
BucketSet newBucketSet = new BucketSet(this, txNew.AbsoluteTimeout);
WeakReference newSetWeak = new WeakReference(newBucketSet);
newBucketSet.nextSetWeak = lastBucketSet.nextSetWeak;
WeakReference oldNextSetWeak = (WeakReference)Interlocked.CompareExchange(
ref lastBucketSet.nextSetWeak, newSetWeak, newBucketSet.nextSetWeak);
if (oldNextSetWeak == newBucketSet.nextSetWeak)
{
// Ladies and Gentlemen we have a winner.
if (oldNextSetWeak != null)
{
BucketSet oldSet = (BucketSet)oldNextSetWeak.Target;
if (oldSet != null)
{
// prev references are just there to root things for the GC. If this object is
// gone we don't really care.
oldSet.prevSet = newBucketSet;
}
}
newBucketSet.prevSet = lastBucketSet;
}
// Special note - We are going to loop back to the BucketSet that preceeds the one we just tried
// to insert because we may have lost the race to insert our new BucketSet into the list to another
// "Add" thread. By looping back, we check again to see if the BucketSet we just created actually
// got added. If it did, we will exit out of the outer loop and add the transaction. But if we
// lost the race, we will again try to add a new BucketSet. In the latter case, the BucketSet
// we created during the first iteration will simply be Garbage Collected because there are no
// strong references to it since we never added the transaction to a bucket and the act of
// creating the second BucketSet with remove the backward reference that was created in the
// first trip thru the loop.
currentBucketSet = lastBucketSet;
lastBucketSet = null;
// The outer loop will iterate and pick up where we left off.
}
}
//
// Great we found a spot.
//
currentBucketSet.Add(txNew);
}
// Remove a transaction from the table.
internal void Remove(InternalTransaction tx)
{
tx._tableBucket.Remove(tx);
tx._tableBucket = null;
}
// Process a timer event
private void ThreadTimer(Object state)
{
//
// Theory of operation.
//
// To timeout transactions we must walk down the list starting from the head
// until we find a link with an absolute timeout that is greater than our own.
// At that point everything further down in the list is elegable to be timed
// out. So simply remove that link in the list and walk down from that point
// timing out any transaction that is found.
//
// There could be a race between this callback being queued and the timer
// being disabled. If we get here when the timer is disabled, just return.
if (!_timerEnabled)
{
return;
}
// Increment the number of ticks
_ticks++;
_lastTimerTime = DateTime.UtcNow.Ticks;
//
// First find the starting point of transactions that should time out. Every transaction after
// that point will timeout so once we've found it then it is just a matter of traversing the
// structure.
//
BucketSet lastBucketSet = null;
BucketSet currentBucketSet = _headBucketSet; // The list always has a head.
// Acquire a writer lock before checking to see if we should disable the timer.
// Adding of transactions acquires a reader lock and might insert a new BucketSet.
// If that races with our check for a BucketSet existing, we may not timeout that
// transaction that is being added.
WeakReference nextWeakSet = null;
BucketSet nextBucketSet = null;
nextWeakSet = (WeakReference)currentBucketSet.nextSetWeak;
if (nextWeakSet != null)
{
nextBucketSet = (BucketSet)nextWeakSet.Target;
}
if (nextBucketSet == null)
{
_rwLock.EnterWriteLock();
try
{
// Access the nextBucketSet again in writer lock to account for any race before disabling the timeout.
nextWeakSet = (WeakReference)currentBucketSet.nextSetWeak;
if (nextWeakSet != null)
{
nextBucketSet = (BucketSet)nextWeakSet.Target;
}
if (nextBucketSet == null)
{
//
// Special case to allow for disabling the timer.
//
// If there are no transactions on the timeout list we can disable the
// timer.
if (!_timer.Change(Timeout.Infinite, Timeout.Infinite))
{
throw TransactionException.CreateInvalidOperationException(
SR.TraceSourceLtm,
SR.UnexpectedTimerFailure,
null
);
}
_timerEnabled = false;
return;
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
// Note it is slightly subtle that we always skip the head node. This is done
// on purpose because the head node contains transactions with essentially
// an infinite timeout.
do
{
do
{
nextWeakSet = (WeakReference)currentBucketSet.nextSetWeak;
if (nextWeakSet == null)
{
// Nothing more to do.
return;
}
nextBucketSet = (BucketSet)nextWeakSet.Target;
if (nextBucketSet == null)
{
// Again nothing more to do.
return;
}
lastBucketSet = currentBucketSet;
currentBucketSet = nextBucketSet;
}
while (currentBucketSet.AbsoluteTimeout > _ticks);
//
// Pinch off the list at this point making sure it is still the correct set.
//
// Note: We may lose a race with an "Add" thread that is inserting a BucketSet in this location in
// the list. If that happens, this CompareExchange will not be performed and the returned abortingSetsWeak
// value will NOT equal nextWeakSet. But we check for that and if this condition occurs, this iteration of
// the timer thread will simply return, not timing out any transactions. When the next timer interval
// expires, the thread will walk the list again, find the appropriate BucketSet to pinch off, and
// then time out the transactions. This means that it is possible for a transaction to live a bit longer,
// but not much.
WeakReference abortingSetsWeak =
(WeakReference)Interlocked.CompareExchange(ref lastBucketSet.nextSetWeak, null, nextWeakSet);
if (abortingSetsWeak == nextWeakSet)
{
// Yea - now proceed to abort the transactions.
BucketSet abortingBucketSets = null;
do
{
if (abortingSetsWeak != null)
{
abortingBucketSets = (BucketSet)abortingSetsWeak.Target;
}
else
{
abortingBucketSets = null;
}
if (abortingBucketSets != null)
{
abortingBucketSets.TimeoutTransactions();
abortingSetsWeak = (WeakReference)abortingBucketSets.nextSetWeak;
}
}
while (abortingBucketSets != null);
// That's all we needed to do.
break;
}
// We missed pulling the right transactions off. Loop back up and try again.
currentBucketSet = lastBucketSet;
}
while (true);
}
}
internal class BucketSet
{
// Buckets are kept in sets. Each element of a set will have the same absoluteTimeout.
internal object nextSetWeak;
internal BucketSet prevSet;
private TransactionTable _table;
private long _absoluteTimeout;
internal Bucket headBucket;
internal BucketSet(TransactionTable table, long absoluteTimeout)
{
headBucket = new Bucket(this);
_table = table;
_absoluteTimeout = absoluteTimeout;
}
internal long AbsoluteTimeout
{
get
{
return _absoluteTimeout;
}
}
internal void Add(InternalTransaction newTx)
{
while (!headBucket.Add(newTx)) ;
}
internal void TimeoutTransactions()
{
Bucket currentBucket = headBucket;
// It will always have a head.
do
{
currentBucket.TimeoutTransactions();
WeakReference nextWeakBucket = (WeakReference)currentBucket.nextBucketWeak;
if (nextWeakBucket != null)
{
currentBucket = (Bucket)nextWeakBucket.Target;
}
else
{
currentBucket = null;
}
}
while (currentBucket != null);
}
}
internal class Bucket
{
private bool _timedOut;
private int _index;
private int _size;
private InternalTransaction[] _transactions;
internal WeakReference nextBucketWeak;
private Bucket _previous;
private BucketSet _owningSet;
internal Bucket(BucketSet owningSet)
{
_timedOut = false;
_index = -1;
_size = 1024; // A possible design change here is to have this scale dynamically based on load.
_transactions = new InternalTransaction[_size];
_owningSet = owningSet;
}
internal bool Add(InternalTransaction tx)
{
int currentIndex = Interlocked.Increment(ref _index);
if (currentIndex < _size)
{
tx._tableBucket = this;
tx._bucketIndex = currentIndex;
Interlocked.MemoryBarrier(); // This data must be written before the transaction
// could be timed out.
_transactions[currentIndex] = tx;
if (_timedOut)
{
lock (tx)
{
tx.State.Timeout(tx);
}
}
}
else
{
Bucket newBucket = new Bucket(_owningSet);
newBucket.nextBucketWeak = new WeakReference(this);
Bucket oldBucket = Interlocked.CompareExchange(ref _owningSet.headBucket, newBucket, this);
if (oldBucket == this)
{
// ladies and gentlemen we have a winner.
_previous = newBucket;
}
return false;
}
return true;
}
internal void Remove(InternalTransaction tx)
{
_transactions[tx._bucketIndex] = null;
}
internal void TimeoutTransactions()
{
int i;
int transactionCount = _index;
_timedOut = true;
Interlocked.MemoryBarrier();
for (i = 0; i <= transactionCount && i < _size; i++)
{
Debug.Assert(transactionCount == _index, "Index changed timing out transactions");
InternalTransaction tx = _transactions[i];
if (tx != null)
{
lock (tx)
{
tx.State.Timeout(tx);
}
}
}
}
}
}
| |
/*
* XmlNamespaceManager.cs - Implementation of the
* "System.Xml.XmlNamespaceManager" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml
{
using System;
using System.Collections;
public class XmlNamespaceManager : IEnumerable
{
// We generally manipulate values as "Object" rather than "String"
// in this class. This allows us to do quicker string comparisons
// using object "==" rather than string "==". For this reason,
// all strings to be compared must have been interned in the name
// table using "nameTable.Add()" or "nameTable.Get()".
// Internal state.
private XmlNameTable nameTable;
private NamespaceInfo namespaces;
private Object xmlCompareQuick;
private Object xmlNsCompareQuick;
// Constructor.
public XmlNamespaceManager(XmlNameTable nameTable)
{
// Validate the parameters.
if(nameTable == null)
{
throw new ArgumentNullException("nameTable");
}
// Record the name table for later.
this.nameTable = nameTable;
// Add special namespaces for "xml" and "xmlns".
xmlCompareQuick = nameTable.Add("xml");
xmlNsCompareQuick = nameTable.Add("xmlns");
namespaces = new NamespaceInfo
(xmlCompareQuick,
nameTable.Add(XmlDocument.xmlnsXml),
null);
namespaces = new NamespaceInfo
(xmlNsCompareQuick,
nameTable.Add(XmlDocument.xmlns),
namespaces);
// Mark the position of the outermost scope level.
namespaces = new NamespaceInfo(null, String.Empty, namespaces);
}
// Add a namespace to this manager.
public virtual void AddNamespace(String prefix, String uri)
{
// Validate the parameters.
if(((Object)prefix) == null)
{
throw new ArgumentNullException("prefix");
}
else if(((Object)uri) == null)
{
throw new ArgumentNullException("uri");
}
prefix = nameTable.Add(prefix);
uri = nameTable.Add(uri);
if(((Object)prefix) == xmlCompareQuick ||
((Object)prefix) == xmlNsCompareQuick)
{
throw new ArgumentException
(S._("Xml_InvalidNamespace"), "prefix");
}
// See if we already have this prefix in the current scope.
NamespaceInfo info = namespaces;
while(info != null && info.prefix != null)
{
if(info.prefix == (Object)prefix)
{
// Update the URI information and return.
info.uri = uri;
return;
}
info = info.next;
}
// Add a new namespace information block to the current scope.
namespaces = new NamespaceInfo(prefix, uri, namespaces);
}
// Implement the IEnumerable interface.
public virtual IEnumerator GetEnumerator()
{
Hashtable list = new Hashtable();
NamespaceInfo info = namespaces;
while(info != null)
{
if(info.prefix != null &&
!list.Contains(info.prefix))
{
list.Add(info.prefix, null);
}
info = info.next;
}
if(!list.Contains(String.Empty))
{
list.Add(String.Empty, null);
}
return list.Keys.GetEnumerator();
}
// Determine if this namespace manager has a specific namespace.
public virtual bool HasNamespace(String prefix)
{
if(((Object)prefix) == null)
{
// The null prefix name is never valid.
return false;
}
else if(prefix.Length == 0)
{
// We always have the default namespace in the scope.
return true;
}
else
{
// Search for the prefix name.
NamespaceInfo info = namespaces;
prefix = nameTable.Get(prefix);
if(prefix == null)
{
// If the prefix is not in the name table, then
// it cannot be in the namespace list either.
return false;
}
while(info != null)
{
if(info.prefix == (Object)prefix)
{
return true;
}
info = info.next;
}
return false;
}
}
// Get the URI associated with a specific namespace prefix.
public virtual String LookupNamespace(String prefix)
{
if(((Object)prefix) == null)
{
return null;
}
else
{
// Search for the prefix name.
NamespaceInfo info = namespaces;
String newPrefix = nameTable.Get(prefix);
if(((Object)newPrefix) == null)
{
// If the prefix is not in the name table, then
// it cannot be in the namespace list unless it
// is the default namespace specifier.
if(prefix.Length == 0)
{
return String.Empty;
}
else
{
return null;
}
}
while(info != null)
{
if(info.prefix == (Object)newPrefix)
{
return (String)(info.uri);
}
info = info.next;
}
if(newPrefix.Length == 0)
{
// The default namespace must alway have a value.
return String.Empty;
}
return null;
}
}
// Look up the prefix that corresponds to a specific URI.
public virtual String LookupPrefix(String uri)
{
if(((Object)uri) == null)
{
return null;
}
else
{
// Search for the URI in the namespace list.
NamespaceInfo info = namespaces;
uri = nameTable.Get(uri);
if(((Object)uri) == null)
{
// If the URI is not in the name table, then
// it cannot be in the namespace list either.
return String.Empty;
}
while(info != null)
{
if(info.uri == (Object)uri)
{
return (String)(info.prefix);
}
info = info.next;
}
return String.Empty;
}
}
// Push the current namespace scope.
public virtual void PushScope()
{
namespaces = new NamespaceInfo(namespaces);
}
// Pop the current namespace scope.
public virtual bool PopScope()
{
// Bail out if there are no namespaces to be popped.
if(namespaces == null ||
(namespaces.prefix == null && namespaces.uri != null))
{
return false;
}
// Find the end of the namespace list, or the next
// scope boundary block.
while(namespaces != null && namespaces.prefix != null)
{
namespaces = namespaces.next;
}
// Pop the scope boundary block also.
if(namespaces != null && namespaces.uri == null)
{
namespaces = namespaces.next;
}
return true;
}
// Remove a namespace from the current scope.
public virtual void RemoveNamespace(String prefix, String uri)
{
// Validate the parameters.
if(((Object)prefix) == null)
{
throw new ArgumentNullException("prefix");
}
else if(((Object)uri) == null)
{
throw new ArgumentNullException("uri");
}
// Map the prefix and URI into the name table.
// If they aren't present, then the namespace scope
// list is guaranteed not to contain the values.
prefix = nameTable.Get(prefix);
uri = nameTable.Get(uri);
if(((Object)prefix) == null || ((Object)uri) == null)
{
return;
}
// Find the prefix and URI in the current namespace scope.
NamespaceInfo info = namespaces;
NamespaceInfo prev = null;
while(info != null && info.prefix != null)
{
if(info.prefix == (Object)prefix &&
info.uri == (Object)uri)
{
// Remove this entry and return.
if(prev != null)
{
prev.next = info.next;
}
else
{
namespaces = info.next;
}
return;
}
else
{
info = info.next;
}
}
}
// Get the URI for the default namespace.
public virtual String DefaultNamespace
{
get
{
String uri = LookupNamespace(String.Empty);
if(((Object)uri) != null)
{
return uri;
}
else
{
return String.Empty;
}
}
}
// Get the name table that is used by this namespace manager.
public XmlNameTable NameTable
{
get
{
return nameTable;
}
}
// Storage for information about a specific namespace.
private sealed class NamespaceInfo
{
// Publicly accessible state.
public Object prefix;
public Object uri;
public NamespaceInfo next;
// Construct a new namespace information block.
public NamespaceInfo(Object prefix, Object uri, NamespaceInfo next)
{
this.prefix = prefix;
this.uri = uri;
this.next = next;
}
// Construct a new scope boundary block.
public NamespaceInfo(NamespaceInfo next)
{
this.prefix = null;
this.uri = null;
this.next = next;
}
}; // class NamespaceInfo
}; // class XmlNamespaceManager
}; // namespace System.Xml
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using NuGet.Commands;
using NuGet.Common;
namespace NuGet
{
public class Program
{
private const string NuGetExtensionsKey = "NUGET_EXTENSIONS_PATH";
private static readonly string ExtensionsDirectoryRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Commands");
[Import]
public HelpCommand HelpCommand { get; set; }
[ImportMany]
public IEnumerable<ICommand> Commands { get; set; }
[Import]
public ICommandManager Manager { get; set; }
/// <summary>
/// Flag meant for unit tests that prevents command line extensions from being loaded.
/// </summary>
public static bool IgnoreExtensions { get; set; }
public static int Main(string[] args)
{
DebugHelper.WaitForAttach(ref args);
var console = new Common.Console();
var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
try
{
// Remove NuGet.exe.old
RemoveOldFile(fileSystem);
// Import Dependencies
var p = new Program();
p.Initialize(fileSystem, console);
// Add commands to the manager
foreach (ICommand cmd in p.Commands)
{
p.Manager.RegisterCommand(cmd);
}
CommandLineParser parser = new CommandLineParser(p.Manager);
// Parse the command
ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;
// Fallback on the help command if we failed to parse a valid command
if (!ArgumentCountValid(command))
{
// Get the command name and add it to the argument list of the help command
string commandName = command.CommandAttribute.CommandName;
// Print invalid command then show help
console.WriteLine(NuGetResources.InvalidArguments, commandName);
p.HelpCommand.ViewHelpForCommand(commandName);
}
else
{
SetConsoleInteractivity(console, command as Command);
command.Execute();
}
}
catch (AggregateException exception)
{
string message;
Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
if (unwrappedEx == exception)
{
// If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(ex => ex.Message).Distinct(StringComparer.CurrentCulture));
}
else
{
message = ExceptionUtility.Unwrap(exception).Message;
}
console.WriteError(message);
return 1;
}
catch (Exception e)
{
console.WriteError(ExceptionUtility.Unwrap(e).Message);
return 1;
}
return 0;
}
private void Initialize(IFileSystem fileSystem, IConsole console)
{
using (var catalog = new AggregateCatalog(new AssemblyCatalog(GetType().Assembly)))
{
if (!IgnoreExtensions)
{
AddExtensionsToCatalog(catalog, console);
}
using (var container = new CompositionContainer(catalog))
{
var settings = Settings.LoadDefaultSettings(fileSystem);
var packageSourceProvider = PackageSourceBuilder.CreateSourceProvider(settings);
// Register an additional provider for the console specific application so that the user
// will be prompted if a proxy is set and credentials are required
var credentialProvider = new SettingsCredentialProvider(new ConsoleCredentialProvider(console), packageSourceProvider, console);
HttpClient.DefaultCredentialProvider = credentialProvider;
container.ComposeExportedValue<IConsole>(console);
container.ComposeExportedValue<ISettings>(settings);
container.ComposeExportedValue<IPackageRepositoryFactory>(new NuGet.Common.CommandLineRepositoryFactory());
container.ComposeExportedValue<IPackageSourceProvider>(packageSourceProvider);
container.ComposeExportedValue<ICredentialProvider>(credentialProvider);
container.ComposeExportedValue<IFileSystem>(fileSystem);
container.ComposeParts(this);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to block the exe from usage if anything failed")]
internal static void RemoveOldFile(IFileSystem fileSystem)
{
string oldFile = typeof(Program).Assembly.Location + ".old";
try
{
if (fileSystem.FileExists(oldFile))
{
fileSystem.DeleteFile(oldFile);
}
}
catch
{
// We don't want to block the exe from usage if anything failed
}
}
public static bool ArgumentCountValid(ICommand command)
{
CommandAttribute attribute = command.CommandAttribute;
return command.Arguments.Count >= attribute.MinArgs &&
command.Arguments.Count <= attribute.MaxArgs;
}
private static void AddExtensionsToCatalog(AggregateCatalog catalog, IConsole console)
{
IEnumerable<string> directories = new[] { ExtensionsDirectoryRoot };
var customExtensions = Environment.GetEnvironmentVariable(NuGetExtensionsKey);
if (!String.IsNullOrEmpty(customExtensions))
{
// Add all directories from the environment variable if available.
directories = directories.Concat(customExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
IEnumerable<string> files;
foreach (var directory in directories)
{
if (Directory.Exists(directory))
{
files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);
RegisterExtensions(catalog, files, console);
}
}
// Ideally we want to look for all files. However, using MEF to identify imports results in assemblies being loaded and locked by our App Domain
// which could be slow, might affect people's build systems and among other things breaks our build.
// Consequently, we'll use a convention - only binaries ending in the name Extensions would be loaded.
var nugetDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location);
files = Directory.EnumerateFiles(nugetDirectory, "*Extensions.dll");
RegisterExtensions(catalog, files, console);
}
private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable<string> enumerateFiles, IConsole console)
{
foreach (var item in enumerateFiles)
{
try
{
catalog.Catalogs.Add(new AssemblyCatalog(item));
}
catch (BadImageFormatException ex)
{
// Ignore if the dll wasn't a valid assembly
console.WriteWarning(ex.Message);
}
catch (FileLoadException ex)
{
// Ignore if we couldn't load the assembly.
console.WriteWarning(ex.Message);
}
}
}
private static void SetConsoleInteractivity(IConsole console, Command command)
{
// Global environment variable to prevent the exe for prompting for credentials
string globalSwitch = Environment.GetEnvironmentVariable("NUGET_EXE_NO_PROMPT");
// When running from inside VS, no input is available to our executable locking up VS.
// VS sets up a couple of environment variables one of which is named VisualStudioVersion.
// Every time this is setup, we will just fail.
// TODO: Remove this in next iteration. This is meant for short-term backwards compat.
string vsSwitch = Environment.GetEnvironmentVariable("VisualStudioVersion");
console.IsNonInteractive = !String.IsNullOrEmpty(globalSwitch) ||
!String.IsNullOrEmpty(vsSwitch) ||
(command != null && command.NonInteractive);
if (command != null)
{
console.Verbosity = command.Verbosity;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static class Assert
{
public static bool HasAssertFired;
public static void AreEqual(Object actual, Object expected)
{
if (!(actual == null && expected == null) && !actual.Equals(expected))
{
Console.WriteLine("Not equal!");
Console.WriteLine("actual = " + actual.ToString());
Console.WriteLine("expected = " + expected.ToString());
HasAssertFired = true;
}
}
}
public interface IMyInterface
{
#if V2
// Adding new methods to interfaces is incompatible change, but we will make sure that it works anyway
void NewInterfaceMethod();
#endif
string InterfaceMethod(string s);
}
public class MyClass : IMyInterface
{
#if V2
public int _field1;
public int _field2;
public int _field3;
#endif
public int InstanceField;
#if V2
public static Object StaticObjectField2;
[ThreadStatic] public static String ThreadStaticStringField2;
[ThreadStatic] public static int ThreadStaticIntField;
public static Nullable<Guid> StaticNullableGuidField;
public static Object StaticObjectField;
[ThreadStatic] public static int ThreadStaticIntField2;
public static long StaticLongField;
[ThreadStatic] public static DateTime ThreadStaticDateTimeField2;
public static long StaticLongField2;
[ThreadStatic] public static DateTime ThreadStaticDateTimeField;
public static Nullable<Guid> StaticNullableGuidField2;
[ThreadStatic] public static String ThreadStaticStringField;
#else
public static Object StaticObjectField;
public static long StaticLongField;
public static Nullable<Guid> StaticNullableGuidField;
[ThreadStatic] public static String ThreadStaticStringField;
[ThreadStatic] public static int ThreadStaticIntField;
[ThreadStatic] public static DateTime ThreadStaticDateTimeField;
#endif
public MyClass()
{
}
#if V2
public virtual void NewVirtualMethod()
{
}
public virtual void NewInterfaceMethod()
{
throw new Exception();
}
#endif
public virtual string VirtualMethod()
{
return "Virtual method result";
}
public virtual string InterfaceMethod(string s)
{
return "Interface" + s + "result";
}
public static string TestInterfaceMethod(IMyInterface i, string s)
{
return i.InterfaceMethod(s);
}
public static void TestStaticFields()
{
StaticObjectField = (int)StaticObjectField + 12345678;
StaticLongField *= 456;
Assert.AreEqual(StaticNullableGuidField, new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673"));
StaticNullableGuidField = null;
ThreadStaticStringField += "World";
ThreadStaticIntField /= 78;
ThreadStaticDateTimeField = ThreadStaticDateTimeField + new TimeSpan(123);
MyGeneric<int,int>.ThreadStatic = new Object();
#if false // TODO: Enable once LDFTN is supported
// Do some operations on static fields on a different thread to verify that we are not mixing thread-static and non-static
Task.Run(() => {
StaticObjectField = (int)StaticObjectField + 1234;
StaticLongField *= 45;
ThreadStaticStringField = "Garbage";
ThreadStaticIntField = 0xBAAD;
ThreadStaticDateTimeField = DateTime.Now;
}).Wait();
#endif
}
[DllImport("api-ms-win-core-sysinfo-l1-1-0.dll")]
public extern static int GetTickCount();
[DllImport("libcoreclr")]
public extern static int GetCurrentThreadId();
static public void TestInterop()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
GetTickCount();
}
else
{
GetCurrentThreadId();
}
}
#if V2
public string MovedToBaseClass()
{
return "MovedToBaseClass";
}
#endif
#if V2
public virtual string ChangedToVirtual()
{
return null;
}
#else
public string ChangedToVirtual()
{
return "ChangedToVirtual";
}
#endif
}
public class MyChildClass : MyClass
{
public MyChildClass()
{
}
#if !V2
public string MovedToBaseClass()
{
return "MovedToBaseClass";
}
#endif
#if V2
public override string ChangedToVirtual()
{
return "ChangedToVirtual";
}
#endif
}
public struct MyStruct : IDisposable
{
int x;
#if V2
void IDisposable.Dispose()
{
}
#else
public void Dispose()
{
}
#endif
}
public class MyGeneric<T,U>
{
#if V2
public object m_unused1;
public string m_Field1;
public object m_unused2;
public T m_Field2;
public object m_unused3;
public List<T> m_Field3;
static public object m_unused4;
static public KeyValuePair<T, int> m_Field4;
static public object m_unused5;
static public int m_Field5;
public object m_unused6;
static public object m_unused7;
#else
public string m_Field1;
public T m_Field2;
public List<T> m_Field3;
static public KeyValuePair<T, int> m_Field4;
static public int m_Field5;
#endif
[ThreadStatic] public static Object ThreadStatic;
public MyGeneric()
{
}
public virtual string GenericVirtualMethod<V,W>()
{
return typeof(T).ToString() + typeof(U).ToString() + typeof(V).ToString() + typeof(W).ToString();
}
#if V2
public string MovedToBaseClass<W>()
{
typeof(Dictionary<W,W>).ToString();
return typeof(List<W>).ToString();
}
#endif
#if V2
public virtual string ChangedToVirtual<W>()
{
return null;
}
#else
public string ChangedToVirtual<W>()
{
return typeof(List<W>).ToString();
}
#endif
public string NonVirtualMethod()
{
return "MyGeneric.NonVirtualMethod";
}
}
public class MyChildGeneric<T> : MyGeneric<T,T>
{
public MyChildGeneric()
{
}
#if !V2
public string MovedToBaseClass<W>()
{
return typeof(List<W>).ToString();
}
#endif
#if V2
public override string ChangedToVirtual<W>()
{
typeof(Dictionary<Int32, W>).ToString();
return typeof(List<W>).ToString();
}
#endif
}
[StructLayout(LayoutKind.Sequential)]
public class MyClassWithLayout
{
#if V2
public int _field1;
public int _field2;
public int _field3;
#endif
}
public struct MyGrowingStruct
{
int x;
int y;
#if V2
Object o1;
Object o2;
#endif
static public MyGrowingStruct Construct()
{
return new MyGrowingStruct() { x = 111, y = 222 };
}
public static void Check(ref MyGrowingStruct s)
{
Assert.AreEqual(s.x, 111);
Assert.AreEqual(s.y, 222);
}
}
public struct MyChangingStruct
{
#if V2
public int y;
public int x;
#else
public int x;
public int y;
#endif
static public MyChangingStruct Construct()
{
return new MyChangingStruct() { x = 111, y = 222 };
}
public static void Check(ref MyChangingStruct s)
{
Assert.AreEqual(s.x, 112);
Assert.AreEqual(s.y, 222);
}
}
public struct MyChangingHFAStruct
{
#if V2
float x;
float y;
#else
int x;
int y;
#endif
static public MyChangingHFAStruct Construct()
{
return new MyChangingHFAStruct() { x = 12, y = 23 };
}
public static void Check(MyChangingHFAStruct s)
{
#if V2
Assert.AreEqual(s.x, 12.0f);
Assert.AreEqual(s.y, 23.0f);
#else
Assert.AreEqual(s.x, 12);
Assert.AreEqual(s.y, 23);
#endif
}
}
public class ByteBaseClass : List<byte>
{
public byte BaseByte;
}
public class ByteChildClass : ByteBaseClass
{
public byte ChildByte;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public ByteChildClass(byte value)
{
ChildByte = 67;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using viadflib.AStar;
namespace viadflib
{
public class Searcher
{
private ViaDFGraph graph;
private AStar.AStar aStar;
private Dictionary<string, string> nameCache;
private Dictionary<int, RoutePiece> routePieceCache;
private Dictionary<int, Route> routeCache;
public Searcher(ViaDFGraph g)
{
graph = g;
aStar = new AStar.AStar(graph);
nameCache = new Dictionary<string, string>();
routePieceCache = new Dictionary<int, RoutePiece>();
routeCache = new Dictionary<int, Route>();
}
private string GetPieceName(ResultRoutePiece piece)
{
return GetNameCached(piece.Lat, piece.Lng);
}
private string GetNameCached(double lat, double lng)
{
string key = lat + "_" + lng;
if (!nameCache.ContainsKey(key))
{
nameCache[key] = DataHandler.GetNameAtPosition(lat, lng);
}
return nameCache[key];
}
private RoutePiece GetRoutePieceCached(int id, DataContext context)
{
if (!routePieceCache.ContainsKey(id))
{
routePieceCache[id] = context.RoutePieces.FirstOrDefault(x => x.ID == id);
}
return routePieceCache[id];
}
private Route GetRouteCached(int id, DataContext context)
{
if (!routeCache.ContainsKey(id))
{
routeCache[id] = context.Routes.FirstOrDefault(x => x.ID == id);
}
return routeCache[id];
}
public List<SearchResult> DoSearch(SearchParams searchParams)
{
List<SearchResult> results = new List<SearchResult>();
var startNode = new Node(searchParams.StartSearch.Lat, searchParams.StartSearch.Lng);
var endNode = new Node(searchParams.EndSearch.Lat, searchParams.EndSearch.Lng);
graph.CreateLinksForTemporaryNode(startNode, true, 100);
graph.CreateLinksForTemporaryNode(endNode, false, 100);
graph.CreateDirectLink(startNode, endNode, 15);
aStar.StartNode = startNode;
aStar.EndNode = endNode;
bool foundResult = aStar.SearchPath(searchParams.NrOfResults);
if (aStar.PathFound)
{
using (var context = new DataContext())
{
var metroIds = context.Routes.Where(x => x.TypeID == (int)TypeEnum.Metro && x.Status != (int)StatusEnum.New).Select(x => x.ID).ToList();
var dlo = new System.Data.Linq.DataLoadOptions();
dlo.LoadWith<RoutePiece>(x => x.Route);
dlo.LoadWith<Route>(x => x.Type);
context.LoadOptions = dlo;
Dictionary<int, RoutePiece> routePieceCache = new Dictionary<int, RoutePiece>();
Dictionary<int, Route> routeCache = new Dictionary<int, Route>();
for (int si = 0; si < aStar.NrOfFoundResults; si++)
{
SearchResult result = new SearchResult();
result.Start = searchParams.StartSearch;
result.End = searchParams.EndSearch;
result.Items = new List<SearchResultItem>();
DateTime currentTime = searchParams.StartTime ?? DateTime.Now;
result.StartTravelTime = currentTime;
var arcs = aStar.GetPathByArcs(si);
double accumulatedTime = 0;
double accumulatedDistance = 0;
Node accumulatedStartNode = null;
List<SearchPosition> accumulatedPath = new List<SearchPosition>();
for (int i = 0; i < arcs.Length; i++)
{
Arc arc = arcs[i];
if (arc.StartNode.RouteID != arc.EndNode.RouteID || arcs.Length == 1)
{
if (accumulatedTime > 0)
{
SearchResultItem item = new SearchResultItem();
Route route = GetRouteCached(arc.StartNode.RouteID, context);
item.Route = ResultRoute.FromRoute(route);
item.Type = ResultType.FromType(route.Type);
item.Start = ResultRoutePiece.FromRoutePiece(GetRoutePieceCached(accumulatedStartNode.RoutePieceID, context));
item.StartName = GetPieceName(item.Start);
item.End = ResultRoutePiece.FromRoutePiece(GetRoutePieceCached(arc.StartNode.RoutePieceID, context));
item.EndName = GetPieceName(item.End);
item.Time = accumulatedTime;
item.Distance = accumulatedDistance;
item.InDirection = ((!item.Route.SplitRoutePieceID.HasValue && item.Start.ID < item.End.ID) || (item.Route.SplitRoutePieceID.HasValue && item.Start.ID < item.Route.SplitRoutePieceID.Value)) ? item.Route.ToName : item.Route.FromName;
// if special price type and last of same type
Route nextRoute = GetRouteCached(arc.EndNode.RouteID, context);
if (route.Type.PriceTypeID != (int)PriceTypeEnum.FixedPriceAllLines || nextRoute == null || nextRoute.TypeID != route.TypeID)
{
item.Price = GetPrice(route, route.Type, item.Distance);
}
else
{
item.Price = 0; // price will be applied later
}
item.StartTravelTime = currentTime;
currentTime = currentTime.AddMinutes(item.Time);
item.EndTravelTime = currentTime;
accumulatedPath.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, ""));
item.Path = accumulatedPath;
accumulatedTime = 0;
accumulatedDistance = 0;
accumulatedPath = new List<SearchPosition>();
result.Items.Add(item);
}
SearchResultItem item2 = new SearchResultItem();
item2.Type = ResultType.FromType(ViaDFGraph.WALKING_TYPE);
item2.Start = ResultRoutePiece.FromRoutePiece(arc.StartNode.RoutePieceID > 0 ? GetRoutePieceCached(arc.StartNode.RoutePieceID, context) : new RoutePiece { Lat = result.Start.Lat, Lng = result.Start.Lng, Name = result.Start.Name });
item2.StartName = GetPieceName(item2.Start);
item2.End = ResultRoutePiece.FromRoutePiece(arc.EndNode.RoutePieceID > 0 ? GetRoutePieceCached(arc.EndNode.RoutePieceID, context) : new RoutePiece { Lat = result.End.Lat, Lng = result.End.Lng, Name = result.End.Name });
item2.EndName = GetPieceName(item2.End);
item2.Time = arc.Cost;
item2.Distance = graph.GetArcDistanceInKm(arc);
item2.StartTravelTime = currentTime;
currentTime = currentTime.AddMinutes(item2.Time);
item2.EndTravelTime = currentTime;
item2.Path.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, ""));
item2.Path.Add(new SearchPosition(arc.EndNode.X, arc.EndNode.Y, ""));
result.Items.Add(item2);
accumulatedStartNode = arc.EndNode;
}
else
{
accumulatedTime += arc.Cost;
accumulatedDistance += graph.GetArcDistanceInKm(arc);
accumulatedPath.Add(new SearchPosition(arc.StartNode.X, arc.StartNode.Y, ""));
}
}
result.EndTravelTime = currentTime;
result.TotalDistance = result.Items.Sum(x => x.Distance);
result.TotalTime = result.Items.Sum(x => x.Time);
result.TotalPrice = result.Items.Sum(x => x.Price);
results.Add(result);
}
}
}
return results.OrderBy(x => x.TotalTime).ToList();
}
public double GetPrice(Route route, Type type, double distance)
{
PriceTypeEnum priceType = (PriceTypeEnum)(route.PriceTypeID ?? type.PriceTypeID);
string priceDefinition = route.PriceTypeID.HasValue ? route.PriceDefinition : type.PriceDefinition;
switch (priceType)
{
case PriceTypeEnum.FixedPrice:
return double.Parse(priceDefinition);
case PriceTypeEnum.VariablePrice:
var ranges = priceDefinition.Split('|');
for (int i = 0; i < ranges.Length; i++)
{
var prices = ranges[i].Split(';');
if (prices.Length < 2 || double.Parse(prices[1]) > distance)
{
return double.Parse(prices[0]);
}
}
break;
case PriceTypeEnum.FixedPriceAllLines:
return double.Parse(priceDefinition);
case PriceTypeEnum.Free:
return 0;
}
return 0;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace SchematicApplication
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
//Ensures that any ESRI libraries that have been used are unloaded in the correct order.
//Failure to do this may result in random crashes on exit due to the operating system unloading
//the libraries in the incorrect order.
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.menuFile = new System.Windows.Forms.ToolStripMenuItem();
this.menuNewDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuOpenDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuSaveDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.menuSeparator = new System.Windows.Forms.ToolStripSeparator();
this.menuExitApp = new System.Windows.Forms.ToolStripMenuItem();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.statusBarXY = new System.Windows.Forms.ToolStripStatusLabel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.cboFrame = new System.Windows.Forms.ComboBox();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.panel1 = new System.Windows.Forms.Panel();
this.axToolbarControl2 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.statusStrip1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl2)).BeginInit();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuFile});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1026, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// menuFile
//
this.menuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuNewDoc,
this.menuOpenDoc,
this.menuSaveDoc,
this.menuSaveAs,
this.menuSeparator,
this.menuExitApp});
this.menuFile.Name = "menuFile";
this.menuFile.Size = new System.Drawing.Size(37, 20);
this.menuFile.Text = "File";
//
// menuNewDoc
//
this.menuNewDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuNewDoc.Image")));
this.menuNewDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuNewDoc.Name = "menuNewDoc";
this.menuNewDoc.Size = new System.Drawing.Size(171, 22);
this.menuNewDoc.Text = "New Document";
this.menuNewDoc.Click += new System.EventHandler(this.menuNewDoc_Click);
//
// menuOpenDoc
//
this.menuOpenDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuOpenDoc.Image")));
this.menuOpenDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuOpenDoc.Name = "menuOpenDoc";
this.menuOpenDoc.Size = new System.Drawing.Size(171, 22);
this.menuOpenDoc.Text = "Open Document...";
this.menuOpenDoc.Click += new System.EventHandler(this.menuOpenDoc_Click);
//
// menuSaveDoc
//
this.menuSaveDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuSaveDoc.Image")));
this.menuSaveDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuSaveDoc.Name = "menuSaveDoc";
this.menuSaveDoc.Size = new System.Drawing.Size(171, 22);
this.menuSaveDoc.Text = "SaveDocument";
this.menuSaveDoc.Click += new System.EventHandler(this.menuSaveDoc_Click);
//
// menuSaveAs
//
this.menuSaveAs.Name = "menuSaveAs";
this.menuSaveAs.Size = new System.Drawing.Size(171, 22);
this.menuSaveAs.Text = "Save As...";
this.menuSaveAs.Click += new System.EventHandler(this.menuSaveAs_Click);
//
// menuSeparator
//
this.menuSeparator.Name = "menuSeparator";
this.menuSeparator.Size = new System.Drawing.Size(168, 6);
//
// menuExitApp
//
this.menuExitApp.Name = "menuExitApp";
this.menuExitApp.Size = new System.Drawing.Size(171, 22);
this.menuExitApp.Text = "Exit";
this.menuExitApp.Click += new System.EventHandler(this.menuExitApp_Click);
//
// axToolbarControl1
//
this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Top;
this.axToolbarControl1.Location = new System.Drawing.Point(0, 24);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(1026, 28);
this.axToolbarControl1.TabIndex = 3;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(466, 278);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 5;
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusBarXY});
this.statusStrip1.Location = new System.Drawing.Point(0, 564);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1026, 22);
this.statusStrip1.Stretch = false;
this.statusStrip1.TabIndex = 7;
this.statusStrip1.Text = "statusBar1";
//
// statusBarXY
//
this.statusBarXY.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter;
this.statusBarXY.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.statusBarXY.Name = "statusBarXY";
this.statusBarXY.Size = new System.Drawing.Size(308, 17);
this.statusBarXY.Text = "Load a map document or a diagram into the MapControl";
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 87);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.cboFrame);
this.splitContainer1.Panel1.Controls.Add(this.axTOCControl1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.axMapControl1);
this.splitContainer1.Size = new System.Drawing.Size(1026, 477);
this.splitContainer1.SplitterDistance = 218;
this.splitContainer1.TabIndex = 8;
//
// cboFrame
//
this.cboFrame.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboFrame.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboFrame.FormattingEnabled = true;
this.cboFrame.Location = new System.Drawing.Point(4, 7);
this.cboFrame.Name = "cboFrame";
this.cboFrame.Size = new System.Drawing.Size(211, 21);
this.cboFrame.TabIndex = 6;
this.cboFrame.SelectedValueChanged += new System.EventHandler(this.onSelectedValueChanged);
//
// axTOCControl1
//
this.axTOCControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.axTOCControl1.Location = new System.Drawing.Point(0, 34);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(218, 443);
this.axTOCControl1.TabIndex = 5;
this.axTOCControl1.OnMouseDown += new ESRI.ArcGIS.Controls.ITOCControlEvents_Ax_OnMouseDownEventHandler(this.axTOCControl1_OnMouseDown);
//
// axMapControl1
//
this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axMapControl1.Location = new System.Drawing.Point(0, 0);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(804, 477);
this.axMapControl1.TabIndex = 3;
this.axMapControl1.OnMouseMove += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseMoveEventHandler(this.axMapControl1_OnMouseMove);
this.axMapControl1.OnMapReplaced += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMapReplacedEventHandler(this.axMapControl1_OnMapReplaced);
//
// panel1
//
this.panel1.Controls.Add(this.axToolbarControl2);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 52);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(1026, 35);
this.panel1.TabIndex = 9;
//
// axToolbarControl2
//
this.axToolbarControl2.Location = new System.Drawing.Point(0, 1);
this.axToolbarControl2.Name = "axToolbarControl2";
this.axToolbarControl2.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl2.OcxState")));
this.axToolbarControl2.Size = new System.Drawing.Size(1023, 28);
this.axToolbarControl2.TabIndex = 0;
this.axToolbarControl2.OnItemClick += new ESRI.ArcGIS.Controls.IToolbarControlEvents_Ax_OnItemClickEventHandler(this.onToolbarItemClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1026, 586);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.axToolbarControl1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.Text = "Schematic Engine Application";
this.Load += new System.EventHandler(this.MainForm_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem menuFile;
private System.Windows.Forms.ToolStripMenuItem menuNewDoc;
private System.Windows.Forms.ToolStripMenuItem menuOpenDoc;
private System.Windows.Forms.ToolStripMenuItem menuSaveDoc;
private System.Windows.Forms.ToolStripMenuItem menuSaveAs;
private System.Windows.Forms.ToolStripMenuItem menuExitApp;
private System.Windows.Forms.ToolStripSeparator menuSeparator;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel statusBarXY;
private System.Windows.Forms.SplitContainer splitContainer1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private System.Windows.Forms.Panel panel1;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl2;
private System.Windows.Forms.ComboBox cboFrame;
}
}
| |
//---------------------------------------------------------------------
// Author: jachymko, Alex K. Angelopoulos
//
// Description: Class representing a terminal server machine.
//
// Creation Date: Sep 24 2006
// Modified Date: Jan 24 2007
//---------------------------------------------------------------------
using System;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using Pscx.Interop;
namespace Pscx.TerminalServices
{
public sealed class TerminalServer
{
private readonly bool _local;
private readonly string _name;
public TerminalServer()
{
_name = System.Net.Dns.GetHostName();
_local = true;
}
public TerminalServer(string name)
{
_name = name;
using (WtsServerCookie cookie = OpenServer())
{
System.Diagnostics.Debug.Assert(cookie.Handle != IntPtr.Zero);
}
}
public string ComputerName
{
get { return _name; }
}
public TerminalSessionCollection Sessions
{
get { return new TerminalSessionCollection(this); }
}
public void TerminateProcess(int processId, int exitCode)
{
using (WtsServerCookie cookie = OpenServer())
{
if (!NativeMethods.WTSTerminateProcess(cookie.Handle, processId, exitCode))
{
throw PscxException.LastWin32Exception();
}
}
}
public void Shutdown(WtsShutdownType type)
{
using (WtsServerCookie cookie = OpenServer())
{
if (!NativeMethods.WTSShutdownSystem(cookie.Handle, (int)(type)))
{
throw PscxException.LastWin32Exception();
}
}
}
public override string ToString()
{
return ComputerName;
}
internal WtsServerCookie OpenServer()
{
if (_local)
{
return new WtsServerCookie();
}
return new WtsServerCookie(NativeMethods.WTSOpenServer(_name));
}
public static int ConsoleSessionId
{
get { return NativeMethods.WTSGetActiveConsoleSessionId(); }
}
}
public sealed class TerminalSessionCollection : ReadOnlyCollection<TerminalSession>
{
internal TerminalSessionCollection(TerminalServer server)
: base (new System.Collections.Generic.List<TerminalSession>())
{
int count = 0;
IntPtr ptr = IntPtr.Zero;
using (WtsServerCookie cookie = server.OpenServer())
{
if (!NativeMethods.WTSEnumerateSessions(cookie.Handle, 0, 1, out ptr, out count))
{
throw PscxException.LastWin32Exception();
}
}
try
{
foreach (WTS_SESSION_INFO info in Utils.ReadNativeArray<WTS_SESSION_INFO>(ptr, count))
{
Items.Add(new TerminalSession(server, info));
}
}
finally
{
NativeMethods.WTSFreeMemory(ptr);
}
}
}
internal struct WtsServerCookie : IDisposable
{
private IntPtr _handle;
internal WtsServerCookie(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
throw PscxException.LastWin32Exception();
}
_handle = handle;
}
public IntPtr Handle
{
get { return _handle; }
}
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
NativeMethods.WTSCloseServer(_handle);
}
}
}
#if FALSE
class TMP {
[StructLayout(LayoutKind.Sequential)]
public struct ServerInfo //WTSAPI32: SERVERInfo // WTSAPI32: WTS_SERVER_INFO
{
IntPtr pServerName; // server name
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessInfo // WTSAPI32: WTS_PROCESS_INFO
{
int SessionId; // session id
int ProcessId; // process id
string ProcessName; // name of process
IntPtr UserSid; // user's SID
}
[StructLayout(LayoutKind.Sequential)]
public struct ClientAddress
{
int AddressFamily; // AF_INET, AF_IPX, AF_NETBIOS, AF_UNSPEC
byte[] Address; // client network address
}
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_DISPLAY
{
int HorizontalResolution; // horizontal dimensions, in pixels
int VerticalResolution; // vertical dimensions, in pixels
int ColorDepth; // 1 = 16, 2 = 256, 4 = 64K, 8 = 16M
}
public enum UserConfiguration
{
//Initial program settings
InitialProgram, // string returned/expected
WorkingDirectory, // string returned/expected
InheritInitialProgram, // long returned/expected
AllowLogon, //long returned/expected
//Timeout settings
TimeoutSettingsConnections, //long returned/expected
TimeoutSettingsDisconnections, //long returned/expected
TimeoutSettingsIdle, //long returned/expected
//Client device settings
DeviceClientDrives, //long returned/expected
DeviceClientPrinters, //long returned/expected
DeviceClientDeaultPrinter, //long returned/expected
//Connection settings
BrokenTimeoutSettings, //long returned/expected
ReconnectSettings, //long returned/expected
//Modem settings
ModemCallbackSettings, //long returned/expected
ModemCallbackPhoneNumber, // string returned/expected
//Shadow settings
ShadowingSettings, //long returned/expected
//User Profile settings
TerminalServerProfilePath, // string returned/expected
//Terminal Server home directory
TerminalServerHomeDir, // string returned/expected
TerminalServerHomeDirDrive, // string returned/expected
HomeLocation,
}
public enum HomeLocation
{
Local = 0,
Remote = 1
}
public enum VirtualChannel
{
VirtualClientData, // Virtual channel client module data
// (C2H data)
VirtualFileHandle
}
public enum SendMessageResponse
{
//Possible pResponse values from WTSSendMessage()
Timeout = 32000,
Asynchronous = 32001
}
[Flags]
public enum WaitSystemEventFlags
{
/* =====================================================================
== EVENT - Event flags for WTSWaitSystemEvent
===================================================================== */
None = 0x00000000, // return no event
CreatedWinstation = 0x00000001, // new WinStation created
DeletedWinstation = 0x00000002, // existing WinStation deleted
RenamedWinstation = 0x00000004, // existing WinStation renamed
ConnectedWinstation = 0x00000008, // WinStation connect to client
DisconnectedWinstation = 0x00000010, // WinStation logged on without client
Disconnected = 0x00000010, // WinStation logged on without client
LogonUser = 0x00000020, // user logged on to existing WinStation
LogoffUser = 0x00000040, // user logged off from existing WinStation
WinstationStateChange = 0x00000080, // WinStation state change
LicenseChange = 0x00000100, // license state change
AllEvents = 0x7fffffff, // wait for all event types
// Unfortunately cannot express this as an unsigned long...
//FlushEvent = 0x80000000 // unblock all waiters
}
public enum Protocol
{
// Not an enum in wtsapi32...
Console = 0,
Ica = 1,
Rdp = 2
}
/* Flags for Console Notification */
[Flags]
public enum Notification
{
ThisSession = 0,
AllSessions = 1
}
}
#endif
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A group of compatible GPUs across the resource pool
/// First published in XenServer 6.0.
/// </summary>
public partial class GPU_group : XenObject<GPU_group>
{
#region Constructors
public GPU_group()
{
}
public GPU_group(string uuid,
string name_label,
string name_description,
List<XenRef<PGPU>> PGPUs,
List<XenRef<VGPU>> VGPUs,
string[] GPU_types,
Dictionary<string, string> other_config,
allocation_algorithm allocation_algorithm,
List<XenRef<VGPU_type>> supported_VGPU_types,
List<XenRef<VGPU_type>> enabled_VGPU_types)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.PGPUs = PGPUs;
this.VGPUs = VGPUs;
this.GPU_types = GPU_types;
this.other_config = other_config;
this.allocation_algorithm = allocation_algorithm;
this.supported_VGPU_types = supported_VGPU_types;
this.enabled_VGPU_types = enabled_VGPU_types;
}
/// <summary>
/// Creates a new GPU_group from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public GPU_group(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new GPU_group from a Proxy_GPU_group.
/// </summary>
/// <param name="proxy"></param>
public GPU_group(Proxy_GPU_group proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given GPU_group.
/// </summary>
public override void UpdateFrom(GPU_group update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
PGPUs = update.PGPUs;
VGPUs = update.VGPUs;
GPU_types = update.GPU_types;
other_config = update.other_config;
allocation_algorithm = update.allocation_algorithm;
supported_VGPU_types = update.supported_VGPU_types;
enabled_VGPU_types = update.enabled_VGPU_types;
}
internal void UpdateFrom(Proxy_GPU_group proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
PGPUs = proxy.PGPUs == null ? null : XenRef<PGPU>.Create(proxy.PGPUs);
VGPUs = proxy.VGPUs == null ? null : XenRef<VGPU>.Create(proxy.VGPUs);
GPU_types = proxy.GPU_types == null ? new string[] {} : (string [])proxy.GPU_types;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
allocation_algorithm = proxy.allocation_algorithm == null ? (allocation_algorithm) 0 : (allocation_algorithm)Helper.EnumParseDefault(typeof(allocation_algorithm), (string)proxy.allocation_algorithm);
supported_VGPU_types = proxy.supported_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.supported_VGPU_types);
enabled_VGPU_types = proxy.enabled_VGPU_types == null ? null : XenRef<VGPU_type>.Create(proxy.enabled_VGPU_types);
}
public Proxy_GPU_group ToProxy()
{
Proxy_GPU_group result_ = new Proxy_GPU_group();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.PGPUs = PGPUs == null ? new string[] {} : Helper.RefListToStringArray(PGPUs);
result_.VGPUs = VGPUs == null ? new string[] {} : Helper.RefListToStringArray(VGPUs);
result_.GPU_types = GPU_types;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.allocation_algorithm = allocation_algorithm_helper.ToString(allocation_algorithm);
result_.supported_VGPU_types = supported_VGPU_types == null ? new string[] {} : Helper.RefListToStringArray(supported_VGPU_types);
result_.enabled_VGPU_types = enabled_VGPU_types == null ? new string[] {} : Helper.RefListToStringArray(enabled_VGPU_types);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this GPU_group
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("PGPUs"))
PGPUs = Marshalling.ParseSetRef<PGPU>(table, "PGPUs");
if (table.ContainsKey("VGPUs"))
VGPUs = Marshalling.ParseSetRef<VGPU>(table, "VGPUs");
if (table.ContainsKey("GPU_types"))
GPU_types = Marshalling.ParseStringArray(table, "GPU_types");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("allocation_algorithm"))
allocation_algorithm = (allocation_algorithm)Helper.EnumParseDefault(typeof(allocation_algorithm), Marshalling.ParseString(table, "allocation_algorithm"));
if (table.ContainsKey("supported_VGPU_types"))
supported_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "supported_VGPU_types");
if (table.ContainsKey("enabled_VGPU_types"))
enabled_VGPU_types = Marshalling.ParseSetRef<VGPU_type>(table, "enabled_VGPU_types");
}
public bool DeepEquals(GPU_group other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._PGPUs, other._PGPUs) &&
Helper.AreEqual2(this._VGPUs, other._VGPUs) &&
Helper.AreEqual2(this._GPU_types, other._GPU_types) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._allocation_algorithm, other._allocation_algorithm) &&
Helper.AreEqual2(this._supported_VGPU_types, other._supported_VGPU_types) &&
Helper.AreEqual2(this._enabled_VGPU_types, other._enabled_VGPU_types);
}
internal static List<GPU_group> ProxyArrayToObjectList(Proxy_GPU_group[] input)
{
var result = new List<GPU_group>();
foreach (var item in input)
result.Add(new GPU_group(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, GPU_group server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
GPU_group.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
GPU_group.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
GPU_group.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_allocation_algorithm, server._allocation_algorithm))
{
GPU_group.set_allocation_algorithm(session, opaqueRef, _allocation_algorithm);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static GPU_group get_record(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_record(session.opaque_ref, _gpu_group);
else
return new GPU_group(session.proxy.gpu_group_get_record(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get a reference to the GPU_group instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<GPU_group> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<GPU_group>.Create(session.proxy.gpu_group_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the GPU_group instances with the given label.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<GPU_group>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<GPU_group>.Create(session.proxy.gpu_group_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static string get_uuid(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_uuid(session.opaque_ref, _gpu_group);
else
return session.proxy.gpu_group_get_uuid(session.opaque_ref, _gpu_group ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static string get_name_label(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_name_label(session.opaque_ref, _gpu_group);
else
return session.proxy.gpu_group_get_name_label(session.opaque_ref, _gpu_group ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static string get_name_description(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_name_description(session.opaque_ref, _gpu_group);
else
return session.proxy.gpu_group_get_name_description(session.opaque_ref, _gpu_group ?? "").parse();
}
/// <summary>
/// Get the PGPUs field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static List<XenRef<PGPU>> get_PGPUs(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_pgpus(session.opaque_ref, _gpu_group);
else
return XenRef<PGPU>.Create(session.proxy.gpu_group_get_pgpus(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get the VGPUs field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static List<XenRef<VGPU>> get_VGPUs(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_vgpus(session.opaque_ref, _gpu_group);
else
return XenRef<VGPU>.Create(session.proxy.gpu_group_get_vgpus(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get the GPU_types field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static string[] get_GPU_types(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_gpu_types(session.opaque_ref, _gpu_group);
else
return (string [])session.proxy.gpu_group_get_gpu_types(session.opaque_ref, _gpu_group ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static Dictionary<string, string> get_other_config(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_other_config(session.opaque_ref, _gpu_group);
else
return Maps.convert_from_proxy_string_string(session.proxy.gpu_group_get_other_config(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get the allocation_algorithm field of the given GPU_group.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static allocation_algorithm get_allocation_algorithm(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_allocation_algorithm(session.opaque_ref, _gpu_group);
else
return (allocation_algorithm)Helper.EnumParseDefault(typeof(allocation_algorithm), (string)session.proxy.gpu_group_get_allocation_algorithm(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get the supported_VGPU_types field of the given GPU_group.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static List<XenRef<VGPU_type>> get_supported_VGPU_types(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_supported_vgpu_types(session.opaque_ref, _gpu_group);
else
return XenRef<VGPU_type>.Create(session.proxy.gpu_group_get_supported_vgpu_types(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Get the enabled_VGPU_types field of the given GPU_group.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static List<XenRef<VGPU_type>> get_enabled_VGPU_types(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_enabled_vgpu_types(session.opaque_ref, _gpu_group);
else
return XenRef<VGPU_type>.Create(session.proxy.gpu_group_get_enabled_vgpu_types(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _gpu_group, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_set_name_label(session.opaque_ref, _gpu_group, _label);
else
session.proxy.gpu_group_set_name_label(session.opaque_ref, _gpu_group ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _gpu_group, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_set_name_description(session.opaque_ref, _gpu_group, _description);
else
session.proxy.gpu_group_set_name_description(session.opaque_ref, _gpu_group ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _gpu_group, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_set_other_config(session.opaque_ref, _gpu_group, _other_config);
else
session.proxy.gpu_group_set_other_config(session.opaque_ref, _gpu_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given GPU_group.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _gpu_group, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_add_to_other_config(session.opaque_ref, _gpu_group, _key, _value);
else
session.proxy.gpu_group_add_to_other_config(session.opaque_ref, _gpu_group ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given GPU_group. If the key is not in that Map, then do nothing.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _gpu_group, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_remove_from_other_config(session.opaque_ref, _gpu_group, _key);
else
session.proxy.gpu_group_remove_from_other_config(session.opaque_ref, _gpu_group ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the allocation_algorithm field of the given GPU_group.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_allocation_algorithm">New value to set</param>
public static void set_allocation_algorithm(Session session, string _gpu_group, allocation_algorithm _allocation_algorithm)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_set_allocation_algorithm(session.opaque_ref, _gpu_group, _allocation_algorithm);
else
session.proxy.gpu_group_set_allocation_algorithm(session.opaque_ref, _gpu_group ?? "", allocation_algorithm_helper.ToString(_allocation_algorithm)).parse();
}
/// <summary>
///
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_name_label"></param>
/// <param name="_name_description"></param>
/// <param name="_other_config"></param>
public static XenRef<GPU_group> create(Session session, string _name_label, string _name_description, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_create(session.opaque_ref, _name_label, _name_description, _other_config);
else
return XenRef<GPU_group>.Create(session.proxy.gpu_group_create(session.opaque_ref, _name_label ?? "", _name_description ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
///
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_name_label"></param>
/// <param name="_name_description"></param>
/// <param name="_other_config"></param>
public static XenRef<Task> async_create(Session session, string _name_label, string _name_description, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_gpu_group_create(session.opaque_ref, _name_label, _name_description, _other_config);
else
return XenRef<Task>.Create(session.proxy.async_gpu_group_create(session.opaque_ref, _name_label ?? "", _name_description ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
///
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static void destroy(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.gpu_group_destroy(session.opaque_ref, _gpu_group);
else
session.proxy.gpu_group_destroy(session.opaque_ref, _gpu_group ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
public static XenRef<Task> async_destroy(Session session, string _gpu_group)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_gpu_group_destroy(session.opaque_ref, _gpu_group);
else
return XenRef<Task>.Create(session.proxy.async_gpu_group_destroy(session.opaque_ref, _gpu_group ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_vgpu_type">The VGPU_type for which the remaining capacity will be calculated</param>
public static long get_remaining_capacity(Session session, string _gpu_group, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_remaining_capacity(session.opaque_ref, _gpu_group, _vgpu_type);
else
return long.Parse(session.proxy.gpu_group_get_remaining_capacity(session.opaque_ref, _gpu_group ?? "", _vgpu_type ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_gpu_group">The opaque_ref of the given gpu_group</param>
/// <param name="_vgpu_type">The VGPU_type for which the remaining capacity will be calculated</param>
public static XenRef<Task> async_get_remaining_capacity(Session session, string _gpu_group, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_gpu_group_get_remaining_capacity(session.opaque_ref, _gpu_group, _vgpu_type);
else
return XenRef<Task>.Create(session.proxy.async_gpu_group_get_remaining_capacity(session.opaque_ref, _gpu_group ?? "", _vgpu_type ?? "").parse());
}
/// <summary>
/// Return a list of all the GPU_groups known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<GPU_group>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_all(session.opaque_ref);
else
return XenRef<GPU_group>.Create(session.proxy.gpu_group_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the GPU_group Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<GPU_group>, GPU_group> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.gpu_group_get_all_records(session.opaque_ref);
else
return XenRef<GPU_group>.Create<Proxy_GPU_group>(session.proxy.gpu_group_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// List of pGPUs in the group
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> PGPUs
{
get { return _PGPUs; }
set
{
if (!Helper.AreEqual(value, _PGPUs))
{
_PGPUs = value;
Changed = true;
NotifyPropertyChanged("PGPUs");
}
}
}
private List<XenRef<PGPU>> _PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of vGPUs using the group
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU>))]
public virtual List<XenRef<VGPU>> VGPUs
{
get { return _VGPUs; }
set
{
if (!Helper.AreEqual(value, _VGPUs))
{
_VGPUs = value;
Changed = true;
NotifyPropertyChanged("VGPUs");
}
}
}
private List<XenRef<VGPU>> _VGPUs = new List<XenRef<VGPU>>() {};
/// <summary>
/// List of GPU types (vendor+device ID) that can be in this group
/// </summary>
public virtual string[] GPU_types
{
get { return _GPU_types; }
set
{
if (!Helper.AreEqual(value, _GPU_types))
{
_GPU_types = value;
Changed = true;
NotifyPropertyChanged("GPU_types");
}
}
}
private string[] _GPU_types = {};
/// <summary>
/// Additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Current allocation of vGPUs to pGPUs for this group
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
[JsonConverter(typeof(allocation_algorithmConverter))]
public virtual allocation_algorithm allocation_algorithm
{
get { return _allocation_algorithm; }
set
{
if (!Helper.AreEqual(value, _allocation_algorithm))
{
_allocation_algorithm = value;
Changed = true;
NotifyPropertyChanged("allocation_algorithm");
}
}
}
private allocation_algorithm _allocation_algorithm = allocation_algorithm.depth_first;
/// <summary>
/// vGPU types supported on at least one of the pGPUs in this group
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU_type>))]
public virtual List<XenRef<VGPU_type>> supported_VGPU_types
{
get { return _supported_VGPU_types; }
set
{
if (!Helper.AreEqual(value, _supported_VGPU_types))
{
_supported_VGPU_types = value;
Changed = true;
NotifyPropertyChanged("supported_VGPU_types");
}
}
}
private List<XenRef<VGPU_type>> _supported_VGPU_types = new List<XenRef<VGPU_type>>() {};
/// <summary>
/// vGPU types supported on at least one of the pGPUs in this group
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU_type>))]
public virtual List<XenRef<VGPU_type>> enabled_VGPU_types
{
get { return _enabled_VGPU_types; }
set
{
if (!Helper.AreEqual(value, _enabled_VGPU_types))
{
_enabled_VGPU_types = value;
Changed = true;
NotifyPropertyChanged("enabled_VGPU_types");
}
}
}
private List<XenRef<VGPU_type>> _enabled_VGPU_types = new List<XenRef<VGPU_type>>() {};
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Generic;
using System.Text;
using Manos.Collections;
using Manos.IO;
namespace Manos.Http
{
/// <summary>
/// A base class for HttpRequest and HttpResponse. Generally user code should not care at all about
/// this class, it just exists to eliminate some code duplication between the two derived types.
/// </summary>
public abstract class HttpEntity : IDisposable
{
private static readonly long MAX_BUFFERED_CONTENT_LENGTH = 2621440;
// 2.5MB (Eventually this will be an environment var)
private readonly StringBuilder current_header_field = new StringBuilder();
private readonly StringBuilder current_header_value = new StringBuilder();
private IHttpBodyHandler body_handler;
private DataDictionary data;
private IAsyncWatcher end_watcher;
private bool finished_reading;
private HttpHeaders headers;
private HttpParser parser;
private ParserSettings parser_settings;
private DataDictionary post_data;
private Dictionary<string, object> properties;
private Dictionary<string, UploadedFile> uploaded_files;
public HttpEntity(Context context)
{
Context = context;
end_watcher = context.CreateAsyncWatcher(HandleEnd);
end_watcher.Start();
}
public Context Context { get; private set; }
public ITcpSocket Socket { get; protected set; }
public HttpStream Stream { get; protected set; }
public HttpHeaders Headers
{
get
{
if (headers == null)
headers = new HttpHeaders();
return headers;
}
set { headers = value; }
}
public HttpMethod Method { get; set; }
public int MajorVersion { get; set; }
public int MinorVersion { get; set; }
public string RemoteAddress { get; set; }
public int RemotePort { get; set; }
public string Path { get; set; }
public Encoding ContentEncoding
{
get { return Headers.ContentEncoding; }
set { Headers.ContentEncoding = value; }
}
public DataDictionary Data
{
get
{
if (data == null)
data = new DataDictionary();
return data;
}
}
public DataDictionary PostData
{
get
{
if (post_data == null)
{
post_data = new DataDictionary();
Data.Children.Add(post_data);
}
return post_data;
}
set
{
SetDataDictionary(post_data, value);
post_data = value;
}
}
public string PostBody { get; set; }
public Dictionary<string, UploadedFile> Files
{
get
{
if (uploaded_files == null)
uploaded_files = new Dictionary<string, UploadedFile>();
return uploaded_files;
}
}
public Dictionary<string, object> Properties
{
get
{
if (properties == null)
properties = new Dictionary<string, object>();
return properties;
}
}
#region IDisposable Members
public void Dispose()
{
Socket = null;
if (Stream != null)
{
Stream.Dispose();
Stream = null;
}
if (end_watcher != null)
{
end_watcher.Dispose();
end_watcher = null;
}
}
#endregion
~HttpEntity()
{
Dispose();
}
public void SetProperty(string name, object o)
{
if (name == null)
throw new ArgumentNullException("name");
if (o == null && properties == null)
return;
if (properties == null)
properties = new Dictionary<string, object>();
if (o == null)
{
properties.Remove(name);
if (properties.Count == 0)
properties = null;
return;
}
properties[name] = o;
}
public object GetProperty(string name)
{
if (name == null)
throw new ArgumentNullException("name");
if (properties == null)
return null;
object res = null;
if (!properties.TryGetValue(name, out res))
return null;
return res;
}
public T GetProperty<T>(string name)
{
object res = GetProperty(name);
if (res == null)
return default (T);
return (T) res;
}
protected void SetDataDictionary(DataDictionary old, DataDictionary newd)
{
if (data != null && old != null)
data.Children.Remove(old);
if (newd != null)
Data.Children.Add(newd);
}
protected void CreateParserSettingsInternal()
{
parser_settings = CreateParserSettings();
parser_settings.OnError = OnParserError;
parser_settings.OnBody = OnBody;
parser_settings.OnMessageBegin = OnMessageBegin;
parser_settings.OnMessageComplete = OnMessageComplete;
parser_settings.OnHeaderField = OnHeaderField;
parser_settings.OnHeaderValue = OnHeaderValue;
parser_settings.OnHeadersComplete = OnHeadersComplete;
}
private int OnMessageBegin(HttpParser parser)
{
return 0;
}
private int OnMessageComplete(HttpParser parser)
{
// Upgrade connections will raise this event at the end of OnBytesRead
if (!parser.Upgrade)
OnFinishedReading(parser);
finished_reading = true;
return 0;
}
public int OnHeaderField(HttpParser parser, ByteBuffer data, int pos, int len)
{
string str = Encoding.ASCII.GetString(data.Bytes, pos, len);
if (current_header_value.Length != 0)
FinishCurrentHeader();
current_header_field.Append(str);
return 0;
}
public int OnHeaderValue(HttpParser parser, ByteBuffer data, int pos, int len)
{
string str = Encoding.ASCII.GetString(data.Bytes, pos, len);
if (current_header_field.Length == 0)
throw new HttpException("Header Value raised with no header field set.");
current_header_value.Append(str);
return 0;
}
private void FinishCurrentHeader()
{
try
{
if (headers == null)
headers = new HttpHeaders();
headers.SetHeader(current_header_field.ToString(), current_header_value.ToString());
current_header_field.Length = 0;
current_header_value.Length = 0;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
protected virtual int OnHeadersComplete(HttpParser parser)
{
if (current_header_field.Length != 0)
FinishCurrentHeader();
MajorVersion = parser.Major;
MinorVersion = parser.Minor;
Method = parser.HttpMethod;
return 0;
}
public int OnBody(HttpParser parser, ByteBuffer data, int pos, int len)
{
if (body_handler == null)
CreateBodyHandler();
if (body_handler != null)
body_handler.HandleData(this, data, pos, len);
return 0;
}
private void CreateBodyHandler()
{
string ct;
if (!Headers.TryGetValue("Content-Type", out ct))
{
body_handler = new HttpBufferedBodyHandler();
return;
}
if (ct.StartsWith("application/x-www-form-urlencoded", StringComparison.InvariantCultureIgnoreCase))
{
body_handler = new HttpFormDataHandler();
return;
}
if (ct.StartsWith("multipart/form-data", StringComparison.InvariantCultureIgnoreCase))
{
string boundary = ParseBoundary(ct);
IUploadedFileCreator file_creator = GetFileCreator();
body_handler = new HttpMultiPartFormDataHandler(boundary, ContentEncoding, file_creator);
return;
}
body_handler = new HttpBufferedBodyHandler();
}
private IUploadedFileCreator GetFileCreator()
{
if (Headers.ContentLength == null || Headers.ContentLength >= MAX_BUFFERED_CONTENT_LENGTH)
return new TempFileUploadedFileCreator();
return new InMemoryUploadedFileCreator();
}
private void OnParserError(HttpParser parser, string message, ByteBuffer buffer, int initial_position)
{
// Transaction.Abort (-1, "HttpParser error: {0}", message);
Socket.Close();
}
public virtual void Reset()
{
Path = null;
ContentEncoding = null;
headers = null;
data = null;
post_data = null;
uploaded_files = null;
finished_reading = false;
if (parser_settings == null)
CreateParserSettingsInternal();
parser = new HttpParser();
}
public void Read()
{
Read(() => { });
}
public void Read(Action onClose)
{
Reset();
Socket.GetSocketStream().Read(OnBytesRead, (obj) => { }, onClose);
}
private void OnBytesRead(ByteBuffer bytes)
{
try
{
parser.Execute(parser_settings, bytes);
}
catch (Exception e)
{
Console.WriteLine("Exception while parsing");
Console.WriteLine(e);
}
if (finished_reading && parser.Upgrade)
{
//
// Well, this is a bit of a hack. Ideally, maybe there should be a putback list
// on the socket so we can put these bytes back into the stream and the upgrade
// protocol handler can read them out as if they were just reading normally.
//
if (bytes.Position < bytes.Length)
{
var upgrade_head = new byte[bytes.Length - bytes.Position];
Array.Copy(bytes.Bytes, bytes.Position, upgrade_head, 0, upgrade_head.Length);
SetProperty("UPGRADE_HEAD", upgrade_head);
}
// This is delayed until here with upgrade connnections.
OnFinishedReading(parser);
}
}
protected virtual void OnFinishedReading(HttpParser parser)
{
if (body_handler != null)
{
body_handler.Finish(this);
body_handler = null;
}
if (OnCompleted != null)
OnCompleted();
}
public static string ParseBoundary(string ct)
{
if (ct == null)
return null;
int start = ct.IndexOf("boundary=");
if (start < 1)
return null;
return ct.Substring(start + "boundary=".Length);
}
public void Write(string str)
{
byte[] data = ContentEncoding.GetBytes(str);
WriteToBody(data, 0, data.Length);
}
public void Write(byte[] data)
{
WriteToBody(data, 0, data.Length);
}
public void Write(byte[] data, int offset, int length)
{
WriteToBody(data, offset, length);
}
public void Write(string str, params object[] prms)
{
Write(String.Format(str, prms));
}
public void End(string str)
{
Write(str);
End();
}
public void End(byte[] data)
{
Write(data);
End();
}
public void End(byte[] data, int offset, int length)
{
Write(data, offset, length);
End();
}
public void End(string str, params object[] prms)
{
Write(str, prms);
End();
}
public void End()
{
end_watcher.Send();
}
internal virtual void HandleEnd()
{
if (OnEnd != null)
OnEnd();
}
public void Complete(Action callback)
{
IAsyncWatcher completeWatcher = null;
completeWatcher = Context.CreateAsyncWatcher(delegate
{
completeWatcher.Dispose();
callback();
});
completeWatcher.Start();
Stream.End(completeWatcher.Send);
}
public void WriteLine(string str)
{
Write(str + Environment.NewLine);
}
public void WriteLine(string str, params object[] prms)
{
WriteLine(String.Format(str, prms));
}
public void SendFile(string file)
{
Stream.SendFile(file);
}
private void WriteToBody(byte[] data, int offset, int length)
{
Stream.Write(data, offset, length);
}
public byte[] GetBody()
{
StringBuilder data = null;
if (PostBody != null)
{
data = new StringBuilder();
data.Append(PostBody);
}
if (post_data != null)
{
data = new StringBuilder();
bool first = true;
foreach (string key in post_data.Keys)
{
if (!first)
data.Append('&');
first = false;
UnsafeString s = post_data.Get(key);
if (s != null)
{
data.AppendFormat("{0}={1}", key, s.UnsafeValue);
continue;
}
}
}
if (data == null)
return null;
return ContentEncoding.GetBytes(data.ToString());
}
public abstract void WriteMetadata(StringBuilder builder);
public abstract ParserSettings CreateParserSettings();
public event Action<string> Error; // TODO: Proper error object of some sort
public event Action OnEnd;
public event Action OnCompleted;
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using NSec.Cryptography.Formatting;
using static Interop.Libsodium;
namespace NSec.Cryptography
{
//
// AES256-GCM
//
// Authenticated Encryption with Associated Data (AEAD) algorithm
// based on the Advanced Encryption Standard (AES) in Galois/Counter
// Mode (GCM) with 256-bit keys
//
// References:
//
// FIPS 197 - Advanced Encryption Standard (AES)
//
// NIST SP 800-38D - Recommendation for Block Cipher Modes of
// Operation: Galois/Counter Mode (GCM) and GMAC
//
// RFC 5116 - An Interface and Algorithms for Authenticated Encryption
//
// Parameters:
//
// Key Size - 32 bytes.
//
// Nonce Size - 12 bytes.
//
// Tag Size - 16 bytes.
//
// Plaintext Size - Between 0 and 2^36-31 bytes. (A Span<byte> can hold
// only up to 2^31-1 bytes.)
//
// Associated Data Size - Between 0 and 2^61-1 bytes.
//
// Ciphertext Size - The ciphertext always has the size of the
// plaintext plus the tag size.
//
public sealed class Aes256Gcm : AeadAlgorithm
{
private const uint NSecBlobHeader = 0xDE6144DE;
private static int s_isSupported;
private static int s_selfTest;
public Aes256Gcm() : base(
keySize: crypto_aead_aes256gcm_KEYBYTES,
nonceSize: crypto_aead_aes256gcm_NPUBBYTES,
tagSize: crypto_aead_aes256gcm_ABYTES)
{
if (s_selfTest == 0)
{
SelfTest();
Interlocked.Exchange(ref s_selfTest, 1);
}
if (s_isSupported == 0)
{
Interlocked.Exchange(ref s_isSupported, crypto_aead_aes256gcm_is_available() != 0 ? 1 : -1);
}
if (s_isSupported < 0)
{
throw Error.PlatformNotSupported_Algorithm();
}
}
public static bool IsSupported
{
get
{
int isSupported = s_isSupported;
if (isSupported == 0)
{
Sodium.Initialize();
Interlocked.Exchange(ref s_isSupported, crypto_aead_aes256gcm_is_available() != 0 ? 1 : -1);
isSupported = s_isSupported;
}
return isSupported > 0;
}
}
internal override void CreateKey(
ReadOnlySpan<byte> seed,
out SecureMemoryHandle keyHandle,
out PublicKey? publicKey)
{
Debug.Assert(seed.Length == crypto_aead_aes256gcm_KEYBYTES);
publicKey = null;
keyHandle = SecureMemoryHandle.CreateFrom(seed);
}
private protected unsafe override void EncryptCore(
SecureMemoryHandle keyHandle,
ReadOnlySpan<byte> nonce,
ReadOnlySpan<byte> associatedData,
ReadOnlySpan<byte> plaintext,
Span<byte> ciphertext)
{
Debug.Assert(keyHandle.Size == crypto_aead_aes256gcm_KEYBYTES);
Debug.Assert(nonce.Length == crypto_aead_aes256gcm_NPUBBYTES);
Debug.Assert(ciphertext.Length == plaintext.Length + crypto_aead_aes256gcm_ABYTES);
fixed (byte* c = ciphertext)
fixed (byte* m = plaintext)
fixed (byte* ad = associatedData)
fixed (byte* n = nonce)
{
int error = crypto_aead_aes256gcm_encrypt(
c,
out ulong clen_p,
m,
(ulong)plaintext.Length,
ad,
(ulong)associatedData.Length,
null,
n,
keyHandle);
Debug.Assert(error == 0);
Debug.Assert((ulong)ciphertext.Length == clen_p);
}
}
internal override int GetSeedSize()
{
return crypto_aead_aes256gcm_KEYBYTES;
}
private protected unsafe override bool DecryptCore(
SecureMemoryHandle keyHandle,
ReadOnlySpan<byte> nonce,
ReadOnlySpan<byte> associatedData,
ReadOnlySpan<byte> ciphertext,
Span<byte> plaintext)
{
Debug.Assert(keyHandle.Size == crypto_aead_aes256gcm_KEYBYTES);
Debug.Assert(nonce.Length == crypto_aead_aes256gcm_NPUBBYTES);
Debug.Assert(plaintext.Length == ciphertext.Length - crypto_aead_aes256gcm_ABYTES);
fixed (byte* m = plaintext)
fixed (byte* c = ciphertext)
fixed (byte* ad = associatedData)
fixed (byte* n = nonce)
{
int error = crypto_aead_aes256gcm_decrypt(
m,
out ulong mlen_p,
null,
c,
(ulong)ciphertext.Length,
ad,
(ulong)associatedData.Length,
n,
keyHandle);
// libsodium clears plaintext if decryption fails
Debug.Assert(error != 0 || (ulong)plaintext.Length == mlen_p);
return error == 0;
}
}
internal override bool TryExportKey(
SecureMemoryHandle keyHandle,
KeyBlobFormat format,
Span<byte> blob,
out int blobSize)
{
return format switch
{
KeyBlobFormat.RawSymmetricKey => RawKeyFormatter.TryExport(keyHandle, blob, out blobSize),
KeyBlobFormat.NSecSymmetricKey => NSecKeyFormatter.TryExport(NSecBlobHeader, crypto_aead_aes256gcm_KEYBYTES, crypto_aead_aes256gcm_ABYTES, keyHandle, blob, out blobSize),
_ => throw Error.Argument_FormatNotSupported(nameof(format), format.ToString()),
};
}
internal override bool TryImportKey(
ReadOnlySpan<byte> blob,
KeyBlobFormat format,
out SecureMemoryHandle? keyHandle,
out PublicKey? publicKey)
{
publicKey = null;
return format switch
{
KeyBlobFormat.RawSymmetricKey => RawKeyFormatter.TryImport(crypto_aead_aes256gcm_KEYBYTES, blob, out keyHandle),
KeyBlobFormat.NSecSymmetricKey => NSecKeyFormatter.TryImport(NSecBlobHeader, crypto_aead_aes256gcm_KEYBYTES, crypto_aead_aes256gcm_ABYTES, blob, out keyHandle),
_ => throw Error.Argument_FormatNotSupported(nameof(format), format.ToString()),
};
}
private static void SelfTest()
{
if ((crypto_aead_aes256gcm_abytes() != crypto_aead_aes256gcm_ABYTES) ||
(crypto_aead_aes256gcm_keybytes() != crypto_aead_aes256gcm_KEYBYTES) ||
(crypto_aead_aes256gcm_npubbytes() != crypto_aead_aes256gcm_NPUBBYTES) ||
(crypto_aead_aes256gcm_nsecbytes() != crypto_aead_aes256gcm_NSECBYTES))
{
throw Error.InvalidOperation_InitializationFailed();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ExpressRouteCircuitAuthorizationsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(response, customHeaders, cancellationToken);
}
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
url = url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 202 && (int)statusCode != 200 && (int)statusCode != 204)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The GET authorization operation retrieves the specified authorization from
/// the specified ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
url = url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in
/// thespecified ExpressRouteCircuits
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitAuthorization> response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync<ExpressRouteCircuitAuthorization>(response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in
/// thespecified ExpressRouteCircuits
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (authorizationParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("authorizationParameters", authorizationParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
url = url.Replace("{authorizationName}", Uri.EscapeDataString(authorizationName));
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(authorizationParameters, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 201 && (int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 201)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(responseContent, this.Client.DeserializationSettings);
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the curcuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "List", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString();
url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName));
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string url = "{nextLink}";
url = url.Replace("{nextLink}", nextPageLink);
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (httpRequest.Headers.Contains("accept-language"))
{
httpRequest.Headers.Remove("accept-language");
}
httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = new HttpRequestMessageWrapper(httpRequest, null);
ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
result.Request = httpRequest;
result.Response = httpResponse;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)statusCode == 200)
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Concurrency;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Configuration;
using RunState = Orleans.Configuration.StreamLifecycleOptions.RunState;
namespace Orleans.Streams
{
internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener
{
private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5);
private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap;
private readonly string streamProviderName;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub pubSub;
private readonly StreamPullingAgentOptions options;
private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications.
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private int latestRingNotificationSequenceNumber;
private int latestCommandNumber;
private IQueueAdapter queueAdapter;
private readonly IQueueAdapterCache queueAdapterCache;
private IStreamQueueBalancer queueBalancer;
private readonly IQueueAdapterFactory adapterFactory;
private RunState managerState;
private IDisposable queuePrintTimer;
private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } }
internal PersistentStreamPullingManager(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
IStreamPubSub streamPubSub,
IQueueAdapterFactory adapterFactory,
IStreamQueueBalancer streamQueueBalancer,
StreamPullingAgentOptions options,
ILoggerFactory loggerFactory)
: base(id, runtime.ExecutingSiloAddress, loggerFactory)
{
if (string.IsNullOrWhiteSpace(strProviderName))
{
throw new ArgumentNullException("strProviderName");
}
if (runtime == null)
{
throw new ArgumentNullException("runtime", "IStreamProviderRuntime runtime reference should not be null");
}
if (streamPubSub == null)
{
throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null");
}
if (streamQueueBalancer == null)
{
throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null");
}
queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>();
streamProviderName = strProviderName;
providerRuntime = runtime;
pubSub = streamPubSub;
this.options = options;
nonReentrancyGuarantor = new AsyncSerialExecutor();
latestRingNotificationSequenceNumber = 0;
latestCommandNumber = 0;
queueBalancer = streamQueueBalancer;
this.adapterFactory = adapterFactory;
queueAdapterCache = adapterFactory.GetQueueAdapterCache();
logger = loggerFactory.CreateLogger($"{GetType().FullName}-{streamProviderName}");
Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName);
this.loggerFactory = loggerFactory;
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count);
}
public async Task Initialize(Immutable<IQueueAdapter> qAdapter)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
Log(ErrorCode.PersistentStreamPullingManager_02, "Init.");
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
await this.queueBalancer.Initialize(this.adapterFactory.GetStreamQueueMapper());
queueBalancer.SubscribeToQueueDistributionChangeEvents(this);
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues)));
queuePrintTimer = this.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD);
managerState = RunState.Initialized;
}
public async Task Stop()
{
await StopAgents();
if (queuePrintTimer != null)
{
queuePrintTimer.Dispose();
this.queuePrintTimer = null;
}
(this.queueBalancer as IDisposable)?.Dispose();
this.queueBalancer = null;
}
public async Task StartAgents()
{
managerState = RunState.AgentsStarted;
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues));
await AddNewQueues(myQueues, true);
Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents.");
}
public async Task StopAgents()
{
managerState = RunState.AgentsStopped;
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList();
Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove));
await RemoveQueues(queuesToRemove);
Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents.");
}
/// <summary>
/// Actions to take when the queue distribution changes due to a failure or a join.
/// Since this pulling manager is system target and queue distribution change notifications
/// are delivered to it as grain method calls, notifications are not reentrant. To simplify
/// notification handling we execute them serially, in a non-reentrant way. We also suppress
/// and don't execute an older notification if a newer one was already delivered.
/// </summary>
public Task QueueDistributionChangeNotification()
{
return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification());
}
public Task HandleQueueDistributionChangeNotification()
{
latestRingNotificationSequenceNumber++;
int notificationSeqNumber = latestRingNotificationSequenceNumber;
Log(ErrorCode.PersistentStreamPullingManager_04,
"Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState);
if (managerState == RunState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous notification since already got a newer range update notification.
if (notificationSeqNumber < latestRingNotificationSequenceNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_05,
"Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " +
"(already have notification number {1}).",
notificationSeqNumber, latestRingNotificationSequenceNumber);
return Task.CompletedTask;
}
if (managerState == RunState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return QueueDistributionChangeNotification(notificationSeqNumber);
});
}
private async Task QueueDistributionChangeNotification(int notificationSeqNumber)
{
HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet();
Log(ErrorCode.PersistentStreamPullingManager_06,
"Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues));
try
{
Task t1 = AddNewQueues(currentQueues, false);
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList();
Task t2 = RemoveQueues(queuesToRemove);
await Task.WhenAll(t1, t2);
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_16,
"Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys));
}
}
/// <summary>
/// Take responsibility for a set of new queues that were assigned to me via a new range.
/// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents.
/// ERROR HANDLING:
/// The responsibility to handle initialization and shutdown failures is inside the Agents code.
/// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded.
/// Same applies to shutdown.
/// </summary>
/// <param name="myQueues"></param>
/// <param name="failOnInit"></param>
/// <returns></returns>
private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit)
{
// Create agents for queues in range that we don't yet have.
// First create them and store in local queuesToAgentsMap.
// Only after that Initialize them all.
var agents = new List<PersistentStreamPullingAgent>();
foreach (var queueId in myQueues.Where(queueId => !queuesToAgentsMap.ContainsKey(queueId)))
{
try
{
var agentId = GrainId.NewSystemTargetGrainIdByTypeCode(Constants.PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE);
var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, providerRuntime, this.loggerFactory, pubSub, queueId, this.options);
providerRuntime.RegisterSystemTarget(agent);
queuesToAgentsMap.Add(queueId, agent);
agents.Add(agent);
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc);
// What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down.
// If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers.
if (failOnInit) throw;
}
}
try
{
var initTasks = new List<Task>();
foreach (var agent in agents)
{
initTasks.Add(InitAgent(agent));
}
await Task.WhenAll(initTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
private async Task InitAgent(PersistentStreamPullingAgent agent)
{
// Init the agent only after it was registered locally.
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var queueAdapterCacheAsImmutable = queueAdapterCache != null ? queueAdapterCache.AsImmutable() : new Immutable<IQueueAdapterCache>(null);
IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(agent.QueueId);
// Need to call it as a grain reference.
var task = OrleansTaskExtentions.SafeExecute(() => agentGrainRef.Initialize(queueAdapter.AsImmutable(), queueAdapterCacheAsImmutable, deliveryFailureHandler.AsImmutable()));
await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId));
}
private async Task RemoveQueues(List<QueueId> queuesToRemove)
{
if (queuesToRemove.Count == 0)
{
return;
}
// Stop the agents that for queues that are not in my range anymore.
var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count);
Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString()));
var removeTasks = new List<Task>();
foreach (var queueId in queuesToRemove)
{
PersistentStreamPullingAgent agent;
if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue;
agents.Add(agent);
queuesToAgentsMap.Remove(queueId);
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown);
task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11,
String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId));
removeTasks.Add(task);
}
try
{
await Task.WhenAll(removeTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
foreach (var agent in agents)
{
try
{
providerRuntime.UnregisterSystemTarget(agent);
}
catch (Exception exc)
{
Log(ErrorCode.PersistentStreamPullingManager_12,
"Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message);
}
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg)
{
latestCommandNumber++;
int commandSeqNumber = latestCommandNumber;
try
{
Log(ErrorCode.PersistentStreamPullingManager_13,
String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.",
command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState));
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
case PersistentStreamProviderCommand.StopAgents:
await QueueCommandForExecution(command, commandSeqNumber);
return null;
case PersistentStreamProviderCommand.GetAgentsState:
return managerState;
case PersistentStreamProviderCommand.GetNumberRunningAgents:
return NumberRunningAgents;
default:
throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command));
}
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_15,
String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.",
command, commandSeqNumber, managerState, NumberRunningAgents));
}
}
// Start and Stop commands are composite commands that take multiple turns.
// Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification.
// Therefore, we serialize them all via the same nonReentrancyGuarantor.
private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber)
{
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous command since already got a newer command.
if (commandSeqNumber < latestCommandNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_15,
"Skipping execution of command number {0} since already received a later command (already have command number {1}).",
commandSeqNumber, latestCommandNumber);
return Task.CompletedTask;
}
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
return StartAgents();
case PersistentStreamProviderCommand.StopAgents:
return StopAgents();
default:
throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command));
}
});
}
private static string PrintQueues(ICollection<QueueId> myQueues)
{
return Utils.EnumerableToString(myQueues, q => q.ToString());
}
// Just print our queue assignment periodicaly, for easy monitoring.
private Task AsyncTimerCallback(object state)
{
Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint,
"I am responsible for a total of {0} queues on stream provider {1}: {2}.",
NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys));
return Task.CompletedTask;
}
private void Log(ErrorCode logCode, string format, params object[] args)
{
logger.Info(logCode, format, args);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="KeywordPlanAdGroupServiceClient"/> instances.</summary>
public sealed partial class KeywordPlanAdGroupServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</returns>
public static KeywordPlanAdGroupServiceSettings GetDefault() => new KeywordPlanAdGroupServiceSettings();
/// <summary>
/// Constructs a new <see cref="KeywordPlanAdGroupServiceSettings"/> object with default settings.
/// </summary>
public KeywordPlanAdGroupServiceSettings()
{
}
private KeywordPlanAdGroupServiceSettings(KeywordPlanAdGroupServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetKeywordPlanAdGroupSettings = existing.GetKeywordPlanAdGroupSettings;
MutateKeywordPlanAdGroupsSettings = existing.MutateKeywordPlanAdGroupsSettings;
OnCopy(existing);
}
partial void OnCopy(KeywordPlanAdGroupServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanAdGroupServiceClient.GetKeywordPlanAdGroup</c> and
/// <c>KeywordPlanAdGroupServiceClient.GetKeywordPlanAdGroupAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeywordPlanAdGroupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroups</c> and
/// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroupsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateKeywordPlanAdGroupsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="KeywordPlanAdGroupServiceSettings"/> object.</returns>
public KeywordPlanAdGroupServiceSettings Clone() => new KeywordPlanAdGroupServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="KeywordPlanAdGroupServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class KeywordPlanAdGroupServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanAdGroupServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public KeywordPlanAdGroupServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public KeywordPlanAdGroupServiceClientBuilder()
{
UseJwtAccessWithScopes = KeywordPlanAdGroupServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref KeywordPlanAdGroupServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanAdGroupServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override KeywordPlanAdGroupServiceClient Build()
{
KeywordPlanAdGroupServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<KeywordPlanAdGroupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<KeywordPlanAdGroupServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private KeywordPlanAdGroupServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<KeywordPlanAdGroupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => KeywordPlanAdGroupServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanAdGroupServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanAdGroupServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>KeywordPlanAdGroupService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan ad groups.
/// </remarks>
public abstract partial class KeywordPlanAdGroupServiceClient
{
/// <summary>
/// The default endpoint for the KeywordPlanAdGroupService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default KeywordPlanAdGroupService scopes.</summary>
/// <remarks>
/// The default KeywordPlanAdGroupService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="KeywordPlanAdGroupServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns>
public static stt::Task<KeywordPlanAdGroupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new KeywordPlanAdGroupServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="KeywordPlanAdGroupServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns>
public static KeywordPlanAdGroupServiceClient Create() => new KeywordPlanAdGroupServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="KeywordPlanAdGroupServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="KeywordPlanAdGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns>
internal static KeywordPlanAdGroupServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanAdGroupServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient = new KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient(callInvoker);
return new KeywordPlanAdGroupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC KeywordPlanAdGroupService client</summary>
public virtual KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, st::CancellationToken cancellationToken) =>
GetKeywordPlanAdGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanAdGroup(new GetKeywordPlanAdGroupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanAdGroupAsync(new GetKeywordPlanAdGroupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(gagvr::KeywordPlanAdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanAdGroup(new GetKeywordPlanAdGroupRequest
{
ResourceNameAsKeywordPlanAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(gagvr::KeywordPlanAdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanAdGroupAsync(new GetKeywordPlanAdGroupRequest
{
ResourceNameAsKeywordPlanAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan ad group to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(gagvr::KeywordPlanAdGroupName resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, st::CancellationToken cancellationToken) =>
MutateKeywordPlanAdGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan ad groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanAdGroups(new MutateKeywordPlanAdGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan ad groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanAdGroupsAsync(new MutateKeywordPlanAdGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan ad groups.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, st::CancellationToken cancellationToken) =>
MutateKeywordPlanAdGroupsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>KeywordPlanAdGroupService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan ad groups.
/// </remarks>
public sealed partial class KeywordPlanAdGroupServiceClientImpl : KeywordPlanAdGroupServiceClient
{
private readonly gaxgrpc::ApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup> _callGetKeywordPlanAdGroup;
private readonly gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> _callMutateKeywordPlanAdGroups;
/// <summary>
/// Constructs a client wrapper for the KeywordPlanAdGroupService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="KeywordPlanAdGroupServiceSettings"/> used within this client.
/// </param>
public KeywordPlanAdGroupServiceClientImpl(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings settings)
{
GrpcClient = grpcClient;
KeywordPlanAdGroupServiceSettings effectiveSettings = settings ?? KeywordPlanAdGroupServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetKeywordPlanAdGroup = clientHelper.BuildApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup>(grpcClient.GetKeywordPlanAdGroupAsync, grpcClient.GetKeywordPlanAdGroup, effectiveSettings.GetKeywordPlanAdGroupSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetKeywordPlanAdGroup);
Modify_GetKeywordPlanAdGroupApiCall(ref _callGetKeywordPlanAdGroup);
_callMutateKeywordPlanAdGroups = clientHelper.BuildApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse>(grpcClient.MutateKeywordPlanAdGroupsAsync, grpcClient.MutateKeywordPlanAdGroups, effectiveSettings.MutateKeywordPlanAdGroupsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateKeywordPlanAdGroups);
Modify_MutateKeywordPlanAdGroupsApiCall(ref _callMutateKeywordPlanAdGroups);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetKeywordPlanAdGroupApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup> call);
partial void Modify_MutateKeywordPlanAdGroupsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> call);
partial void OnConstruction(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC KeywordPlanAdGroupService client</summary>
public override KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient { get; }
partial void Modify_GetKeywordPlanAdGroupRequest(ref GetKeywordPlanAdGroupRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateKeywordPlanAdGroupsRequest(ref MutateKeywordPlanAdGroupsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanAdGroupRequest(ref request, ref callSettings);
return _callGetKeywordPlanAdGroup.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested Keyword Plan ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanAdGroupRequest(ref request, ref callSettings);
return _callGetKeywordPlanAdGroup.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanAdGroups.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupError]()
/// [KeywordPlanError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanAdGroups.Async(request, callSettings);
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace WixSharp
{
/// <summary>
/// Defines WiX <c>Condition</c>. <c>Condition</c> is normally associated with <c>CustomActions</c> or WiX elements (e.g. <c>Shortcut</c>).
/// <para>
/// <see cref="Condition"/> is nothing else but an XML friendly string wrapper, containing
/// some predefined (commonly used) condition values. You can either use one of the
/// predefined condition values (static members) or define your by specifying full string representation of
/// the required WiX condition when calling the constructor or static method <c>Create</c>.
/// </para>
/// </summary>
/// <example>The following is an example of initializing the Shortcut.<see cref="Shortcut.Condition"/>
/// with custom value <c>INSTALLDESKTOPSHORTCUT="yes"</c> and
/// the InstalledFileAction.<see cref="T:WixSharp.InstalledFileAction.Condition"/> with perefined value <c>NOT_Installed</c>:
/// <code>
/// var project =
/// new Project("My Product",
/// ...
/// new Dir(@"%Desktop%",
/// new WixSharp.Shortcut("MyApp", "[INSTALL_DIR]MyApp.exe", "")
/// {
/// Condition = new Condition("INSTALLDESKTOPSHORTCUT=\"yes\"")
/// }),
/// new InstalledFileAction("MyApp.exe", "",
/// Return.check,
/// When.After,
/// Step.InstallFinalize,
/// Condition.NOT_Installed),
/// ...
/// </code>
/// </example>
public partial class Condition : WixEntity
{
/// <summary>
/// String value of WiX <c>Condition</c>.
/// </summary>
public string Value = "";
/// <summary>
/// Initializes a new instance of the <see cref="Condition"/> class.
/// </summary>
/// <param name="value">The value of the WiX condition expression.</param>
public Condition(string value)
{
//Value = System.Security.SecurityElement.Escape(value);
//Value = "<![CDATA[" + value + "]]>";
Value = value;
}
/// <summary>
/// Returns the WiX <c>Condition</c> as a string.
/// </summary>
/// <returns>A string representing the condition.</returns>
public override string ToString()
{
return Value.Replace("'", "\"");
}
/// <summary>
/// Extracts the distinct names of properties from the condition string expression.
/// </summary>
/// <returns></returns>
public string[] GetDistinctProperties()
{
//"NETFRAMEWORK30_SP_LEVEL and NOT NETFRAMEWORK30_SP_LEVEL='#0'"
var text = this.ToString();
string[] parts = text.Split("[]()!=><\t \n\r".ToCharArray());
var props = parts.Where(x => x.IsNotEmpty() &&
!x.SameAs("AND", true) &&
!x.SameAs("NOT", true) &&
!x.SameAs("OR", true) &&
!x.StartsWith("\""))
.Distinct()
.ToArray();
return props;
}
/// <summary>
/// Performs an implicit conversion from <see cref="Condition"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator string(Condition obj)
{
return obj.ToString();
}
/// <summary>
/// Returns the WiX <c>Condition</c> as a <see cref="T:System.Xml.Linq.XCData"/>.
/// <remarks> Normally <c>Condition</c> is not designed to be parsed by the XML parser thus it should be embedded as CDATA</remarks>
/// <code>
/// <Condition><![CDATA[NETFRAMEWORK20="#0"]]></Condition>
/// </code>
/// </summary>
/// <returns>A CDATA string representing the condition.</returns>
public XCData ToCData()
{
return new XCData(Value);
}
/// <summary>
/// String representation of the <c>Custom_UI_Command = "back"</c> condition. This condition is triggered when user presses 'Back' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_BackPressed = new Condition(" Custom_UI_Command = \"back\" ");
/// <summary>
/// String representation of the <c>Custom_UI_Command = "next"</c> condition. This condition is triggered when user presses 'Next' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_NextPressed = new Condition(" Custom_UI_Command = \"next\" ");
/// <summary>
/// String representation of the <c>Custom_UI_Command = "abort"</c> condition. This condition is triggered when user presses 'Cancel' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_CancelPressed = new Condition(" Custom_UI_Command = \"abort\" ");
/// <summary>
/// String representation of the <c>NOT Installed</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_Installed = new Condition(" (NOT Installed) ");
/// <summary>
/// String representation of the <c>Installed</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Installed = new Condition(" (Installed) ");
/// <summary>
/// String representation of "always true" condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Always = new Condition(" (1) ");
/// <summary>
/// String representation of the <c>NOT (REMOVE="ALL")</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_BeingRemoved = new Condition(" (NOT (REMOVE=\"ALL\")) ");
/// <summary>
/// String representation of the <c>UILevel > 3</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_Silent = new Condition(" (UILevel > 3) ");
/// <summary>
/// String representation of the <c>UILevel < 4</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Silent = new Condition(" (UILevel < 4) ");
/// <summary>
/// String representation of the <c>REMOVE="ALL"</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition BeingRemoved = new Condition(" (REMOVE=\"ALL\") ");
/// <summary>
/// The .NET2.0 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net20_Installed = new Condition(" (NETFRAMEWORK20='#1') ");
/// <summary>
/// The .NET3.5 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net35_Installed = new Condition(" (NETFRAMEWORK35='#1') ");
/// <summary>
/// The .NET4.5 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net45_Installed = new Condition(" (NETFRAMEWORK45 >= '#378389') ");
/// <summary>
/// The .NET3.0 SP installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net30_SP_Installed = new Condition(" (NETFRAMEWORK30_SP_LEVEL and NOT NETFRAMEWORK30_SP_LEVEL='#0') ");
/// <summary>
/// Creates WiX <c>Condition</c> condition from the given string value.
/// </summary>
/// <param name="value">String value of the <c>Condition</c> to be created.</param>
/// <returns>Instance of the <c>Condition</c></returns>
/// <example>The following is an example of initializing the Shortcut.<see cref="Shortcut.Condition"/>
/// with custom value <c>INSTALLDESKTOPSHORTCUT="yes"</c>:
/// <code>
/// new Dir(@"%Desktop%",
/// new WixSharp.Shortcut("MyApp", "[INSTALL_DIR]MyApp.exe", "")
/// {
/// Condition = Condition.Create("INSTALLDESKTOPSHORTCUT=\"yes\"")
/// })
///
/// </code>
/// </example>
public static Condition Create(string value) { return new Condition(value); }
//public Condition And(Condition condition)
//{
// return Create("(" + this.ToString() + " AND " + condition.ToString() + ")");
//}
//public Condition Or(Condition condition)
//{
// return Create("(" + this.ToString() + " OR " + condition.ToString() + ")");
//}
//public Condition Invert()
//{
// return Create("NOT (" + this.ToString() + ")");
//}
}
/// <summary>
/// Specialized Condition for conditionally installing WiX Features.
/// </summary>
/// <remarks>
/// Setting Attributes on FeatureCondition is ignored.
/// </remarks>
public class FeatureCondition : Condition
{
/// <summary>
/// Initializes a new instance of the <see cref="FeatureCondition"/> class.
/// </summary>
/// <param name="value">The value of the WiX condition expression.</param>
/// <param name="level">The level value of the WiX condition.</param>
public FeatureCondition(string value, int level)
: base(value)
{
Level = level;
}
/// <summary>
/// Allows modifying the level of a Feature based on the result of this condition.
/// </summary>
public int Level { get; set; }
/// <summary>
/// Not Supported.
/// </summary>
/// <exception cref="NotImplementedException">Raised when getting or setting Attributes.</exception>
public new Dictionary<string, string> Attributes
{
get { throw new NotImplementedException("Attributes is not a valid property for FeatureCondition"); }
set { throw new NotImplementedException("Attributes is not a valid property for FeatureCondition"); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using B2Lib.Client;
using B2Lib.Enums;
using B2Lib.Exceptions;
using B2Lib.SyncExtensions;
using B2Lib.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace B2Lib.Tests
{
[TestClass]
public class FileTests
{
private static B2Client _client;
private static B2Bucket _bucket;
private static string _tmpPath;
[ClassInitialize]
public static void TestSetup(TestContext context)
{
_client = new B2Client();
_client.Login(TestConfig.AccountId, TestConfig.ApplicationKey);
try
{
_bucket = _client.CreateBucket("test-bucket-b2lib", B2BucketType.AllPrivate);
}
catch (Exception)
{
_bucket = _client.GetBucketByName("test-bucket-b2lib");
}
_tmpPath = Path.GetRandomFileName();
}
[ClassCleanup]
public static void TestCleanup()
{
List<B2FileItemBase> files = _bucket.GetFileVersions().ToList();
foreach (B2FileItemBase file in files)
file.Delete();
_bucket.Delete();
try
{
if (File.Exists(_tmpPath))
File.Delete(_tmpPath);
}
catch (Exception)
{
}
}
[TestMethod]
[ExpectedException(typeof(B2Exception))]
public void GetMissingFile()
{
B2File res = _bucket.GetFile("4_z4b156694d986f47c54320610_f200866faa871bf5f_d20160408_m223411_c001_v0001022_t0052");
Assert.Fail();
}
[TestMethod]
[ExpectedException(typeof(B2Exception))]
public void GetMissingLargeFile()
{
B2LargeFile res = _bucket.GetLargeFile("4_z4b156694d986f47c54320610_f200866faa871bf5f_d20160408_m223411_c001_v0001022_t0052");
Assert.Fail();
}
[TestMethod]
public void ListMultiplePages()
{
File.WriteAllText(_tmpPath, "Testworld,123");
List<B2File> files = new List<B2File>();
// Upload it
Parallel.For(1, 10, i =>
{
B2File file = _bucket.CreateFile("test-pages-" + i);
file.UploadFileData(new FileInfo(_tmpPath));
TestFileContents(file);
lock (files)
files.Add(file);
});
// Get enumerators
B2FilesIterator listFiles = _bucket.GetFiles();
B2FileVersionsIterator listFileVersions = _bucket.GetFileVersions();
Assert.IsNotNull(listFiles);
Assert.IsNotNull(listFileVersions);
listFiles.PageSize = 2;
listFileVersions.PageSize = 2;
// Enumerate it
List<B2File> list = listFiles.ToList();
List<B2FileItemBase> listVersions = listFileVersions.ToList();
foreach (B2File expected in files)
{
Assert.IsTrue(list.Any(s => s.FileId == expected.FileId));
Assert.IsTrue(listVersions.Any(s => s.FileId == expected.FileId));
}
// Delete files
Parallel.ForEach(files, info =>
{
info.Delete();
});
}
[TestMethod]
public void UploadFileVersionsListDelete()
{
File.WriteAllText(_tmpPath, "Testworld,123");
// Upload it
B2File file1 = _bucket.CreateFile("test").UploadFileData(new FileInfo(_tmpPath));
TestFileContents(file1);
// Upload again
B2File file2 = _bucket.CreateFile("test").UploadFileData(new FileInfo(_tmpPath));
TestFileContents(file2);
// Enumerate it
List<B2FileItemBase> list = _bucket.GetFileVersions().ToList();
List<B2FileItemBase> listFiles = list.Where(s => s.FileName == "test").ToList();
Assert.AreEqual(2, listFiles.Count);
Assert.IsTrue(listFiles.Any(s => s.FileId == file1.FileId));
Assert.IsTrue(listFiles.Any(s => s.FileId == file2.FileId));
foreach (B2FileItemBase b2FileItemBase in listFiles)
{
B2File listFile = (B2File)b2FileItemBase;
TestFileContents(listFile, B2FileAction.Upload);
}
// Delete file
file1.Delete();
file2.Delete();
// Ensure list is blank
list = _bucket.GetFileVersions().ToList();
Assert.IsFalse(list.Any(s => s.FileId == file1.FileId));
Assert.IsFalse(list.Any(s => s.FileId == file2.FileId));
}
[TestMethod]
public void UploadFileListDelete()
{
File.WriteAllText(_tmpPath, "Testworld,123");
// Upload it
B2File file = _bucket.CreateFile("test").UploadFileData(new FileInfo(_tmpPath));
TestFileContents(file);
// Enumerate it
List<B2File> list = _bucket.GetFiles().ToList();
B2File listFile = list.FirstOrDefault(s => s.FileId == file.FileId);
TestFileContents(listFile, B2FileAction.Upload);
// Delete file
file.Delete();
// Ensure list is blank
list = _bucket.GetFiles().ToList();
Assert.IsFalse(list.Any(s => s.FileId == file.FileId));
}
[TestMethod]
public void UploadFileHideDelete()
{
// B2 has a weird way of working with hidden files
// Read more here: https://www.backblaze.com/b2/docs/file_versions.html
File.WriteAllText(_tmpPath, "Testworld,123");
// Upload it
B2File originalFile = _bucket.CreateFile("test").UploadFileData(new FileInfo(_tmpPath));
TestFileContents(originalFile);
// Enumerate it
List<B2File> list = _bucket.GetFiles().ToList();
B2File listFile = list.FirstOrDefault(s => s.FileId == originalFile.FileId);
TestFileContents(listFile, B2FileAction.Upload);
// Hide it
_bucket.HideFile(originalFile.FileName);
// Enumerate it (it should now be hidden)
list = _bucket.GetFiles().ToList();
listFile = list.FirstOrDefault(s => s.FileId == originalFile.FileId);
Assert.IsNull(listFile);
// Enumerate versions (it should be visible)
List<B2FileItemBase> versions = _bucket.GetFileVersions().ToList();
B2File hideFile = versions.OfType<B2File>().FirstOrDefault(s => s.FileName == originalFile.FileName && s.Action == B2FileAction.Hide);
listFile = versions.OfType<B2File>().FirstOrDefault(s => s.FileId == originalFile.FileId);
TestFileContents(hideFile, B2FileAction.Hide);
TestFileContents(listFile, B2FileAction.Upload);
// Delete file
originalFile.Delete();
// Ensure list is blank
List<B2FileItemBase> blankFilesList = _bucket.GetFileVersions().ToList();
Assert.IsFalse(blankFilesList.Any(s => s.FileId == originalFile.FileId));
}
[TestMethod]
public void UploadFileGetInfoDelete()
{
File.WriteAllText(_tmpPath, "Testworld,123");
// Upload it
B2File file = _bucket.CreateFile("test").UploadFileData(new FileInfo(_tmpPath));
TestFileContents(file);
// Fetch info
B2File info = _bucket.GetFiles().FirstOrDefault(s => s.FileId == file.FileId);
TestFileContents(info);
Assert.AreEqual(file.FileId, info.FileId);
Assert.AreEqual(file.ContentLength, info.ContentLength);
// Delete file
info.Delete();
// Ensure info is blank
try
{
info = file.Refresh();
Assert.Fail();
}
catch (B2Exception ex)
{
Assert.AreEqual(HttpStatusCode.NotFound, ex.HttpStatusCode);
}
}
private void TestFileContents(B2FileItemBase file)
{
Assert.IsNotNull(file);
Assert.IsFalse(string.IsNullOrWhiteSpace(file.FileId));
Assert.IsFalse(string.IsNullOrWhiteSpace(file.FileName));
Assert.IsFalse(string.IsNullOrWhiteSpace(file.BucketId));
Assert.IsFalse(string.IsNullOrWhiteSpace(file.AccountId));
Assert.IsTrue(file.UploadTimestamp > DateTime.MinValue);
Assert.IsNotNull(file.FileInfo);
}
private void TestFileContents(B2File file, B2FileAction expectedAction)
{
TestFileContents(file);
Assert.IsTrue(Enum.IsDefined(typeof(B2FileAction), file.Action));
if (file.Action == B2FileAction.Hide)
{
Assert.AreEqual(0, file.ContentLength);
Assert.IsTrue(string.IsNullOrWhiteSpace(file.ContentSha1));
Assert.IsTrue(string.IsNullOrWhiteSpace(file.ContentType));
}
else if (file.Action == B2FileAction.Upload)
{
Assert.IsTrue(file.ContentLength > 0);
Assert.IsFalse(string.IsNullOrWhiteSpace(file.ContentSha1));
Assert.IsFalse(string.IsNullOrWhiteSpace(file.ContentType));
}
else
{
Assert.Fail();
}
Assert.AreEqual(expectedAction, file.Action);
if (file.Action == B2FileAction.Upload)
Assert.IsTrue(file.ContentLength > 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using GMessenger.Areas.HelpPage.ModelDescriptions;
using GMessenger.Areas.HelpPage.Models;
namespace GMessenger.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductSupplierItem (editable child object).<br/>
/// This is a generated base class of <see cref="ProductSupplierItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductSupplierColl"/> collection.
/// </remarks>
[Serializable]
public partial class ProductSupplierItem : BusinessBase<ProductSupplierItem>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductSupplierId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductSupplierIdProperty = RegisterProperty<int>(p => p.ProductSupplierId, "Product Supplier Id");
/// <summary>
/// Gets the Product Supplier Id.
/// </summary>
/// <value>The Product Supplier Id.</value>
public int ProductSupplierId
{
get { return GetProperty(ProductSupplierIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SupplierId"/> property.
/// </summary>
public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id");
/// <summary>
/// Gets or sets the Supplier Id.
/// </summary>
/// <value>The Supplier Id.</value>
public int SupplierId
{
get { return GetProperty(SupplierIdProperty); }
set { SetProperty(SupplierIdProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductSupplierItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductSupplierItem()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductSupplierItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(ProductSupplierIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="ProductSupplierItem"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductSupplierIdProperty, dr.GetInt32("ProductSupplierId"));
LoadProperty(SupplierIdProperty, dr.GetInt32("SupplierId"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="ProductSupplierItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(ProductEdit parent)
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
int productSupplierId = -1;
dal.Insert(
parent.ProductId,
out productSupplierId,
SupplierId
);
LoadProperty(ProductSupplierIdProperty, productSupplierId);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductSupplierItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
dal.Update(
ProductSupplierId,
SupplierId
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="ProductSupplierItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(ProductSupplierIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//#define Trace
// BZip2OutputStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 16:44:11>
//
// ------------------------------------------------------------------
//
// This module defines the BZip2OutputStream class, which is a
// compressing stream that handles BZIP2. This code may have been
// derived in part from Apache commons source code. The license below
// applies to the original Apache code.
//
// ------------------------------------------------------------------
// flymake: csc.exe /t:module BZip2InputStream.cs BZip2Compressor.cs Rand.cs BCRC32.cs @@FILE@@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Design Notes:
//
// This class follows the classic Decorator pattern: it is a Stream that
// wraps itself around a Stream, and in doing so provides bzip2
// compression as callers Write into it.
//
// BZip2 is a straightforward data format: there are 4 magic bytes at
// the top of the file, followed by 1 or more compressed blocks. There
// is a small "magic byte" trailer after all compressed blocks. This
// class emits the magic bytes for the header and trailer, and relies on
// a BZip2Compressor to generate each of the compressed data blocks.
//
// BZip2 does byte-shredding - it uses partial fractions of bytes to
// represent independent pieces of information. This class relies on the
// BitWriter to adapt the bit-oriented BZip2 output to the byte-oriented
// model of the .NET Stream class.
//
// ----
//
// Regarding the Apache code base: Most of the code in this particular
// class is related to stream operations, and is my own code. It largely
// does not rely on any code obtained from Apache commons. If you
// compare this code with the Apache commons BZip2OutputStream, you will
// see very little code that is common, except for the
// nearly-boilerplate structure that is common to all subtypes of
// System.IO.Stream. There may be some small remnants of code in this
// module derived from the Apache stuff, which is why I left the license
// in here. Most of the Apache commons compressor magic has been ported
// into the BZip2Compressor class.
//
using System;
using System.IO;
namespace Ionic.BZip2
{
/// <summary>
/// A write-only decorator stream that compresses data as it is
/// written using the BZip2 algorithm.
/// </summary>
public class BZip2OutputStream : System.IO.Stream
{
private int totalBytesWrittenIn;
private bool leaveOpen;
private BZip2Compressor compressor;
private uint combinedCRC;
private Stream output;
private BitWriter bw;
private int blockSize100k; // 0...9
private TraceBits desiredTrace = TraceBits.Crc | TraceBits.Write;
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c>, that sends its
/// compressed output to the given output stream.
/// </summary>
///
/// <param name='output'>
/// The destination stream, to which compressed output will be sent.
/// </param>
///
/// <example>
///
/// This example reads a file, then compresses it with bzip2 file,
/// and writes the compressed data into a newly created file.
///
/// <code>
/// var fname = "logfile.log";
/// using (var fs = File.OpenRead(fname))
/// {
/// var outFname = fname + ".bz2";
/// using (var output = File.Create(outFname))
/// {
/// using (var compressor = new Ionic.BZip2.BZip2OutputStream(output))
/// {
/// byte[] buffer = new byte[2048];
/// int n;
/// while ((n = fs.Read(buffer, 0, buffer.Length)) > 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public BZip2OutputStream(Stream output)
: this(output, BZip2.MaxBlockSize, false)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c> with specified blocksize.
/// </summary>
/// <param name = "output">the destination stream.</param>
/// <param name = "blockSize">
/// The blockSize in units of 100000 bytes.
/// The valid range is 1..9.
/// </param>
public BZip2OutputStream(Stream output, int blockSize)
: this(output, blockSize, false)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c>.
/// </summary>
/// <param name = "output">the destination stream.</param>
/// <param name = "leaveOpen">
/// whether to leave the captive stream open upon closing this stream.
/// </param>
public BZip2OutputStream(Stream output, bool leaveOpen)
: this(output, BZip2.MaxBlockSize, leaveOpen)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c> with specified blocksize,
/// and explicitly specifies whether to leave the wrapped stream open.
/// </summary>
///
/// <param name = "output">the destination stream.</param>
/// <param name = "blockSize">
/// The blockSize in units of 100000 bytes.
/// The valid range is 1..9.
/// </param>
/// <param name = "leaveOpen">
/// whether to leave the captive stream open upon closing this stream.
/// </param>
public BZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
{
if (blockSize < BZip2.MinBlockSize ||
blockSize > BZip2.MaxBlockSize)
{
var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}",
blockSize,
BZip2.MinBlockSize, BZip2.MaxBlockSize);
throw new ArgumentException(msg, nameof(blockSize));
}
this.output = output;
if (!this.output.CanWrite)
throw new ArgumentException("The stream is not writable.", nameof(output));
this.bw = new BitWriter(this.output);
this.blockSize100k = blockSize;
this.compressor = new BZip2Compressor(this.bw, blockSize);
this.leaveOpen = leaveOpen;
this.combinedCRC = 0;
EmitHeader();
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not close the underlying stream. Check the
/// constructors that accept a bool value.
/// </para>
/// </remarks>
public override void Close()
{
if (output != null)
{
Stream o = this.output;
Finish();
if (!leaveOpen)
o.Close();
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (this.output != null)
{
this.bw.Flush();
this.output.Flush();
}
}
private void EmitHeader()
{
var magic = new byte[] {
(byte) 'B',
(byte) 'Z',
(byte) 'h',
(byte) ('0' + this.blockSize100k)
};
// not necessary to shred the initial magic bytes
this.output.Write(magic, 0, magic.Length);
}
private void EmitTrailer()
{
// A magic 48-bit number, 0x177245385090, to indicate the end
// of the last block. (sqrt(pi), if you want to know)
TraceOutput(TraceBits.Write, "total written out: {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut);
// must shred
this.bw.WriteByte(0x17);
this.bw.WriteByte(0x72);
this.bw.WriteByte(0x45);
this.bw.WriteByte(0x38);
this.bw.WriteByte(0x50);
this.bw.WriteByte(0x90);
this.bw.WriteInt(this.combinedCRC);
this.bw.FinishAndPad();
TraceOutput(TraceBits.Write, "final total: {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut);
}
private void Finish()
{
// Console.WriteLine("BZip2:Finish");
try
{
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
this.combinedCRC ^= (uint) compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
this.compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (final) : {0:X8}",
this.combinedCRC);
EmitTrailer();
}
finally
{
this.output = null;
this.compressor = null;
this.bw = null;
}
}
/// <summary>
/// The blocksize parameter specified at construction time.
/// </summary>
public int BlockSize
{
get { return this.blockSize100k; }
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// Use the <c>BZip2OutputStream</c> to compress data while writing:
/// create a <c>BZip2OutputStream</c> with a writable output stream.
/// Then call <c>Write()</c> on that <c>BZip2OutputStream</c>, providing
/// uncompressed data as input. The data sent to the output stream will
/// be the compressed form of the input data.
/// </para>
///
/// <para>
/// A <c>BZip2OutputStream</c> can be used only for <c>Write()</c> not for <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
if (count < 0)
throw new IndexOutOfRangeException(String.Format("count ({0}) must be > 0", count));
if (offset + count > buffer.Length)
throw new IndexOutOfRangeException(String.Format("offset({0}) count({1}) bLength({2})",
offset, count, buffer.Length));
if (this.output == null)
throw new IOException("the stream is not open");
if (count == 0) return; // nothing to do
int bytesWritten = 0;
int bytesRemaining = count;
do
{
int n = compressor.Fill(buffer, offset, bytesRemaining);
if (n != bytesRemaining)
{
// The compressor data block is full. Compress and
// write out the compressed data, then reset the
// compressor and continue.
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
// and now any remaining bits
TraceOutput(TraceBits.Write,
" remaining: {0} 0x{1:X}",
this.bw.NumRemainingBits,
this.bw.RemainingBits);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
this.combinedCRC ^= (uint) compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (after) : {0:X8}",
this.combinedCRC);
offset += n;
}
bytesRemaining -= n;
bytesWritten += n;
} while (bytesRemaining > 0);
totalBytesWrittenIn += bytesWritten;
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value is always false.
/// </remarks>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value should always be true, unless and until the
/// object is disposed and closed.
/// </remarks>
public override bool CanWrite
{
get
{
if (this.output == null) throw new ObjectDisposedException("BZip2Stream");
return this.output.CanWrite;
}
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes written through.
/// </remarks>
public override long Position
{
get
{
return this.totalBytesWrittenIn;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name='buffer'>this parameter is never used</param>
/// <param name='offset'>this parameter is never used</param>
/// <param name='count'>this parameter is never used</param>
/// <returns>never returns anything; always throws</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
// used only when Trace is defined
[Flags]
private enum TraceBits : uint
{
None = 0,
Crc = 1,
Write = 2,
All = 0xffffffff,
}
[System.Diagnostics.ConditionalAttribute("Trace")]
private void TraceOutput(TraceBits bits, string format, params object[] varParams)
{
if ((bits & this.desiredTrace) != 0)
{
//lock(outputLock)
{
int tid = System.Threading.Thread.CurrentThread.GetHashCode();
#if FEATURE_FULL_CONSOLE
Console.ForegroundColor = (ConsoleColor) (tid % 8 + 10);
#endif
Console.Write("{0:000} PBOS ", tid);
Console.WriteLine(format, varParams);
#if FEATURE_FULL_CONSOLE
Console.ResetColor();
#endif
}
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="UserSettingName.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Autodiscover
{
/// <summary>
/// User settings that can be requested using GetUserSettings.
/// </summary>
/// <remarks>
/// Add new values to the end and keep in sync with Microsoft.Exchange.Autodiscover.ConfigurationSettings.UserConfigurationSettingName.
/// </remarks>
public enum UserSettingName
{
/// <summary>
/// The display name of the user.
/// </summary>
UserDisplayName = 0,
/// <summary>
/// The legacy distinguished name of the user.
/// </summary>
UserDN = 1,
/// <summary>
/// The deployment Id of the user.
/// </summary>
UserDeploymentId = 2,
/// <summary>
/// The fully qualified domain name of the mailbox server.
/// </summary>
InternalMailboxServer = 3,
/// <summary>
/// The fully qualified domain name of the RPC client server.
/// </summary>
InternalRpcClientServer = 4,
/// <summary>
/// The legacy distinguished name of the mailbox server.
/// </summary>
InternalMailboxServerDN = 5,
/// <summary>
/// The internal URL of the Exchange Control Panel.
/// </summary>
InternalEcpUrl = 6,
/// <summary>
/// The internal URL of the Exchange Control Panel for VoiceMail Customization.
/// </summary>
InternalEcpVoicemailUrl = 7,
/// <summary>
/// The internal URL of the Exchange Control Panel for Email Subscriptions.
/// </summary>
InternalEcpEmailSubscriptionsUrl = 8,
/// <summary>
/// The internal URL of the Exchange Control Panel for Text Messaging.
/// </summary>
InternalEcpTextMessagingUrl = 9,
/// <summary>
/// The internal URL of the Exchange Control Panel for Delivery Reports.
/// </summary>
InternalEcpDeliveryReportUrl = 10,
/// <summary>
/// The internal URL of the Exchange Control Panel for RetentionPolicy Tags.
/// </summary>
InternalEcpRetentionPolicyTagsUrl = 11,
/// <summary>
/// The internal URL of the Exchange Control Panel for Publishing.
/// </summary>
InternalEcpPublishingUrl = 12,
/// <summary>
/// The internal URL of the Exchange Control Panel for photos.
/// </summary>
InternalEcpPhotoUrl = 13,
/// <summary>
/// The internal URL of the Exchange Control Panel for People Connect subscriptions.
/// </summary>
InternalEcpConnectUrl = 14,
/// <summary>
/// The internal URL of the Exchange Control Panel for Team Mailbox.
/// </summary>
InternalEcpTeamMailboxUrl = 15,
/// <summary>
/// The internal URL of the Exchange Control Panel for creating Team Mailbox.
/// </summary>
InternalEcpTeamMailboxCreatingUrl = 16,
/// <summary>
/// The internal URL of the Exchange Control Panel for editing Team Mailbox.
/// </summary>
InternalEcpTeamMailboxEditingUrl = 17,
/// <summary>
/// The internal URL of the Exchange Control Panel for hiding Team Mailbox.
/// </summary>
InternalEcpTeamMailboxHidingUrl = 18,
/// <summary>
/// The internal URL of the Exchange Control Panel for the extension installation.
/// </summary>
InternalEcpExtensionInstallationUrl = 19,
/// <summary>
/// The internal URL of the Exchange Web Services.
/// </summary>
InternalEwsUrl = 20,
/// <summary>
/// The internal URL of the Exchange Management Web Services.
/// </summary>
InternalEmwsUrl = 21,
/// <summary>
/// The internal URL of the Offline Address Book.
/// </summary>
InternalOABUrl = 22,
/// <summary>
/// The internal URL of the Photos service.
/// </summary>
InternalPhotosUrl = 23,
/// <summary>
/// The internal URL of the Unified Messaging services.
/// </summary>
InternalUMUrl = 24,
/// <summary>
/// The internal URLs of the Exchange web client.
/// </summary>
InternalWebClientUrls = 25,
/// <summary>
/// The distinguished name of the mailbox database of the user's mailbox.
/// </summary>
MailboxDN = 26,
/// <summary>
/// The name of the Public Folders server.
/// </summary>
PublicFolderServer = 27,
/// <summary>
/// The name of the Active Directory server.
/// </summary>
ActiveDirectoryServer = 28,
/// <summary>
/// The name of the RPC over HTTP server.
/// </summary>
ExternalMailboxServer = 29,
/// <summary>
/// Indicates whether the RPC over HTTP server requires SSL.
/// </summary>
ExternalMailboxServerRequiresSSL = 30,
/// <summary>
/// The authentication methods supported by the RPC over HTTP server.
/// </summary>
ExternalMailboxServerAuthenticationMethods = 31,
/// <summary>
/// The URL fragment of the Exchange Control Panel for VoiceMail Customization.
/// </summary>
EcpVoicemailUrlFragment = 32,
/// <summary>
/// The URL fragment of the Exchange Control Panel for Email Subscriptions.
/// </summary>
EcpEmailSubscriptionsUrlFragment = 33,
/// <summary>
/// The URL fragment of the Exchange Control Panel for Text Messaging.
/// </summary>
EcpTextMessagingUrlFragment = 34,
/// <summary>
/// The URL fragment of the Exchange Control Panel for Delivery Reports.
/// </summary>
EcpDeliveryReportUrlFragment = 35,
/// <summary>
/// The URL fragment of the Exchange Control Panel for RetentionPolicy Tags.
/// </summary>
EcpRetentionPolicyTagsUrlFragment = 36,
/// <summary>
/// The URL fragment of the Exchange Control Panel for Publishing.
/// </summary>
EcpPublishingUrlFragment = 37,
/// <summary>
/// The URL fragment of the Exchange Control Panel for photos.
/// </summary>
EcpPhotoUrlFragment = 38,
/// <summary>
/// The URL fragment of the Exchange Control Panel for People Connect.
/// </summary>
EcpConnectUrlFragment = 39,
/// <summary>
/// The URL fragment of the Exchange Control Panel for Team Mailbox.
/// </summary>
EcpTeamMailboxUrlFragment = 40,
/// <summary>
/// The URL fragment of the Exchange Control Panel for creating Team Mailbox.
/// </summary>
EcpTeamMailboxCreatingUrlFragment = 41,
/// <summary>
/// The URL fragment of the Exchange Control Panel for editing Team Mailbox.
/// </summary>
EcpTeamMailboxEditingUrlFragment = 42,
/// <summary>
/// The URL fragment of the Exchange Control Panel for installing extension.
/// </summary>
EcpExtensionInstallationUrlFragment = 43,
/// <summary>
/// The external URL of the Exchange Control Panel.
/// </summary>
ExternalEcpUrl = 44,
/// <summary>
/// The external URL of the Exchange Control Panel for VoiceMail Customization.
/// </summary>
ExternalEcpVoicemailUrl = 45,
/// <summary>
/// The external URL of the Exchange Control Panel for Email Subscriptions.
/// </summary>
ExternalEcpEmailSubscriptionsUrl = 46,
/// <summary>
/// The external URL of the Exchange Control Panel for Text Messaging.
/// </summary>
ExternalEcpTextMessagingUrl = 47,
/// <summary>
/// The external URL of the Exchange Control Panel for Delivery Reports.
/// </summary>
ExternalEcpDeliveryReportUrl = 48,
/// <summary>
/// The external URL of the Exchange Control Panel for RetentionPolicy Tags.
/// </summary>
ExternalEcpRetentionPolicyTagsUrl = 49,
/// <summary>
/// The external URL of the Exchange Control Panel for Publishing.
/// </summary>
ExternalEcpPublishingUrl = 50,
/// <summary>
/// The external URL of the Exchange Control Panel for photos.
/// </summary>
ExternalEcpPhotoUrl = 51,
/// <summary>
/// The external URL of the Exchange Control Panel for People Connect subscriptions.
/// </summary>
ExternalEcpConnectUrl = 52,
/// <summary>
/// The external URL of the Exchange Control Panel for Team Mailbox.
/// </summary>
ExternalEcpTeamMailboxUrl = 53,
/// <summary>
/// The external URL of the Exchange Control Panel for creating Team Mailbox.
/// </summary>
ExternalEcpTeamMailboxCreatingUrl = 54,
/// <summary>
/// The external URL of the Exchange Control Panel for editing Team Mailbox.
/// </summary>
ExternalEcpTeamMailboxEditingUrl = 55,
/// <summary>
/// The external URL of the Exchange Control Panel for hiding Team Mailbox.
/// </summary>
ExternalEcpTeamMailboxHidingUrl = 56,
/// <summary>
/// The external URL of the Exchange Control Panel for the extension installation.
/// </summary>
ExternalEcpExtensionInstallationUrl = 57,
/// <summary>
/// The external URL of the Exchange Web Services.
/// </summary>
ExternalEwsUrl = 58,
/// <summary>
/// The external URL of the Exchange Management Web Services.
/// </summary>
ExternalEmwsUrl = 59,
/// <summary>
/// The external URL of the Offline Address Book.
/// </summary>
ExternalOABUrl = 60,
/// <summary>
/// The external URL of the Photos service.
/// </summary>
ExternalPhotosUrl = 61,
/// <summary>
/// The external URL of the Unified Messaging services.
/// </summary>
ExternalUMUrl = 62,
/// <summary>
/// The external URLs of the Exchange web client.
/// </summary>
ExternalWebClientUrls = 63,
/// <summary>
/// Indicates that cross-organization sharing is enabled.
/// </summary>
CrossOrganizationSharingEnabled = 64,
/// <summary>
/// Collection of alternate mailboxes.
/// </summary>
AlternateMailboxes = 65,
/// <summary>
/// The version of the Client Access Server serving the request (e.g. 14.XX.YYY.ZZZ)
/// </summary>
CasVersion = 66,
/// <summary>
/// Comma-separated list of schema versions supported by Exchange Web Services. The schema version values
/// will be the same as the values of the ExchangeServerVersion enumeration.
/// </summary>
EwsSupportedSchemas = 67,
/// <summary>
/// The internal connection settings list for pop protocol
/// </summary>
InternalPop3Connections = 68,
/// <summary>
/// The external connection settings list for pop protocol
/// </summary>
ExternalPop3Connections = 69,
/// <summary>
/// The internal connection settings list for imap4 protocol
/// </summary>
InternalImap4Connections = 70,
/// <summary>
/// The external connection settings list for imap4 protocol
/// </summary>
ExternalImap4Connections = 71,
/// <summary>
/// The internal connection settings list for smtp protocol
/// </summary>
InternalSmtpConnections = 72,
/// <summary>
/// The external connection settings list for smtp protocol
/// </summary>
ExternalSmtpConnections = 73,
/// <summary>
/// If set to "Off" then clients should not connect via this protocol.
/// The protocol contents are for informational purposes only.
/// </summary>
InternalServerExclusiveConnect = 74,
/// <summary>
/// The version of the Exchange Web Services server ExternalEwsUrl is pointing to.
/// </summary>
ExternalEwsVersion = 75,
/// <summary>
/// Mobile Mailbox policy settings.
/// </summary>
MobileMailboxPolicy = 76,
/// <summary>
/// Document sharing locations and their settings.
/// </summary>
DocumentSharingLocations = 77,
/// <summary>
/// Whether the user account is an MSOnline account.
/// </summary>
UserMSOnline = 78,
/// <summary>
/// The authentication methods supported by the RPC client server.
/// </summary>
InternalMailboxServerAuthenticationMethods = 79,
/// <summary>
/// Version of the server hosting the user's mailbox.
/// </summary>
MailboxVersion = 80,
/// <summary>
/// Sharepoint MySite Host URL.
/// </summary>
SPMySiteHostURL = 81,
/// <summary>
/// Site mailbox creation URL in SharePoint.
/// It's used by Outlook to create site mailbox from SharePoint directly.
/// </summary>
SiteMailboxCreationURL = 82,
/// <summary>
/// The FQDN of the server used for internal RPC/HTTP connectivity.
/// </summary>
InternalRpcHttpServer = 83,
/// <summary>
/// Indicates whether SSL is required for internal RPC/HTTP connectivity.
/// </summary>
InternalRpcHttpConnectivityRequiresSsl = 84,
/// <summary>
/// The authentication method used for internal RPC/HTTP connectivity.
/// </summary>
InternalRpcHttpAuthenticationMethod = 85,
/// <summary>
/// If set to "On" then clients should only connect via this protocol.
/// </summary>
ExternalServerExclusiveConnect = 86,
/// <summary>
/// If set, then clients can call the server via XTC
/// </summary>
ExchangeRpcUrl = 87,
/// <summary>
/// If set to false then clients should not show the GAL by default, but show the contact list.
/// </summary>
ShowGalAsDefaultView = 88,
/// <summary>
/// AutoDiscover Primary SMTP Address for the user.
/// </summary>
AutoDiscoverSMTPAddress = 89,
/// <summary>
/// The 'interop' external URL of the Exchange Web Services.
/// By interop it means a URL to E14 (or later) server that can serve mailboxes
/// that are hosted in downlevel server (E2K3 and earlier).
/// </summary>
InteropExternalEwsUrl = 90,
/// <summary>
/// Version of server InteropExternalEwsUrl is pointing to.
/// </summary>
InteropExternalEwsVersion = 91,
/// <summary>
/// Public Folder (Hierarchy) information
/// </summary>
PublicFolderInformation = 92,
/// <summary>
/// The version appropriate URL of the AutoDiscover service that should answer this query.
/// </summary>
RedirectUrl = 93,
/// <summary>
/// The URL of the Exchange Web Services for Office365 partners.
/// </summary>
EwsPartnerUrl = 94,
/// <summary>
/// SSL certificate name
/// </summary>
CertPrincipalName = 95,
/// <summary>
/// The grouping hint for certain clients.
/// </summary>
GroupingInformation = 96,
/// <summary>
/// Internal OutlookService URL
/// </summary>
InternalOutlookServiceUrl = 98,
/// <summary>
/// External OutlookService URL
/// </summary>
ExternalOutlookServiceUrl = 99
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace NotificationHubsSample.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// ArtworkManager.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Mono.Unix;
using Gdk;
using Hyena;
using Hyena.Gui;
using Hyena.Collections;
using Banshee.Base;
using Banshee.ServiceStack;
namespace Banshee.Collection.Gui
{
public class ArtworkManager : IService
{
private Dictionary<int, SurfaceCache> scale_caches = new Dictionary<int, SurfaceCache> ();
private class SurfaceCache : LruCache<string, Cairo.ImageSurface>
{
public SurfaceCache (int max_items) : base (max_items)
{
}
protected override void ExpireItem (Cairo.ImageSurface item)
{
if (item != null) {
((IDisposable)item).Dispose ();
}
}
}
public ArtworkManager ()
{
try {
MigrateLegacyAlbumArt ();
} catch (Exception e) {
Log.Error ("Could not migrate old album artwork to new location.", e.Message, true);
}
}
private void MigrateLegacyAlbumArt ()
{
if (Directory.Exists (CoverArtSpec.RootPath)) {
return;
}
// FIXME: Replace with Directory.Move for release
Directory.CreateDirectory (CoverArtSpec.RootPath);
string legacy_artwork_path = Path.Combine (Paths.LegacyApplicationData, "covers");
int artwork_count = 0;
if (Directory.Exists (legacy_artwork_path)) {
foreach (string path in Directory.GetFiles (legacy_artwork_path)) {
string dest_path = Path.Combine (CoverArtSpec.RootPath, Path.GetFileName (path));
File.Copy (path, dest_path);
artwork_count++;
}
}
Log.Debug (String.Format ("Migrated {0} album art images.", artwork_count));
}
public Cairo.ImageSurface LookupSurface (string id)
{
return LookupScaleSurface (id, 0);
}
public Cairo.ImageSurface LookupScaleSurface (string id, int size)
{
return LookupScaleSurface (id, size, false);
}
public Cairo.ImageSurface LookupScaleSurface (string id, int size, bool useCache)
{
SurfaceCache cache = null;
Cairo.ImageSurface surface = null;
if (id == null) {
return null;
}
if (useCache && scale_caches.TryGetValue (size, out cache) && cache.TryGetValue (id, out surface)) {
return surface;
}
Pixbuf pixbuf = LookupScalePixbuf (id, size);
if (pixbuf == null || pixbuf.Handle == IntPtr.Zero) {
return null;
}
try {
surface = PixbufImageSurface.Create (pixbuf);
if (surface == null) {
return null;
}
if (!useCache) {
return surface;
}
if (cache == null) {
int bytes = 4 * size * size;
int max = (1 << 20) / bytes;
Log.DebugFormat ("Creating new surface cache for {0} KB (max) images, capped at 1 MB ({1} items)",
bytes, max);
cache = new SurfaceCache (max);
scale_caches.Add (size, cache);
}
cache.Add (id, surface);
return surface;
} finally {
DisposePixbuf (pixbuf);
}
}
public Pixbuf LookupPixbuf (string id)
{
return LookupScalePixbuf (id, 0);
}
public Pixbuf LookupScalePixbuf (string id, int size)
{
if (id == null || (size != 0 && size < 10)) {
return null;
}
// Find the scaled, cached file
string path = CoverArtSpec.GetPathForSize (id, size);
if (File.Exists (path)) {
try {
return new Pixbuf (path);
} catch {
return null;
}
}
string orig_path = CoverArtSpec.GetPathForSize (id, 0);
bool orig_exists = File.Exists (orig_path);
if (!orig_exists) {
// It's possible there is an image with extension .cover that's waiting
// to be converted into a jpeg
string unconverted_path = Path.ChangeExtension (orig_path, "cover");
if (File.Exists (unconverted_path)) {
try {
Pixbuf pixbuf = new Pixbuf (unconverted_path);
if (pixbuf.Width < 50 || pixbuf.Height < 50) {
Hyena.Log.DebugFormat ("Ignoring cover art {0} because less than 50x50", unconverted_path);
return null;
}
pixbuf.Save (orig_path, "jpeg");
orig_exists = true;
} catch {
} finally {
File.Delete (unconverted_path);
}
}
}
if (orig_exists && size >= 10) {
try {
Pixbuf pixbuf = new Pixbuf (orig_path);
Pixbuf scaled_pixbuf = pixbuf.ScaleSimple (size, size, Gdk.InterpType.Bilinear);
Directory.CreateDirectory (Path.GetDirectoryName (path));
scaled_pixbuf.Save (path, "jpeg");
DisposePixbuf (pixbuf);
return scaled_pixbuf;
} catch {}
}
return null;
}
private static int dispose_count = 0;
public static void DisposePixbuf (Pixbuf pixbuf)
{
if (pixbuf != null && pixbuf.Handle != IntPtr.Zero) {
pixbuf.Dispose ();
pixbuf = null;
// There is an issue with disposing Pixbufs where we need to explicitly
// call the GC otherwise it doesn't get done in a timely way. But if we
// do it every time, it slows things down a lot; so only do it every 100th.
if (++dispose_count % 100 == 0) {
System.GC.Collect ();
dispose_count = 0;
}
}
}
string IService.ServiceName {
get { return "ArtworkManager"; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
{
public class DynamicTextureModule : IRegionModule, IDynamicTextureManager
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int ALL_SIDES = -1;
public const int DISP_EXPIRE = 1;
public const int DISP_TEMP = 2;
private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>();
private Dictionary<string, IDynamicTextureRender> RenderPlugins =
new Dictionary<string, IDynamicTextureRender>();
private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>();
#region IDynamicTextureManager Members
public void RegisterRender(string handleType, IDynamicTextureRender render)
{
if (!RenderPlugins.ContainsKey(handleType))
{
RenderPlugins.Add(handleType, render);
}
}
/// <summary>
/// Called by code which actually renders the dynamic texture to supply texture data.
/// </summary>
/// <param name="id"></param>
/// <param name="data"></param>
public void ReturnData(UUID id, byte[] data)
{
DynamicTextureUpdater updater = null;
lock (Updaters)
{
if (Updaters.ContainsKey(id))
{
updater = Updaters[id];
}
}
if (updater != null)
{
if (RegisteredScenes.ContainsKey(updater.SimUUID))
{
Scene scene = RegisteredScenes[updater.SimUUID];
updater.DataReceived(data, scene);
}
}
if (updater.UpdateTimer == 0)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Remove(updater.UpdaterID);
}
}
}
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer)
{
return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureURL(simID, primID, contentType, url,
extraParams, updateTimer, SetBlending,
(int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending,
int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.Url = url;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Disp = disp;
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending,
(int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.BodyData = data;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Url = "Local image";
updater.Disp = disp;
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
if (RenderPlugins.ContainsKey(contentType))
{
RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
}
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IDynamicTextureManager>(this);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "DynamicTextureModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
#region Nested type: DynamicTextureUpdater
public class DynamicTextureUpdater
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool BlendWithOldTexture = false;
public string BodyData;
public string ContentType;
public byte FrontAlpha = 255;
public UUID LastAssetID;
public string Params;
public UUID PrimID;
public bool SetNewFrontAlpha = false;
public UUID SimUUID;
public UUID UpdaterID;
public int UpdateTimer;
public int Face;
public int Disp;
public string Url;
public DynamicTextureUpdater()
{
LastAssetID = UUID.Zero;
UpdateTimer = 0;
BodyData = null;
}
/// <summary>
/// Called once new texture data has been received for this updater.
/// </summary>
public void DataReceived(byte[] data, Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
if (part == null || data == null || data.Length <= 1)
{
string msg =
String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
return;
}
byte[] assetData;
AssetBase oldAsset = null;
if (BlendWithOldTexture)
{
UUID lastTextureID = part.Shape.Textures.DefaultTexture.TextureID;
oldAsset = scene.AssetService.Get(lastTextureID.ToString());
if (oldAsset != null)
{
assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
}
else
{
assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length);
}
}
else
{
assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length);
}
// Create a new asset for user
AssetBase asset = new AssetBase();
asset.FullID = UUID.Random();
asset.Data = assetData;
asset.Name = "DynamicImage" + Util.RandomClass.Next(1, 10000);
asset.Type = 0;
asset.Description = String.Format("URL image : {0}", Url);
asset.Local = false;
asset.Temporary = ((Disp & DISP_TEMP) != 0);
scene.AssetService.Store(asset);
// scene.CommsManager.AssetCache.AddAsset(asset);
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
{
cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
cacheLayerDecode = null;
LastAssetID = asset.FullID;
}
UUID oldID = UUID.Zero;
lock (part)
{
// mostly keep the values from before
Primitive.TextureEntry tmptex = part.Shape.Textures;
// remove the old asset from the cache
oldID = tmptex.DefaultTexture.TextureID;
if (Face == ALL_SIDES)
{
tmptex.DefaultTexture.TextureID = asset.FullID;
}
else
{
try
{
Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
texface.TextureID = asset.FullID;
tmptex.FaceTextures[Face] = texface;
}
catch (Exception)
{
tmptex.DefaultTexture.TextureID = asset.FullID;
}
}
// I'm pretty sure we always want to force this to true
// I'm pretty sure noone whats to set fullbright true if it wasn't true before.
// tmptex.DefaultTexture.Fullbright = true;
part.UpdateTexture(tmptex);
}
if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
{
// scene.CommsManager.AssetCache.ExpireAsset(oldID);
scene.AssetService.Delete(oldID.ToString());
}
}
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image))
{
Bitmap image1 = new Bitmap(image);
if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image))
{
Bitmap image2 = new Bitmap(image);
if (setNewAlpha)
SetAlpha(ref image1, newAlpha);
Bitmap joint = MergeBitMaps(image1, image2);
byte[] result = new byte[0];
try
{
result = OpenJPEG.EncodeFromImage(joint, true);
}
catch (Exception)
{
m_log.Error("[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!");
}
return result;
}
}
return null;
}
public Bitmap MergeBitMaps(Bitmap front, Bitmap back)
{
Bitmap joint;
Graphics jG;
joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb);
jG = Graphics.FromImage(joint);
jG.DrawImage(back, 0, 0, back.Width, back.Height);
jG.DrawImage(front, 0, 0, back.Width, back.Height);
return joint;
}
private void SetAlpha(ref Bitmap b, byte alpha)
{
for (int w = 0; w < b.Width; w++)
{
for (int h = 0; h < b.Height; h++)
{
b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h)));
}
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt16()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestNotZAndNotCInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCInt16 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt16();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace System.ServiceModel.Syndication.Tests
{
public enum NodePosition
{
Before = 0,
After = 1,
Unknown = 2
}
public enum XmlDiffNodeType
{
Element = 0,
Attribute = 1,
ER = 2,
Text = 3,
CData = 4,
Comment = 5,
PI = 6,
WS = 7,
Document = 8
}
internal class PositionInfo : IXmlLineInfo
{
public virtual bool HasLineInfo() => false;
public virtual int LineNumber => 0;
public virtual int LinePosition => 0;
public static PositionInfo GetPositionInfo(object o)
{
if (o is IXmlLineInfo lineInfo && lineInfo.HasLineInfo())
{
return new ReaderPositionInfo(lineInfo);
}
else
{
return new PositionInfo();
}
}
}
internal class ReaderPositionInfo : PositionInfo
{
private IXmlLineInfo _mlineInfo;
public ReaderPositionInfo(IXmlLineInfo lineInfo)
{
_mlineInfo = lineInfo;
}
public override bool HasLineInfo() => true;
public override int LineNumber => _mlineInfo.LineNumber;
public override int LinePosition => _mlineInfo.LinePosition;
}
//nametable could be added for next "release"
public class XmlDiffNameTable
{
}
public class XmlDiffDocument : XmlDiffNode, IXPathNavigable
{
private bool _bLoaded;
public XmlNameTable nameTable;
public XmlDiffDocument() : base()
{
_bLoaded = false;
IgnoreAttributeOrder = false;
IgnoreChildOrder = false;
IgnoreComments = false;
IgnoreWhitespace = false;
IgnoreDTD = false;
CDataAsText = false;
WhitespaceAsText = false;
}
public XmlDiffOption Option
{
set
{
IgnoreAttributeOrder = (((int)value & (int)(XmlDiffOption.IgnoreAttributeOrder)) > 0);
IgnoreChildOrder = (((int)value & (int)(XmlDiffOption.IgnoreChildOrder)) > 0);
IgnoreComments = (((int)value & (int)(XmlDiffOption.IgnoreComments)) > 0);
IgnoreWhitespace = (((int)value & (int)(XmlDiffOption.IgnoreWhitespace)) > 0);
IgnoreDTD = (((int)value & (int)(XmlDiffOption.IgnoreDTD)) > 0);
IgnoreNS = (((int)value & (int)(XmlDiffOption.IgnoreNS)) > 0);
IgnorePrefix = (((int)value & (int)(XmlDiffOption.IgnorePrefix)) > 0);
CDataAsText = (((int)value & (int)(XmlDiffOption.CDataAsText)) > 0);
NormalizeNewline = (((int)value & (int)(XmlDiffOption.NormalizeNewline)) > 0);
TreatWhitespaceTextAsWSNode = (((int)value & (int)(XmlDiffOption.TreatWhitespaceTextAsWSNode)) > 0);
IgnoreEmptyTextNodes = (((int)value & (int)(XmlDiffOption.IgnoreEmptyTextNodes)) > 0);
WhitespaceAsText = (((int)value & (int)(XmlDiffOption.WhitespaceAsText)) > 0);
}
}
public override XmlDiffNodeType NodeType => XmlDiffNodeType.Document;
public bool IgnoreAttributeOrder { get; set; }
public bool IgnoreChildOrder { get; set; }
public bool IgnoreComments { get; set; }
public bool IgnoreWhitespace { get; set; }
public bool IgnoreDTD { get; set; }
public bool IgnoreNS { get; set; }
public bool IgnorePrefix { get; set; }
public bool CDataAsText { get; set; }
public bool NormalizeNewline { get; set; }
public bool TreatWhitespaceTextAsWSNode { get; set; } = false;
public bool IgnoreEmptyTextNodes { get; set; } = false;
public bool WhitespaceAsText { get; set; } = false;
//NodePosition.Before is returned if node2 should be before node1;
//NodePosition.After is returned if node2 should be after node1;
//In any case, NodePosition.Unknown should never be returned.
internal NodePosition ComparePosition(XmlDiffNode node1, XmlDiffNode node2)
{
int nt1 = (int)(node1.NodeType);
int nt2 = (int)(node2.NodeType);
if (nt2 > nt1)
return NodePosition.After;
if (nt2 < nt1)
return NodePosition.Before;
//now nt1 == nt2
if (nt1 == (int)XmlDiffNodeType.Element)
{
return CompareElements(node1 as XmlDiffElement, node2 as XmlDiffElement);
}
else if (nt1 == (int)XmlDiffNodeType.Attribute)
{
return CompareAttributes(node1 as XmlDiffAttribute, node2 as XmlDiffAttribute);
}
else if (nt1 == (int)XmlDiffNodeType.ER)
{
return CompareERs(node1 as XmlDiffEntityReference, node2 as XmlDiffEntityReference);
}
else if (nt1 == (int)XmlDiffNodeType.PI)
{
return ComparePIs(node1 as XmlDiffProcessingInstruction, node2 as XmlDiffProcessingInstruction);
}
else if (node1 is XmlDiffCharacterData)
{
return CompareTextLikeNodes(node1 as XmlDiffCharacterData, node2 as XmlDiffCharacterData);
}
else
{
//something really wrong here, what should we do???
Debug.Assert(false, "ComparePosition meets an undecision situation.");
return NodePosition.Unknown;
}
}
private NodePosition CompareElements(XmlDiffElement elem1, XmlDiffElement elem2)
{
Debug.Assert(elem1 != null);
Debug.Assert(elem2 != null);
int nCompare = 0;
if ((nCompare = CompareText(elem2.LocalName, elem1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(elem2.NamespaceURI, elem1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(elem2.Prefix, elem1.Prefix)) == 0)
{
if ((nCompare = CompareText(elem2.Value, elem1.Value)) == 0)
{
if ((nCompare = CompareAttributes(elem2, elem1)) == 0)
{
return NodePosition.After;
}
}
}
}
}
if (nCompare > 0)
//elem2 > elem1
return NodePosition.After;
else
//elem2 < elem1
return NodePosition.Before;
}
private int CompareAttributes(XmlDiffElement elem1, XmlDiffElement elem2)
{
int count1 = elem1.AttributeCount;
int count2 = elem2.AttributeCount;
if (count1 > count2)
return 1;
else if (count1 < count2)
return -1;
else
{
XmlDiffAttribute current1 = elem1.FirstAttribute;
XmlDiffAttribute current2 = elem2.FirstAttribute;
// NodePosition result = 0;
int nCompare = 0;
while (current1 != null && current2 != null && nCompare == 0)
{
if ((nCompare = CompareText(current2.LocalName, current1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(current2.NamespaceURI, current1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(current2.Prefix, current1.Prefix)) == 0)
{
if ((nCompare = CompareText(current2.Value, current1.Value)) == 0)
{
//do nothing!
}
}
}
}
current1 = (XmlDiffAttribute)current1._next;
current2 = (XmlDiffAttribute)current2._next;
}
if (nCompare > 0)
//elem1 > attr2
return 1;
else
//elem1 < elem2
return -1;
}
}
private NodePosition CompareAttributes(XmlDiffAttribute attr1, XmlDiffAttribute attr2)
{
Debug.Assert(attr1 != null);
Debug.Assert(attr2 != null);
int nCompare = 0;
if ((nCompare = CompareText(attr2.LocalName, attr1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(attr2.NamespaceURI, attr1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(attr2.Prefix, attr1.Prefix)) == 0)
{
if ((nCompare = CompareText(attr2.Value, attr1.Value)) == 0)
{
return NodePosition.After;
}
}
}
}
if (nCompare > 0)
//attr2 > attr1
return NodePosition.After;
else
//attr2 < attr1
return NodePosition.Before;
}
private NodePosition CompareERs(XmlDiffEntityReference er1, XmlDiffEntityReference er2)
{
Debug.Assert(er1 != null);
Debug.Assert(er2 != null);
int nCompare = CompareText(er2.Name, er1.Name);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
private NodePosition ComparePIs(XmlDiffProcessingInstruction pi1, XmlDiffProcessingInstruction pi2)
{
Debug.Assert(pi1 != null);
Debug.Assert(pi2 != null);
int nCompare = 0;
if ((nCompare = CompareText(pi2.Name, pi1.Name)) == 0)
{
if ((nCompare = CompareText(pi2.Value, pi1.Value)) == 0)
{
return NodePosition.After;
}
}
if (nCompare > 0)
{
//pi2 > pi1
return NodePosition.After;
}
else
{
//pi2 < pi1
return NodePosition.Before;
}
}
private NodePosition CompareTextLikeNodes(XmlDiffCharacterData t1, XmlDiffCharacterData t2)
{
Debug.Assert(t1 != null);
Debug.Assert(t2 != null);
int nCompare = CompareText(t2.Value, t1.Value);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
//returns 0 if the same string; 1 if s1 > s1 and -1 if s1 < s2
private int CompareText(string s1, string s2) => Math.Sign(string.Compare(s1, s2, StringComparison.Ordinal));
public virtual void Load(string xmlFileName)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
if (IgnoreDTD)
{
readerSettings.ValidationType = ValidationType.None;
}
else
{
readerSettings.ValidationType = ValidationType.DTD;
}
using (XmlReader reader = XmlReader.Create(xmlFileName))
{
Load(reader);
reader.Close();
}
}
public virtual void Load(XmlReader reader)
{
if (_bLoaded)
throw new InvalidOperationException("The document already contains data and should not be used again.");
if (reader.ReadState == ReadState.Initial)
{
if (!reader.Read())
{
return;
}
}
PositionInfo pInfo = PositionInfo.GetPositionInfo(reader);
ReadChildNodes(this, reader, pInfo);
_bLoaded = true;
nameTable = reader.NameTable;
}
internal void ReadChildNodes(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
bool lookAhead = false;
do
{
lookAhead = false;
switch (reader.NodeType)
{
case XmlNodeType.Element:
LoadElement(parent, reader, pInfo);
break;
case XmlNodeType.Comment:
if (!IgnoreComments)
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Comment);
break;
case XmlNodeType.ProcessingInstruction:
LoadPI(parent, reader, pInfo);
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if (!IgnoreWhitespace)
{
if (WhitespaceAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Text);
}
else
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.WS);
}
}
break;
case XmlNodeType.CDATA:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.CData);
}
else //merge with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.Text:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, TextNodeIsWhitespace(reader.Value) ? XmlDiffNodeType.WS : XmlDiffNodeType.Text);
}
else //merge with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
string txt = text.ToString();
LoadTextNode(parent, txt, pInfo, TextNodeIsWhitespace(txt) ? XmlDiffNodeType.WS : XmlDiffNodeType.Text);
}
break;
case XmlNodeType.EntityReference:
LoadEntityReference(parent, reader, pInfo);
break;
case XmlNodeType.EndElement:
SetElementEndPosition(parent as XmlDiffElement, pInfo);
return;
case XmlNodeType.Attribute: //attribute at top level
string attrVal = reader.Name + "=\"" + reader.Value + "\"";
LoadTopLevelAttribute(parent, attrVal, pInfo, XmlDiffNodeType.Text);
break;
default:
break;
}
} while (lookAhead || reader.Read());
}
private bool TextNodeIsWhitespace(string p)
{
if (!TreatWhitespaceTextAsWSNode)
{
return false;
}
for (int i = 0; i < p.Length; i++)
{
if (!char.IsWhiteSpace(p[i]))
{
return false;
}
}
return true;
}
private void LoadElement(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffElement elem = null;
bool bEmptyElement = reader.IsEmptyElement;
if (bEmptyElement)
elem = new XmlDiffEmptyElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
else
elem = new XmlDiffElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
elem.LineNumber = pInfo.LineNumber;
elem.LinePosition = pInfo.LinePosition;
ReadAttributes(elem, reader, pInfo);
if (!bEmptyElement)
{
// bool rtn = reader.Read();
// rtn = reader.Read();
reader.Read(); //move to child
ReadChildNodes(elem, reader, pInfo);
}
InsertChild(parent, elem);
}
private void ReadAttributes(XmlDiffElement parent, XmlReader reader, PositionInfo pInfo)
{
if (reader.MoveToFirstAttribute())
{
do
{
XmlDiffAttribute attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.SetValueAsQName(reader, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
}
while (reader.MoveToNextAttribute());
}
}
private void LoadTextNode(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo, XmlDiffNodeType nt)
{
LoadTextNode(parent, reader.Value, pInfo, nt);
}
private void LoadTextNode(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
if (!IgnoreEmptyTextNodes || !string.IsNullOrEmpty(text))
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, NormalizeNewline)
{
LineNumber = pInfo.LineNumber,
LinePosition = pInfo.LinePosition
};
InsertChild(parent, textNode);
}
}
private void LoadTopLevelAttribute(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, NormalizeNewline)
{
LineNumber = pInfo.LineNumber,
LinePosition = pInfo.LinePosition
};
InsertTopLevelAttributeAsText(parent, textNode);
}
private void LoadPI(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffProcessingInstruction pi = new XmlDiffProcessingInstruction(reader.Name, reader.Value)
{
LineNumber = pInfo.LineNumber,
LinePosition = pInfo.LinePosition
};
InsertChild(parent, pi);
}
private void LoadEntityReference(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffEntityReference er = new XmlDiffEntityReference(reader.Name)
{
LineNumber = pInfo.LineNumber,
LinePosition = pInfo.LinePosition
};
InsertChild(parent, er);
}
private void SetElementEndPosition(XmlDiffElement elem, PositionInfo pInfo)
{
Debug.Assert(elem != null);
elem.EndLineNumber = pInfo.LineNumber;
elem.EndLinePosition = pInfo.LinePosition;
}
private void InsertChild(XmlDiffNode parent, XmlDiffNode newChild)
{
if (IgnoreChildOrder)
{
XmlDiffNode child = parent.FirstChild;
XmlDiffNode prevChild = null;
while (child != null && (ComparePosition(child, newChild) == NodePosition.After))
{
prevChild = child;
child = child.NextSibling;
}
parent.InsertChildAfter(prevChild, newChild);
}
else
parent.InsertChildAfter(parent.LastChild, newChild);
}
private void InsertTopLevelAttributeAsText(XmlDiffNode parent, XmlDiffCharacterData newChild)
{
if (parent.LastChild != null && (parent.LastChild.NodeType == XmlDiffNodeType.Text || parent.LastChild.NodeType == XmlDiffNodeType.WS))
{
((XmlDiffCharacterData)parent.LastChild).Value = ((XmlDiffCharacterData)parent.LastChild).Value + " " + newChild.Value;
}
else
{
parent.InsertChildAfter(parent.LastChild, newChild);
}
}
private void InsertAttribute(XmlDiffElement parent, XmlDiffAttribute newAttr)
{
Debug.Assert(parent != null);
Debug.Assert(newAttr != null);
newAttr._parent = parent;
if (IgnoreAttributeOrder)
{
XmlDiffAttribute attr = parent.FirstAttribute;
XmlDiffAttribute prevAttr = null;
while (attr != null && (CompareAttributes(attr, newAttr) == NodePosition.After))
{
prevAttr = attr;
attr = (XmlDiffAttribute)(attr.NextSibling);
}
parent.InsertAttributeAfter(prevAttr, newAttr);
}
else
parent.InsertAttributeAfter(parent.LastAttribute, newAttr);
}
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
//IXPathNavigable override
public XPathNavigator CreateNavigator() => new XmlDiffNavigator(this);
public void SortChildren(XPathExpression expr)
{
if (expr == null)
{
return;
}
XPathNavigator _nav = CreateNavigator();
XPathNodeIterator _iter = _nav.Select(expr);
while (_iter.MoveNext())
{
if (((XmlDiffNavigator)_iter.Current).CurrentNode is XmlDiffElement)
{
SortChildren((XmlDiffElement)((XmlDiffNavigator)_iter.Current).CurrentNode);
}
}
}
public void IgnoreNodes(XPathExpression expr)
{
if (expr == null)
{
return;
}
XPathNavigator _nav = CreateNavigator();
XPathNodeIterator _iter = _nav.Select(expr);
while (_iter.MoveNext())
{
if (((XmlDiffNavigator)_iter.Current).CurrentNode is XmlDiffAttribute)
{
((XmlDiffElement)((XmlDiffNavigator)_iter.Current).CurrentNode.ParentNode).DeleteAttribute((XmlDiffAttribute)((XmlDiffNavigator)_iter.Current).CurrentNode);
}
else
{
((XmlDiffNavigator)_iter.Current).CurrentNode.ParentNode.DeleteChild(((XmlDiffNavigator)_iter.Current).CurrentNode);
}
}
}
public void IgnoreValues(XPathExpression expr)
{
if (expr == null)
{
return;
}
XPathNavigator _nav = CreateNavigator();
XPathNodeIterator _iter = _nav.Select(expr);
while (_iter.MoveNext())
{
((XmlDiffNavigator)_iter.Current).CurrentNode.IgnoreValue = true; ;
}
}
private void SortChildren(XmlDiffElement elem)
{
if (elem.FirstChild != null)
{
XmlDiffNode _first = elem.FirstChild;
XmlDiffNode _current = elem.FirstChild;
XmlDiffNode _last = elem.LastChild;
elem._firstChild = null;
elem._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(elem, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
}
//navgator over the xmldiffdocument
public class XmlDiffNavigator : XPathNavigator
{
private XmlDiffDocument _document;
public XmlDiffNavigator(XmlDiffDocument doc)
{
_document = doc;
CurrentNode = _document;
}
public override XPathNavigator Clone()
{
XmlDiffNavigator _clone = new XmlDiffNavigator(_document);
if (!_clone.MoveTo(this))
throw new Exception("Cannot clone");
return _clone;
}
public override XmlNodeOrder ComparePosition(XPathNavigator nav)
{
XmlDiffNode targetNode = ((XmlDiffNavigator)nav).CurrentNode;
if (!(nav is XmlDiffNavigator))
{
return XmlNodeOrder.Unknown;
}
if (targetNode == CurrentNode)
{
return XmlNodeOrder.Same;
}
else
{
if (CurrentNode.ParentNode == null) //this is root
{
return XmlNodeOrder.After;
}
else if (targetNode.ParentNode == null) //this is root
{
return XmlNodeOrder.Before;
}
else //look in the following nodes
{
if (targetNode.LineNumber + targetNode.LinePosition > CurrentNode.LinePosition + CurrentNode.LineNumber)
{
return XmlNodeOrder.After;
}
return XmlNodeOrder.Before;
}
}
}
public override string GetAttribute(string localName, string namespaceURI)
{
if (CurrentNode is XmlDiffElement)
{
return ((XmlDiffElement)CurrentNode).GetAttributeValue(localName, namespaceURI);
}
return "";
}
public override string GetNamespace(string name)
{
Debug.Assert(false, "GetNamespace is NYI");
return "";
}
public override bool IsSamePosition(XPathNavigator other)
{
if (other is XmlDiffNavigator)
{
if (CurrentNode == ((XmlDiffNavigator)other).CurrentNode)
return true;
}
return false;
}
public override bool MoveTo(XPathNavigator other)
{
if (other is XmlDiffNavigator)
{
CurrentNode = ((XmlDiffNavigator)other).CurrentNode;
return true;
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceURI)
{
if (CurrentNode is XmlDiffElement)
{
XmlDiffAttribute _attr = ((XmlDiffElement)CurrentNode).GetAttribute(localName, namespaceURI);
if (_attr != null)
{
CurrentNode = _attr;
return true;
}
}
return false;
}
public override bool MoveToFirst()
{
if (!(CurrentNode is XmlDiffAttribute))
{
if (CurrentNode.ParentNode.FirstChild == CurrentNode)
{
if (CurrentNode.ParentNode.FirstChild._next != null)
{
CurrentNode = CurrentNode.ParentNode.FirstChild._next;
return true;
}
}
else
{
CurrentNode = CurrentNode.ParentNode.FirstChild;
return true;
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
if (CurrentNode is XmlDiffElement)
{
if (((XmlDiffElement)CurrentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)CurrentNode).FirstAttribute;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
CurrentNode = _attr;
return true;
}
}
}
return false;
}
public override bool MoveToFirstChild()
{
if ((CurrentNode is XmlDiffDocument || CurrentNode is XmlDiffElement) && CurrentNode.FirstChild != null)
{
CurrentNode = CurrentNode.FirstChild;
return true;
}
return false;
}
public new bool MoveToFirstNamespace()
{
if (CurrentNode is XmlDiffElement)
{
if (((XmlDiffElement)CurrentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)CurrentNode).FirstAttribute;
while (_attr != null && !IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
CurrentNode = _attr;
return true;
}
}
}
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope)
{
return MoveToFirstNamespace();
}
public override bool MoveToId(string id)
{
Debug.Assert(false, "MoveToId is NYI");
return false;
}
public override bool MoveToNamespace(string name)
{
Debug.Assert(false, "MoveToNamespace is NYI");
return false;
}
public override bool MoveToNext()
{
if (!(CurrentNode is XmlDiffAttribute) && CurrentNode._next != null)
{
CurrentNode = CurrentNode._next;
return true;
}
return false;
}
public override bool MoveToNextAttribute()
{
if (CurrentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)CurrentNode._next;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
CurrentNode = _attr;
return true;
}
}
return false;
}
public new bool MoveToNextNamespace()
{
if (CurrentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)CurrentNode._next;
while (_attr != null && !IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
CurrentNode = _attr;
return true;
}
}
return false;
}
private bool IsNamespaceNode(XmlDiffAttribute attr)
{
return attr.LocalName.ToLower(CultureInfo.InvariantCulture) == "xmlns" ||
attr.Prefix.ToLower(CultureInfo.InvariantCulture) == "xmlns";
}
public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope)
{
return MoveToNextNamespace();
}
public override bool MoveToParent()
{
if (!(CurrentNode is XmlDiffDocument))
{
CurrentNode = CurrentNode.ParentNode;
return true;
}
return false;
}
public override bool MoveToPrevious()
{
if (CurrentNode != CurrentNode.ParentNode.FirstChild)
{
XmlDiffNode _current = CurrentNode.ParentNode.FirstChild;
XmlDiffNode _prev = CurrentNode.ParentNode.FirstChild;
while (_current != CurrentNode)
{
_prev = _current;
_current = _current._next;
}
CurrentNode = _prev;
return true;
}
return false;
}
public override void MoveToRoot() => CurrentNode = _document;
public override XPathNodeType NodeType
{
get
{
//namespace, comment and whitespace node types are not supported
switch (CurrentNode.NodeType)
{
case XmlDiffNodeType.Element:
return XPathNodeType.Element;
case XmlDiffNodeType.Attribute:
return XPathNodeType.Attribute;
case XmlDiffNodeType.ER:
return XPathNodeType.Text;
case XmlDiffNodeType.Text:
return XPathNodeType.Text;
case XmlDiffNodeType.CData:
return XPathNodeType.Text;
case XmlDiffNodeType.Comment:
return XPathNodeType.Comment;
case XmlDiffNodeType.PI:
return XPathNodeType.ProcessingInstruction;
case XmlDiffNodeType.WS:
return XPathNodeType.SignificantWhitespace;
case XmlDiffNodeType.Document:
return XPathNodeType.Root;
default:
return XPathNodeType.All;
}
}
}
public override string LocalName
{
get
{
if (CurrentNode.NodeType == XmlDiffNodeType.Element)
{
return ((XmlDiffElement)CurrentNode).LocalName;
}
else if (CurrentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)CurrentNode).LocalName;
}
else if (CurrentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)CurrentNode).Name;
}
return "";
}
}
public override string Name
{
get
{
if (CurrentNode.NodeType == XmlDiffNodeType.Element)
{
return _document.nameTable.Get(((XmlDiffElement)CurrentNode).Name);
}
else if (CurrentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)CurrentNode).Name;
}
else if (CurrentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)CurrentNode).Name;
}
return "";
}
}
public override string NamespaceURI
{
get
{
if (CurrentNode is XmlDiffElement)
{
return ((XmlDiffElement)CurrentNode).NamespaceURI;
}
else if (CurrentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)CurrentNode).NamespaceURI;
}
return "";
}
}
public override string Value
{
get
{
if (CurrentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)CurrentNode).Value;
}
else if (CurrentNode is XmlDiffCharacterData)
{
return ((XmlDiffCharacterData)CurrentNode).Value;
}
else if (CurrentNode is XmlDiffElement)
{
return ((XmlDiffElement)CurrentNode).Value;
}
return "";
}
}
public override string Prefix
{
get
{
if (CurrentNode is XmlDiffElement)
{
return ((XmlDiffElement)CurrentNode).Prefix;
}
else if (CurrentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)CurrentNode).Prefix;
}
return "";
}
}
public override string BaseURI
{
get
{
Debug.Assert(false, "BaseURI is NYI");
return "";
}
}
public override string XmlLang
{
get
{
Debug.Assert(false, "XmlLang not supported");
return "";
}
}
public override bool HasAttributes
{
get => (CurrentNode is XmlDiffElement && ((XmlDiffElement)CurrentNode).FirstAttribute != null) ? true : false;
}
public override bool HasChildren => CurrentNode._next != null ? true : false;
public override bool IsEmptyElement => CurrentNode is XmlDiffEmptyElement ? true : false;
public override XmlNameTable NameTable => _document.nameTable;
public XmlDiffNode CurrentNode { get; private set; }
public bool IsOnRoot() => CurrentNode == null ? true : false;
}
public class PropertyCollection : Hashtable { }
public abstract class XmlDiffNode
{
internal XmlDiffNode _next;
internal XmlDiffNode _firstChild;
internal XmlDiffNode _lastChild;
internal XmlDiffNode _parent;
internal int _lineNumber, _linePosition;
internal bool _bIgnoreValue;
private PropertyCollection _extendedProperties;
public XmlDiffNode()
{
_next = null;
_firstChild = null;
_lastChild = null;
_parent = null;
_lineNumber = 0;
_linePosition = 0;
}
public XmlDiffNode FirstChild => _firstChild;
public XmlDiffNode LastChild => _lastChild;
public XmlDiffNode NextSibling => _next;
public XmlDiffNode ParentNode => _parent;
public virtual bool IgnoreValue
{
get => _bIgnoreValue;
set
{
_bIgnoreValue = value;
XmlDiffNode current = _firstChild;
while (current != null)
{
current.IgnoreValue = value;
current = current._next;
}
}
}
public abstract XmlDiffNodeType NodeType { get; }
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
WriteTo(xw);
xw.Close();
return sw.ToString();
}
}
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
WriteContentTo(xw);
xw.Close();
return sw.ToString();
}
}
public abstract void WriteTo(XmlWriter w);
public abstract void WriteContentTo(XmlWriter w);
public PropertyCollection ExtendedProperties
{
get => _extendedProperties ?? (_extendedProperties = new PropertyCollection());
}
public virtual void InsertChildAfter(XmlDiffNode child, XmlDiffNode newChild)
{
Debug.Assert(newChild != null);
newChild._parent = this;
if (child == null)
{
newChild._next = _firstChild;
_firstChild = newChild;
}
else
{
Debug.Assert(child._parent == this);
newChild._next = child._next;
child._next = newChild;
}
if (newChild._next == null)
_lastChild = newChild;
}
public virtual void DeleteChild(XmlDiffNode child)
{
if (child == FirstChild)//delete head
{
_firstChild = FirstChild.NextSibling;
}
else
{
XmlDiffNode current = FirstChild;
XmlDiffNode previous = null;
while (current != child)
{
previous = current;
current = current.NextSibling;
}
Debug.Assert(current != null);
if (current == LastChild) //tail being deleted
{
_lastChild = current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int LineNumber
{
get => _lineNumber;
set => _lineNumber = value;
}
public int LinePosition
{
get => _linePosition;
set => _linePosition = value;
}
}
public class XmlDiffElement : XmlDiffNode
{
private int _attrC;
public XmlDiffElement(string localName, string prefix, string ns)
: base()
{
LocalName = localName;
Prefix = prefix;
NamespaceURI = ns;
FirstAttribute = null;
LastAttribute = null;
_attrC = -1;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Element; } }
public string LocalName { get; }
public string NamespaceURI { get; }
public string Prefix { get; }
public string Name
{
get
{
if (Prefix.Length > 0)
return Prefix + ":" + LocalName;
else
return LocalName;
}
}
public XmlDiffAttribute FirstAttribute { get; private set; }
public XmlDiffAttribute LastAttribute { get; private set; }
public string GetAttributeValue(string LocalName, string NamespaceUri)
{
if (FirstAttribute != null)
{
XmlDiffAttribute _current = FirstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current.Value;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != LastAttribute);
}
return "";
}
public XmlDiffAttribute GetAttribute(string LocalName, string NamespaceUri)
{
if (FirstAttribute != null)
{
XmlDiffAttribute _current = FirstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != LastAttribute);
}
return null;
}
internal void InsertAttributeAfter(XmlDiffAttribute attr, XmlDiffAttribute newAttr)
{
Debug.Assert(newAttr != null);
newAttr._ownerElement = this;
if (attr == null)
{
newAttr._next = FirstAttribute;
FirstAttribute = newAttr;
}
else
{
Debug.Assert(attr._ownerElement == this);
newAttr._next = attr._next;
attr._next = newAttr;
}
if (newAttr._next == null)
LastAttribute = newAttr;
}
internal void DeleteAttribute(XmlDiffAttribute attr)
{
if (attr == FirstAttribute)//delete head
{
if (attr == LastAttribute) //tail being deleted
{
LastAttribute = (XmlDiffAttribute)attr.NextSibling;
}
FirstAttribute = (XmlDiffAttribute)FirstAttribute.NextSibling;
}
else
{
XmlDiffAttribute current = FirstAttribute;
XmlDiffAttribute previous = null;
while (current != attr)
{
previous = current;
current = (XmlDiffAttribute)current.NextSibling;
}
Debug.Assert(current != null);
if (current == LastAttribute) //tail being deleted
{
LastAttribute = (XmlDiffAttribute)current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int AttributeCount
{
get
{
if (_attrC != -1)
return _attrC;
XmlDiffAttribute attr = FirstAttribute;
_attrC = 0;
while (attr != null)
{
_attrC++;
attr = (XmlDiffAttribute)attr.NextSibling;
}
return _attrC;
}
}
public override bool IgnoreValue
{
set
{
base.IgnoreValue = value;
XmlDiffAttribute current = FirstAttribute;
while (current != null)
{
current.IgnoreValue = value;
current = (XmlDiffAttribute)current._next;
}
}
}
public int EndLineNumber { get; set; }
public int EndLinePosition { get; set; }
public override void WriteTo(XmlWriter w)
{
w.WriteStartElement(Prefix, LocalName, NamespaceURI);
XmlDiffAttribute attr = FirstAttribute;
while (attr != null)
{
attr.WriteTo(w);
attr = (XmlDiffAttribute)(attr.NextSibling);
}
WriteContentTo(w);
w.WriteFullEndElement();
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public string Value
{
get
{
if (IgnoreValue)
{
return "";
}
if (_firstChild != null)
{
StringBuilder _bldr = new StringBuilder();
XmlDiffNode _current = _firstChild;
do
{
if (_current is XmlDiffCharacterData && _current.NodeType != XmlDiffNodeType.Comment && _current.NodeType != XmlDiffNodeType.PI)
{
_bldr.Append(((XmlDiffCharacterData)_current).Value);
}
else if (_current is XmlDiffElement)
{
_bldr.Append(((XmlDiffElement)_current).Value);
}
_current = _current._next;
}
while (_current != null);
return _bldr.ToString();
}
return "";
}
}
}
public class XmlDiffEmptyElement : XmlDiffElement
{
public XmlDiffEmptyElement(string localName, string prefix, string ns) : base(localName, prefix, ns) { }
}
public class XmlDiffAttribute : XmlDiffNode
{
internal XmlDiffElement _ownerElement;
private readonly string _value;
public XmlDiffAttribute(string localName, string prefix, string ns, string value) : base()
{
LocalName = localName;
Prefix = prefix;
NamespaceURI = ns;
_value = value;
}
public string Value => IgnoreValue ? "" : _value;
public XmlQualifiedName ValueAsQName { get; private set; }
internal void SetValueAsQName(XmlReader reader, string value)
{
int indexOfColon = value.IndexOf(':');
if (indexOfColon == -1)
{
ValueAsQName = new XmlQualifiedName(value);
}
else
{
string prefix = value.Substring(0, indexOfColon);
string ns = reader.LookupNamespace(prefix);
if (ns == null)
{
ValueAsQName = null;
}
else
{
try
{
string localName = XmlConvert.VerifyNCName(value.Substring(indexOfColon + 1));
ValueAsQName = new XmlQualifiedName(localName, ns);
}
catch (XmlException)
{
ValueAsQName = null;
}
}
}
}
public string LocalName { get; }
public string NamespaceURI { get; }
public string Prefix { get; }
public string Name
{
get
{
if (Prefix.Length > 0)
return Prefix + ":" + LocalName;
else
return LocalName;
}
}
public override XmlDiffNodeType NodeType => XmlDiffNodeType.Attribute;
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
public override void WriteContentTo(XmlWriter w) => w.WriteString(Value);
}
public class XmlDiffEntityReference : XmlDiffNode
{
public XmlDiffEntityReference(string name) : base()
{
Name = name;
}
public override XmlDiffNodeType NodeType => XmlDiffNodeType.ER;
public string Name { get; }
public override void WriteTo(XmlWriter w) => w.WriteEntityRef(Name);
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
}
public class XmlDiffCharacterData : XmlDiffNode
{
private string _value;
private XmlDiffNodeType _nodetype;
public XmlDiffCharacterData(string value, XmlDiffNodeType nt, bool NormalizeNewline) : base()
{
_value = value;
if (NormalizeNewline)
{
_value = _value.Replace("\n", "");
_value = _value.Replace("\r", "");
}
_nodetype = nt;
}
public string Value
{
get => IgnoreValue ? "" : _value;
set => _value = value;
}
public override XmlDiffNodeType NodeType => _nodetype;
public override void WriteTo(XmlWriter w)
{
switch (_nodetype)
{
case XmlDiffNodeType.Comment:
w.WriteComment(Value);
break;
case XmlDiffNodeType.CData:
w.WriteCData(Value);
break;
case XmlDiffNodeType.WS:
case XmlDiffNodeType.Text:
w.WriteString(Value);
break;
default:
Debug.Assert(false, "Wrong type for text-like node : " + _nodetype.ToString());
break;
}
}
public override void WriteContentTo(XmlWriter w) { }
}
public class XmlDiffProcessingInstruction : XmlDiffCharacterData
{
public XmlDiffProcessingInstruction(string name, string value) : base(value, XmlDiffNodeType.PI, false)
{
Name = name;
}
public string Name { get; }
public override void WriteTo(XmlWriter w) => w.WriteProcessingInstruction(Name, Value);
public override void WriteContentTo(XmlWriter w) { }
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.FirebaseML.v1beta2
{
/// <summary>The FirebaseML Service.</summary>
public class FirebaseMLService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta2";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public FirebaseMLService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public FirebaseMLService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "firebaseml";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://firebaseml.googleapis.com/";
#else
"https://firebaseml.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://firebaseml.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Firebase ML API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Firebase ML API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for FirebaseML requests.</summary>
public abstract class FirebaseMLBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new FirebaseMLBaseServiceRequest instance.</summary>
protected FirebaseMLBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes FirebaseML parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Models = new ModelsResource(service);
Operations = new OperationsResource(service);
}
/// <summary>Gets the Models resource.</summary>
public virtual ModelsResource Models { get; }
/// <summary>The "models" collection of methods.</summary>
public class ModelsResource
{
private const string Resource = "models";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ModelsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Creates a model in Firebase ML. The longrunning operation will eventually return a Model
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent project resource where the model is to be created. The parent must have the form
/// `projects/{project_id}`
/// </param>
public virtual CreateRequest Create(Google.Apis.FirebaseML.v1beta2.Data.Model body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Creates a model in Firebase ML. The longrunning operation will eventually return a Model
/// </summary>
public class CreateRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseML.v1beta2.Data.Model body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent project resource where the model is to be created. The parent must have the
/// form `projects/{project_id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseML.v1beta2.Data.Model Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+parent}/models";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Deletes a model</summary>
/// <param name="name">
/// Required. The name of the model to delete. The name must have the form
/// `projects/{project_id}/models/{model_id}`
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a model</summary>
public class DeleteRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the model to delete. The name must have the form
/// `projects/{project_id}/models/{model_id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/models/[^/]+$",
});
}
}
/// <summary>
/// Gets Download information for a model. This is meant for downloading model resources onto devices. It
/// gives very limited information about the model.
/// </summary>
/// <param name="name">
/// Required. The name of the model to download. The name must have the form
/// `projects/{project}/models/{model}`
/// </param>
public virtual DownloadRequest Download(string name)
{
return new DownloadRequest(service, name);
}
/// <summary>
/// Gets Download information for a model. This is meant for downloading model resources onto devices. It
/// gives very limited information about the model.
/// </summary>
public class DownloadRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.DownloadModelResponse>
{
/// <summary>Constructs a new Download request.</summary>
public DownloadRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the model to download. The name must have the form
/// `projects/{project}/models/{model}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "download";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+name}:download";
/// <summary>Initializes Download parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/models/[^/]+$",
});
}
}
/// <summary>Gets a model resource.</summary>
/// <param name="name">
/// Required. The name of the model to get. The name must have the form
/// `projects/{project_id}/models/{model_id}`
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a model resource.</summary>
public class GetRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.Model>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the model to get. The name must have the form
/// `projects/{project_id}/models/{model_id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/models/[^/]+$",
});
}
}
/// <summary>Lists the models</summary>
/// <param name="parent">
/// Required. The name of the parent to list models for. The parent must have the form
/// `projects/{project_id}'
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists the models</summary>
public class ListRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.ListModelsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The name of the parent to list models for. The parent must have the form
/// `projects/{project_id}'
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>A filter for the list e.g. 'tags: abc' to list models which are tagged with "abc"</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The maximum number of items to return</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The next_page_token value returned from a previous List request, if any.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+parent}/models";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates a model. The longrunning operation will eventually return a Model.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the Model. Model names have the form `projects/{project_id}/models/{model_id}` The
/// name is ignored when creating a model.
/// </param>
public virtual PatchRequest Patch(Google.Apis.FirebaseML.v1beta2.Data.Model body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates a model. The longrunning operation will eventually return a Model.</summary>
public class PatchRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseML.v1beta2.Data.Model body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the Model. Model names have the form `projects/{project_id}/models/{model_id}`
/// The name is ignored when creating a model.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The update mask</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseML.v1beta2.Data.Model Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/models/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
public class GetRequest : FirebaseMLBaseServiceRequest<Google.Apis.FirebaseML.v1beta2.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta2/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/operations/[^/]+$",
});
}
}
}
}
}
namespace Google.Apis.FirebaseML.v1beta2.Data
{
/// <summary>The response for downloading a model to device.</summary>
public class DownloadModelResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. A download URI for the model/zip file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("downloadUri")]
public virtual string DownloadUri { get; set; }
/// <summary>
/// Output only. The time that the download URI link expires. If the link has expired, the REST call must be
/// repeated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("expireTime")]
public virtual object ExpireTime { get; set; }
/// <summary>Output only. The format of the model being downloaded.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("modelFormat")]
public virtual string ModelFormat { get; set; }
/// <summary>Output only. The size of the file(s), if this information is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sizeBytes")]
public virtual System.Nullable<long> SizeBytes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response for list models</summary>
public class ListModelsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of models</summary>
[Newtonsoft.Json.JsonPropertyAttribute("models")]
public virtual System.Collections.Generic.IList<Model> Models { get; set; }
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An ML model hosted in Firebase ML</summary>
public class Model : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Lists operation ids associated with this model whose status is NOT done.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("activeOperations")]
public virtual System.Collections.Generic.IList<Operation> ActiveOperations { get; set; }
/// <summary>Output only. Timestamp when this model was created in Firebase ML.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Required. The name of the model to create. The name can be up to 32 characters long and can consist only of
/// ASCII Latin letters A-Z and a-z, underscores(_) and ASCII digits 0-9. It must start with a letter.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Output only. See RFC7232 https://tools.ietf.org/html/rfc7232#section-2.3</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Output only. The model_hash will change if a new file is available for download.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("modelHash")]
public virtual string ModelHash { get; set; }
/// <summary>
/// The resource name of the Model. Model names have the form `projects/{project_id}/models/{model_id}` The name
/// is ignored when creating a model.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>State common to all model types. Includes publishing and validation information.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual ModelState State { get; set; }
/// <summary>User defined tags which can be used to group/filter models during listing</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tags")]
public virtual System.Collections.Generic.IList<string> Tags { get; set; }
/// <summary>A TFLite Model</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tfliteModel")]
public virtual TfLiteModel TfliteModel { get; set; }
/// <summary>Output only. Timestamp when this model was updated in Firebase ML.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
}
/// <summary>This is returned in the longrunning operations for create/update.</summary>
public class ModelOperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("basicOperationStatus")]
public virtual string BasicOperationStatus { get; set; }
/// <summary>
/// The name of the model we are creating/updating The name must have the form
/// `projects/{project_id}/models/{model_id}`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State common to all model types. Includes publishing and validation information.</summary>
public class ModelState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Indicates if this model has been published.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("published")]
public virtual System.Nullable<bool> Published { get; set; }
/// <summary>
/// Output only. Indicates the latest validation error on the model if any. A model may have validation errors
/// if there were problems during the model creation/update. e.g. in the case of a TfLiteModel, if a tflite
/// model file was missing or in the wrong format. This field will be empty for valid models.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("validationError")]
public virtual Status ValidationError { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Information that is specific to TfLite models.</summary>
public class TfLiteModel : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The AutoML model id referencing a model you created with the AutoML API. The name should have format
/// 'projects//locations//models/' (This is the model resource name returned from the AutoML API)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("automlModel")]
public virtual string AutomlModel { get; set; }
/// <summary>
/// The TfLite file containing the model. (Stored in Google Cloud). The gcs_tflite_uri should have form:
/// gs://some-bucket/some-model.tflite Note: If you update the file in the original location, it is necessary to
/// call UpdateModel for ML to pick up and validate the updated file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsTfliteUri")]
public virtual string GcsTfliteUri { get; set; }
/// <summary>Output only. The size of the TFLite model</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sizeBytes")]
public virtual string SizeBytes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
internal class CLRIPropertyValueImpl : IPropertyValue
{
private PropertyType _type;
private Object _data;
// Numeric scalar types which participate in coersion
private static volatile Tuple<Type, PropertyType>[] s_numericScalarTypes;
internal CLRIPropertyValueImpl(PropertyType type, Object data)
{
_type = type;
_data = data;
}
private static Tuple<Type, PropertyType>[] NumericScalarTypes {
get {
if (s_numericScalarTypes == null) {
Tuple<Type, PropertyType>[] numericScalarTypes = new Tuple<Type, PropertyType>[] {
new Tuple<Type, PropertyType>(typeof(Byte), PropertyType.UInt8),
new Tuple<Type, PropertyType>(typeof(Int16), PropertyType.Int16),
new Tuple<Type, PropertyType>(typeof(UInt16), PropertyType.UInt16),
new Tuple<Type, PropertyType>(typeof(Int32), PropertyType.Int32),
new Tuple<Type, PropertyType>(typeof(UInt32), PropertyType.UInt32),
new Tuple<Type, PropertyType>(typeof(Int64), PropertyType.Int64),
new Tuple<Type, PropertyType>(typeof(UInt64), PropertyType.UInt64),
new Tuple<Type, PropertyType>(typeof(Single), PropertyType.Single),
new Tuple<Type, PropertyType>(typeof(Double), PropertyType.Double)
};
s_numericScalarTypes = numericScalarTypes;
}
return s_numericScalarTypes;
}
}
public PropertyType Type {
[Pure]
get { return _type; }
}
public bool IsNumericScalar {
[Pure]
get {
return IsNumericScalarImpl(_type, _data);
}
}
public override string ToString()
{
if (_data != null)
{
return _data.ToString();
}
else
{
return base.ToString();
}
}
[Pure]
public Byte GetUInt8()
{
return CoerceScalarValue<Byte>(PropertyType.UInt8);
}
[Pure]
public Int16 GetInt16()
{
return CoerceScalarValue<Int16>(PropertyType.Int16);
}
public UInt16 GetUInt16()
{
return CoerceScalarValue<UInt16>(PropertyType.UInt16);
}
[Pure]
public Int32 GetInt32()
{
return CoerceScalarValue<Int32>(PropertyType.Int32);
}
[Pure]
public UInt32 GetUInt32()
{
return CoerceScalarValue<UInt32>(PropertyType.UInt32);
}
[Pure]
public Int64 GetInt64()
{
return CoerceScalarValue<Int64>(PropertyType.Int64);
}
[Pure]
public UInt64 GetUInt64()
{
return CoerceScalarValue<UInt64>(PropertyType.UInt64);
}
[Pure]
public Single GetSingle()
{
return CoerceScalarValue<Single>(PropertyType.Single);
}
[Pure]
public Double GetDouble()
{
return CoerceScalarValue<Double>(PropertyType.Double);
}
[Pure]
public char GetChar16()
{
if (this.Type != PropertyType.Char16)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char)_data;
}
[Pure]
public Boolean GetBoolean()
{
if (this.Type != PropertyType.Boolean)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool)_data;
}
[Pure]
public String GetString()
{
return CoerceScalarValue<String>(PropertyType.String);
}
[Pure]
public Object GetInspectable()
{
if (this.Type != PropertyType.Inspectable)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return _data;
}
[Pure]
public Guid GetGuid()
{
return CoerceScalarValue<Guid>(PropertyType.Guid);
}
[Pure]
public DateTimeOffset GetDateTime()
{
if (this.Type != PropertyType.DateTime)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset)_data;
}
[Pure]
public TimeSpan GetTimeSpan()
{
if (this.Type != PropertyType.TimeSpan)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan)_data;
}
[Pure]
[SecuritySafeCritical]
public Point GetPoint()
{
if (this.Type != PropertyType.Point)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Point>(IReferenceFactory.s_pointType);
}
[Pure]
[SecuritySafeCritical]
public Size GetSize()
{
if (this.Type != PropertyType.Size)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Size>(IReferenceFactory.s_sizeType);
}
[Pure]
[SecuritySafeCritical]
public Rect GetRect()
{
if (this.Type != PropertyType.Rect)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Rect>(IReferenceFactory.s_rectType);
}
[Pure]
public Byte[] GetUInt8Array()
{
return CoerceArrayValue<Byte>(PropertyType.UInt8Array);
}
[Pure]
public Int16[] GetInt16Array()
{
return CoerceArrayValue<Int16>(PropertyType.Int16Array);
}
[Pure]
public UInt16[] GetUInt16Array()
{
return CoerceArrayValue<UInt16>(PropertyType.UInt16Array);
}
[Pure]
public Int32[] GetInt32Array()
{
return CoerceArrayValue<Int32>(PropertyType.Int32Array);
}
[Pure]
public UInt32[] GetUInt32Array()
{
return CoerceArrayValue<UInt32>(PropertyType.UInt32Array);
}
[Pure]
public Int64[] GetInt64Array()
{
return CoerceArrayValue<Int64>(PropertyType.Int64Array);
}
[Pure]
public UInt64[] GetUInt64Array()
{
return CoerceArrayValue<UInt64>(PropertyType.UInt64Array);
}
[Pure]
public Single[] GetSingleArray()
{
return CoerceArrayValue<Single>(PropertyType.SingleArray);
}
[Pure]
public Double[] GetDoubleArray()
{
return CoerceArrayValue<Double>(PropertyType.DoubleArray);
}
[Pure]
public char[] GetChar16Array()
{
if (this.Type != PropertyType.Char16Array)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char[])_data;
}
[Pure]
public Boolean[] GetBooleanArray()
{
if (this.Type != PropertyType.BooleanArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool[])_data;
}
[Pure]
public String[] GetStringArray()
{
return CoerceArrayValue<String>(PropertyType.StringArray);
}
[Pure]
public Object[] GetInspectableArray()
{
if (this.Type != PropertyType.InspectableArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (Object[])_data;
}
[Pure]
public Guid[] GetGuidArray()
{
return CoerceArrayValue<Guid>(PropertyType.GuidArray);
}
[Pure]
public DateTimeOffset[] GetDateTimeArray()
{
if (this.Type != PropertyType.DateTimeArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset[])_data;
}
[Pure]
public TimeSpan[] GetTimeSpanArray()
{
if (this.Type != PropertyType.TimeSpanArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan[])_data;
}
[Pure]
[SecuritySafeCritical]
public Point[] GetPointArray()
{
if (this.Type != PropertyType.PointArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Point>(IReferenceFactory.s_pointType);
}
[Pure]
[SecuritySafeCritical]
public Size[] GetSizeArray()
{
if (this.Type != PropertyType.SizeArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Size>(IReferenceFactory.s_sizeType);
}
[Pure]
[SecuritySafeCritical]
public Rect[] GetRectArray()
{
if (this.Type != PropertyType.RectArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Rect>(IReferenceFactory.s_rectType);
}
private T[] CoerceArrayValue<T>(PropertyType unboxType) {
// If we contain the type being looked for directly, then take the fast-path
if (Type == unboxType) {
return (T[])_data;
}
// Make sure we have an array to begin with
Array dataArray = _data as Array;
if (dataArray == null) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
// Array types are 1024 larger than their equivilent scalar counterpart
BCLDebug.Assert((int)Type > 1024, "Unexpected array PropertyType value");
PropertyType scalarType = Type - 1024;
// If we do not have the correct array type, then we need to convert the array element-by-element
// to a new array of the requested type
T[] coercedArray = new T[dataArray.Length];
for (int i = 0; i < dataArray.Length; ++i) {
try {
coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i));
} catch (InvalidCastException elementCastException) {
Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
e.SetErrorCode(elementCastException._HResult);
throw e;
}
}
return coercedArray;
}
private T CoerceScalarValue<T>(PropertyType unboxType)
{
// If we are just a boxed version of the requested type, then take the fast path out
if (Type == unboxType) {
return (T)_data;
}
return CoerceScalarValue<T>(Type, _data);
}
private static T CoerceScalarValue<T>(PropertyType type, object value) {
// If the property type is neither one of the coercable numeric types nor IInspectable, we
// should not attempt coersion, even if the underlying value is technically convertable
if (!IsCoercable(type, value) && type != PropertyType.Inspectable) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
try {
// Try to coerce:
// * String <--> Guid
// * Numeric scalars
if (type == PropertyType.String && typeof(T) == typeof(Guid)) {
return (T)(object)Guid.Parse((string)value);
}
else if (type == PropertyType.Guid && typeof(T) == typeof(String)) {
return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture);
}
else {
// Iterate over the numeric scalars, to see if we have a match for one of the known conversions
foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
if (numericScalar.Item1 == typeof(T)) {
return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
}
}
catch (FormatException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
catch (InvalidCastException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
catch (OverflowException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW);
}
// If the property type is IInspectable, and we have a nested IPropertyValue, then we need
// to pass along the request to coerce the value.
IPropertyValue ipv = value as IPropertyValue;
if (type == PropertyType.Inspectable && ipv != null) {
if (typeof(T) == typeof(Byte)) {
return (T)(object)ipv.GetUInt8();
}
else if (typeof(T) == typeof(Int16)) {
return (T)(object)ipv.GetInt16();
}
else if (typeof(T) == typeof(UInt16)) {
return (T)(object)ipv.GetUInt16();
}
else if (typeof(T) == typeof(Int32)) {
return (T)(object)ipv.GetUInt32();
}
else if (typeof(T) == typeof(UInt32)) {
return (T)(object)ipv.GetUInt32();
}
else if (typeof(T) == typeof(Int64)) {
return (T)(object)ipv.GetInt64();
}
else if (typeof(T) == typeof(UInt64)) {
return (T)(object)ipv.GetUInt64();
}
else if (typeof(T) == typeof(Single)) {
return (T)(object)ipv.GetSingle();
}
else if (typeof(T) == typeof(Double)) {
return (T)(object)ipv.GetDouble();
}
else {
BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync");
}
}
// Otherwise, this is an invalid coersion
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
private static bool IsCoercable(PropertyType type, object data) {
// String <--> Guid is allowed
if (type == PropertyType.Guid || type == PropertyType.String) {
return true;
}
// All numeric scalars can also be coerced
return IsNumericScalarImpl(type, data);
}
private static bool IsNumericScalarImpl(PropertyType type, object data) {
if (data.GetType().IsEnum) {
return true;
}
foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
if (numericScalar.Item2 == type) {
return true;
}
}
return false;
}
// Unbox the data stored in the property value to a structurally equivilent type
[Pure]
[SecurityCritical]
private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
Contract.Requires(expectedBoxedType != null);
Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));
if (_data.GetType() != expectedBoxedType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T unboxed = new T();
fixed (byte *pData = &JitHelpers.GetPinningHelper(_data).m_data) {
byte* pUnboxed = (byte*)JitHelpers.UnsafeCastToStackPointer(ref unboxed);
Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed));
}
return unboxed;
}
// Convert the array stored in the property value to a structurally equivilent array type
[Pure]
[SecurityCritical]
private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
Contract.Requires(expectedArrayElementType != null);
Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));
Array dataArray = _data as Array;
if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T[] converted = new T[dataArray.Length];
if (converted.Length > 0) {
fixed (byte * dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) {
fixed (byte * convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) {
byte *pData = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0);
byte *pConverted = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0);
Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length));
}
}
}
return converted;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Viewport3DDecorator.cs" company="">
//
// </copyright>
// <summary>
// This class enables a Viewport3D to be enhanced by allowing UIElements to be placed
// behind and in front of the Viewport3D. These can then be used for various enhancements.
// For examples see the Trackball, or InteractiveViewport3D.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft._3DTools
{
using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
/// <summary>
/// This class enables a Viewport3D to be enhanced by allowing UIElements to be placed
/// behind and in front of the Viewport3D. These can then be used for various enhancements.
/// For examples see the Trackball, or InteractiveViewport3D.
/// </summary>
[ContentProperty("Content")]
public abstract class Viewport3DDecorator : FrameworkElement, IAddChild
{
/// <summary>
/// The _post viewport children.
/// </summary>
private readonly UIElementCollection _postViewportChildren;
/// <summary>
/// The _pre viewport children.
/// </summary>
private readonly UIElementCollection _preViewportChildren;
/// <summary>
/// The _content.
/// </summary>
private UIElement _content;
/// <summary>
/// Initializes a new instance of the <see cref="Viewport3DDecorator"/> class.
/// Creates the Viewport3DDecorator
/// </summary>
protected Viewport3DDecorator()
{
// create the two lists of children
this._preViewportChildren = new UIElementCollection(this, this);
this._postViewportChildren = new UIElementCollection(this, this);
// no content yet
this._content = null;
}
/// <summary>
/// The content/child of the Viewport3DDecorator. A Viewport3DDecorator only has one
/// child and this child must be either another Viewport3DDecorator or a Viewport3D.
/// </summary>
public UIElement Content
{
get
{
return this._content;
}
set
{
// check to make sure it is a Viewport3D or a Viewport3DDecorator
if (!(value is Viewport3D || value is Viewport3DDecorator))
{
throw new ArgumentException("Not a valid child type", "value");
}
// check to make sure we're attempting to set something new
if (this._content == value)
{
return;
}
var oldContent = this._content;
var newContent = value;
// remove the previous child
this.RemoveVisualChild(oldContent);
this.RemoveLogicalChild(oldContent);
// set the private variable
this._content = value;
// link in the new child
this.AddLogicalChild(newContent);
this.AddVisualChild(newContent);
// let anyone know that derives from us that there was a change
this.OnViewport3DDecoratorContentChange(oldContent, newContent);
// data bind to what is below us so that we have the same width/height
// as the Viewport3D being enhanced
// create the bindings now for use later
this.BindToContentsWidthHeight(newContent);
// Invalidate measure to indicate a layout update may be necessary
this.InvalidateMeasure();
}
}
/// <summary>
/// Property to get the Viewport3D that is being enhanced.
/// </summary>
public Viewport3D Viewport3D
{
get
{
Viewport3D viewport3D = null;
var currEnhancer = this;
// we follow the enhancers down until we get the
// Viewport3D they are enhancing
while (true)
{
var currContent = currEnhancer.Content;
if (currContent == null)
{
break;
}
if (currContent is Viewport3D)
{
viewport3D = (Viewport3D)currContent;
break;
}
currEnhancer = (Viewport3DDecorator)currContent;
}
return viewport3D;
}
}
/// <summary>
/// The UIElements that occur before the Viewport3D
/// </summary>
protected UIElementCollection PreViewportChildren
{
get
{
return this._preViewportChildren;
}
}
/// <summary>
/// The UIElements that occur after the Viewport3D
/// </summary>
protected UIElementCollection PostViewportChildren
{
get
{
return this._postViewportChildren;
}
}
/// <summary>
/// Returns the number of Visual children this element has.
/// </summary>
protected override int VisualChildrenCount
{
get
{
var contentCount = this.Content == null ? 0 : 1;
return this.PreViewportChildren.Count + this.PostViewportChildren.Count + contentCount;
}
}
/// <summary>
/// Returns an enumerator to this element's logical children
/// </summary>
protected override IEnumerator LogicalChildren
{
get
{
var logicalChildren = new Visual[this.VisualChildrenCount];
for (var i = 0; i < this.VisualChildrenCount; i++)
{
logicalChildren[i] = this.GetVisualChild(i);
}
// return an enumerator to the ArrayList
return logicalChildren.GetEnumerator();
}
}
// ------------------------------------------------------
// IAddChild implementation
// ------------------------------------------------------
/// <summary>
/// The add child.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <exception cref="ArgumentNullException">
/// </exception>
/// <exception cref="ArgumentException">
/// </exception>
void IAddChild.AddChild(object value)
{
// check against null
if (value == null)
{
throw new ArgumentNullException("value");
}
// we only can have one child
if (this.Content != null)
{
throw new ArgumentException("Viewport3DDecorator can only have one child");
}
// now we can actually set the content
this.Content = (UIElement)value;
}
/// <summary>
/// The add text.
/// </summary>
/// <param name="text">
/// The text.
/// </param>
/// <exception cref="ArgumentException">
/// </exception>
void IAddChild.AddText(string text)
{
// The only text we accept is whitespace, which we ignore.
if (text.Any(t => !char.IsWhiteSpace(t)))
{
throw new ArgumentException("Non whitespace in add text", text);
}
}
/// <summary>
/// Data binds the (Max/Min)Width and (Max/Min)Height properties to the same
/// ones as the content. This will make it so we end up being sized to be
/// exactly the same ActualWidth and ActualHeight as waht is below us.
/// </summary>
/// <param name="newContent">
/// What to bind to
/// </param>
private void BindToContentsWidthHeight(UIElement newContent)
{
// bind to width height
var _widthBinding = new Binding("Width") { Mode = BindingMode.OneWay };
var _heightBinding = new Binding("Height") { Mode = BindingMode.OneWay };
_widthBinding.Source = newContent;
_heightBinding.Source = newContent;
BindingOperations.SetBinding(this, WidthProperty, _widthBinding);
BindingOperations.SetBinding(this, HeightProperty, _heightBinding);
// bind to max width and max height
var _maxWidthBinding = new Binding("MaxWidth") { Mode = BindingMode.OneWay };
var _maxHeightBinding = new Binding("MaxHeight") { Mode = BindingMode.OneWay };
_maxWidthBinding.Source = newContent;
_maxHeightBinding.Source = newContent;
BindingOperations.SetBinding(this, MaxWidthProperty, _maxWidthBinding);
BindingOperations.SetBinding(this, MaxHeightProperty, _maxHeightBinding);
// bind to min width and min height
var _minWidthBinding = new Binding("MinWidth") { Mode = BindingMode.OneWay };
var _minHeightBinding = new Binding("MinHeight") { Mode = BindingMode.OneWay };
_minWidthBinding.Source = newContent;
_minHeightBinding.Source = newContent;
BindingOperations.SetBinding(this, MinWidthProperty, _minWidthBinding);
BindingOperations.SetBinding(this, MinHeightProperty, _minHeightBinding);
}
/// <summary>
/// Extenders of Viewport3DDecorator can override this function to be notified
/// when the Content property changes
/// </summary>
/// <param name="oldContent">
/// The old value of the Content property
/// </param>
/// <param name="newContent">
/// The new value of the Content property
/// </param>
protected virtual void OnViewport3DDecoratorContentChange(UIElement oldContent, UIElement newContent)
{
}
/// <summary>
/// Returns the child at the specified index.
/// </summary>
/// <param name="index">
/// The index.
/// </param>
/// <returns>
/// The <see cref="Visual"/>.
/// </returns>
protected override Visual GetVisualChild(int index)
{
var originalIndex = index;
// see if index is in the pre viewport children
if (index < this.PreViewportChildren.Count)
{
return this.PreViewportChildren[index];
}
index -= this.PreViewportChildren.Count;
// see if it's the content
if (this.Content != null && index == 0)
{
return this.Content;
}
index -= this.Content == null ? 0 : 1;
// see if it's the post viewport children
if (index < this.PostViewportChildren.Count)
{
return this.PostViewportChildren[index];
}
// if we didn't return then the index is out of range - throw an error
throw new ArgumentOutOfRangeException("index", originalIndex, "Out of range visual requested");
}
/// <summary>
/// Updates the DesiredSize of the Viewport3DDecorator
/// </summary>
/// <param name="constraint">
/// The "upper limit" that the return value should not exceed
/// </param>
/// <returns>
/// The desired size of the Viewport3DDecorator
/// </returns>
protected override Size MeasureOverride(Size constraint)
{
var finalSize = new Size();
this.MeasurePreViewportChildren(constraint);
// measure our Viewport3D(Enhancer)
if (this.Content != null)
{
this.Content.Measure(constraint);
finalSize = this.Content.DesiredSize;
}
this.MeasurePostViewportChildren(constraint);
return finalSize;
}
/// <summary>
/// Measures the size of all the PreViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="constraint">
/// The "upper limit" on the size of an element
/// </param>
protected virtual void MeasurePreViewportChildren(Size constraint)
{
// measure the pre viewport children
this.MeasureUIElementCollection(this.PreViewportChildren, constraint);
}
/// <summary>
/// Measures the size of all the PostViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="constraint">
/// The "upper limit" on the size of an element
/// </param>
protected virtual void MeasurePostViewportChildren(Size constraint)
{
// measure the post viewport children
this.MeasureUIElementCollection(this.PostViewportChildren, constraint);
}
/// <summary>
/// Measures all of the UIElements in a UIElementCollection
/// </summary>
/// <param name="collection">
/// The collection to measure
/// </param>
/// <param name="constraint">
/// The "upper limit" on the size of an element
/// </param>
private void MeasureUIElementCollection(UIElementCollection collection, Size constraint)
{
// measure the pre viewport visual visuals
foreach (UIElement uiElem in collection)
{
uiElem.Measure(constraint);
}
}
/// <summary>
/// Arranges the Pre and Post Viewport children, and arranges itself
/// </summary>
/// <param name="arrangeSize">
/// The final size to use to arrange itself and its children
/// </param>
/// <returns>
/// The <see cref="Size"/>.
/// </returns>
protected override Size ArrangeOverride(Size arrangeSize)
{
this.ArrangePreViewportChildren(arrangeSize);
// arrange our Viewport3D(Enhancer)
if (this.Content != null)
{
this.Content.Arrange(new Rect(arrangeSize));
}
this.ArrangePostViewportChildren(arrangeSize);
return arrangeSize;
}
/// <summary>
/// Arranges all the PreViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="arrangeSize">
/// The final size to use to arrange each child
/// </param>
protected virtual void ArrangePreViewportChildren(Size arrangeSize)
{
this.ArrangeUIElementCollection(this.PreViewportChildren, arrangeSize);
}
/// <summary>
/// Arranges all the PostViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="arrangeSize">
/// The final size to use to arrange each child
/// </param>
protected virtual void ArrangePostViewportChildren(Size arrangeSize)
{
this.ArrangeUIElementCollection(this.PostViewportChildren, arrangeSize);
}
/// <summary>
/// Arranges all the UIElements in the passed in UIElementCollection
/// </summary>
/// <param name="collection">
/// The collection that should be arranged
/// </param>
/// <param name="constraint">
/// The final size that element should use to arrange itself and its children
/// </param>
private void ArrangeUIElementCollection(UIElementCollection collection, Size constraint)
{
// measure the pre viewport visual visuals
foreach (UIElement uiElem in collection)
{
uiElem.Arrange(new Rect(constraint));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
namespace System.Threading.Tests
{
public class TimerFiringTests
{
internal const int MaxPositiveTimeoutInMs = 30000;
[Fact]
public void Timer_Fires_After_DueTime_Ellapses()
{
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
are.Set();
}), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_Fires_AndPassesStateThroughCallback()
{
AutoResetEvent are = new AutoResetEvent(false);
object state = new object();
using (var t = new Timer(new TimerCallback((object s) =>
{
Assert.Same(s, state);
are.Set();
}), state, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_Fires_AndPassesNullStateThroughCallback()
{
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
Assert.Null(s);
are.Set();
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[OuterLoop("Several second delays")]
[Theory] // values chosen based on knowing the 333 pivot used in implementation
[InlineData(1, 1)]
[InlineData(50, 50)]
[InlineData(250, 50)]
[InlineData(50, 250)]
[InlineData(50, 400)]
[InlineData(400, 50)]
[InlineData(400, 400)]
public void Timer_Fires_After_DueTime_AndOn_Period(int dueTime, int period)
{
int count = 0;
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
if (Interlocked.Increment(ref count) >= 2)
{
are.Set();
}
}), null, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period)))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod()
{
int count = 0;
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
if (Interlocked.Increment(ref count) >= 2)
{
are.Set();
}
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(250 /*enough for 2 fires + buffer*/)));
}
}
[OuterLoop("Waits seconds")]
[Fact]
public void Timer_ChangeToDelete_DoesntFire()
{
RetryHelper.Execute(() =>
{
const int DueTime = 1000;
var mres = new ManualResetEventSlim();
using (var t = new Timer(_ => mres.Set(), null, DueTime, -1))
{
t.Change(Timeout.Infinite, Timeout.Infinite);
Assert.False(mres.Wait(DueTime * 2));
}
});
}
[Fact]
public void Timer_CanDisposeSelfInCallback()
{
Timer t = null;
AutoResetEvent are = new AutoResetEvent(false);
TimerCallback tc = new TimerCallback((object o) =>
{
t.Dispose();
are.Set();
});
t = new Timer(tc, null, -1, -1);
t.Change(1, -1);
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs));
GC.KeepAlive(t);
}
[Fact]
public void Timer_CanBeDisposedMultipleTimes()
{
// There's nothing to validate besides that we don't throw an exception, so rely on xunit
// to catch any exception that would be thrown and signal a test failure
TimerCallback tc = new TimerCallback((object o) => { });
var t = new Timer(tc, null, 100, -1);
for (int i = 0; i < 10; i++)
t.Dispose();
}
[Fact]
public void NonRepeatingTimer_ThatHasAlreadyFired_CanChangeAndFireAgain()
{
AutoResetEvent are = new AutoResetEvent(false);
TimerCallback tc = new TimerCallback((object o) => are.Set());
using (var t = new Timer(tc, null, 1, Timeout.Infinite))
{
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received first timer event");
Assert.False(are.WaitOne(500), "Should not have received a second timer event");
t.Change(10, Timeout.Infinite);
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received a second timer event after changing it");
}
}
[Fact]
public void MultpleTimers_PeriodicTimerIsntBlockedByBlockedCallback()
{
int callbacks = 2;
Barrier b = new Barrier(callbacks + 1);
Timer t = null;
t = new Timer(_ =>
{
if (Interlocked.Decrement(ref callbacks) >= 0)
{
Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs));
}
t.Dispose();
}, null, -1, -1);
t.Change(1, 50);
Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs));
GC.KeepAlive(t);
}
[Fact]
public void ManyTimers_EachTimerDoesFire()
{
int maxTimers = 10000;
CountdownEvent ce = new CountdownEvent(maxTimers);
Timer[] timers = System.Linq.Enumerable.Range(0, maxTimers).Select(_ => new Timer(s => ce.Signal(), null, 100 /* enough time to wait on the are */, -1)).ToArray();
try
{
Assert.True(ce.Wait(MaxPositiveTimeoutInMs), string.Format("Not all timers fired, {0} left of {1}", ce.CurrentCount, maxTimers));
}
finally
{
foreach (Timer t in timers)
t.Dispose();
}
}
[Fact]
public void Timer_Constructor_CallbackOnly_Change()
{
var e = new ManualResetEvent(false);
using (var t = new Timer(s => e.Set()))
{
t.Change(0u, 0u);
Assert.True(e.WaitOne(MaxPositiveTimeoutInMs));
}
}
[Fact]
public void Timer_Dispose_WaitHandle_Negative()
{
Assert.Throws<ArgumentNullException>(() => new Timer(s => { }).Dispose(null));
}
[Fact]
public void Timer_Dispose_WaitHandle()
{
int tickCount = 0;
var someTicksPending = new ManualResetEvent(false);
var completeTicks = new ManualResetEvent(false);
var allTicksCompleted = new ManualResetEvent(false);
var t =
new Timer(s =>
{
if (Interlocked.Increment(ref tickCount) == 2)
someTicksPending.Set();
Assert.True(completeTicks.WaitOne(MaxPositiveTimeoutInMs));
Interlocked.Decrement(ref tickCount);
}, null, 0, 1);
Assert.True(someTicksPending.WaitOne(MaxPositiveTimeoutInMs));
completeTicks.Set();
t.Dispose(allTicksCompleted);
Assert.True(allTicksCompleted.WaitOne(MaxPositiveTimeoutInMs));
Assert.Equal(0, tickCount);
Assert.Throws<ObjectDisposedException>(() => t.Change(0, 0));
}
[OuterLoop("Incurs seconds delay to wait for events that should never happen")]
[Fact]
public async Task Timer_LongTimersDontFirePrematurely_ShortTimersFireSuccessfully()
{
var tcsShort1 = new TaskCompletionSource<bool>();
var tcsShort2 = new TaskCompletionSource<bool>();
var tcsLong1 = new TaskCompletionSource<bool>();
var tcsLong2 = new TaskCompletionSource<bool>();
using (var timerLong1 = new Timer(_ => tcsLong1.SetResult(true), null, TimeSpan.FromDays(30), Timeout.InfiniteTimeSpan))
using (var timerLong2 = new Timer(_ => tcsLong2.SetResult(true), null, TimeSpan.FromDays(40), Timeout.InfiniteTimeSpan))
using (var timerShort1 = new Timer(_ => tcsShort1.SetResult(true), null, 100, -1))
using (var timerShort2 = new Timer(_ => tcsShort2.SetResult(true), null, 200, -1))
{
await Task.WhenAll(tcsShort1.Task, tcsShort2.Task);
await Task.Delay(2_000); // wait a few seconds to see if long timers complete when they shouldn't
Assert.Equal(TaskStatus.WaitingForActivation, tcsLong1.Task.Status);
Assert.Equal(TaskStatus.WaitingForActivation, tcsLong2.Task.Status);
}
}
[OuterLoop("Takes several seconds")]
[Fact]
public async Task Timer_ManyDifferentSingleDueTimes_AllFireSuccessfully()
{
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from i in Enumerable.Range(1, 1_000) select DueTimeAsync(i));
await Task.WhenAll(from i in Enumerable.Range(1, 1_000) select DueTimeAsync(1_001 - i));
}));
}
[OuterLoop("Takes several seconds")]
[Fact]
public async Task Timer_ManyDifferentPeriodicTimes_AllFireSuccessfully()
{
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from i in Enumerable.Range(1, 400) select PeriodAsync(period: i, iterations: 3));
await Task.WhenAll(from i in Enumerable.Range(1, 400) select PeriodAsync(period: 401 - i, iterations: 3));
}));
}
[PlatformSpecific(~TestPlatforms.OSX)] // macOS in CI appears to have a lot more variation
[OuterLoop("Takes several seconds")]
[Theory] // selection based on 333ms threshold used by implementation
[InlineData(new int[] { 15 })]
[InlineData(new int[] { 333 })]
[InlineData(new int[] { 332, 333, 334 })]
[InlineData(new int[] { 200, 300, 400 })]
[InlineData(new int[] { 200, 250, 300 })]
[InlineData(new int[] { 400, 450, 500 })]
[InlineData(new int[] { 1000 })]
public async Task Timer_ManyDifferentSerialSingleDueTimes_AllFireWithinAllowedRange(int[] dueTimes)
{
const int MillisecondsPadding = 100; // for each timer, out of range == Math.Abs(actualTime - dueTime) > MillisecondsPadding
const int MaxAllowedOutOfRangePercentage = 20; // max % allowed out of range to pass test
for (int tries = 0; ; tries++)
{
try
{
var outOfRange = new ConcurrentQueue<KeyValuePair<int, long>>();
long totalTimers = 0;
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from dueTimeTemplate in dueTimes
from dueTime in Enumerable.Repeat(dueTimeTemplate, 10)
select Task.Run(async () =>
{
var sw = new Stopwatch();
for (int i = 1; i <= 1_000 / dueTime; i++)
{
sw.Restart();
await DueTimeAsync(dueTime);
sw.Stop();
Interlocked.Increment(ref totalTimers);
if (Math.Abs(sw.ElapsedMilliseconds - dueTime) > MillisecondsPadding)
{
outOfRange.Enqueue(new KeyValuePair<int, long>(dueTime, sw.ElapsedMilliseconds));
}
}
}));
}));
double percOutOfRange = (double)outOfRange.Count / totalTimers * 100;
if (percOutOfRange > MaxAllowedOutOfRangePercentage)
{
IOrderedEnumerable<IGrouping<int, KeyValuePair<int, long>>> results =
from sample in outOfRange
group sample by sample.Key into groupedByDueTime
orderby groupedByDueTime.Key
select groupedByDueTime;
var sb = new StringBuilder();
sb.AppendFormat("{0}% out of {1} timer firings were off by more than {2}ms",
percOutOfRange, totalTimers, MillisecondsPadding);
foreach (IGrouping<int, KeyValuePair<int, long>> result in results)
{
sb.AppendLine();
sb.AppendFormat("Expected: {0}, Actuals: {1}", result.Key, string.Join(", ", result.Select(k => k.Value)));
}
Assert.True(false, sb.ToString());
}
}
catch (XunitException) when (tries < 3)
{
// This test will occasionally fail apparently because it was switched out
// for a short period. Eat and go around again
await Task.Delay(TimeSpan.FromSeconds(10)); // Should be very rare: wait for machine to settle
continue;
}
return;
}
}
private static Task DueTimeAsync(int dueTime)
{
// We could just use Task.Delay, but it only uses Timer as an implementation detail.
// Since these are Timer tests, we use an implementation that explicitly uses Timer.
var tcs = new TaskCompletionSource<bool>();
var t = new Timer(_ => tcs.SetResult(true)); // rely on Timer(TimerCallback) rooting itself
t.Change(dueTime, -1);
return tcs.Task;
}
private static async Task PeriodAsync(int period, int iterations)
{
var tcs = new TaskCompletionSource<bool>();
using (var t = new Timer(_ => { if (Interlocked.Decrement(ref iterations) == 0) tcs.SetResult(true); })) // rely on Timer(TimerCallback) rooting itself
{
t.Change(period, period);
await tcs.Task.ConfigureAwait(false);
}
}
}
}
| |
using System;
using System.Text;
using Rynchodon.Autopilot.Data;
using Rynchodon.Autopilot.Pathfinding;
using Rynchodon.Threading;
using Rynchodon.Utility;
using Rynchodon.Utility.Collections;
using Sandbox.Game.Entities;
using VRageMath;
namespace Rynchodon.Autopilot.Navigator.Mining
{
class SurfaceMiner : AMinerComponent
{
public enum Stage : byte { None, GetSurface, Mine, Escape }
private static ThreadManager Thread = new ThreadManager(1, true, "Surface Miner");
private Vector3 m_perp1, m_perp2;
private int m_ringIndex, m_squareIndex;
private Vector3D m_surfacePoint;
private bool m_finalMine;
private Stage value_stage;
private Stage m_stage
{
get { return value_stage; }
set
{
if (value_stage == value)
return;
Log.DebugLog("stage changed from " + value_stage + " to " + value, Logger.severity.DEBUG);
switch (value)
{
case Stage.GetSurface:
Thread.EnqueueAction(SetNextSurfacePoint);
break;
case Stage.Mine:
EnableDrills(true);
break;
}
m_navSet.OnTaskComplete_NavWay();
value_stage = value;
}
}
private Logable Log
{ get { return LogableFrom.Pseudo(m_navSet.Settings_Current.NavigationBlock, m_stage.ToString()); } }
public SurfaceMiner(Pathfinder pathfinder, Destination target, string oreName) : base(pathfinder, oreName)
{
m_target = target;
Vector3 toDeposit = Vector3.Normalize(m_target.WorldPosition() - m_grid.GetCentre());
toDeposit.CalculatePerpendicularVector(out m_perp1);
Vector3.Cross(ref toDeposit, ref m_perp1, out m_perp2);
AllNavigationSettings.SettingsLevel level = m_navSet.Settings_Task_NavMove;
level.NavigatorMover = this;
level.NavigatorRotator = this;
level.IgnoreAsteroid = true;
level.SpeedTarget = 1f;
level.PathfinderCanChangeCourse = false;
m_stage = Stage.GetSurface;
Log.DebugLog("started", Logger.severity.DEBUG);
}
public override void AppendCustomInfo(StringBuilder customInfo)
{
switch (m_stage)
{
case Stage.GetSurface:
customInfo.AppendLine("Scanning surface.");
break;
case Stage.Mine:
customInfo.Append("Surface mining ");
customInfo.Append(m_oreName);
customInfo.Append(" at ");
customInfo.AppendLine(m_target.WorldPosition().ToPretty());
break;
}
}
public override void Move()
{
switch (m_stage)
{
case Stage.GetSurface:
m_mover.StopMove();
break;
case Stage.Mine:
MineTarget();
break;
case Stage.Escape:
m_stage = Stage.GetSurface;
break;
}
}
public override void Rotate()
{
switch (m_stage)
{
case Stage.GetSurface:
{
m_mover.StopRotate();
break;
}
case Stage.Mine:
{
Vector3 direction = Vector3.Normalize(m_target.WorldPosition() - m_navBlock.WorldPosition);
m_mover.CalcRotate(m_navBlock, RelativeDirection3F.FromWorld(m_grid, direction));
break;
}
}
}
private void MineTarget()
{
if (m_navSet.Settings_Current.Distance > 10f && !m_navSet.DirectionMatched() && IsNearVoxel())
{
// match direction
m_mover.StopMove();
}
else if (AbortMining())
{
m_stage = Stage.Escape;
new EscapeMiner(m_pathfinder, TargetVoxel);
}
else if (m_navSet.DistanceLessThan(1f))
{
if (m_finalMine)
{
Log.DebugLog("Reached target", Logger.severity.DEBUG);
m_stage = Stage.Escape;
new EscapeMiner(m_pathfinder, TargetVoxel);
}
else
{
Log.DebugLog("Reached surface point", Logger.severity.DEBUG);
m_stage = Stage.GetSurface;
}
}
else
{
Destination dest = Destination.FromWorld(m_target.Entity, ref m_surfacePoint);
m_pathfinder.MoveTo(destinations: dest);
}
}
private void SetNextSurfacePoint()
{
CapsuleD surfaceFinder;
surfaceFinder.Radius = 1f;
float maxRingSize = m_grid.LocalVolume.Radius; maxRingSize *= maxRingSize;
bool overMax = false;
surfaceFinder.P0 = m_grid.GetCentre();
Vector3D targetWorld = m_target.WorldPosition();
for (int i = 0; i < 1000; i++)
{
ExpandingRings.Ring ring = ExpandingRings.GetRing(m_ringIndex);
if (m_squareIndex >= ring.Squares.Length)
{
ring = ExpandingRings.GetRing(++m_ringIndex);
m_squareIndex = 0;
}
Vector2I square = ring.Squares[m_squareIndex++];
Vector3 direct1; Vector3.Multiply(ref m_perp1, square.X, out direct1);
Vector3 direct2; Vector3.Multiply(ref m_perp2, square.Y, out direct2);
surfaceFinder.P1 = targetWorld + direct1 + direct2;
if (CapsuleDExtensions.Intersects(ref surfaceFinder, (MyVoxelBase)m_target.Entity, out m_surfacePoint))
{
Log.DebugLog("test from " + surfaceFinder.P0 + " to " + surfaceFinder.P1 + ", hit voxel at " + m_surfacePoint);
m_finalMine = Vector3D.DistanceSquared(m_surfacePoint, m_target.WorldPosition()) < 1d;
m_stage = Stage.Mine;
return;
}
Log.DebugLog("test from " + surfaceFinder.P0 + " to " + surfaceFinder.P1 + ", did not hit voxel. P1 constructed from " + targetWorld + ", " + direct1 + ", " + direct2);
if (ring.DistanceSquared > maxRingSize)
{
if (overMax)
{
Log.AlwaysLog("Infinite loop", Logger.severity.FATAL);
throw new Exception("Infinte loop");
}
overMax = true;
Log.DebugLog("Over max ring size, starting next level", Logger.severity.INFO);
m_squareIndex = 0;
m_ringIndex = 0;
}
}
Log.AlwaysLog("Infinite loop", Logger.severity.FATAL);
throw new Exception("Infinte loop");
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Index
{
using Lucene.Net.Support;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
/// <summary>
/// Exposes flex API, merged from flex API of sub-segments.
///
/// @lucene.experimental
/// </summary>
public sealed class MultiDocsAndPositionsEnum : DocsAndPositionsEnum
{
private readonly MultiTermsEnum Parent;
internal readonly DocsAndPositionsEnum[] SubDocsAndPositionsEnum;
private EnumWithSlice[] Subs_Renamed;
internal int NumSubs_Renamed;
internal int Upto;
internal DocsAndPositionsEnum Current;
internal int CurrentBase;
internal int Doc = -1;
/// <summary>
/// Sole constructor. </summary>
public MultiDocsAndPositionsEnum(MultiTermsEnum parent, int subReaderCount)
{
this.Parent = parent;
SubDocsAndPositionsEnum = new DocsAndPositionsEnum[subReaderCount];
}
/// <summary>
/// Returns {@code true} if this instance can be reused by
/// the provided <seealso cref="MultiTermsEnum"/>.
/// </summary>
public bool CanReuse(MultiTermsEnum parent)
{
return this.Parent == parent;
}
/// <summary>
/// Rre-use and reset this instance on the provided slices. </summary>
public MultiDocsAndPositionsEnum Reset(EnumWithSlice[] subs, int numSubs)
{
this.NumSubs_Renamed = numSubs;
this.Subs_Renamed = new EnumWithSlice[subs.Length];
for (int i = 0; i < subs.Length; i++)
{
this.Subs_Renamed[i] = new EnumWithSlice();
this.Subs_Renamed[i].DocsAndPositionsEnum = subs[i].DocsAndPositionsEnum;
this.Subs_Renamed[i].Slice = subs[i].Slice;
}
Upto = -1;
Doc = -1;
Current = null;
return this;
}
/// <summary>
/// How many sub-readers we are merging. </summary>
/// <seealso cref= #getSubs </seealso>
public int NumSubs
{
get
{
return NumSubs_Renamed;
}
}
/// <summary>
/// Returns sub-readers we are merging. </summary>
public EnumWithSlice[] Subs
{
get
{
return Subs_Renamed;
}
}
public override int Freq()
{
Debug.Assert(Current != null);
return Current.Freq();
}
public override int DocID()
{
return Doc;
}
public override int Advance(int target)
{
Debug.Assert(target > Doc);
while (true)
{
if (Current != null)
{
int doc;
if (target < CurrentBase)
{
// target was in the previous slice but there was no matching doc after it
doc = Current.NextDoc();
}
else
{
doc = Current.Advance(target - CurrentBase);
}
if (doc == NO_MORE_DOCS)
{
Current = null;
}
else
{
return this.Doc = doc + CurrentBase;
}
}
else if (Upto == NumSubs_Renamed - 1)
{
return this.Doc = NO_MORE_DOCS;
}
else
{
Upto++;
Current = Subs_Renamed[Upto].DocsAndPositionsEnum;
CurrentBase = Subs_Renamed[Upto].Slice.Start;
}
}
}
public override int NextDoc()
{
while (true)
{
if (Current == null)
{
if (Upto == NumSubs_Renamed - 1)
{
return this.Doc = NO_MORE_DOCS;
}
else
{
Upto++;
Current = Subs_Renamed[Upto].DocsAndPositionsEnum;
CurrentBase = Subs_Renamed[Upto].Slice.Start;
}
}
int doc = Current.NextDoc();
if (doc != NO_MORE_DOCS)
{
return this.Doc = CurrentBase + doc;
}
else
{
Current = null;
}
}
}
public override int NextPosition()
{
return Current.NextPosition();
}
public override int StartOffset()
{
return Current.StartOffset();
}
public override int EndOffset()
{
return Current.EndOffset();
}
public override BytesRef Payload
{
get
{
return Current.Payload;
}
}
// TODO: implement bulk read more efficiently than super
/// <summary>
/// Holds a <seealso cref="DocsAndPositionsEnum"/> along with the
/// corresponding <seealso cref="ReaderSlice"/>.
/// </summary>
public sealed class EnumWithSlice
{
internal EnumWithSlice()
{
}
/// <summary>
/// <seealso cref="DocsAndPositionsEnum"/> for this sub-reader. </summary>
public DocsAndPositionsEnum DocsAndPositionsEnum;
/// <summary>
/// <seealso cref="ReaderSlice"/> describing how this sub-reader
/// fits into the composite reader.
/// </summary>
public ReaderSlice Slice;
public override string ToString()
{
return Slice.ToString() + ":" + DocsAndPositionsEnum;
}
}
public override long Cost()
{
long cost = 0;
for (int i = 0; i < NumSubs_Renamed; i++)
{
cost += Subs_Renamed[i].DocsAndPositionsEnum.Cost();
}
return cost;
}
public override string ToString()
{
return "MultiDocsAndPositionsEnum(" + Arrays.ToString(Subs) + ")";
}
}
}
| |
#region License
/*
* HttpBase.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp
{
internal abstract class HttpBase
{
#region Private Fields
private NameValueCollection _headers;
private const int _headersMaxLength = 8192;
private Version _version;
#endregion
#region Internal Fields
internal byte[] EntityBodyData;
#endregion
#region Protected Fields
protected const string CrLf = "\r\n";
#endregion
#region Protected Constructors
protected HttpBase (Version version, NameValueCollection headers)
{
_version = version;
_headers = headers;
}
#endregion
#region Public Properties
public string EntityBody {
get {
if (EntityBodyData == null || EntityBodyData.LongLength == 0)
return String.Empty;
Encoding enc = null;
var contentType = _headers["Content-Type"];
if (contentType != null && contentType.Length > 0)
enc = HttpUtility.GetEncoding (contentType);
return (enc ?? Encoding.UTF8).GetString (EntityBodyData);
}
}
public NameValueCollection Headers {
get {
return _headers;
}
}
public Version ProtocolVersion {
get {
return _version;
}
}
#endregion
#region Private Methods
private static byte[] readEntityBody (Stream stream, string length)
{
long len;
if (!Int64.TryParse (length, out len))
throw new ArgumentException ("Cannot be parsed.", "length");
if (len < 0)
throw new ArgumentOutOfRangeException ("length", "Less than zero.");
return len > 1024
? stream.ReadBytes (len, 1024)
: len > 0
? stream.ReadBytes ((int) len)
: null;
}
private static string[] readHeaders (Stream stream, int maxLength)
{
var buff = new List<byte> ();
var cnt = 0;
Action<int> add = i => {
if (i == -1)
throw new EndOfStreamException ("The header cannot be read from the data source.");
buff.Add ((byte) i);
cnt++;
};
var read = false;
while (cnt < maxLength) {
if (stream.ReadByte ().IsEqualTo ('\r', add) &&
stream.ReadByte ().IsEqualTo ('\n', add) &&
stream.ReadByte ().IsEqualTo ('\r', add) &&
stream.ReadByte ().IsEqualTo ('\n', add)) {
read = true;
break;
}
}
if (!read)
throw new WebSocketException ("The length of header part is greater than the max length.");
return Encoding.UTF8.GetString (buff.ToArray ())
.Replace (CrLf + " ", " ")
.Replace (CrLf + "\t", " ")
.Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
}
#endregion
#region Protected Methods
protected static T Read<T> (Stream stream, Func<string[], T> parser, int millisecondsTimeout)
where T : HttpBase
{
var timeout = false;
var timer = new Timer (
state => {
timeout = true;
stream.Close ();
},
null,
millisecondsTimeout,
-1);
T http = null;
Exception exception = null;
try {
http = parser (readHeaders (stream, _headersMaxLength));
var contentLen = http.Headers["Content-Length"];
if (contentLen != null && contentLen.Length > 0)
http.EntityBodyData = readEntityBody (stream, contentLen);
}
catch (Exception ex) {
exception = ex;
}
finally {
timer.Change (-1, -1);
timer.Dispose ();
}
var msg = timeout
? "A timeout has occurred while reading an HTTP request/response."
: exception != null
? "An exception has occurred while reading an HTTP request/response."
: null;
if (msg != null)
throw new WebSocketException (msg, exception);
return http;
}
#endregion
#region Public Methods
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Reinforcement.CS
{
/// <summary>
/// The class derived from FramReinMaker shows how to create the rebars for a beam
/// </summary>
public class BeamFramReinMaker : FramReinMaker
{
#region Private Members
BeamGeometrySupport m_geometry; // The geometry support for beam rebar creation
// The rebar type, hook type and spacing information
RebarBarType m_topEndType = null; //type of the end rebar in the top of beam
RebarBarType m_topCenterType = null; //type of the center rebar in the center of beam
RebarBarType m_bottomType = null; //type of the rebar on bottom of the beam
RebarBarType m_transverseType = null; //type of the transverse rebar
RebarHookType m_topHookType = null; //type of the hook in the top end rebar
RebarHookType m_transverseHookType = null; // type of the hook in the transverse rebar
double m_transverseEndSpacing = 0; //the spacing value of end transverse rebar
double m_transverseCenterSpacing = 0; //the spacing value of center transverse rebar
#endregion
#region Properties
/// <summary>
/// get and set the type of the end rebar in the top of beam
/// </summary>
public RebarBarType TopEndRebarType
{
get
{
return m_topEndType;
}
set
{
m_topEndType = value;
}
}
/// <summary>
/// get and set the type of the center rebar in the top of beam
/// </summary>
public RebarBarType TopCenterRebarType
{
get
{
return m_topCenterType;
}
set
{
m_topCenterType = value;
}
}
/// <summary>
/// get and set the type of the rebar in the bottom of beam
/// </summary>
public RebarBarType BottomRebarType
{
get
{
return m_bottomType;
}
set
{
m_bottomType = value;
}
}
/// <summary>
/// get and set the type of the transverse rebar
/// </summary>
public RebarBarType TransverseRebarType
{
get
{
return m_transverseType;
}
set
{
m_transverseType = value;
}
}
/// <summary>
/// get and set the spacing value of end transverse rebar
/// </summary>
public double TransverseEndSpacing
{
get
{
return m_transverseEndSpacing;
}
set
{
if (0 > value)
{
throw new Exception("Transverse end spacing should be above zero");
}
m_transverseEndSpacing = value;
}
}
/// <summary>
/// get and set the spacing value of center transverse rebar
/// </summary>
public double TransverseCenterSpacing
{
get
{
return m_transverseCenterSpacing;
}
set
{
if (0 > value)
{
throw new Exception("Transverse center spacing should be above zero");
}
m_transverseCenterSpacing = value;
}
}
/// <summary>
/// get and set the hook type of top end rebar
/// </summary>
public RebarHookType TopHookType
{
get
{
return m_topHookType;
}
set
{
m_topHookType = value;
}
}
/// <summary>
/// get and set the hook type of transverse rebar
/// </summary>
public RebarHookType TransverseHookType
{
get
{
return m_transverseHookType;
}
set
{
m_transverseHookType = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor of the BeamFramReinMaker
/// </summary>
/// <param name="commandData">the ExternalCommandData reference</param>
/// <param name="hostObject">the host beam</param>
public BeamFramReinMaker(ExternalCommandData commandData, FamilyInstance hostObject)
: base(commandData, hostObject)
{
//create new options for current project
Options geoOptions = commandData.Application.Application.Create.NewGeometryOptions();
geoOptions.ComputeReferences = true;
//create a BeamGeometrySupport instance.
m_geometry = new BeamGeometrySupport(hostObject, geoOptions);
}
#endregion
#region Override Methods
/// <summary>
/// Override method to do some further checks
/// </summary>
/// <returns>true if the the data is right and enough, otherwise false.</returns>
protected override bool AssertData()
{
return base.AssertData();
}
/// <summary>
/// Display a form to collect the information for beam reinforcement creation
/// </summary>
/// <returns>true if the information collection is successful, otherwise false</returns>
protected override bool DisplayForm()
{
// Display BeamFramReinMakerForm for the user to input information
using (BeamFramReinMakerForm displayForm = new BeamFramReinMakerForm(this))
{
if (DialogResult.OK != displayForm.ShowDialog())
{
return false;
}
}
return base.DisplayForm();
}
/// <summary>
/// Override method to create rebar on the selected beam
/// </summary>
/// <returns>true if the creation is successful, otherwise false</returns>
protected override bool FillWithBars()
{
// create the top rebars
bool flag = FillTopBars();
// create the bottom rebars
flag = flag && FillBottomBars();
// create the transverse rebars
flag = flag && FillTransverseBars();
return base.FillWithBars();
}
#endregion
/// <summary>
/// Create the rebar at the bottom of beam
/// </summary>
/// <returns>true if the creation is successful, otherwise false</returns>
public bool FillBottomBars()
{
// get the geometry information of the bottom rebar
RebarGeometry geomInfo = m_geometry.GetBottomRebar();
// create the rebar
Rebar rebar = PlaceRebars(m_bottomType, null, null, geomInfo,
RebarHookOrientation.Left, RebarHookOrientation.Left);
return (null != rebar);
}
/// <summary>
/// Create the transverse rebars
/// </summary>
/// <returns>true if the creation is successful, otherwise false</returns>
public bool FillTransverseBars()
{
// create all kinds of transverse rebars according to the TransverseRebarLocation
foreach (TransverseRebarLocation location in Enum.GetValues(
typeof(TransverseRebarLocation)))
{
Rebar createdRebar = FillTransverseBar(location);
//judge whether the transverse rebar creation is successful
if (null == createdRebar)
{
return false;
}
}
return true;
}
/// <summary>
/// Create the transverse rebars, according to the location of transverse rebars
/// </summary>
/// <param name="location">location of rebar which need to be created</param>
/// <returns>the created rebar, return null if the creation is unsuccessful</returns>
public Rebar FillTransverseBar(TransverseRebarLocation location)
{
// Get the geometry information which support rebar creation
RebarGeometry geomInfo = new RebarGeometry();
switch (location)
{
case TransverseRebarLocation.Start: // start transverse rebar
case TransverseRebarLocation.End: // end transverse rebar
geomInfo = m_geometry.GetTransverseRebar(location, m_transverseEndSpacing);
break;
case TransverseRebarLocation.Center:// center transverse rebar
geomInfo = m_geometry.GetTransverseRebar(location, m_transverseCenterSpacing);
break;
}
RebarHookOrientation startHook = RebarHookOrientation.Right;
RebarHookOrientation endHook = RebarHookOrientation.Left;
if (!GeomUtil.IsInRightDir(geomInfo.Normal))
{
startHook = RebarHookOrientation.Left;
endHook = RebarHookOrientation.Right;
}
// create the rebar
return PlaceRebars(m_transverseType, m_transverseHookType, m_transverseHookType,
geomInfo, startHook, endHook);
}
/// <summary>
/// Get the hook orient of the top rebar
/// </summary>
/// <param name="geomInfo">the rebar geometry support information</param>
/// <param name="location">the location of top rebar</param>
/// <returns>the hook orient of the top hook</returns>
private RebarHookOrientation GetTopHookOrient(RebarGeometry geomInfo, TopRebarLocation location)
{
// Top center rebar doesn't need hook.
if (TopRebarLocation.Center == location)
{
throw new Exception("Center top rebar doesn't have any hook.");
}
// Get the hook direction, rebar normal and rebar line
Autodesk.Revit.DB.XYZ hookVec = m_geometry.GetDownDirection();
Autodesk.Revit.DB.XYZ normal = geomInfo.Normal;
Line rebarLine = geomInfo.Curves[0] as Line;
// get the top start hook orient
if (TopRebarLocation.Start == location)
{
Autodesk.Revit.DB.XYZ curveVec = GeomUtil.SubXYZ(rebarLine.get_EndPoint(1), rebarLine.get_EndPoint(0));
return GeomUtil.GetHookOrient(curveVec, normal, hookVec);
}
else // get the top end hook orient
{
Autodesk.Revit.DB.XYZ curveVec = GeomUtil.SubXYZ(rebarLine.get_EndPoint(0), rebarLine.get_EndPoint(1));
return GeomUtil.GetHookOrient(curveVec, normal, hookVec);
}
}
/// <summary>
/// Create the rebar at the top of beam
/// </summary>
/// <returns>true if the creation is successful, otherwise false</returns>
private bool FillTopBars()
{
// create all kinds of top rebars according to the TopRebarLocation
foreach (TopRebarLocation location in Enum.GetValues(typeof(TopRebarLocation)))
{
Rebar createdRebar = FillTopBar(location);
//judge whether the top rebar creation is successful
if (null == createdRebar)
{
return false;
}
}
return true;
}
/// <summary>
/// Create the rebar at the top of beam, according to the top rebar location
/// </summary>
/// <param name="location">location of rebar which need to be created</param>
/// <returns>the created rebar, return null if the creation is unsuccessful</returns>
private Rebar FillTopBar(TopRebarLocation location)
{
//get the geometry information of the rebar
RebarGeometry geomInfo = m_geometry.GetTopRebar(location);
RebarHookType startHookType = null; //the start hook type of the rebar
RebarHookType endHookType = null; // the end hook type of the rebar
RebarBarType rebarType = null; // the rebar type
RebarHookOrientation startOrient = RebarHookOrientation.Right;// the start hook orient
RebarHookOrientation endOrient = RebarHookOrientation.Left; // the end hook orient
// decide the rebar type, hook type and hook orient according to location
switch (location)
{
case TopRebarLocation.Start:
startHookType = m_topHookType; // start hook type
rebarType = m_topEndType; // rebar type
startOrient = GetTopHookOrient(geomInfo, location); // start hook orient
break;
case TopRebarLocation.Center:
rebarType = m_topCenterType; // rebar type
break;
case TopRebarLocation.End:
endHookType = m_topHookType; // end hook type
rebarType = m_topEndType; // rebar type
endOrient = GetTopHookOrient(geomInfo, location); // end hook orient
break;
}
// create the rebar
return PlaceRebars(rebarType, startHookType, endHookType,
geomInfo, startOrient, endOrient);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DbgEng
{
[ComImport, ComConversionLoss, Guid("8C31E98C-983A-48A5-9016-6FE5D667A950"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDebugSymbols
{
uint GetSymbolOptions();
void AddSymbolOptions(
[In] uint Options);
void RemoveSymbolOptions(
[In] uint Options);
void SetSymbolOptions(
[In] uint Options);
void GetNameByOffset(
[In] ulong Offset,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer,
[In] uint NameBufferSize,
[Out] out uint NameSize,
[Out] out ulong Displacement);
ulong GetOffsetByName(
[In, MarshalAs(UnmanagedType.LPStr)] string Symbol);
void GetNearNameByOffset(
[In] ulong Offset,
[In] int Delta,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer,
[In] uint NameBufferSize,
[Out] out uint NameSize,
[Out] out ulong Displacement);
void GetLineByOffset(
[In] ulong Offset,
[Out] out uint Line,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer,
[In] uint FileBufferSize,
[Out] out uint FileSize,
[Out] out ulong Displacement);
ulong GetOffsetByLine(
[In] uint Line,
[In, MarshalAs(UnmanagedType.LPStr)] string File);
void GetNumberModules(
[Out] out uint Loaded,
[Out] out uint Unloaded);
ulong GetModuleByIndex(
[In] uint Index);
void GetModuleByModuleName(
[In, MarshalAs(UnmanagedType.LPStr)] string Name,
[In] uint StartIndex,
[Out] out uint Index,
[Out] out ulong Base);
void GetModuleByOffset(
[In] ulong Offset,
[In] uint StartIndex,
[Out] out uint Index,
[Out] out ulong Base);
void GetModuleNames(
[In] uint Index,
[In] ulong Base,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ImageNameBuffer,
[In] uint ImageNameBufferSize,
[Out] out uint ImageNameSize,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ModuleNameBuffer,
[In] uint ModuleNameBufferSize,
[Out] out uint ModuleNameSize,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder LoadedImageNameBuffer,
[In] uint LoadedImageNameBufferSize,
[Out] out uint LoadedImageNameSize);
void GetModuleParameters(
[In] uint Count,
[In] ref ulong Bases,
[In] uint Start = default(uint),
[Out] IntPtr Params = default(IntPtr));
ulong GetSymbolModule(
[In, MarshalAs(UnmanagedType.LPStr)] string Symbol);
void GetTypeName(
[In] ulong Module,
[In] uint TypeId,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer,
[In] uint NameBufferSize,
[Out] out uint NameSize);
uint GetTypeId(
[In] ulong Module,
[In, MarshalAs(UnmanagedType.LPStr)] string Name);
uint GetTypeSize(
[In] ulong Module,
[In] uint TypeId);
uint GetFieldOffset(
[In] ulong Module,
[In] uint TypeId,
[In, MarshalAs(UnmanagedType.LPStr)] string Field);
void GetSymbolTypeId(
[In, MarshalAs(UnmanagedType.LPStr)] string Symbol,
[Out] out uint TypeId,
[Out] out ulong Module);
void GetOffsetTypeId(
[In] ulong Offset,
[Out] out uint TypeId,
[Out] out ulong Module);
void ReadTypedDataVirtual(
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteTypedDataVirtual(
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
void OutputTypedDataVirtual(
[In] uint OutputControl,
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[In] uint Flags);
void ReadTypedDataPhysical(
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[Out] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesRead);
void WriteTypedDataPhysical(
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[In] IntPtr Buffer,
[In] uint BufferSize,
[Out] out uint BytesWritten);
void OutputTypedDataPhysical(
[In] uint OutputControl,
[In] ulong Offset,
[In] ulong Module,
[In] uint TypeId,
[In] uint Flags);
void GetScope(
[Out] out ulong InstructionOffset,
[Out] out _DEBUG_STACK_FRAME ScopeFrame,
[Out] IntPtr ScopeContext = default(IntPtr),
[In] uint ScopeContextSize = default(uint));
void SetScope(
[In] ulong InstructionOffset,
[In] ref _DEBUG_STACK_FRAME ScopeFrame,
[In] IntPtr ScopeContext = default(IntPtr),
[In] uint ScopeContextSize = default(uint));
void ResetScope();
void GetScopeSymbolGroup(
[In] uint Flags,
[In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup Update,
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols);
[return: MarshalAs(UnmanagedType.Interface)]
IDebugSymbolGroup CreateSymbolGroup();
ulong StartSymbolMatch(
[In, MarshalAs(UnmanagedType.LPStr)] string Pattern);
void GetNextSymbolMatch(
[In] ulong Handle,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize, [Out] out uint MatchSize,
[Out] out ulong Offset);
void EndSymbolMatch(
[In] ulong Handle);
void Reload(
[In, MarshalAs(UnmanagedType.LPStr)] string Module);
void GetSymbolPath(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint PathSize);
void SetSymbolPath(
[In, MarshalAs(UnmanagedType.LPStr)] string Path);
void AppendSymbolPath(
[In, MarshalAs(UnmanagedType.LPStr)] string Addition);
void GetImagePath(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint PathSize);
void SetImagePath(
[In, MarshalAs(UnmanagedType.LPStr)] string Path);
void AppendImagePath(
[In, MarshalAs(UnmanagedType.LPStr)] string Addition);
void GetSourcePath(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint PathSize);
void GetSourcePathElement(
[In] uint Index,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint ElementSize);
void SetSourcePath(
[In, MarshalAs(UnmanagedType.LPStr)] string Path);
void AppendSourcePath(
[In, MarshalAs(UnmanagedType.LPStr)] string Addition);
void FindSourceFile(
[In] uint StartElement,
[In, MarshalAs(UnmanagedType.LPStr)] string File,
[In] uint Flags,
[Out] out uint FoundElement,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint FoundSize);
void GetSourceFileLineOffsets(
[In, MarshalAs(UnmanagedType.LPStr)] string File,
[Out] out ulong Buffer,
[In] uint BufferLines,
[Out] out uint FileLines);
}
}
| |
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Areas.Admin.ViewModels.Campaign;
using AllReady.Extensions;
using AllReady.Models;
using AllReady.Security;
using AllReady.Services;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using AllReady.Constants;
using AllReady.ViewModels.Campaign;
namespace AllReady.Areas.Admin.Controllers
{
[Area(AreaNames.Admin)]
[Authorize]
public class CampaignController : Controller
{
public Func<DateTime> DateTimeNow = () => DateTime.Now;
private readonly IMediator _mediator;
private readonly IImageService _imageService;
public CampaignController(IMediator mediator, IImageService imageService)
{
_mediator = mediator;
_imageService = imageService;
}
// GET: Campaign
[Authorize(nameof(UserType.OrgAdmin))]
public async Task<IActionResult> Index()
{
var query = new IndexQuery();
if (User.IsUserType(UserType.OrgAdmin))
{
query.OrganizationId = User.GetOrganizationId();
}
return View(await _mediator.SendAsync(query));
}
public async Task<IActionResult> Details(int id)
{
var viewModel = await _mediator.SendAsync(new CampaignDetailQuery { CampaignId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(viewModel.Id));
if (!await authorizableCampaign.UserCanView())
{
return new ForbidResult();
}
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CampaignPreview(CampaignSummaryViewModel campaign, IFormFile fileUpload)
{
return PartialView("_CampaignPreview", new CampaignViewModel(campaign));
}
// GET: Campaign/Create
[Authorize(nameof(UserType.OrgAdmin))]
public IActionResult Create()
{
return View("Edit", new CampaignSummaryViewModel
{
StartDate = DateTimeNow(),
EndDate = DateTimeNow().AddMonths(1),
TimeZoneId = User.GetTimeZoneId()
});
}
// GET: Campaign/Edit/5
public async Task<IActionResult> Edit(int id)
{
var viewModel = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(viewModel.Id));
if (!await authorizableCampaign.UserCanView())
{
return new ForbidResult();
}
return View(viewModel);
}
// POST: Campaign/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CampaignSummaryViewModel campaign, IFormFile fileUpload)
{
if (campaign == null)
{
return BadRequest();
}
if (campaign.Id == 0)
{
if (!User.IsOrganizationAdmin(campaign.OrganizationId))
{
return new ForbidResult();
}
}
else
{
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id));
if (!await authorizableCampaign.UserCanEdit())
{
return new ForbidResult();
}
}
if (campaign.EndDate < campaign.StartDate)
{
ModelState.AddModelError(nameof(campaign.EndDate), "The end date must fall on or after the start date.");
}
if (ModelState.IsValid)
{
if (fileUpload != null)
{
if (fileUpload.IsAcceptableImageContentType())
{
var existingImageUrl = campaign.ImageUrl;
var newImageUrl = await _imageService.UploadCampaignImageAsync(campaign.OrganizationId, campaign.Id, fileUpload);
if (!string.IsNullOrEmpty(newImageUrl))
{
campaign.ImageUrl = newImageUrl;
if (existingImageUrl != null && existingImageUrl != newImageUrl)
{
await _imageService.DeleteImageAsync(existingImageUrl);
}
}
}
else
{
ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)");
return View(campaign);
}
}
var id = await _mediator.SendAsync(new EditCampaignCommand { Campaign = campaign });
return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id });
}
return View(campaign);
}
// GET: Campaign/Delete/5
public async Task<IActionResult> Delete(int id)
{
var viewModel = await _mediator.SendAsync(new DeleteViewModelQuery { CampaignId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableOrganization = await _mediator.SendAsync(new Features.Organizations.AuthorizableOrganizationQuery(viewModel.OrganizationId));
if (!await authorizableOrganization.UserCanDelete())
{
return new ForbidResult();
}
viewModel.Title = $"Delete campaign {viewModel.Name}";
return View(viewModel);
}
// POST: Campaign/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var viewModel = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = id });
var authorizableOrganization = await _mediator.SendAsync(new Features.Organizations.AuthorizableOrganizationQuery(viewModel.OrganizationId));
if (!await authorizableOrganization.UserCanDelete())
{
return new ForbidResult();
}
await _mediator.SendAsync(new DeleteCampaignCommand { CampaignId = id });
return RedirectToAction(nameof(Index), new { area = AreaNames.Admin });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> DeleteCampaignImage(int campaignId)
{
var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = campaignId });
if (campaign == null)
{
return Json(new { status = "NotFound" });
}
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id));
if (!await authorizableCampaign.UserCanEdit())
{
return Json(new { status = "Unauthorized" });
}
if (campaign.EndDate < campaign.StartDate)
{
return Json(new { status = "DateInvalid", message = "The end date must fall on or after the start date." });
}
if (campaign.ImageUrl != null)
{
await _imageService.DeleteImageAsync(campaign.ImageUrl);
campaign.ImageUrl = null;
await _mediator.SendAsync(new EditCampaignCommand { Campaign = campaign });
return Json(new { status = "Success" });
}
return Json(new { status = "NothingToDelete" });
}
public async Task<IActionResult> Publish(int id)
{
var viewModel = await _mediator.SendAsync(new PublishViewModelQuery { CampaignId = id });
if (viewModel == null)
{
return NotFound();
}
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(viewModel.Id));
if (!await authorizableCampaign.UserCanView())
{
return new ForbidResult();
}
viewModel.Title = $"Publish campaign {viewModel.Name}";
viewModel.UserIsOrgAdmin = true;
return View(viewModel);
}
// POST: Campaign/Publish/5
[HttpPost, ActionName("Publish")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> PublishConfirmed(PublishViewModel viewModel)
{
var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(viewModel.Id));
if (!await authorizableCampaign.UserCanEdit())
{
return new ForbidResult();
}
await _mediator.SendAsync(new PublishCampaignCommand { CampaignId = viewModel.Id });
return RedirectToAction(nameof(Index), new { area = AreaNames.Admin });
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(nameof(UserType.OrgAdmin))]
public async Task<IActionResult> LockUnlock(int id)
{
if (!User.IsUserType(UserType.SiteAdmin))
{
return new ForbidResult();
}
await _mediator.SendAsync(new LockUnlockCampaignCommand { CampaignId = id });
return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id });
}
}
}
| |
using System.Data;
using System.Data.SqlClient;
using Appleseed.Framework.Settings;
namespace Appleseed.Framework.Content.Data
{
/// <summary>
/// DiscussionDB Class
///
/// Class that encapsulates all data logic necessary to add/query/delete
/// discussions within the Portal database.
/// </summary>
public class DiscussionDB
{
/// <summary>
/// GetTopLevelMessages Method
/// Returns details for all of the messages in the discussion specified by ModuleID.
/// Other relevant sources:
/// + <a href="GetTopLevelMessages.htm" style="color:green">GetTopLevelMessages Stored Procedure</a>
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns></returns>
public SqlDataReader GetTopLevelMessages(int moduleID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionGetTopLevelMessages", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.Parameters.Add(parameterModuleID);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return result;
}
/// <summary>
/// GetThreadMessages Method
/// Returns details for all of the messages the thread, as identified by the Parent id string.
/// displayOrder csan be the full display order of any post, it will be truncated
/// by the stored procedure to find the root of the thread, and then all children
/// are returned
/// Other relevant sources:
/// + <a href="GetThreadMessages.htm" style="color:green">GetThreadMessages Stored Procedure</a>
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <param name="showRoot">The show root.</param>
/// <returns></returns>
public SqlDataReader GetThreadMessages(int itemID, char showRoot)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionGetThreadMessages", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterParent = new SqlParameter("@ItemID", SqlDbType.NVarChar, 750);
parameterParent.Value = itemID;
myCommand.Parameters.Add(parameterParent);
// Add Parameters to SPROC
SqlParameter parameterShowRoot = new SqlParameter("@IncludeRoot", SqlDbType.Char);
parameterShowRoot.Value = showRoot;
myCommand.Parameters.Add(parameterShowRoot);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return result;
}
/// <summary>
/// Deletes the single message.
/// </summary>
/// <param name="itemID">The item ID.</param>
public void DeleteSingleMessage(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionDeleteMessage", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return;
}
/// <summary>
/// Increments the view count.
/// </summary>
/// <param name="itemID">The item ID.</param>
public void IncrementViewCount(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionIncrementViewCount", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return;
}
/// <summary>
/// Deletes the children.
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <returns></returns>
public int DeleteChildren(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionDeleteChildren", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
SqlParameter parameterNumDeletedMessages = new SqlParameter("@NumDeletedMessages", SqlDbType.Int, 4);
parameterNumDeletedMessages.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterNumDeletedMessages);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return (int) parameterNumDeletedMessages.Value;
}
/// <summary>
/// GetSingleMessage Method
/// The GetSingleMessage method returns the details for the message
/// specified by the itemID parameter.
/// Other relevant sources:
/// + <a href="GetSingleMessage.htm" style="color:green">GetSingleMessage Stored Procedure</a>
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <returns></returns>
public SqlDataReader GetSingleMessage(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionGetMessage", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return result;
}
/// <summary>
/// AddMessage Method
/// The AddMessage method adds a new message within the
/// Discussions database table, and returns ItemID value as a result.
/// Other relevant sources:
/// + <a href="AddMessage.htm" style="color:green">AddMessage Stored Procedure</a>
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <param name="parentID">The parent ID.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="title">The title.</param>
/// <param name="body">The body.</param>
/// <param name="mode">The mode.</param>
/// <returns></returns>
public int AddMessage(int moduleID, int parentID, string userName, string title, string body, string mode)
{
/* ParentID = actual ItemID if this is an edit operation */
if (userName.Length < 1)
{
userName = "unknown";
}
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DiscussionAddMessage", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterMode = new SqlParameter("@Mode", SqlDbType.Text, 20);
parameterMode.Value = mode;
myCommand.Parameters.Add(parameterMode);
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterItemID);
SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
parameterTitle.Value = title;
myCommand.Parameters.Add(parameterTitle);
SqlParameter parameterBody = new SqlParameter("@Body", SqlDbType.NVarChar, 3000);
parameterBody.Value = body;
myCommand.Parameters.Add(parameterBody);
SqlParameter parameterParentID = new SqlParameter("@ParentID", SqlDbType.Int, 4);
parameterParentID.Value = parentID;
myCommand.Parameters.Add(parameterParentID);
SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
parameterUserName.Value = userName;
myCommand.Parameters.Add(parameterUserName);
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.Parameters.Add(parameterModuleID);
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
return (int) parameterItemID.Value;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet enters into an interactive session with the specified local process by
/// creating a remote runspace to the process and pushing it on the current PSHost.
/// If the selected process does not contain PowerShell then an error message will result.
/// If the current user does not have sufficient privileges to attach to the selected process
/// then an error message will result.
/// </summary>
[Cmdlet(VerbsCommon.Enter, "PSHostProcess", DefaultParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096580")]
public sealed class EnterPSHostProcessCommand : PSCmdlet
{
#region Members
private IHostSupportsInteractiveSession _interactiveHost;
private RemoteRunspace _connectingRemoteRunspace;
#region Strings
private const string ProcessParameterSet = "ProcessParameterSet";
private const string ProcessNameParameterSet = "ProcessNameParameterSet";
private const string ProcessIdParameterSet = "ProcessIdParameterSet";
private const string PipeNameParameterSet = "PipeNameParameterSet";
private const string PSHostProcessInfoParameterSet = "PSHostProcessInfoParameterSet";
private const string NamedPipeRunspaceName = "PSAttachRunspace";
#endregion
#endregion
#region Parameters
/// <summary>
/// Process to enter.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.ProcessParameterSet)]
[ValidateNotNull()]
public Process Process
{
get;
set;
}
/// <summary>
/// Id of process to enter.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet)]
[ValidateRange(0, int.MaxValue)]
public int Id
{
get;
set;
}
/// <summary>
/// Name of process to enter. An error will result if more than one such process exists.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.ProcessNameParameterSet)]
[ValidateNotNullOrEmpty()]
public string Name
{
get;
set;
}
/// <summary>
/// Host Process Info object that describes a connectible process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.PSHostProcessInfoParameterSet)]
[ValidateNotNull()]
public PSHostProcessInfo HostProcessInfo
{
get;
set;
}
/// <summary>
/// Gets or sets the custom named pipe name to connect to. This is usually used in conjunction with `pwsh -CustomPipeName`.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.PipeNameParameterSet)]
public string CustomPipeName
{
get;
set;
}
/// <summary>
/// Optional name of AppDomain in process to enter. If not specified then the default AppDomain is used.
/// </summary>
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessNameParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.PSHostProcessInfoParameterSet)]
[ValidateNotNullOrEmpty]
public string AppDomainName
{
get;
set;
}
#endregion
#region Overrides
/// <summary>
/// End Processing.
/// </summary>
protected override void EndProcessing()
{
// Check if system is in locked down mode, in which case this cmdlet is disabled.
if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
{
WriteError(
new ErrorRecord(
new PSSecurityException(RemotingErrorIdStrings.EnterPSHostProcessCmdletDisabled),
"EnterPSHostProcessCmdletDisabled",
ErrorCategory.SecurityError,
null));
return;
}
// Check for host that supports interactive remote sessions.
_interactiveHost = this.Host as IHostSupportsInteractiveSession;
if (_interactiveHost == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
"EnterPSHostProcessHostDoesNotSupportIASession",
ErrorCategory.InvalidArgument,
null));
return;
}
// Check selected process for existence, and whether it hosts PowerShell.
Runspace namedPipeRunspace = null;
switch (ParameterSetName)
{
case ProcessIdParameterSet:
Process = GetProcessById(Id);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case ProcessNameParameterSet:
Process = GetProcessByName(Name);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case PSHostProcessInfoParameterSet:
Process = GetProcessByHostProcessInfo(HostProcessInfo);
VerifyProcess(Process);
// Create named pipe runspace for selected process and open.
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case PipeNameParameterSet:
VerifyPipeName(CustomPipeName);
namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName);
break;
}
// Set runspace prompt. The runspace is closed on pop so we don't
// have to reverse this change.
PrepareRunspace(namedPipeRunspace);
try
{
// Push runspace onto host.
_interactiveHost.PushRunspace(namedPipeRunspace);
}
catch (Exception e)
{
namedPipeRunspace.Close();
ThrowTerminatingError(
new ErrorRecord(
e,
"EnterPSHostProcessCannotPushRunspace",
ErrorCategory.InvalidOperation,
this));
}
}
/// <summary>
/// Stop Processing.
/// </summary>
protected override void StopProcessing()
{
RemoteRunspace connectingRunspace = _connectingRemoteRunspace;
if (connectingRunspace != null)
{
connectingRunspace.AbortOpen();
}
}
#endregion
#region Private Methods
private Runspace CreateNamedPipeRunspace(string customPipeName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(customPipeName);
return CreateNamedPipeRunspace(connectionInfo);
}
private Runspace CreateNamedPipeRunspace(int procId, string appDomainName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(procId, appDomainName);
return CreateNamedPipeRunspace(connectionInfo);
}
private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo)
{
TypeTable typeTable = TypeTable.LoadDefaultTypeFiles();
RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, this.Host, typeTable) as RemoteRunspace;
remoteRunspace.Name = NamedPipeRunspaceName;
remoteRunspace.ShouldCloseOnPop = true;
_connectingRemoteRunspace = remoteRunspace;
try
{
remoteRunspace.Open();
remoteRunspace.Debugger?.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
}
catch (RuntimeException e)
{
// Unwrap inner exception for original error message, if any.
string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty;
if (connectionInfo.CustomPipeName != null)
{
ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToPipe,
connectionInfo.CustomPipeName,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToPipe",
ErrorCategory.OperationTimeout,
this));
}
else
{
string msgAppDomainName = connectionInfo.AppDomainName ?? NamedPipeUtils.DefaultAppDomainName;
ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
msgAppDomainName,
connectionInfo.ProcessId,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToProcess",
ErrorCategory.OperationTimeout,
this));
}
}
finally
{
_connectingRemoteRunspace = null;
}
return remoteRunspace;
}
private static void PrepareRunspace(Runspace runspace)
{
string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessPrompt,
@"function global:prompt { """,
@"$($PID)",
@"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }"
);
// Set prompt in pushed named pipe runspace.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.Runspace = runspace;
try
{
// Set pushed runspace prompt.
ps.AddScript(promptFn).Invoke();
}
catch (Exception)
{
}
}
}
private Process GetProcessById(int procId)
{
var process = PSHostProcessUtils.GetProcessById(procId);
if (process is null)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithId, procId)),
"EnterPSHostProcessNoProcessFoundWithId",
ErrorCategory.InvalidArgument,
this)
);
}
return process;
}
private Process GetProcessByHostProcessInfo(PSHostProcessInfo hostProcessInfo)
{
return GetProcessById(hostProcessInfo.ProcessId);
}
private Process GetProcessByName(string name)
{
Collection<Process> foundProcesses;
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
ps.AddCommand("Get-Process").AddParameter("Name", name);
foundProcesses = ps.Invoke<Process>();
}
if (foundProcesses.Count == 0)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithName, name)),
"EnterPSHostProcessNoProcessFoundWithName",
ErrorCategory.InvalidArgument,
this)
);
}
else if (foundProcesses.Count > 1)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessMultipleProcessesFoundWithName, name)),
"EnterPSHostProcessMultipleProcessesFoundWithName",
ErrorCategory.InvalidArgument,
this)
);
}
return foundProcesses[0];
}
private void VerifyProcess(Process process)
{
if (process.Id == Environment.ProcessId)
{
ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(RemotingErrorIdStrings.EnterPSHostProcessCantEnterSameProcess),
"EnterPSHostProcessCantEnterSameProcess",
ErrorCategory.InvalidOperation,
this)
);
}
bool hostsSMA = false;
IReadOnlyCollection<PSHostProcessInfo> availableProcInfo = GetPSHostProcessInfoCommand.GetAppDomainNamesFromProcessId(null);
foreach (var procInfo in availableProcInfo)
{
if (process.Id == procInfo.ProcessId)
{
hostsSMA = true;
break;
}
}
if (!hostsSMA)
{
ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoPowerShell, Process.Id)),
"EnterPSHostProcessNoPowerShell",
ErrorCategory.InvalidOperation,
this)
);
}
}
private void VerifyPipeName(string customPipeName)
{
// Named Pipes are represented differently on Windows vs macOS & Linux
var sb = new StringBuilder(customPipeName.Length);
if (Platform.IsWindows)
{
sb.Append(@"\\.\pipe\");
}
else
{
sb.Append(Path.GetTempPath()).Append("CoreFxPipe_");
}
sb.Append(customPipeName);
string pipePath = sb.ToString();
if (!File.Exists(pipePath))
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoNamedPipeFound, customPipeName)),
"EnterPSHostProcessNoNamedPipeFound",
ErrorCategory.InvalidArgument,
this));
}
}
#endregion
}
/// <summary>
/// This cmdlet exits an interactive session with a local process.
/// </summary>
[Cmdlet(VerbsCommon.Exit, "PSHostProcess",
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096583")]
public sealed class ExitPSHostProcessCommand : PSCmdlet
{
#region Overrides
/// <summary>
/// Process Record.
/// </summary>
protected override void ProcessRecord()
{
var _interactiveHost = this.Host as IHostSupportsInteractiveSession;
if (_interactiveHost == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
"ExitPSHostProcessHostDoesNotSupportIASession",
ErrorCategory.InvalidArgument,
null));
return;
}
_interactiveHost.PopRunspace();
}
#endregion
}
/// <summary>
/// This cmdlet returns a collection of PSHostProcessInfo objects containing
/// process and AppDomain name information for processes that have PowerShell loaded.
/// </summary>
[Cmdlet(VerbsCommon.Get, "PSHostProcessInfo", DefaultParameterSetName = GetPSHostProcessInfoCommand.ProcessNameParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=517012")]
[OutputType(typeof(PSHostProcessInfo))]
public sealed class GetPSHostProcessInfoCommand : PSCmdlet
{
#region Strings
private const string ProcessParameterSet = "ProcessParameterSet";
private const string ProcessIdParameterSet = "ProcessIdParameterSet";
private const string ProcessNameParameterSet = "ProcessNameParameterSet";
#if UNIX
// CoreFx uses the system temp path to store the file used for named pipes and is not settable.
// This member is only used by Get-PSHostProcessInfo to know where to look for the named pipe files.
private static readonly string NamedPipePath = Path.GetTempPath();
#else
private const string NamedPipePath = @"\\.\pipe\";
#endif
#endregion
#region Parameters
/// <summary>
/// Name of Process.
/// </summary>
[Parameter(Position = 0, ParameterSetName = GetPSHostProcessInfoCommand.ProcessNameParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty()]
public string[] Name
{
get;
set;
}
/// <summary>
/// Process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty()]
public Process[] Process
{
get;
set;
}
/// <summary>
/// Id of process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessIdParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty()]
public int[] Id
{
get;
set;
}
#endregion
#region Overrides
/// <summary>
/// End bock processing.
/// </summary>
protected override void EndProcessing()
{
IReadOnlyCollection<PSHostProcessInfo> processAppDomainInfo;
switch (ParameterSetName)
{
case ProcessNameParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(GetProcIdsFromNames(Name));
break;
case ProcessIdParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(Id);
break;
case ProcessParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(GetProcIdsFromProcs(Process));
break;
default:
Debug.Fail("Unknown parameter set.");
processAppDomainInfo = new ReadOnlyCollection<PSHostProcessInfo>(new Collection<PSHostProcessInfo>());
break;
}
WriteObject(processAppDomainInfo, true);
}
#endregion
#region Private Methods
private static int[] GetProcIdsFromProcs(Process[] processes)
{
List<int> returnIds = new List<int>();
foreach (Process process in processes)
{
returnIds.Add(process.Id);
}
return returnIds.ToArray();
}
private static int[] GetProcIdsFromNames(string[] names)
{
if ((names == null) || (names.Length == 0))
{
return null;
}
List<int> returnIds = new List<int>();
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
foreach (string name in names)
{
WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase);
foreach (var proc in processes)
{
// Skip processes that have already terminated.
if (proc.HasExited)
{
continue;
}
try
{
if (namePattern.IsMatch(proc.ProcessName))
{
returnIds.Add(proc.Id);
}
}
catch (InvalidOperationException)
{
// Ignore if process has exited in the mean time.
}
}
}
return returnIds.ToArray();
}
#endregion
#region Internal Methods
/// <summary>
/// Returns all named pipe AppDomain names for given process Ids or all PowerShell
/// processes if procIds parameter is null.
/// PowerShell pipe name example:
/// PSHost.130566795082911445.8224.DefaultAppDomain.powershell.
/// </summary>
/// <param name="procIds">Process Ids or null.</param>
/// <returns>Collection of process AppDomain info.</returns>
internal static IReadOnlyCollection<PSHostProcessInfo> GetAppDomainNamesFromProcessId(int[] procIds)
{
var procAppDomainInfo = new List<PSHostProcessInfo>();
// Get all named pipe 'files' on local machine.
List<string> namedPipes = new List<string>();
var namedPipeDirectory = new DirectoryInfo(NamedPipePath);
foreach (var pipeFileInfo in namedPipeDirectory.EnumerateFiles(NamedPipeUtils.NamedPipeNamePrefixSearch))
{
namedPipes.Add(Path.Combine(pipeFileInfo.DirectoryName, pipeFileInfo.Name));
}
// Collect all PowerShell named pipes for given process Ids.
foreach (string namedPipe in namedPipes)
{
int startIndex = namedPipe.IndexOf(NamedPipeUtils.NamedPipeNamePrefix, StringComparison.OrdinalIgnoreCase);
if (startIndex > -1)
{
int pStartTimeIndex = namedPipe.IndexOf('.', startIndex);
if (pStartTimeIndex > -1)
{
int pIdIndex = namedPipe.IndexOf('.', pStartTimeIndex + 1);
if (pIdIndex > -1)
{
int pAppDomainIndex = namedPipe.IndexOf('.', pIdIndex + 1);
if (pAppDomainIndex > -1)
{
ReadOnlySpan<char> idString = namedPipe.AsSpan(pIdIndex + 1, (pAppDomainIndex - pIdIndex - 1));
int id = -1;
if (int.TryParse(idString, out id))
{
// Filter on provided proc Ids.
if (procIds != null)
{
bool found = false;
foreach (int procId in procIds)
{
if (id == procId)
{
found = true;
break;
}
}
if (!found) { continue; }
}
}
else
{
// Process id is not valid so we'll skip
continue;
}
int pNameIndex = namedPipe.IndexOf('.', pAppDomainIndex + 1);
if (pNameIndex > -1)
{
string appDomainName = namedPipe.Substring(pAppDomainIndex + 1, (pNameIndex - pAppDomainIndex - 1));
string pName = namedPipe.Substring(pNameIndex + 1);
Process process = null;
try
{
process = PSHostProcessUtils.GetProcessById(id);
}
catch (Exception)
{
// Do nothing if the process no longer exists
}
if (process == null)
{
try
{
// If the process is gone, try removing the PSHost named pipe
var pipeFile = new FileInfo(namedPipe);
pipeFile.Delete();
}
catch (Exception)
{
// best effort to cleanup
}
}
else
{
try
{
if (process.ProcessName.Equals(pName, StringComparison.Ordinal))
{
// only add if the process name matches
procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe));
}
}
catch (InvalidOperationException)
{
// Ignore if process has exited in the mean time.
}
}
}
}
}
}
}
}
if (procAppDomainInfo.Count > 1)
{
// Sort list by process name.
var comparerInfo = CultureInfo.InvariantCulture.CompareInfo;
procAppDomainInfo.Sort((firstItem, secondItem) => comparerInfo.Compare(firstItem.ProcessName, secondItem.ProcessName, CompareOptions.IgnoreCase));
}
return new ReadOnlyCollection<PSHostProcessInfo>(procAppDomainInfo);
}
#endregion
}
#region PSHostProcessInfo class
/// <summary>
/// PowerShell host process information class.
/// </summary>
public sealed class PSHostProcessInfo
{
#region Members
private readonly string _pipeNameFilePath;
#endregion
#region Properties
/// <summary>
/// Name of process.
/// </summary>
public string ProcessName { get; }
/// <summary>
/// Id of process.
/// </summary>
public int ProcessId { get; }
/// <summary>
/// Name of PowerShell AppDomain in process.
/// </summary>
public string AppDomainName { get; }
/// <summary>
/// Main window title of the process.
/// </summary>
public string MainWindowTitle { get; }
#endregion
#region Constructors
private PSHostProcessInfo() { }
/// <summary>
/// Initializes a new instance of the PSHostProcessInfo type.
/// </summary>
/// <param name="processName">Name of process.</param>
/// <param name="processId">Id of process.</param>
/// <param name="appDomainName">Name of process AppDomain.</param>
/// <param name="pipeNameFilePath">File path of pipe name.</param>
internal PSHostProcessInfo(
string processName,
int processId,
string appDomainName,
string pipeNameFilePath)
{
if (string.IsNullOrEmpty(processName))
{
throw new PSArgumentNullException(nameof(processName));
}
if (string.IsNullOrEmpty(appDomainName))
{
throw new PSArgumentNullException(nameof(appDomainName));
}
MainWindowTitle = string.Empty;
try
{
var process = PSHostProcessUtils.GetProcessById(processId);
MainWindowTitle = process?.MainWindowTitle ?? string.Empty;
}
catch (ArgumentException)
{
// Window title is optional.
}
catch (InvalidOperationException)
{
// Window title is optional.
}
this.ProcessName = processName;
this.ProcessId = processId;
this.AppDomainName = appDomainName;
_pipeNameFilePath = pipeNameFilePath;
}
#endregion
#region Methods
/// <summary>
/// Retrieves the pipe name file path.
/// </summary>
/// <returns>Pipe name file path.</returns>
public string GetPipeNameFilePath()
{
return _pipeNameFilePath;
}
#endregion
}
#endregion
#region PSHostProcessUtils
internal static class PSHostProcessUtils
{
/// <summary>
/// Return a System.Diagnostics.Process object by process Id,
/// or null if not found or process has exited.
/// </summary>
/// <param name="procId">Process of Id to find.</param>
/// <returns>Process object or null.</returns>
public static Process GetProcessById(int procId)
{
try
{
var process = Process.GetProcessById(procId);
return process.HasExited ? null : process;
}
catch (System.ArgumentException)
{
return null;
}
}
}
#endregion
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Anima2D
{
public static class BoneUtils
{
public static string GetUniqueBoneName(Bone2D root)
{
string boneName = "bone";
Bone2D[] bones = null;
if(root)
{
bones = root.GetComponentsInChildren<Bone2D>(true);
boneName = boneName + " " + (bones.Length + 1).ToString();
}
return boneName;
}
public static void DrawBoneCap(Bone2D bone)
{
Color color = bone.color * 0.25f;
color.a = 1f;
DrawBoneCap(bone, color);
}
public static void DrawBoneCap(Bone2D bone, Color color)
{
Handles.matrix = bone.transform.localToWorldMatrix;
DrawBoneCap(Vector3.zero,GetBoneRadius(bone),color);
}
public static void DrawBoneCap(Vector3 position, float radius, Color color)
{
Handles.color = color;
HandlesExtra.DrawCircle(position, radius*0.65f);
}
public static void DrawBoneBody(Bone2D bone)
{
DrawBoneBody(bone,bone.color);
}
public static void DrawBoneBody(Bone2D bone, Color color)
{
Handles.matrix = bone.transform.localToWorldMatrix;
DrawBoneBody(Vector3.zero, bone.localEndPosition, GetBoneRadius(bone),color);
}
public static void DrawBoneBody(Vector3 position, Vector3 endPosition, float radius, Color color)
{
Vector3 distance = position - endPosition;
if(distance.magnitude > radius && color.a > 0f)
{
HandlesExtra.DrawLine(position,endPosition,Vector3.back,2f*radius,0f,color);
HandlesExtra.DrawSolidArc(position,Vector3.back,Vector3.Cross(endPosition-position,Vector3.forward),180f,radius,color);
}
}
public static void DrawBoneOutline(Bone2D bone, float outlineSize, Color color)
{
Handles.matrix = bone.transform.localToWorldMatrix;
DrawBoneOutline(Vector3.zero,
bone.localEndPosition,
GetBoneRadius(bone),
outlineSize / Handles.matrix.GetScale().x,
color);
}
public static void DrawBoneOutline(Vector3 position, Vector3 endPoint, float radius, float outlineSize, Color color)
{
Handles.color = color;
HandlesExtra.DrawLine(position,endPoint,Vector3.back, 2f * (radius + outlineSize), 2f * outlineSize);
HandlesExtra.DrawSolidArc(position,Vector3.forward,Vector3.Cross(endPoint-position,Vector3.back),180f,radius + outlineSize,color);
if(outlineSize > 0f)
{
HandlesExtra.DrawSolidArc(endPoint,Vector3.back,Vector3.Cross(endPoint-position,Vector3.back),180f,outlineSize,color);
}
}
public static float GetBoneRadius(Bone2D bone)
{
return Mathf.Min(bone.localLength / 20f, 0.125f * HandleUtility.GetHandleSize(bone.transform.position));
}
public static string GetBonePath(Bone2D bone)
{
return GetBonePath(bone.root.transform,bone);
}
public static string GetBonePath(Transform root, Bone2D bone)
{
return GetPath(root, bone.transform);
}
public static string GetPath(Transform root, Transform transform)
{
string path = "";
Transform current = transform;
if(root)
{
while(current && current != root)
{
path = current.name + path;
current = current.parent;
if(current != root)
{
path = "/" + path;
}
}
if(!current)
{
path = "";
}
}
return path;
}
public static Bone2D ReconstructHierarchy(List<Bone2D> bones, List<string> paths)
{
Bone2D rootBone = null;
for (int i = 0; i < bones.Count; i++)
{
Bone2D bone = bones[i];
string path = paths[i];
for (int j = 0; j < bones.Count; j++)
{
Bone2D other = bones [j];
string otherPath = paths[j];
if(bone != other && !path.Equals(otherPath) && otherPath.Contains(path))
{
other.transform.parent = bone.transform;
other.transform.localScale = Vector3.one;
}
}
}
for (int i = 0; i < bones.Count; i++)
{
Bone2D bone = bones[i];
if(bone.parentBone)
{
if((bone.transform.position - bone.parentBone.endPosition).sqrMagnitude < 0.00001f)
{
bone.parentBone.child = bone;
}
}else{
rootBone = bone;
}
}
return rootBone;
}
public static void OrientToChild(Bone2D bone, bool freezeChildren, string undoName, bool recordObject)
{
if(!bone || !bone.child) return;
Vector3 l_childPosition = Vector3.zero;
/*
if(recordObject)
{
Undo.RecordObject(bone.child.transform,undoName);
}else{
Undo.RegisterCompleteObjectUndo(bone.child.transform,undoName);
}
*/
l_childPosition = bone.child.transform.position;
Quaternion l_deltaRotation = OrientToLocalPosition(bone,bone.child.transform.localPosition,freezeChildren,undoName,recordObject);
bone.child.transform.position = l_childPosition;
bone.child.transform.localRotation *= Quaternion.Inverse(l_deltaRotation);
EditorUtility.SetDirty(bone.child.transform);
}
public static Quaternion OrientToLocalPosition(Bone2D bone, Vector3 localPosition, bool freezeChildren, string undoName, bool recordObject)
{
Quaternion l_deltaRotation = Quaternion.identity;
if(bone && localPosition.sqrMagnitude > 0f)
{
List<Vector3> l_childPositions = new List<Vector3>(bone.transform.childCount);
List<Transform> l_children = new List<Transform>(bone.transform.childCount);
if(freezeChildren)
{
Transform l_mainChild = null;
if(bone.child)
{
l_mainChild = bone.child.transform;
}
foreach(Transform child in bone.transform)
{
if(child != l_mainChild)
{
if(recordObject)
{
Undo.RecordObject(child,undoName);
}else{
Undo.RegisterCompleteObjectUndo(child,undoName);
}
l_children.Add(child);
l_childPositions.Add(child.position);
}
}
}
Quaternion l_deltaInverseRotation = Quaternion.identity;
float angle = Mathf.Atan2(localPosition.y,localPosition.x) * Mathf.Rad2Deg;
if(recordObject)
{
Undo.RecordObject(bone.transform,undoName);
}else{
Undo.RegisterCompleteObjectUndo(bone.transform,undoName);
}
l_deltaRotation = Quaternion.AngleAxis(angle, Vector3.forward);
l_deltaInverseRotation = Quaternion.Inverse(l_deltaRotation);
bone.transform.localRotation *= l_deltaRotation;
FixLocalEulerHint(bone.transform);
for (int i = 0; i < l_children.Count; i++)
{
Transform l_child = l_children[i];
l_child.position = l_childPositions[i];
l_child.localRotation *= l_deltaInverseRotation;
FixLocalEulerHint(l_child);
EditorUtility.SetDirty (l_child);
}
EditorUtility.SetDirty(bone.transform);
}
return l_deltaRotation;
}
static Type s_TransformType = typeof(Transform);
static bool s_Initialized = false;
static MethodInfo s_SetLocalEulerHintMethod = null;
static MethodInfo s_GetLocalEulerAnglesMethod = null;
static PropertyInfo s_GetRotationOrderProperty = null;
static void InitializeReflection()
{
if(!s_Initialized)
{
if(s_SetLocalEulerHintMethod == null)
{
s_SetLocalEulerHintMethod = s_TransformType.GetMethod("SetLocalEulerHint",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
if(s_GetLocalEulerAnglesMethod == null)
{
s_GetLocalEulerAnglesMethod = s_TransformType.GetMethod("GetLocalEulerAngles",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
if(s_GetRotationOrderProperty == null)
{
s_GetRotationOrderProperty = s_TransformType.GetProperty("rotationOrder",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
s_Initialized = true;
}
}
public static void FixLocalEulerHint(Transform transform)
{
InitializeReflection();
if(transform && s_SetLocalEulerHintMethod != null)
{
object[] parameters = { GetLocalEulerAngles(transform) };
s_SetLocalEulerHintMethod.Invoke(transform,parameters);
}
}
public static Vector3 GetLocalEulerAngles(Transform transform)
{
InitializeReflection();
object rotationOrder = GetRotationOrder(transform);
if(transform && s_GetLocalEulerAnglesMethod != null && rotationOrder != null)
{
object[] parameters = { rotationOrder };
return (Vector3) s_GetLocalEulerAnglesMethod.Invoke(transform,parameters);
}
return Vector3.zero;
}
static object GetRotationOrder(Transform transform)
{
InitializeReflection();
if(transform && s_GetRotationOrderProperty != null)
{
return s_GetRotationOrderProperty.GetValue(transform, null);
}
return null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace System.Resources
{
public sealed class ResourceReader : IDisposable
{
private const int ResSetVersion = 2;
private const int ResourceTypeCodeString = 1;
private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE);
private const int ResourceManagerHeaderVersionNumber = 1;
private Stream _stream; // backing store we're reading from.
private long _nameSectionOffset; // Offset to name section of file.
private long _dataSectionOffset; // Offset to Data section of file.
private int[] _namePositions; // relative locations of names
private int _stringTypeIndex;
private int _numOfTypes;
private int _numResources; // Num of resources files, in case arrays aren't allocated.
private int _version;
// "System.String, mscorlib" representation in resources stream
private readonly static byte[] s_SystemStringName = EncodeStringName();
public ResourceReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
if (!stream.CanSeek)
throw new ArgumentException(SR.Argument_StreamNotSeekable);
_stream = stream;
ReadResources();
}
public void Dispose()
{
Dispose(true);
}
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void Dispose(bool disposing)
{
if (_stream != null) {
if (disposing) {
Stream stream = _stream;
_stream = null;
if (stream != null) {
stream.Dispose();
}
_namePositions = null;
}
}
}
private void SkipString()
{
int stringLength;
if (!_stream.TryReadInt327BitEncoded(out stringLength) || stringLength < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_stream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNamePosition(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
int r;
r = _namePositions[index];
if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesNameInvalidOffset + ":" + r);
}
return r;
}
public IDictionaryEnumerator GetEnumerator()
{
if (_stream == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
private void SuccessElseEosException(bool condition)
{
if (!condition) {
throw new EndOfStreamException();
}
}
private string GetKeyForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
var result = _stream.ReadString(utf16: true);
int dataOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataOffset));
if (dataOffset < 0 || dataOffset >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + " offset :" + dataOffset);
}
return result;
}
}
private string GetValueForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
int dataPos;
SuccessElseEosException(_stream.TryReadInt32(out dataPos));
if (dataPos < 0 || dataPos >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + dataPos);
}
try
{
return ReadStringElseNull(dataPos);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
}
//returns null if the resource is not a string
private string ReadStringElseNull(int pos)
{
_stream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex;
if(!_stream.TryReadInt327BitEncoded(out typeIndex)) {
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
if (_version == 1) {
if (typeIndex == -1 || !IsString(typeIndex)) {
return null;
}
}
else
{
if (ResourceTypeCodeString != typeIndex) {
return null;
}
}
return _stream.ReadString(utf16 : false);
}
private void ReadResources()
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
catch (IndexOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
private void _ReadResources()
{
// Read out the ResourceManager header
// Read out magic number
int magicNum;
SuccessElseEosException(_stream.TryReadInt32(out magicNum));
if (magicNum != ResourceManagerMagicNumber)
throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion;
SuccessElseEosException(_stream.TryReadInt32(out resMgrHeaderVersion));
//number of bytes to skip over to get past ResMgr header
int numBytesToSkip;
SuccessElseEosException(_stream.TryReadInt32(out numBytesToSkip));
if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
if (resMgrHeaderVersion > 1) {
_stream.Seek(numBytesToSkip, SeekOrigin.Current);
}
else {
// We don't care about numBytesToSkip; read the rest of the header
//Due to legacy : this field is always a variant of System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
//So we Skip the type name for resourcereader unlike Desktop
SkipString();
// Skip over type name for a suitable ResourceSet
SkipString();
}
// Read RuntimeResourceSet header
// Do file version check
SuccessElseEosException(_stream.TryReadInt32(out _version));
if (_version != ResSetVersion && _version != 1) {
throw new ArgumentException(SR.Arg_ResourceFileUnsupportedVersion + "Expected:" + ResSetVersion + "but got:" + _version);
}
// number of resources
SuccessElseEosException(_stream.TryReadInt32(out _numResources));
if (_numResources < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
SuccessElseEosException(_stream.TryReadInt32(out _numOfTypes));
if (_numOfTypes < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// find index of System.String
for (int i = 0; i < _numOfTypes; i++)
{
if(_stream.StartsWith(s_SystemStringName, advance : true)){
_stringTypeIndex = i;
}
}
// Prepare to read in the array of name hashes
// Note that the name hashes array is aligned to 8 bytes so
// we can use pointers into it on 64 bit machines. (4 bytes
// may be sufficient, but let's plan for the future)
// Skip over alignment stuff. All public .resources files
// should be aligned No need to verify the byte values.
long pos = _stream.Position;
int alignBytes = ((int)pos) & 7;
if (alignBytes != 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
{
_stream.ReadByte();
}
}
//Skip over the array of name hashes
for (int i = 0; i < _numResources; i++)
{
int hash;
SuccessElseEosException(_stream.TryReadInt32(out hash));
}
// Read in the array of relative positions for all the names.
_namePositions = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
int namePosition;
SuccessElseEosException(_stream.TryReadInt32(out namePosition));
if (namePosition < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
// Read location of data section.
int dataSectionOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataSectionOffset));
if (dataSectionOffset < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_dataSectionOffset = dataSectionOffset;
// Store current location as start of name section
_nameSectionOffset = _stream.Position;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
if (_dataSectionOffset < _nameSectionOffset)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
}
private bool IsString(int typeIndex)
{
if (typeIndex < 0 || typeIndex >= _numOfTypes)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
return typeIndex == _stringTypeIndex;
}
private static byte[] EncodeStringName()
{
var type = typeof(string);
var name = type.AssemblyQualifiedName;
int length = name.IndexOf(", Version=");
var buffer = new byte[length + 1];
var encoded = Encoding.UTF8.GetBytes(name, 0, length, buffer, 1);
// all characters should be single byte encoded and the type name shorter than 128 bytes
// this restriction is needed to encode without multiple allocations of the buffer
if (encoded > 127 || encoded != length)
{
throw new NotSupportedException();
}
checked { buffer[0] = (byte)encoded; }
return buffer;
}
internal sealed class ResourceEnumerator : IDictionaryEnumerator
{
private const int ENUM_DONE = Int32.MinValue;
private const int ENUM_NOT_STARTED = -1;
private ResourceReader _reader;
private bool _currentIsValid;
private int _currentName;
internal ResourceEnumerator(ResourceReader reader)
{
_currentName = ENUM_NOT_STARTED;
_reader = reader;
}
public bool MoveNext()
{
if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
{
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
}
_currentIsValid = true;
_currentName++;
return true;
}
public Object Key
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetKeyForNameIndex(_currentName);
}
}
public Object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
string key = _reader.GetKeyForNameIndex(_currentName);
string value = _reader.GetValueForNameIndex(_currentName);
return new DictionaryEntry(key, value);
}
}
public Object Value
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetValueForNameIndex(_currentName);
}
}
public void Reset()
{
if (_reader._stream == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
}
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
[TestFixture]
public class TestSurrogates : LuceneTestCase
{
/// <summary>
/// we will manually instantiate preflex-rw here
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
}
private static string MakeDifficultRandomUnicodeString(Random r)
{
int end = r.Next(20);
if (end == 0)
{
// allow 0 length
return "";
}
char[] buffer = new char[end];
for (int i = 0; i < end; i++)
{
int t = r.Next(5);
if (0 == t && i < end - 1)
{
// hi
buffer[i++] = (char)(0xd800 + r.Next(2));
// lo
buffer[i] = (char)(0xdc00 + r.Next(2));
}
else if (t <= 3)
{
buffer[i] = (char)('a' + r.Next(2));
}
else if (4 == t)
{
buffer[i] = (char)(0xe000 + r.Next(2));
}
}
return new string(buffer, 0, end);
}
private static string ToHexString(Term t)
{
return t.Field + ":" + UnicodeUtil.ToHexString(t.Text());
}
private string GetRandomString(Random r)
{
string s;
if (r.Next(5) == 1)
{
if (r.Next(3) == 1)
{
s = MakeDifficultRandomUnicodeString(r);
}
else
{
s = TestUtil.RandomUnicodeString(r);
}
}
else
{
s = TestUtil.RandomRealisticUnicodeString(r);
}
return s;
}
private sealed class SortTermAsUTF16Comparer : IComparer<Term>
{
#pragma warning disable 612, 618
private static readonly IComparer<BytesRef> LegacyComparer = BytesRef.UTF8SortedAsUTF16Comparer;
#pragma warning restore 612, 618
public int Compare(Term term1, Term term2)
{
if (term1.Field.Equals(term2.Field))
{
return LegacyComparer.Compare(term1.Bytes, term2.Bytes);
}
else
{
return System.String.Compare(term1.Field, term2.Field, System.StringComparison.Ordinal);
}
}
}
private static readonly SortTermAsUTF16Comparer TermAsUTF16Comparer = new SortTermAsUTF16Comparer();
// single straight enum
private void DoTestStraightEnum(IList<Term> fieldTerms, IndexReader reader, int uniqueTermCount)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: top now enum reader=" + reader);
}
Fields fields = MultiFields.GetFields(reader);
{
// Test straight enum:
int termCount = 0;
foreach (string field in fields)
{
Terms terms = fields.GetTerms(field);
Assert.IsNotNull(terms);
TermsEnum termsEnum = terms.GetIterator(null);
BytesRef text;
BytesRef lastText = null;
while ((text = termsEnum.Next()) != null)
{
Term exp = fieldTerms[termCount];
if (VERBOSE)
{
Console.WriteLine(" got term=" + field + ":" + UnicodeUtil.ToHexString(text.Utf8ToString()));
Console.WriteLine(" exp=" + exp.Field + ":" + UnicodeUtil.ToHexString(exp.Text()));
Console.WriteLine();
}
if (lastText == null)
{
lastText = BytesRef.DeepCopyOf(text);
}
else
{
Assert.IsTrue(lastText.CompareTo(text) < 0);
lastText.CopyBytes(text);
}
Assert.AreEqual(exp.Field, field);
Assert.AreEqual(exp.Bytes, text);
termCount++;
}
if (VERBOSE)
{
Console.WriteLine(" no more terms for field=" + field);
}
}
Assert.AreEqual(uniqueTermCount, termCount);
}
}
// randomly seeks to term that we know exists, then next's
// from there
private void DoTestSeekExists(Random r, IList<Term> fieldTerms, IndexReader reader)
{
IDictionary<string, TermsEnum> tes = new Dictionary<string, TermsEnum>();
// Test random seek to existing term, then enum:
if (VERBOSE)
{
Console.WriteLine("\nTEST: top now seek");
}
int num = AtLeast(100);
for (int iter = 0; iter < num; iter++)
{
// pick random field+term
int spot = r.Next(fieldTerms.Count);
Term term = fieldTerms[spot];
string field = term.Field;
if (VERBOSE)
{
Console.WriteLine("TEST: exist seek field=" + field + " term=" + UnicodeUtil.ToHexString(term.Text()));
}
// seek to it
TermsEnum te;
if (!tes.TryGetValue(field, out te))
{
te = MultiFields.GetTerms(reader, field).GetIterator(null);
tes[field] = te;
}
if (VERBOSE)
{
Console.WriteLine(" done get enum");
}
// seek should find the term
Assert.AreEqual(TermsEnum.SeekStatus.FOUND, te.SeekCeil(term.Bytes));
// now .next() this many times:
int ct = TestUtil.NextInt(r, 5, 100);
for (int i = 0; i < ct; i++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: now next()");
}
if (1 + spot + i >= fieldTerms.Count)
{
break;
}
term = fieldTerms[1 + spot + i];
if (!term.Field.Equals(field))
{
Assert.IsNull(te.Next());
break;
}
else
{
BytesRef t = te.Next();
if (VERBOSE)
{
Console.WriteLine(" got term=" + (t == null ? null : UnicodeUtil.ToHexString(t.Utf8ToString())));
Console.WriteLine(" exp=" + UnicodeUtil.ToHexString(term.Text().ToString()));
}
Assert.AreEqual(term.Bytes, t);
}
}
}
}
private void DoTestSeekDoesNotExist(Random r, int numField, IList<Term> fieldTerms, Term[] fieldTermsArray, IndexReader reader)
{
IDictionary<string, TermsEnum> tes = new Dictionary<string, TermsEnum>();
if (VERBOSE)
{
Console.WriteLine("TEST: top random seeks");
}
{
int num = AtLeast(100);
for (int iter = 0; iter < num; iter++)
{
// seek to random spot
string field = ("f" + r.Next(numField)).Intern();
Term tx = new Term(field, GetRandomString(r));
int spot = Array.BinarySearch(fieldTermsArray, tx);
if (spot < 0)
{
if (VERBOSE)
{
Console.WriteLine("TEST: non-exist seek to " + field + ":" + UnicodeUtil.ToHexString(tx.Text()));
}
// term does not exist:
TermsEnum te;
if (!tes.TryGetValue(field, out te))
{
te = MultiFields.GetTerms(reader, field).GetIterator(null);
tes[field] = te;
}
if (VERBOSE)
{
Console.WriteLine(" got enum");
}
spot = -spot - 1;
if (spot == fieldTerms.Count || !fieldTerms[spot].Field.Equals(field))
{
Assert.AreEqual(TermsEnum.SeekStatus.END, te.SeekCeil(tx.Bytes));
}
else
{
Assert.AreEqual(TermsEnum.SeekStatus.NOT_FOUND, te.SeekCeil(tx.Bytes));
if (VERBOSE)
{
Console.WriteLine(" got term=" + UnicodeUtil.ToHexString(te.Term.Utf8ToString()));
Console.WriteLine(" exp term=" + UnicodeUtil.ToHexString(fieldTerms[spot].Text()));
}
Assert.AreEqual(fieldTerms[spot].Bytes, te.Term);
// now .next() this many times:
int ct = TestUtil.NextInt(r, 5, 100);
for (int i = 0; i < ct; i++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: now next()");
}
if (1 + spot + i >= fieldTerms.Count)
{
break;
}
Term term = fieldTerms[1 + spot + i];
if (!term.Field.Equals(field))
{
Assert.IsNull(te.Next());
break;
}
else
{
BytesRef t = te.Next();
if (VERBOSE)
{
Console.WriteLine(" got term=" + (t == null ? null : UnicodeUtil.ToHexString(t.Utf8ToString())));
Console.WriteLine(" exp=" + UnicodeUtil.ToHexString(term.Text().ToString()));
}
Assert.AreEqual(term.Bytes, t);
}
}
}
}
}
}
}
[Test, LongRunningTest]
public virtual void TestSurrogatesOrder()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetCodec(new PreFlexRWCodec()));
int numField = TestUtil.NextInt(Random(), 2, 5);
int uniqueTermCount = 0;
int tc = 0;
var fieldTerms = new List<Term>();
for (int f = 0; f < numField; f++)
{
string field = "f" + f;
int numTerms = AtLeast(200);
ISet<string> uniqueTerms = new HashSet<string>();
for (int i = 0; i < numTerms; i++)
{
string term = GetRandomString(Random()) + "_ " + (tc++);
uniqueTerms.Add(term);
fieldTerms.Add(new Term(field, term));
Documents.Document doc = new Documents.Document();
doc.Add(NewStringField(field, term, Field.Store.NO));
w.AddDocument(doc);
}
uniqueTermCount += uniqueTerms.Count;
}
IndexReader reader = w.Reader;
if (VERBOSE)
{
fieldTerms.Sort(TermAsUTF16Comparer);
Console.WriteLine("\nTEST: UTF16 order");
foreach (Term t in fieldTerms)
{
Console.WriteLine(" " + ToHexString(t));
}
}
// sorts in code point order:
fieldTerms.Sort();
if (VERBOSE)
{
Console.WriteLine("\nTEST: codepoint order");
foreach (Term t in fieldTerms)
{
Console.WriteLine(" " + ToHexString(t));
}
}
Term[] fieldTermsArray = fieldTerms.ToArray();
//SegmentInfo si = makePreFlexSegment(r, "_0", dir, fieldInfos, codec, fieldTerms);
//FieldsProducer fields = codec.fieldsProducer(new SegmentReadState(dir, si, fieldInfos, 1024, 1));
//Assert.IsNotNull(fields);
DoTestStraightEnum(fieldTerms, reader, uniqueTermCount);
DoTestSeekExists(Random(), fieldTerms, reader);
DoTestSeekDoesNotExist(Random(), numField, fieldTerms, fieldTermsArray, reader);
reader.Dispose();
w.Dispose();
dir.Dispose();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Appleseed.Framework.Web.UI.WebControls
{
/// <summary>
/// Paging class, Appleseed special edition
/// </summary>
[
DefaultProperty("PageNumber"),
ToolboxData("<{0}:Paging TextKey='' runat=server></{0}:Paging>"),
Designer("Appleseed.Framework.UI.Design.PagingDesigner")
]
public class Paging : WebControl, IPaging
{
/// <summary>
/// Page number
/// </summary>
protected TextBox tbPageNumber;
/// <summary>
/// Total page count
/// </summary>
protected Label lblPageCount;
/// <summary>
/// Label containg text 'of'
/// </summary>
protected Label lblof;
/// <summary>
/// Button 'First'
/// </summary>
protected Button btnFirst;
/// <summary>
/// Button 'Previous'
/// </summary>
protected Button btnPrev;
/// <summary>
/// Button 'Next'
/// </summary>
protected Button btnNext;
/// <summary>
/// Button 'Last'
/// </summary>
protected Button btnLast;
/// <summary>
/// Move event raised when a move is performed
/// </summary>
public event EventHandler OnMove;
// variables we use to manage state
private int m_recordsPerPage = 10;
/// <summary>
/// Number of records per page
/// </summary>
/// <value>The records per page.</value>
public int RecordsPerPage
{
get { return m_recordsPerPage; }
set { m_recordsPerPage = value; }
}
/// <summary>
/// Hide when on single page hides controls when
/// there is only one page
/// </summary>
/// <value><c>true</c> if [hide on single page]; otherwise, <c>false</c>.</value>
public bool HideOnSinglePage
{
get { return Convert.ToBoolean(ViewState["HideOnSinglePage"]); }
set { ViewState["HideOnSinglePage"] = value.ToString(); }
}
/// <summary>
/// Current page number
/// </summary>
/// <value>The page number.</value>
public int PageNumber
{
get { return Convert.ToInt32(tbPageNumber.Text); }
set { tbPageNumber.Text = value.ToString(); }
}
/// <summary>
/// Gets or sets a value indicating whether validation is performed when the control buttons are clicked.
/// </summary>
/// <value><c>true</c> if [causes validation]; otherwise, <c>false</c>.</value>
[
Description(
"Gets or sets a value indicating whether validation is performed when the control buttons are clicked.")
]
public bool CausesValidation
{
get
{
object causesValidation = ViewState["CausesValidation"];
if (causesValidation != null)
return (bool) causesValidation;
else
return true;
}
set { ViewState["CausesValidation"] = value; }
}
/// <summary>
/// Total Record Count
/// </summary>
/// <value>The record count.</value>
public int RecordCount
{
get { return Convert.ToInt32(ViewState["RecordCount"]); }
set { ViewState["RecordCount"] = value.ToString(); }
}
/// <summary>
/// Total pages count
/// </summary>
/// <value>The page count.</value>
public int PageCount
{
get
{
// Calculate page count
int _PageCount = RecordCount/RecordsPerPage;
// adjust for spillover
if (RecordCount%RecordsPerPage > 0)
_PageCount++;
if (_PageCount < 1)
_PageCount = 1;
return _PageCount;
}
}
/// <summary>
/// Used by OnMove event
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnMoveHandler(EventArgs e)
{
if (OnMove != null)
{
OnMove(this, e);
}
}
/// <summary>
/// Enable/disable the nav controls based on the current context, update labels
/// </summary>
public void RefreshButtons()
{
// enable/disable the nav controls based on the current context
// we should only show the first button if we're NOT on the first page already
btnFirst.Enabled = (PageNumber != 1);
btnPrev.Enabled = (PageNumber > 1);
btnNext.Enabled = (PageNumber < PageCount);
btnLast.Enabled = (PageNumber != PageCount);
//Update labels
lblPageCount.Text = PageCount.ToString();
if (PageCount <= 1 && HideOnSinglePage)
{
btnFirst.Visible = false;
btnPrev.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
lblof.Visible = false;
lblPageCount.Visible = false;
tbPageNumber.Visible = false;
}
else
{
btnFirst.Visible = true;
btnPrev.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblof.Visible = true;
lblPageCount.Visible = true;
tbPageNumber.Visible = true;
}
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
RefreshButtons();
}
/// <summary>
/// Main class manging pages
/// </summary>
public Paging()
{
//Construct controls
btnFirst = new Button();
btnFirst.Width = new Unit("25px");
btnFirst.Font.Bold = true;
btnFirst.Text = " |< ";
btnFirst.CommandArgument = "first";
btnFirst.EnableViewState = false;
Controls.Add(btnFirst);
btnPrev = new Button();
btnPrev.Width = new Unit("25px");
btnPrev.Font.Bold = true;
btnPrev.Text = " < ";
btnPrev.CommandArgument = "prev";
btnPrev.EnableViewState = false;
Controls.Add(btnPrev);
Controls.Add(new LiteralControl(" "));
tbPageNumber = new TextBox();
tbPageNumber.Width = new Unit("30px");
tbPageNumber.EnableViewState = true;
tbPageNumber.AutoPostBack = true;
Controls.Add(tbPageNumber);
Controls.Add(new LiteralControl(" "));
btnNext = new Button();
btnNext.Width = new Unit("25px");
btnNext.Font.Bold = true;
btnNext.Text = " > ";
btnNext.CommandArgument = "next";
btnNext.EnableViewState = false;
Controls.Add(btnNext);
btnLast = new Button();
btnLast.Width = new Unit("25px");
btnLast.Font.Bold = true;
btnLast.Text = " >| ";
btnLast.CommandArgument = "last";
btnLast.EnableViewState = false;
Controls.Add(btnLast);
lblof = new Label();
lblof.EnableViewState = false;
lblof.Text = " / ";
Controls.Add(lblof);
lblPageCount = new Label();
lblPageCount.EnableViewState = false;
Controls.Add(lblPageCount);
//Set defaults
if (ViewState["PageNumber"] == null)
PageNumber = 1;
if (ViewState["RecordCount"] == null)
RecordCount = 1;
if (ViewState["HideOnSinglePage"] == null)
HideOnSinglePage = true;
//Add handlers
Load += new EventHandler(Page_Load);
tbPageNumber.TextChanged += new EventHandler(NavigationTbClick);
btnFirst.Click += new EventHandler(NavigationButtonClick);
btnPrev.Click += new EventHandler(NavigationButtonClick);
btnNext.Click += new EventHandler(NavigationButtonClick);
btnLast.Click += new EventHandler(NavigationButtonClick);
}
/// <summary>
/// Navigations the button click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void NavigationButtonClick(Object sender, EventArgs e)
{
// get the command
string arg = ((Button) sender).CommandArgument;
// do the command
switch (arg)
{
case ("next"):
if (PageNumber < PageCount)
PageNumber++;
break;
case ("prev"):
if (PageNumber > 1)
PageNumber--;
break;
case ("last"):
PageNumber = PageCount;
break;
case ("first"):
PageNumber = 1;
break;
}
RefreshButtons();
//Raise the event OnMove
OnMoveHandler(new EventArgs());
}
/// <summary>
/// Navigations the tb click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void NavigationTbClick(Object sender, EventArgs e)
{
int _PageNumber = Convert.ToInt32(tbPageNumber.Text);
if (_PageNumber > PageCount)
{
PageNumber = PageCount;
}
else if (_PageNumber < 1)
{
PageNumber = 1;
}
else
{
PageNumber = _PageNumber;
}
RefreshButtons();
//Raise the event OnMove
OnMoveHandler(new EventArgs());
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Lucene.Net.Fluent.Documents.FieldAttributes;
using Lucene.Net.Fluent.Documents.FieldBuilders;
using Lucene.Net.Fluent.Extentions;
namespace Lucene.Net.Documents
{
public static class DocumentExtentions
{
public static void AddFields<T>(this Document document, T value)
{
new FieldAttributeBuilder<T>(document, value).Build();
new NumericFieldAttributeBuilder<T>(document, value).Build();
}
public static IStringFieldBuilder Add(this Document document, String value)
{
return new StringFieldBuilder(document, value);
}
public static INumericFieldBuilder<Int32> Add(this Document document, Int32 value)
{
return new Int32FieldBuilder(document, value);
}
public static INumericFieldBuilder<Int64> Add(this Document document, Int64 value)
{
return new Int64FieldBuilder(document, value);
}
public static INumericFieldBuilder<Boolean> Add(this Document document, Boolean value)
{
return new BooleanFieldBuilder(document, value);
}
public static INumericFieldBuilder<Single> Add(this Document document, Single value)
{
return new SingleFieldBuilder(document, value);
}
public static INumericFieldBuilder<Double> Add(this Document document, Double value)
{
return new DoubleFieldBuilder(document, value);
}
public static INumericFieldBuilder<DateTime> Add(this Document document, DateTime value)
{
return new DateTimeFieldBuilder(document, value);
}
public static ISerializedObjectFieldBuilder Add(this Document document, Object value)
{
return new SerializedObjectFieldBuilder(document, value);
}
public static String GetString(this Document document, String name)
{
var result = document.Get(name);
if (result == null)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result;
}
public static String GetStringOrNull(this Document document, String name)
{
return document.Get(name);
}
public static String GetStringWithCompression(this Document document, String name)
{
var result = document.GetStringWithCompressionOrNull(name);
if (result == null)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result;
}
public static String GetStringWithCompressionOrNull(this Document document, String name)
{
var value = document.GetBinaryValue(name);
if (value == null)
{
return null;
}
return CompressionTools.DecompressString(value);
}
public static Int32 GetInt32(this Document document, String name)
{
var result = document.GetInt32OrNull(name);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static Int32? GetInt32OrNull(this Document document, String name)
{
var value = document.Get(name);
Int32 result;
if (!Int32.TryParse(value, out result))
{
return null;
}
return result;
}
public static Int64 GetInt64(this Document document, String name)
{
var result = document.GetInt64OrNull(name);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static Int64? GetInt64OrNull(this Document document, String name)
{
var value = document.Get(name);
Int64 result;
if (!Int64.TryParse(value, out result))
{
return null;
}
return result;
}
public static Single GetSingle(this Document document, String name)
{
var result = document.GetSingleOrNull(name);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static Single? GetSingleOrNull(this Document document, String name)
{
var value = document.Get(name);
Single result;
if (Lucene.Net.Support.Single.TryParse(value, out result))
{
return result;
}
if (value == Single.MaxValue.ToString(CultureInfo.InvariantCulture))
{
return Single.MaxValue;
}
if (value == Single.MinValue.ToString(CultureInfo.InvariantCulture))
{
return Single.MinValue;
}
return null;
}
public static Double GetDouble(this Document document, String name)
{
var result = document.GetDoubleOrNull(name);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static Double? GetDoubleOrNull(this Document document, String name)
{
var value = document.Get(name);
Double result;
if (Double.TryParse(value, out result))
{
return result;
}
if (value == Double.MaxValue.ToString(CultureInfo.InvariantCulture))
{
return Double.MaxValue;
}
if (value == Double.MinValue.ToString(CultureInfo.InvariantCulture))
{
return Double.MinValue;
}
return null;
}
public static DateTime GetDateTime(this Document document, String name, DateTimeKind kind)
{
var result = document.GetDateTimeOrNull(name, kind);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static DateTime? GetDateTimeOrNull(this Document document, String name, DateTimeKind kind)
{
var value = document.Get(name);
Int64 result;
if (!Int64.TryParse(value, out result))
{
return null;
}
return new DateTime(result, kind);
}
public static Boolean GetBoolean(this Document document, String name)
{
var result = document.GetBooleanOrNull(name);
if (!result.HasValue)
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return result.Value;
}
public static Boolean? GetBooleanOrNull(this Document document, String name)
{
var value = document.Get(name);
if (new[] { "0", "1" }.Contains(value))
{
return value == "1";
}
Boolean result;
if(!Boolean.TryParse(value, out result))
{
return null;
}
return result;
}
public static T GetSerializedObject<T>(this Document document, String name) where T : class
{
var value = document.GetBinaryValue(name);
if (value == null || !value.Any())
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
return value.BinaryDeserialize<T>();
}
public static T GetSerializedObjectOrNull<T>(this Document document, String name) where T : class
{
var value = document.GetBinaryValue(name);
if (value == null || !value.Any())
{
return null;
}
try
{
return value.BinaryDeserialize<T>();
}
catch (Exception ex)
{
Trace.WriteLine("Failed to deserialize object. " + ex);
}
return null;
}
public static T GetSerializedObjectWithCompression<T>(this Document document, String name) where T : class
{
var value = document.GetBinaryValue(name);
if (value == null || !value.Any())
{
throw new InvalidOperationException("Document does not contain a field named " + name);
}
value = CompressionTools.Decompress(value);
return value.BinaryDeserialize<T>();
}
public static T GetSerializedObjectWithCompressionOrNull<T>(this Document document, String name) where T : class
{
var value = document.GetBinaryValue(name);
if (value == null || !value.Any())
{
return null;
}
try
{
value = CompressionTools.Decompress(value);
return value.BinaryDeserialize<T>();
}
catch (Exception ex)
{
Trace.WriteLine("Failed to decompress and deserialize object. " + ex);
}
return null;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: TextWriter
**
**
** Purpose: Abstract base class for Text-only Writers.
** Subclasses will include StreamWriter & StringWriter.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
namespace System.IO
{
// This abstract base class represents a writer that can write a sequential
// stream of characters. A subclass must minimally implement the
// Write(char) method.
//
// This class is intended for character output, not bytes.
// There are methods on the Stream class for writing bytes.
[Serializable]
public abstract class TextWriter : MarshalByRefObject, IDisposable
{
public static readonly TextWriter Null = new NullTextWriter();
// This should be initialized to Environment.NewLine, but
// to avoid loading Environment unnecessarily so I've duplicated
// the value here.
#if !PLATFORM_UNIX
private const String InitialNewLine = "\r\n";
protected char[] CoreNewLine = new char[] { '\r', '\n' };
#else
private const String InitialNewLine = "\n";
protected char[] CoreNewLine = new char[] {'\n'};
#endif // !PLATFORM_UNIX
// Can be null - if so, ask for the Thread's CurrentCulture every time.
private IFormatProvider InternalFormatProvider;
protected TextWriter()
{
InternalFormatProvider = null; // Ask for CurrentCulture all the time.
}
protected TextWriter( IFormatProvider formatProvider )
{
InternalFormatProvider = formatProvider;
}
public virtual IFormatProvider FormatProvider
{
get
{
if(InternalFormatProvider == null)
{
return Thread.CurrentThread.CurrentCulture;
}
else
{
return InternalFormatProvider;
}
}
}
// Closes this TextWriter and releases any system resources associated with the
// TextWriter. Following a call to Close, any operations on the TextWriter
// may raise exceptions. This default method is empty, but descendant
// classes can override the method to provide the appropriate
// functionality.
public virtual void Close()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
// Clears all buffers for this TextWriter and causes any buffered data to be
// written to the underlying device. This default method is empty, but
// descendant classes can override the method to provide the appropriate
// functionality.
public virtual void Flush()
{
}
public abstract Encoding Encoding
{
get;
}
// Returns the line terminator string used by this TextWriter. The default line
// terminator string is a carriage return followed by a line feed ("\r\n").
//
// Sets the line terminator string for this TextWriter. The line terminator
// string is written to the text stream whenever one of the
// WriteLine methods are called. In order for text written by
// the TextWriter to be readable by a TextReader, only one of the following line
// terminator strings should be used: "\r", "\n", or "\r\n".
//
public virtual String NewLine
{
get
{
return new String( CoreNewLine );
}
set
{
if(value == null)
{
value = InitialNewLine;
}
CoreNewLine = value.ToCharArray();
}
}
//// [HostProtection( Synchronization = true )]
public static TextWriter Synchronized( TextWriter writer )
{
if(writer == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "writer" );
#else
throw new ArgumentNullException();
#endif
}
if(writer is SyncTextWriter)
{
return writer;
}
return new SyncTextWriter( writer );
}
// Writes a character to the text stream. This default method is empty,
// but descendant classes can override the method to provide the
// appropriate functionality.
//
public virtual void Write( char value )
{
}
// Writes a character array to the text stream. This default method calls
// Write(char) for each of the characters in the character array.
// If the character array is null, nothing is written.
//
public virtual void Write( char[] buffer )
{
if(buffer != null)
{
Write( buffer, 0, buffer.Length );
}
}
// Writes a range of a character array to the text stream. This method will
// write count characters of data into this TextWriter from the
// buffer character array starting at position index.
//
public virtual void Write( char[] buffer, int index, int count )
{
if(buffer == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) );
#else
throw new ArgumentNullException();
#endif
}
if(index < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(count < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(buffer.Length - index < count)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) );
#else
throw new ArgumentException();
#endif
}
for(int i = 0; i < count; i++)
{
Write( buffer[index + i] );
}
}
// Writes the text representation of a boolean to the text stream. This
// method outputs either Boolean.TrueString or Boolean.FalseString.
//
public virtual void Write( bool value )
{
Write( value ? Boolean.TrueLiteral : Boolean.FalseLiteral );
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// Int32.ToString() method.
//
public virtual void Write( int value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// UInt32.ToString() method.
//
[CLSCompliant( false )]
public virtual void Write( uint value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes the text representation of a long to the text stream. The
// text representation of the given value is produced by calling the
// Int64.ToString() method.
//
public virtual void Write( long value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes the text representation of an unsigned long to the text
// stream. The text representation of the given value is produced
// by calling the UInt64.ToString() method.
//
[CLSCompliant( false )]
public virtual void Write( ulong value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes the text representation of a float to the text stream. The
// text representation of the given value is produced by calling the
// Float.toString(float) method.
//
public virtual void Write( float value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes the text representation of a double to the text stream. The
// text representation of the given value is produced by calling the
// Double.toString(double) method.
//
public virtual void Write( double value )
{
Write( value.ToString( FormatProvider ) );
}
public virtual void Write( Decimal value )
{
Write( value.ToString( FormatProvider ) );
}
// Writes a string to the text stream. If the given string is null, nothing
// is written to the text stream.
//
public virtual void Write( String value )
{
if(value != null)
{
Write( value.ToCharArray() );
}
}
// Writes the text representation of an object to the text stream. If the
// given object is null, nothing is written to the text stream.
// Otherwise, the object's ToString method is called to produce the
// string representation, and the resulting string is then written to the
// output stream.
//
public virtual void Write( Object value )
{
if(value != null)
{
IFormattable f = value as IFormattable;
if(f != null)
{
Write( f.ToString( null, FormatProvider ) );
}
else
{
Write( value.ToString() );
}
}
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write( String format, Object arg0 )
{
Write( String.Format( FormatProvider, format, arg0 ) );
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write( String format, Object arg0, Object arg1 )
{
Write( String.Format( FormatProvider, format, arg0, arg1 ) );
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write( String format, Object arg0, Object arg1, Object arg2 )
{
Write( String.Format( FormatProvider, format, arg0, arg1, arg2 ) );
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write( String format, params Object[] arg )
{
Write( String.Format( FormatProvider, format, arg ) );
}
// Writes a line terminator to the text stream. The default line terminator
// is a carriage return followed by a line feed ("\r\n"), but this value
// can be changed by setting the NewLine property.
//
public virtual void WriteLine()
{
Write( CoreNewLine );
}
// Writes a character followed by a line terminator to the text stream.
//
public virtual void WriteLine( char value )
{
Write( value );
WriteLine();
}
// Writes an array of characters followed by a line terminator to the text
// stream.
//
public virtual void WriteLine( char[] buffer )
{
Write( buffer );
WriteLine();
}
// Writes a range of a character array followed by a line terminator to the
// text stream.
//
public virtual void WriteLine( char[] buffer, int index, int count )
{
Write( buffer, index, count );
WriteLine();
}
// Writes the text representation of a boolean followed by a line
// terminator to the text stream.
//
public virtual void WriteLine( bool value )
{
Write( value );
WriteLine();
}
// Writes the text representation of an integer followed by a line
// terminator to the text stream.
//
public virtual void WriteLine( int value )
{
Write( value );
WriteLine();
}
// Writes the text representation of an unsigned integer followed by
// a line terminator to the text stream.
//
[CLSCompliant( false )]
public virtual void WriteLine( uint value )
{
Write( value );
WriteLine();
}
// Writes the text representation of a long followed by a line terminator
// to the text stream.
//
public virtual void WriteLine( long value )
{
Write( value );
WriteLine();
}
// Writes the text representation of an unsigned long followed by
// a line terminator to the text stream.
//
[CLSCompliant( false )]
public virtual void WriteLine( ulong value )
{
Write( value );
WriteLine();
}
// Writes the text representation of a float followed by a line terminator
// to the text stream.
//
public virtual void WriteLine( float value )
{
Write( value );
WriteLine();
}
// Writes the text representation of a double followed by a line terminator
// to the text stream.
//
public virtual void WriteLine( double value )
{
Write( value );
WriteLine();
}
public virtual void WriteLine( decimal value )
{
Write( value );
WriteLine();
}
// Writes a string followed by a line terminator to the text stream.
//
public virtual void WriteLine( String value )
{
if(value == null)
{
WriteLine();
}
else
{
// We'd ideally like WriteLine to be atomic, in that one call
// to WriteLine equals one call to the OS (ie, so writing to
// console while simultaneously calling printf will guarantee we
// write out a string and new line chars, without any interference).
// Additionally, we need to call ToCharArray on Strings anyways,
// so allocating a char[] here isn't any worse than what we were
// doing anyways. We do reduce the number of calls to the
// backing store this way, potentially.
int vLen = value.Length;
int nlLen = CoreNewLine.Length;
char[] chars = new char[vLen + nlLen];
value.CopyTo( 0, chars, 0, vLen );
// CoreNewLine will almost always be 2 chars, and possibly 1.
if(nlLen == 2)
{
chars[vLen] = CoreNewLine[0];
chars[vLen + 1] = CoreNewLine[1];
}
else if(nlLen == 1)
{
chars[vLen] = CoreNewLine[0];
}
else
{
Buffer.BlockCopy( CoreNewLine, 0, chars, vLen * 2, nlLen * 2 );
}
Write( chars, 0, vLen + nlLen );
}
/*
Write(value); // We could call Write(String) on StreamWriter...
WriteLine();
*/
}
// Writes the text representation of an object followed by a line
// terminator to the text stream.
//
public virtual void WriteLine( Object value )
{
if(value == null)
{
WriteLine();
}
else
{
// Call WriteLine(value.ToString), not Write(Object), WriteLine().
// This makes calls to WriteLine(Object) atomic.
IFormattable f = value as IFormattable;
if(f != null)
{
WriteLine( f.ToString( null, FormatProvider ) );
}
else
{
WriteLine( value.ToString() );
}
}
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine( String format, Object arg0 )
{
WriteLine( String.Format( FormatProvider, format, arg0 ) );
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine( String format, Object arg0, Object arg1 )
{
WriteLine( String.Format( FormatProvider, format, arg0, arg1 ) );
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine( String format, Object arg0, Object arg1, Object arg2 )
{
WriteLine( String.Format( FormatProvider, format, arg0, arg1, arg2 ) );
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine( String format, params Object[] arg )
{
WriteLine( String.Format( FormatProvider, format, arg ) );
}
[Serializable()]
private sealed class NullTextWriter : TextWriter
{
internal NullTextWriter() : base( CultureInfo.InvariantCulture )
{
}
public override Encoding Encoding
{
get
{
return Encoding.Default;
}
}
public override void Write( char[] buffer, int index, int count )
{
}
public override void Write( String value )
{
}
// Not strictly necessary, but for perf reasons
public override void WriteLine()
{
}
// Not strictly necessary, but for perf reasons
public override void WriteLine( String value )
{
}
public override void WriteLine( Object value )
{
}
}
[Serializable()]
internal sealed class SyncTextWriter : TextWriter, IDisposable
{
private TextWriter _out;
internal SyncTextWriter( TextWriter t ) : base( t.FormatProvider )
{
_out = t;
}
public override Encoding Encoding
{
get
{
return _out.Encoding;
}
}
public override IFormatProvider FormatProvider
{
get
{
return _out.FormatProvider;
}
}
public override String NewLine
{
[MethodImplAttribute( MethodImplOptions.Synchronized )]
get
{
return _out.NewLine;
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
set
{
_out.NewLine = value;
}
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Close()
{
// So that any overriden Close() gets run
_out.Close();
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
protected override void Dispose( bool disposing )
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if(disposing)
{
((IDisposable)_out).Dispose();
}
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Flush()
{
_out.Flush();
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( char value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( char[] buffer )
{
_out.Write( buffer );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( char[] buffer, int index, int count )
{
_out.Write( buffer, index, count );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( bool value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( int value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( uint value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( long value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( ulong value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( float value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( double value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( Decimal value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( String value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( Object value )
{
_out.Write( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( String format, Object arg0 )
{
_out.Write( format, arg0 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( String format, Object arg0, Object arg1 )
{
_out.Write( format, arg0, arg1 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( String format, Object arg0, Object arg1, Object arg2 )
{
_out.Write( format, arg0, arg1, arg2 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void Write( String format, Object[] arg )
{
_out.Write( format, arg );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine()
{
_out.WriteLine();
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( char value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( decimal value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( char[] buffer )
{
_out.WriteLine( buffer );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( char[] buffer, int index, int count )
{
_out.WriteLine( buffer, index, count );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( bool value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( int value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( uint value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( long value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( ulong value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( float value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( double value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( String value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( Object value )
{
_out.WriteLine( value );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( String format, Object arg0 )
{
_out.WriteLine( format, arg0 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( String format, Object arg0, Object arg1 )
{
_out.WriteLine( format, arg0, arg1 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( String format, Object arg0, Object arg1, Object arg2 )
{
_out.WriteLine( format, arg0, arg1, arg2 );
}
[MethodImplAttribute( MethodImplOptions.Synchronized )]
public override void WriteLine( String format, Object[] arg )
{
_out.WriteLine( format, arg );
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Security.Principal;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using TextMatch;
using TextMatch.Models;
namespace TextMatch.Controllers
{
[Authorize]
public class ManageController : Controller
{
public ManageController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
//
// GET: /Account/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await UserManager.HasPasswordAsync(user),
PhoneNumber = await UserManager.GetPhoneNumberAsync(user),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(user),
Logins = await UserManager.GetLoginsAsync(user),
BrowserRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin()
{
var user = await GetCurrentUserAsync();
var linkedAccounts = await UserManager.GetLoginsAsync(user);
ViewBag.ShowRemoveButton = await UserManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Account/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Account/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(user, model.Number);
await MessageServices.SendSmsAsync(model.Number, "Your security code is: " + code);
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await UserManager.SetTwoFactorEnabledAsync(user, true);
await SignInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await UserManager.SetTwoFactorEnabledAsync(user, false);
await SignInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Account/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Account/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Account/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//GET: /Account/Manage
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(user);
var otherLogins = SignInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await SignInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction("ManageLogins", new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<bool> HasPhoneNumber()
{
var user = await UserManager.FindByIdAsync(User.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="etwprovider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
using System.Security;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing
{
public class EventProvider : IDisposable
{
[SecurityCritical]
private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function
private long _regHandle; // Trace Registration Handle
private byte _level; // Tracing Level
private long _anyKeywordMask; // Trace Enable Flags
private long _allKeywordMask; // Match all keyword
private int _enabled; // Enabled flag from Trace callback
private Guid _providerId; // Control Guid
private int _disposed; // when 1, provider has unregister
[ThreadStatic]
private static WriteEventErrorCode t_returnCode; // thread slot to keep last error
[ThreadStatic]
private static Guid t_activityId;
private const int s_basicTypeAllocationBufferSize = 16;
private const int s_etwMaxMumberArguments = 32;
private const int s_etwAPIMaxStringCount = 8;
private const int s_maxEventDataDescriptors = 128;
private const int s_traceEventMaximumSize = 65482;
private const int s_traceEventMaximumStringSize = 32724;
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public enum WriteEventErrorCode : int
{
//check mapping to runtime codes
NoError = 0,
NoFreeBuffers = 1,
EventTooBig = 2
}
[StructLayout(LayoutKind.Explicit, Size = 16)]
private struct EventData
{
[FieldOffset(0)]
internal ulong DataPointer;
[FieldOffset(8)]
internal uint Size;
[FieldOffset(12)]
internal int Reserved;
}
private enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
}
/// <summary>
/// Constructor for EventProvider class.
/// </summary>
/// <param name="providerGuid">
/// Unique GUID among all trace sources running on a system
/// </param>
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
public EventProvider(Guid providerGuid)
{
_providerId = providerGuid;
//
// EtwRegister the ProviderId with ETW
//
EtwRegister();
}
/// <summary>
/// This method registers the controlGuid of this class with ETW.
/// We need to be running on Vista or above. If not an
/// PlatformNotSupported exception will be thrown.
/// If for some reason the ETW EtwRegister call failed
/// a NotSupported exception will be thrown.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void EtwRegister()
{
uint status;
_etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack);
status = UnsafeNativeMethods.EventRegister(ref _providerId, _etwCallback, null, ref _regHandle);
if (status != 0)
{
throw new Win32Exception((int)status);
}
}
//
// implement Dispose Pattern to early deregister from ETW insted of waiting for
// the finalizer to call deregistration.
// Once the user is done with the provider it needs to call Close() or Dispose()
// If neither are called the finalizer will unregister the provider anyway
//
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
//
// explicit cleanup is done by calling Dispose with true from
// Dispose() or Close(). The disposing arguement is ignored because there
// are no unmanaged resources.
// The finalizer calls Dispose with false.
//
//
// check if the object has been already disposed
//
if (_disposed == 1) return;
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
// somebody is allready disposing the provider
return;
}
//
// Disables Tracing in the provider, then unregister
//
_enabled = 0;
Deregister();
}
/// <summary>
/// This method deregisters the controlGuid of this class with ETW.
///
/// </summary>
public virtual void Close()
{
Dispose();
}
~EventProvider()
{
Dispose(false);
}
/// <summary>
/// This method un-registers from ETW.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void Deregister()
{
//
// Unregister from ETW using the RegHandle saved from
// the register call.
//
if (_regHandle != 0)
{
UnsafeNativeMethods.EventUnregister(_regHandle);
_regHandle = 0;
}
}
[System.Security.SecurityCritical]
private unsafe void EtwEnableCallBack(
[In] ref System.Guid sourceId,
[In] int isEnabled,
[In] byte setLevel,
[In] long anyKeyword,
[In] long allKeyword,
[In] void* filterData,
[In] void* callbackContext
)
{
_enabled = isEnabled;
_level = setLevel;
_anyKeywordMask = anyKeyword;
_allKeywordMask = allKeyword;
return;
}
/// <summary>
/// IsEnabled, method used to test if provider is enabled
/// </summary>
public bool IsEnabled()
{
return (_enabled != 0) ? true : false;
}
/// <summary>
/// IsEnabled, method used to test if event is enabled
/// </summary>
/// <param name="level">
/// Level to test
/// </param>
/// <param name="keywords">
/// Keyword to test
/// </param>
public bool IsEnabled(byte level, long keywords)
{
//
// If not enabled at all, return false.
//
if (_enabled == 0)
{
return false;
}
// This also covers the case of Level == 0.
if ((level <= _level) ||
(_level == 0))
{
//
// Check if Keyword is enabled
//
if ((keywords == 0) ||
(((keywords & _anyKeywordMask) != 0) &&
((keywords & _allKeywordMask) == _allKeywordMask)))
{
return true;
}
}
return false;
}
public static WriteEventErrorCode GetLastWriteEventError()
{
return t_returnCode;
}
//
// Helper function to set the last error on the thread
//
private static void SetLastError(int error)
{
switch (error)
{
case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW:
case UnsafeNativeMethods.ERROR_MORE_DATA:
t_returnCode = WriteEventErrorCode.EventTooBig;
break;
case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY:
t_returnCode = WriteEventErrorCode.NoFreeBuffers;
break;
}
}
[System.Security.SecurityCritical]
private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer)
/*++
Routine Description:
This routine is used by WriteEvent to unbox the object type and
to fill the passed in ETW data descriptor.
Arguments:
data - argument to be decoded
dataDescriptor - pointer to the descriptor to be filled
dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
Return Value:
null if the object is a basic type other than string. String otherwise
--*/
{
dataDescriptor->Reserved = 0;
string sRet = data as string;
if (sRet != null)
{
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
if (data == null)
{
dataDescriptor->Size = 0;
dataDescriptor->DataPointer = 0;
}
else if (data is IntPtr)
{
dataDescriptor->Size = (uint)sizeof(IntPtr);
IntPtr* intptrPtr = (IntPtr*)dataBuffer;
*intptrPtr = (IntPtr)data;
dataDescriptor->DataPointer = (ulong)intptrPtr;
}
else if (data is int)
{
dataDescriptor->Size = (uint)sizeof(int);
int* intptrPtr = (int*)dataBuffer;
*intptrPtr = (int)data;
dataDescriptor->DataPointer = (ulong)intptrPtr;
}
else if (data is long)
{
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = (long)data;
dataDescriptor->DataPointer = (ulong)longptr;
}
else if (data is uint)
{
dataDescriptor->Size = (uint)sizeof(uint);
uint* uintptr = (uint*)dataBuffer;
*uintptr = (uint)data;
dataDescriptor->DataPointer = (ulong)uintptr;
}
else if (data is UInt64)
{
dataDescriptor->Size = (uint)sizeof(ulong);
UInt64* ulongptr = (ulong*)dataBuffer;
*ulongptr = (ulong)data;
dataDescriptor->DataPointer = (ulong)ulongptr;
}
else if (data is char)
{
dataDescriptor->Size = (uint)sizeof(char);
char* charptr = (char*)dataBuffer;
*charptr = (char)data;
dataDescriptor->DataPointer = (ulong)charptr;
}
else if (data is byte)
{
dataDescriptor->Size = (uint)sizeof(byte);
byte* byteptr = (byte*)dataBuffer;
*byteptr = (byte)data;
dataDescriptor->DataPointer = (ulong)byteptr;
}
else if (data is short)
{
dataDescriptor->Size = (uint)sizeof(short);
short* shortptr = (short*)dataBuffer;
*shortptr = (short)data;
dataDescriptor->DataPointer = (ulong)shortptr;
}
else if (data is sbyte)
{
dataDescriptor->Size = (uint)sizeof(sbyte);
sbyte* sbyteptr = (sbyte*)dataBuffer;
*sbyteptr = (sbyte)data;
dataDescriptor->DataPointer = (ulong)sbyteptr;
}
else if (data is ushort)
{
dataDescriptor->Size = (uint)sizeof(ushort);
ushort* ushortptr = (ushort*)dataBuffer;
*ushortptr = (ushort)data;
dataDescriptor->DataPointer = (ulong)ushortptr;
}
else if (data is float)
{
dataDescriptor->Size = (uint)sizeof(float);
float* floatptr = (float*)dataBuffer;
*floatptr = (float)data;
dataDescriptor->DataPointer = (ulong)floatptr;
}
else if (data is double)
{
dataDescriptor->Size = (uint)sizeof(double);
double* doubleptr = (double*)dataBuffer;
*doubleptr = (double)data;
dataDescriptor->DataPointer = (ulong)doubleptr;
}
else if (data is bool)
{
dataDescriptor->Size = (uint)sizeof(bool);
bool* boolptr = (bool*)dataBuffer;
*boolptr = (bool)data;
dataDescriptor->DataPointer = (ulong)boolptr;
}
else if (data is Guid)
{
dataDescriptor->Size = (uint)sizeof(Guid);
Guid* guidptr = (Guid*)dataBuffer;
*guidptr = (Guid)data;
dataDescriptor->DataPointer = (ulong)guidptr;
}
else if (data is decimal)
{
dataDescriptor->Size = (uint)sizeof(decimal);
decimal* decimalptr = (decimal*)dataBuffer;
*decimalptr = (decimal)data;
dataDescriptor->DataPointer = (ulong)decimalptr;
}
else if (data is Boolean)
{
dataDescriptor->Size = (uint)sizeof(Boolean);
Boolean* booleanptr = (Boolean*)dataBuffer;
*booleanptr = (Boolean)data;
dataDescriptor->DataPointer = (ulong)booleanptr;
}
else
{
//To our eyes, everything else is a just a string
sRet = data.ToString();
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
return null;
}
/// <summary>
/// WriteMessageEvent, method to write a string with level and Keyword.
/// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId().
/// </summary>
/// <param name="eventMessage">
/// Message to write
/// </param>
/// <param name="eventLevel">
/// Level to test
/// </param>
/// <param name="eventKeywords">
/// Keyword to test
/// </param>
[System.Security.SecurityCritical]
public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKeywords)
{
int status = 0;
if (eventMessage == null)
{
throw new ArgumentNullException("eventMessage");
}
if (IsEnabled(eventLevel, eventKeywords))
{
if (eventMessage.Length > s_traceEventMaximumStringSize)
{
t_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
unsafe
{
fixed (char* pdata = eventMessage)
{
status = (int)UnsafeNativeMethods.EventWriteString(_regHandle, eventLevel, eventKeywords, pdata);
}
if (status != 0)
{
SetLastError(status);
return false;
}
}
}
return true;
}
/// <summary>
/// WriteMessageEvent, method to write a string with level=0 and Keyword=0
/// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId().
/// </summary>
/// <param name="eventMessage">
/// Message to log
/// </param>
public bool WriteMessageEvent(string eventMessage)
{
return WriteMessageEvent(eventMessage, 0, 0);
}
/// <summary>
/// WriteEvent method to write parameters with event schema properties
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="eventPayload">
/// </param>
public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload)
{
return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload);
}
/// <summary>
/// WriteEvent, method to write a string with event schema properties
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="data">
/// string to log.
/// </param>
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
public bool WriteEvent(ref EventDescriptor eventDescriptor, string data)
{
uint status = 0;
if (data == null)
{
throw new ArgumentNullException("dataString");
}
if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
{
if (data.Length > s_traceEventMaximumStringSize)
{
t_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
EventData userData;
userData.Size = (uint)((data.Length + 1) * 2);
userData.Reserved = 0;
unsafe
{
fixed (char* pdata = data)
{
Guid activityId = GetActivityId();
userData.DataPointer = (ulong)pdata;
status = UnsafeNativeMethods.EventWriteTransfer(_regHandle,
ref eventDescriptor,
(activityId == Guid.Empty) ? null : &activityId,
null,
1,
&userData);
}
}
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
/// <summary>
/// WriteEvent, method to be used by generated code on a derived class
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="dataCount">
/// number of event descriptors
/// </param>
/// <param name="data">
/// pointer do the event data
/// </param>
[System.Security.SecurityCritical]
protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, IntPtr data)
{
uint status = 0;
unsafe
{
Guid activityId = GetActivityId();
status = UnsafeNativeMethods.EventWriteTransfer(
_regHandle,
ref eventDescriptor,
(activityId == Guid.Empty) ? null : &activityId,
null,
(uint)dataCount,
(void*)data);
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
/// <summary>
/// WriteTransferEvent, method to write a parameters with event schema properties
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="relatedActivityId">
/// </param>
/// <param name="eventPayload">
/// </param>
[System.Security.SecurityCritical]
public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload)
{
uint status = 0;
if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
{
Guid activityId = GetActivityId();
unsafe
{
int argCount = 0;
EventData* userDataPtr = null;
if ((eventPayload != null) && (eventPayload.Length != 0))
{
argCount = eventPayload.Length;
if (argCount > s_etwMaxMumberArguments)
{
//
//too many arguments to log
//
throw new ArgumentOutOfRangeException("eventPayload",
string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxMumberArguments));
}
uint totalEventSize = 0;
int index;
int stringIndex = 0;
int[] stringPosition = new int[s_etwAPIMaxStringCount]; //used to keep the position of strings in the eventPayload parameter
string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter
EventData* userData = stackalloc EventData[argCount]; // allocation for the data descriptors
userDataPtr = (EventData*)userData;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument
byte* currentBuffer = dataBuffer;
//
// The loop below goes through all the arguments and fills in the data
// descriptors. For strings save the location in the dataString array.
// Caculates the total size of the event by adding the data descriptor
// size value set in EncodeObjec method.
//
for (index = 0; index < eventPayload.Length; index++)
{
string isString;
isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer);
currentBuffer += s_basicTypeAllocationBufferSize;
totalEventSize += userDataPtr->Size;
userDataPtr++;
if (isString != null)
{
if (stringIndex < s_etwAPIMaxStringCount)
{
dataString[stringIndex] = isString;
stringPosition[stringIndex] = index;
stringIndex++;
}
else
{
throw new ArgumentOutOfRangeException("eventPayload",
string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount));
}
}
}
if (totalEventSize > s_traceEventMaximumSize)
{
t_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3],
v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7])
{
userDataPtr = (EventData*)userData;
if (dataString[0] != null)
{
userDataPtr[stringPosition[0]].DataPointer = (ulong)v0;
}
if (dataString[1] != null)
{
userDataPtr[stringPosition[1]].DataPointer = (ulong)v1;
}
if (dataString[2] != null)
{
userDataPtr[stringPosition[2]].DataPointer = (ulong)v2;
}
if (dataString[3] != null)
{
userDataPtr[stringPosition[3]].DataPointer = (ulong)v3;
}
if (dataString[4] != null)
{
userDataPtr[stringPosition[4]].DataPointer = (ulong)v4;
}
if (dataString[5] != null)
{
userDataPtr[stringPosition[5]].DataPointer = (ulong)v5;
}
if (dataString[6] != null)
{
userDataPtr[stringPosition[6]].DataPointer = (ulong)v6;
}
if (dataString[7] != null)
{
userDataPtr[stringPosition[7]].DataPointer = (ulong)v7;
}
}
}
status = UnsafeNativeMethods.EventWriteTransfer(_regHandle,
ref eventDescriptor,
(activityId == Guid.Empty) ? null : &activityId,
(relatedActivityId == Guid.Empty) ? null : &relatedActivityId,
(uint)argCount,
userDataPtr);
}
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
[System.Security.SecurityCritical]
protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data)
{
uint status = 0;
Guid activityId = GetActivityId();
unsafe
{
status = UnsafeNativeMethods.EventWriteTransfer(
_regHandle,
ref eventDescriptor,
(activityId == Guid.Empty) ? null : &activityId,
&relatedActivityId,
(uint)dataCount,
(void*)data);
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
[System.Security.SecurityCritical]
private static Guid GetActivityId()
{
return t_activityId;
}
[System.Security.SecurityCritical]
public static void SetActivityId(ref Guid id)
{
t_activityId = id;
UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref id);
}
[System.Security.SecurityCritical]
public static Guid CreateActivityId()
{
Guid newId = new Guid();
UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId);
return newId;
}
}
}
| |
using System;
using System.Windows.Input;
using Xunit;
using Prism.Commands;
namespace Prism.Tests.Mvvm
{
public class CompositeCommandFixture
{
[Fact]
public void RegisterACommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(new TestCommand());
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldDelegateExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.False(testCommand.ExecuteCalled);
multiCommand.Execute(null);
Assert.True(testCommand.ExecuteCalled);
}
[Fact]
public void ShouldDelegateExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(testCommandOne.ExecuteCalled);
Assert.False(testCommandTwo.ExecuteCalled);
multiCommand.Execute(null);
Assert.True(testCommandOne.ExecuteCalled);
Assert.True(testCommandTwo.ExecuteCalled);
}
[Fact]
public void ShouldDelegateCanExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.False(testCommand.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.True(testCommand.CanExecuteCalled);
}
[Fact]
public void ShouldDelegateCanExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(testCommandOne.CanExecuteCalled);
Assert.False(testCommandTwo.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.True(testCommandOne.CanExecuteCalled);
Assert.True(testCommandTwo.CanExecuteCalled);
}
[Fact]
public void CanExecuteShouldReturnTrueIfAllRegistrantsTrue()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.True(multiCommand.CanExecute(null));
}
[Fact]
public void CanExecuteShouldReturnFalseIfASingleRegistrantsFalse()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = false };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(multiCommand.CanExecute(null));
}
[Fact]
public void ShouldReraiseCanExecuteChangedEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldReraiseCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
testCommandOne.FireCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldReraiseDelegateCommandCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
DelegateCommand<object> delegateCommand = new DelegateCommand<object>(delegate { });
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(delegateCommand);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
delegateCommand.RaiseCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void UnregisteringCommandWithNullThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.UnregisterCommand(null);
});
}
[Fact]
public void UnregisterCommandRemovesFromExecuteDelegation()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
Assert.False(testCommandOne.ExecuteCalled);
multiCommand.Execute(null);
Assert.False(testCommandOne.ExecuteCalled);
}
[Fact]
public void UnregisterCommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
multiCommand.UnregisterCommand(testCommandOne);
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ExecuteDoesNotThrowWhenAnExecuteCommandModifiesTheCommandsCollection()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
SelfUnregisterableCommand commandOne = new SelfUnregisterableCommand(multiCommand);
SelfUnregisterableCommand commandTwo = new SelfUnregisterableCommand(multiCommand);
multiCommand.RegisterCommand(commandOne);
multiCommand.RegisterCommand(commandTwo);
multiCommand.Execute(null);
Assert.True(commandOne.ExecutedCalled);
Assert.True(commandTwo.ExecutedCalled);
}
[Fact]
public void UnregisterCommandDisconnectsCanExecuteChangedDelegate()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.False(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void UnregisterCommandDisconnectsIsActiveChangedDelegate()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.True(activeAwareCommand.CanExecute(null));
activeAwareCommand.UnregisterCommand(commandOne);
Assert.False(activeAwareCommand.CanExecute(null));
}
[Fact]
public void ShouldBubbleException()
{
Assert.Throws<DivideByZeroException>(() =>
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
BadDivisionCommand testCommand = new BadDivisionCommand();
multiCommand.RegisterCommand(testCommand);
multiCommand.Execute(null);
});
}
[Fact]
public void CanExecuteShouldReturnFalseWithNoCommandsRegistered()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
Assert.False(multiCommand.CanExecute(null));
}
[Fact]
public void MultiDispatchCommandExecutesActiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand();
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = true;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.True(command.WasExecuted);
}
[Fact]
public void MultiDispatchCommandDoesNotExecutesInactiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = false;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.False(command.WasExecuted);
}
[Fact]
public void DispatchCommandDoesNotIncludeInactiveRegisteredCommandInVoting()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsValid = true;
command.IsActive = false;
Assert.False(activeAwareCommand.CanExecute(null), "Registered Click is inactive so should not participate in CanExecute vote");
command.IsActive = true;
Assert.True(activeAwareCommand.CanExecute(null));
command.IsValid = false;
Assert.False(activeAwareCommand.CanExecute(null));
}
[Fact]
public void DispatchCommandShouldIgnoreInactiveCommandsInCanExecuteVote()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.True(activeAwareCommand.CanExecute(null));
}
[Fact]
public void ActivityCausesActiveAwareCommandToRequeryCanExecute()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsActive = true;
bool globalCanExecuteChangeFired = false;
activeAwareCommand.CanExecuteChanged += delegate
{
globalCanExecuteChangeFired = true;
};
Assert.False(globalCanExecuteChangeFired);
command.IsActive = false;
Assert.True(globalCanExecuteChangeFired);
}
[Fact]
public void ShouldNotMonitorActivityIfUseActiveMonitoringFalse()
{
var mockCommand = new MockActiveAwareCommand();
mockCommand.IsValid = true;
mockCommand.IsActive = true;
var nonActiveAwareCompositeCommand = new CompositeCommand(false);
bool canExecuteChangedRaised = false;
nonActiveAwareCompositeCommand.RegisterCommand(mockCommand);
nonActiveAwareCompositeCommand.CanExecuteChanged += delegate
{
canExecuteChangedRaised = true;
};
mockCommand.IsActive = false;
Assert.False(canExecuteChangedRaised);
nonActiveAwareCompositeCommand.Execute(null);
Assert.True(mockCommand.WasExecuted);
}
[Fact]
public void ShouldRemoveCanExecuteChangedHandler()
{
bool canExecuteChangedRaised = false;
var compositeCommand = new CompositeCommand();
var commmand = new DelegateCommand(() => { });
compositeCommand.RegisterCommand(commmand);
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
compositeCommand.CanExecuteChanged += handler;
commmand.RaiseCanExecuteChanged();
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
compositeCommand.CanExecuteChanged -= handler;
commmand.RaiseCanExecuteChanged();
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void ShouldIgnoreChangesToIsActiveDuringExecution()
{
var firstCommand = new MockActiveAwareCommand { IsActive = true };
var secondCommand = new MockActiveAwareCommand { IsActive = true };
// During execution set the second command to inactive, this should not affect the currently
// executed selection.
firstCommand.ExecuteAction += new Action<object>((object parameter) => secondCommand.IsActive = false);
var compositeCommand = new CompositeCommand(true);
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
compositeCommand.Execute(null);
Assert.True(secondCommand.WasExecuted);
}
[Fact]
public void RegisteringCommandInItselfThrows()
{
Assert.Throws<ArgumentException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(compositeCommand);
});
}
[Fact]
public void RegisteringCommandWithNullThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(null);
});
}
[Fact]
public void RegisteringCommandTwiceThrows()
{
Assert.Throws<InvalidOperationException>(() =>
{
var compositeCommand = new CompositeCommand();
var duplicateCommand = new TestCommand();
compositeCommand.RegisterCommand(duplicateCommand);
compositeCommand.RegisterCommand(duplicateCommand);
});
}
[Fact]
public void ShouldGetRegisteredCommands()
{
var firstCommand = new TestCommand();
var secondCommand = new TestCommand();
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
var commands = compositeCommand.RegisteredCommands;
Assert.True(commands.Count > 0);
}
}
internal class MockActiveAwareCommand : IActiveAware, ICommand
{
private bool _isActive;
public Action<object> ExecuteAction;
#region IActiveAware Members
public bool IsActive
{
get { return _isActive; }
set
{
if (_isActive != value)
{
_isActive = value;
OnActiveChanged(this, EventArgs.Empty);
}
}
}
public event EventHandler IsActiveChanged = delegate { };
#endregion
virtual protected void OnActiveChanged(object sender, EventArgs e)
{
IsActiveChanged(sender, e);
}
public bool WasExecuted { get; set; }
public bool IsValid { get; set; }
#region ICommand Members
public bool CanExecute(object parameter)
{
return IsValid;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
WasExecuted = true;
if (ExecuteAction != null)
ExecuteAction(parameter);
}
#endregion
}
internal class TestableCompositeCommand : CompositeCommand
{
public bool CanExecuteChangedRaised;
private EventHandler handler;
public TestableCompositeCommand()
{
this.handler = ((sender, e) => CanExecuteChangedRaised = true);
CanExecuteChanged += this.handler;
}
}
internal class TestCommand : ICommand
{
public bool CanExecuteCalled { get; set; }
public bool ExecuteCalled { get; set; }
public int ExecuteCallCount { get; set; }
public bool CanExecuteValue = true;
public void FireCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#region ICommand Members
public bool CanExecute(object parameter)
{
CanExecuteCalled = true;
return CanExecuteValue;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
ExecuteCalled = true;
ExecuteCallCount += 1;
}
#endregion
}
internal class BadDivisionCommand : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
throw new DivideByZeroException("Test Divide By Zero");
}
#endregion
}
internal class SelfUnregisterableCommand : ICommand
{
public CompositeCommand Command;
public bool ExecutedCalled = false;
public SelfUnregisterableCommand(CompositeCommand command)
{
Command = command;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Command.UnregisterCommand(this);
ExecutedCalled = true;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using ControlzEx.Theming;
using MahApps.Metro.Automation.Peers;
using MahApps.Metro.Controls.Helper;
namespace MahApps.Metro.Controls.Dialogs
{
/// <summary>
/// The base class for dialogs.
///
/// You probably don't want to use this class, if you want to add arbitrary content to your dialog,
/// use the <see cref="CustomDialog"/> class.
/// </summary>
[TemplatePart(Name = PART_Top, Type = typeof(ContentPresenter))]
[TemplatePart(Name = PART_Content, Type = typeof(ContentPresenter))]
[TemplatePart(Name = PART_Bottom, Type = typeof(ContentPresenter))]
public abstract class BaseMetroDialog : ContentControl
{
private const string PART_Top = "PART_Top";
private const string PART_Content = "PART_Content";
private const string PART_Bottom = "PART_Bottom";
#region DependencyProperties
/// <summary>Identifies the <see cref="ColorScheme"/> dependency property.</summary>
public static readonly DependencyProperty ColorSchemeProperty
= DependencyProperty.Register(nameof(ColorScheme),
typeof(MetroDialogColorScheme),
typeof(BaseMetroDialog),
new PropertyMetadata(MetroDialogColorScheme.Theme));
public MetroDialogColorScheme ColorScheme
{
get => (MetroDialogColorScheme)this.GetValue(ColorSchemeProperty);
set => this.SetValue(ColorSchemeProperty, value);
}
/// <summary>Identifies the <see cref="DialogContentMargin"/> dependency property.</summary>
public static readonly DependencyProperty DialogContentMarginProperty
= DependencyProperty.Register(nameof(DialogContentMargin),
typeof(GridLength),
typeof(BaseMetroDialog),
new PropertyMetadata(new GridLength(25, GridUnitType.Star)));
/// <summary>
/// Gets or sets the left and right margin for the dialog content.
/// </summary>
public GridLength DialogContentMargin
{
get => (GridLength)this.GetValue(DialogContentMarginProperty);
set => this.SetValue(DialogContentMarginProperty, value);
}
/// <summary>Identifies the <see cref="DialogContentWidth"/> dependency property.</summary>
public static readonly DependencyProperty DialogContentWidthProperty
= DependencyProperty.Register(nameof(DialogContentWidth),
typeof(GridLength),
typeof(BaseMetroDialog),
new PropertyMetadata(new GridLength(50, GridUnitType.Star)));
/// <summary>
/// Gets or sets the width for the dialog content.
/// </summary>
public GridLength DialogContentWidth
{
get => (GridLength)this.GetValue(DialogContentWidthProperty);
set => this.SetValue(DialogContentWidthProperty, value);
}
/// <summary>Identifies the <see cref="Title"/> dependency property.</summary>
public static readonly DependencyProperty TitleProperty
= DependencyProperty.Register(nameof(Title),
typeof(string),
typeof(BaseMetroDialog),
new PropertyMetadata(default(string)));
/// <summary>
/// Gets or sets the title of the dialog.
/// </summary>
public string? Title
{
get => (string?)this.GetValue(TitleProperty);
set => this.SetValue(TitleProperty, value);
}
/// <summary>Identifies the <see cref="DialogTop"/> dependency property.</summary>
public static readonly DependencyProperty DialogTopProperty
= DependencyProperty.Register(nameof(DialogTop),
typeof(object),
typeof(BaseMetroDialog),
new PropertyMetadata(null, UpdateLogicalChild));
/// <summary>
/// Gets or sets the content above the dialog.
/// </summary>
public object? DialogTop
{
get => this.GetValue(DialogTopProperty);
set => this.SetValue(DialogTopProperty, value);
}
/// <summary>Identifies the <see cref="DialogBottom"/> dependency property.</summary>
public static readonly DependencyProperty DialogBottomProperty
= DependencyProperty.Register(nameof(DialogBottom),
typeof(object),
typeof(BaseMetroDialog),
new PropertyMetadata(null, UpdateLogicalChild));
/// <summary>
/// Gets or sets the content below the dialog.
/// </summary>
public object? DialogBottom
{
get => this.GetValue(DialogBottomProperty);
set => this.SetValue(DialogBottomProperty, value);
}
/// <summary>Identifies the <see cref="DialogTitleFontSize"/> dependency property.</summary>
public static readonly DependencyProperty DialogTitleFontSizeProperty
= DependencyProperty.Register(nameof(DialogTitleFontSize),
typeof(double),
typeof(BaseMetroDialog),
new PropertyMetadata(26D));
/// <summary>
/// Gets or sets the font size of the dialog title.
/// </summary>
public double DialogTitleFontSize
{
get => (double)this.GetValue(DialogTitleFontSizeProperty);
set => this.SetValue(DialogTitleFontSizeProperty, value);
}
/// <summary>Identifies the <see cref="DialogMessageFontSize"/> dependency property.</summary>
public static readonly DependencyProperty DialogMessageFontSizeProperty
= DependencyProperty.Register(nameof(DialogMessageFontSize),
typeof(double),
typeof(BaseMetroDialog),
new PropertyMetadata(15D));
/// <summary>
/// Gets or sets the font size of the dialog message text.
/// </summary>
public double DialogMessageFontSize
{
get => (double)this.GetValue(DialogMessageFontSizeProperty);
set => this.SetValue(DialogMessageFontSizeProperty, value);
}
/// <summary>Identifies the <see cref="DialogButtonFontSize"/> dependency property.</summary>
public static readonly DependencyProperty DialogButtonFontSizeProperty
= DependencyProperty.Register(nameof(DialogButtonFontSize),
typeof(double),
typeof(BaseMetroDialog),
new PropertyMetadata(SystemFonts.MessageFontSize));
/// <summary>
/// Gets or sets the font size of any dialog buttons.
/// </summary>
public double DialogButtonFontSize
{
get => (double)this.GetValue(DialogButtonFontSizeProperty);
set => this.SetValue(DialogButtonFontSizeProperty, value);
}
/// <summary>Identifies the <see cref="Icon"/> dependency property.</summary>
public static readonly DependencyProperty IconProperty
= DependencyProperty.Register(nameof(Icon),
typeof(object),
typeof(BaseMetroDialog),
new PropertyMetadata());
public object? Icon
{
get => this.GetValue(IconProperty);
set => this.SetValue(IconProperty, value);
}
/// <summary>Identifies the <see cref="IconTemplate"/> dependency property.</summary>
public static readonly DependencyProperty IconTemplateProperty
= DependencyProperty.Register(nameof(IconTemplate),
typeof(DataTemplate),
typeof(BaseMetroDialog));
public DataTemplate? IconTemplate
{
get => (DataTemplate?)this.GetValue(IconTemplateProperty);
set => this.SetValue(IconTemplateProperty, value);
}
#endregion DependencyProperties
public MetroDialogSettings DialogSettings { get; private set; } = null!;
internal SizeChangedEventHandler? SizeChangedHandler { get; set; }
#region Constructor
static BaseMetroDialog()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BaseMetroDialog), new FrameworkPropertyMetadata(typeof(BaseMetroDialog)));
}
/// <summary>
/// Initializes a new <see cref="BaseMetroDialog"/>.
/// </summary>
/// <param name="owningWindow">The window that is the parent of the dialog.</param>
/// <param name="settings">The settings for the message dialog.</param>
protected BaseMetroDialog(MetroWindow? owningWindow, MetroDialogSettings? settings)
{
this.Initialize(owningWindow, settings);
}
/// <summary>
/// Initializes a new <see cref="BaseMetroDialog"/>.
/// </summary>
protected BaseMetroDialog()
: this(null, new MetroDialogSettings())
{
}
#endregion Constructor
private static void UpdateLogicalChild(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
if (dependencyObject is not BaseMetroDialog dialog)
{
return;
}
if (e.OldValue is FrameworkElement oldChild)
{
dialog.RemoveLogicalChild(oldChild);
}
if (e.NewValue is FrameworkElement newChild)
{
dialog.AddLogicalChild(newChild);
newChild.DataContext = dialog.DataContext;
}
}
/// <inheritdoc />
protected override IEnumerator LogicalChildren
{
get
{
// cheat, make a list with all logical content and return the enumerator
ArrayList children = new ArrayList();
if (this.DialogTop != null)
{
children.Add(this.DialogTop);
}
if (this.Content != null)
{
children.Add(this.Content);
}
if (this.DialogBottom != null)
{
children.Add(this.DialogBottom);
}
return children.GetEnumerator();
}
}
/// <summary>
/// With this method it's possible to return your own settings in a custom dialog.
/// </summary>
/// <param name="settings">
/// Settings from the <see cref="MetroWindow.MetroDialogOptions"/> or from constructor.
/// The default is a new created settings.
/// </param>
/// <returns></returns>
protected virtual MetroDialogSettings ConfigureSettings(MetroDialogSettings settings)
{
return settings;
}
private void Initialize(MetroWindow? owningWindow, MetroDialogSettings? settings)
{
AccessKeyHelper.SetIsAccessKeyScope(this, true);
this.OwningWindow = owningWindow;
this.DialogSettings = this.ConfigureSettings(settings ?? owningWindow?.MetroDialogOptions ?? new MetroDialogSettings());
if (this.DialogSettings.CustomResourceDictionary is not null)
{
this.Resources.MergedDictionaries.Add(this.DialogSettings.CustomResourceDictionary);
}
this.SetCurrentValue(ColorSchemeProperty, this.DialogSettings.ColorScheme);
this.SetCurrentValue(IconProperty, this.DialogSettings.Icon);
this.SetCurrentValue(IconTemplateProperty, this.DialogSettings.IconTemplate);
this.HandleThemeChange();
this.DataContextChanged += this.BaseMetroDialogDataContextChanged;
this.Loaded += this.BaseMetroDialogLoaded;
this.Unloaded += this.BaseMetroDialogUnloaded;
}
private void BaseMetroDialogDataContextChanged(object? sender, DependencyPropertyChangedEventArgs e)
{
// MahApps add these content presenter to the dialog with AddLogicalChild method.
// This has the side effect that the DataContext doesn't update, so do this now here.
if (this.DialogTop is FrameworkElement elementTop)
{
elementTop.DataContext = this.DataContext;
}
if (this.DialogBottom is FrameworkElement elementBottom)
{
elementBottom.DataContext = this.DataContext;
}
}
private void BaseMetroDialogLoaded(object? sender, RoutedEventArgs e)
{
ThemeManager.Current.ThemeChanged -= this.HandleThemeManagerThemeChanged;
ThemeManager.Current.ThemeChanged += this.HandleThemeManagerThemeChanged;
this.OnLoaded();
}
private void BaseMetroDialogUnloaded(object? sender, RoutedEventArgs e)
{
ThemeManager.Current.ThemeChanged -= this.HandleThemeManagerThemeChanged;
}
private void HandleThemeManagerThemeChanged(object? sender, ThemeChangedEventArgs e)
{
this.Invoke(this.HandleThemeChange);
}
private static object? TryGetResource(Theme? theme, string key)
{
return theme?.Resources[key];
}
internal void HandleThemeChange()
{
var theme = DetectTheme(this);
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)
|| theme is null)
{
return;
}
switch (this.DialogSettings.ColorScheme)
{
case MetroDialogColorScheme.Theme:
ThemeManager.Current.ChangeTheme(this, this.Resources, theme);
this.SetCurrentValue(BackgroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Background"));
this.SetCurrentValue(ForegroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Foreground"));
break;
case MetroDialogColorScheme.Inverted:
theme = ThemeManager.Current.GetInverseTheme(theme);
if (theme is null)
{
throw new InvalidOperationException("The inverse dialog theme only works if the window theme abides the naming convention. " +
"See ThemeManager.GetInverseAppTheme for more infos");
}
ThemeManager.Current.ChangeTheme(this, this.Resources, theme);
this.SetCurrentValue(BackgroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Background"));
this.SetCurrentValue(ForegroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Foreground"));
break;
case MetroDialogColorScheme.Accented:
ThemeManager.Current.ChangeTheme(this, this.Resources, theme);
this.SetCurrentValue(BackgroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Background.Accent"));
this.SetCurrentValue(ForegroundProperty, TryGetResource(theme, "MahApps.Brushes.Dialog.Foreground.Accent"));
break;
}
if (this.ParentDialogWindow != null)
{
this.ParentDialogWindow.SetCurrentValue(BackgroundProperty, this.Background);
var glowBrush = TryGetResource(theme, "MahApps.Brushes.Dialog.Glow");
if (glowBrush != null)
{
this.ParentDialogWindow.SetCurrentValue(MetroWindow.GlowBrushProperty, glowBrush);
}
}
}
/// <summary>
/// This is called in the loaded event.
/// </summary>
protected virtual void OnLoaded()
{
// nothing here
}
private static Theme? DetectTheme(BaseMetroDialog? dialog)
{
if (dialog is null)
{
return null;
}
// first look for owner
var window = dialog.OwningWindow ?? dialog.TryFindParent<MetroWindow>();
var theme = window != null ? ThemeManager.Current.DetectTheme(window) : null;
if (theme != null)
{
return theme;
}
// second try, look for main window and then for current application
if (Application.Current != null)
{
theme = Application.Current.MainWindow is null
? ThemeManager.Current.DetectTheme(Application.Current)
: ThemeManager.Current.DetectTheme(Application.Current.MainWindow);
if (theme != null)
{
return theme;
}
}
return null;
}
private RoutedEventHandler? dialogOnLoaded;
/// <summary>
/// Waits for the dialog to become ready for interaction.
/// </summary>
/// <returns>A task that represents the operation and it's status.</returns>
public Task WaitForLoadAsync()
{
this.Dispatcher.VerifyAccess();
if (this.IsLoaded)
{
return Task.CompletedTask;
}
var tcs = new TaskCompletionSource<object>();
if (this.DialogSettings.AnimateShow != true)
{
this.SetCurrentValue(OpacityProperty, 1.0); // skip the animation
}
this.dialogOnLoaded = (_, _) =>
{
this.Loaded -= this.dialogOnLoaded;
this.Focus();
tcs.TrySetResult(null!);
};
this.Loaded += this.dialogOnLoaded;
return tcs.Task;
}
/// <summary>
/// Requests an externally shown Dialog to close. Will throw an exception if the Dialog is inside of a MetroWindow.
/// </summary>
public async Task RequestCloseAsync()
{
if (this.OnRequestClose())
{
// Technically, the Dialog is /always/ inside of a MetroWindow.
// If the dialog is inside of a user-created MetroWindow, not one created by the external dialog APIs.
if (this.ParentDialogWindow is null)
{
// this is very bad, or the user called the close event before we can do this
if (this.OwningWindow is null)
{
Trace.TraceWarning($"{this}: Can not request async closing, because the OwningWindow is already null. This can maybe happen if the dialog was closed manually.");
return;
}
// This is from a user-created MetroWindow
await this.OwningWindow.HideMetroDialogAsync(this);
return;
}
// This is from a MetroWindow created by the external dialog APIs.
await this.WaitForCloseAsync();
this.ParentDialogWindow.Close();
}
}
internal void FireOnShown()
{
this.OnShown();
}
protected virtual void OnShown()
{
}
internal void FireOnClose()
{
this.OnClose();
// this is only set when a dialog is shown (externally) in it's OWN window.
this.ParentDialogWindow?.Close();
}
protected virtual void OnClose()
{
}
/// <summary>
/// A last chance virtual method for stopping an external dialog from closing.
/// </summary>
/// <returns></returns>
protected virtual bool OnRequestClose()
{
return true; //allow the dialog to close.
}
/// <summary>
/// Gets the window that owns the current Dialog IF AND ONLY IF the dialog is shown externally.
/// </summary>
protected internal Window? ParentDialogWindow { get; internal set; }
/// <summary>
/// Gets the window that owns the current Dialog IF AND ONLY IF the dialog is shown inside of a window.
/// </summary>
protected MetroWindow? OwningWindow { get; private set; }
/// <summary>
/// Waits until this dialog gets unloaded.
/// </summary>
/// <returns></returns>
public Task WaitUntilUnloadedAsync()
{
var tcs = new TaskCompletionSource<object>();
this.Unloaded += (_, _) => { tcs.TrySetResult(null!); };
return tcs.Task;
}
private EventHandler? closingStoryboardOnCompleted;
public Task WaitForCloseAsync()
{
var tcs = new TaskCompletionSource<object>();
if (this.DialogSettings.AnimateHide)
{
if (this.TryFindResource("MahApps.Storyboard.Dialogs.Close") is not Storyboard closingStoryboard)
{
throw new InvalidOperationException("Unable to find the dialog closing storyboard. Did you forget to add BaseMetroDialog.xaml to your merged dictionaries?");
}
closingStoryboard = closingStoryboard.Clone();
this.closingStoryboardOnCompleted = (_, _) =>
{
closingStoryboard.Completed -= this.closingStoryboardOnCompleted;
tcs.TrySetResult(null!);
};
closingStoryboard.Completed += this.closingStoryboardOnCompleted;
closingStoryboard.Begin(this);
}
else
{
this.SetCurrentValue(OpacityProperty, 0.0);
tcs.TrySetResult(null!); //skip the animation
}
return tcs.Task;
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new MetroDialogAutomationPeer(this);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.System && e.SystemKey is Key.LeftAlt or Key.RightAlt or Key.F10)
{
if (ReferenceEquals(e.Source, this))
{
// Try to look if there is a main menu inside the dialog.
// If no main menu exists then handle the Alt-Key and F10-Key
// to prevent focusing the first menu item at the main menu (window).
var menu = this.FindChildren<Menu>(true).FirstOrDefault(m => m.IsMainMenu);
if (menu is null)
{
e.Handled = true;
}
}
}
base.OnKeyDown(e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI Packet
/// </summary>
internal sealed class SNIPacket
{
private byte[] _data;
private int _length;
#if DEBUG
private string _description;
#endif
private SNIAsyncCallback _completionCallback;
/// <summary>
/// Constructor
/// </summary>
public SNIPacket()
{
}
public SNIPacket(byte[] buffer)
{
_data = buffer;
}
public SNIPacket(byte[] buffer, int length)
{
_data = buffer;
_length = length;
}
#if DEBUG
/// <summary>
/// Packet description (used for debugging)
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
#endif
/// <summary>
/// Length of data
/// </summary>
public int Length
{
get
{
return _length;
}
}
/// <summary>
/// Set async completion callback
/// </summary>
/// <param name="completionCallback">Completion callback</param>
public void SetCompletionCallback(SNIAsyncCallback completionCallback)
{
_completionCallback = completionCallback;
}
/// <summary>
/// Invoke the completion callback
/// </summary>
/// <param name="sniError">SNI error</param>
public void InvokeCompletionCallback(SNIError sniError)
{
_completionCallback(this, sniError);
}
/// <summary>
/// Allocate space for data
/// </summary>
/// <param name="capacity">Bytes to allocate</param>
public void Allocate(int capacity)
{
if ((_data == null) || (_data.Length < capacity))
{
_data = new byte[capacity];
}
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data in packet</param>
public void GetData(byte[] buffer, ref int dataSize)
{
if (_data != buffer)
{
Buffer.BlockCopy(_data, 0, buffer, 0, _length);
}
dataSize = _length;
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void SetData(byte[] data, int length)
{
_data = data;
_length = length;
}
/// <summary>
/// Take data from another packet
/// </summary>
/// <param name="packet">Packet</param>
/// <param name="size">Data to take</param>
/// <returns>Amount of data taken</returns>
public int TakeData(int offset, SNIPacket packet, int size)
{
int dataSize = TakeData(offset, packet._data, packet._length, size);
packet._length += dataSize;
return dataSize;
}
/// <summary>
/// Append data
/// </summary>
/// <param name="data">Data</param>
/// <param name="size">Size</param>
public void AppendData(byte[] data, int size)
{
Buffer.BlockCopy(data, 0, _data, _length, size);
_length += size;
}
/// <summary>
/// Append another packet
/// </summary>
/// <param name="packet">Packet</param>
public void AppendPacket(SNIPacket packet)
{
Buffer.BlockCopy(packet._data, 0, _data, _length, packet._length);
_length += packet._length;
}
/// <summary>
/// Take data from packet and advance offset
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="bufferOffset">Data offset</param>
/// <param name="size">Size</param>
/// <returns></returns>
public int TakeData(int packetOffset, byte[] buffer, int bufferOffset, int size)
{
if (packetOffset >= _length)
{
return 0;
}
if (packetOffset + size > _length)
{
size = _length - packetOffset;
}
Buffer.BlockCopy(_data, packetOffset, buffer, bufferOffset, size);
return size;
}
/// <summary>
/// Read data from a stream asynchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
/// <param name="callback">Completion callback</param>
public void ReadFromStreamAsync(Stream stream, SNIAsyncCallback callback)
{
_completionCallback = callback;
stream.ReadAsync(_data, 0, _data.Length).ContinueWith(
ReadFromStreamAsyncContinuation,
this,
CancellationToken.None,
TaskContinuationOptions.DenyChildAttach,
TaskScheduler.Default);
}
private static void ReadFromStreamAsyncContinuation(Task<int> t, object state)
{
SNIPacket packet = (SNIPacket)state;
SNIError error = null;
Exception e = t.Exception?.InnerException;
if (e != null)
{
error = new SNIError(SNIProviders.TCP_PROV, 0, 0, e.Message);
}
else
{
packet._length = t.Result;
if (packet._length == 0)
{
error = new SNIError(SNIProviders.TCP_PROV, 0, SNIErrorCode.ConnTerminatedError, string.Empty);
}
}
SNIAsyncCallback callback = packet._completionCallback;
packet._completionCallback = null;
callback(packet, error);
}
/// <summary>
/// Read data from a stream synchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
public void ReadFromStream(Stream stream)
{
_length = stream.Read(_data, 0, _data.Length);
}
/// <summary>
/// Write data to a stream synchronously
/// </summary>
/// <param name="stream">Stream to write to</param>
public void WriteToStream(Stream stream)
{
stream.Write(_data, 0, _length);
}
/// <summary>
/// Write data to a stream asynchronously
/// </summary>
/// <param name="stream">Stream to write to</param>
public Task WriteToStreamAsync(Stream stream)
{
return stream.WriteAsync(_data, 0, _length);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
public partial class FileSystemWatcher
{
/// <summary>Start monitoring the current directory.</summary>
private void StartRaisingEvents()
{
// If we're called when "Initializing" is true, set enabled to true
if (IsSuspended())
{
_enabled = true;
return;
}
// If we're already running, don't do anything.
if (!IsHandleInvalid(_directoryHandle))
return;
// Create handle to directory being monitored
_directoryHandle = Interop.Kernel32.CreateFile(
lpFileName: _directory,
dwDesiredAccess: Interop.Kernel32.FileOperations.FILE_LIST_DIRECTORY,
dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write,
dwCreationDisposition: FileMode.Open,
dwFlagsAndAttributes: Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS | Interop.Kernel32.FileOperations.FILE_FLAG_OVERLAPPED);
if (IsHandleInvalid(_directoryHandle))
{
_directoryHandle = null;
throw new FileNotFoundException(SR.Format(SR.FSW_IOError, _directory));
}
// Create the state associated with the operation of monitoring the direction
AsyncReadState state;
try
{
// Start ignoring all events that were initiated before this, and
// allocate the buffer to be pinned and used for the duration of the operation
int session = Interlocked.Increment(ref _currentSession);
byte[] buffer = AllocateBuffer();
// Store all state, including a preallocated overlapped, into the state object that'll be
// passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned
// from now until the end of the operation.
state = new AsyncReadState(session, buffer, _directoryHandle, ThreadPoolBoundHandle.BindHandle(_directoryHandle), this);
unsafe
{
state.PreAllocatedOverlapped = new PreAllocatedOverlapped((errorCode, numBytes, overlappedPointer) =>
{
AsyncReadState state = (AsyncReadState)ThreadPoolBoundHandle.GetNativeOverlappedState(overlappedPointer);
state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer);
if (state.WeakWatcher.TryGetTarget(out FileSystemWatcher watcher))
{
watcher.ReadDirectoryChangesCallback(errorCode, numBytes, state);
}
}, state, buffer);
}
}
catch
{
// Make sure we don't leave a valid directory handle set if we're not running
_directoryHandle.Dispose();
_directoryHandle = null;
throw;
}
// Start monitoring
_enabled = true;
Monitor(state);
}
/// <summary>Stop monitoring the current directory.</summary>
private void StopRaisingEvents()
{
_enabled = false;
if (IsSuspended())
return;
// If we're not running, do nothing.
if (IsHandleInvalid(_directoryHandle))
return;
// Start ignoring all events occurring after this.
Interlocked.Increment(ref _currentSession);
// Close the directory handle. This will cause the async operation to stop processing.
// This operation doesn't need to be atomic because the API will deal with a closed
// handle appropriately. If we get here while asynchronously waiting on a change notification,
// closing the directory handle should cause ReadDirectoryChangesCallback be called,
// cleaning up the operation. Note that it's critical to also null out the handle. If the
// handle is currently in use in a P/Invoke, it will have its reference count temporarily
// increased, such that the disposal operation won't take effect and close the handle
// until that P/Invoke returns; if during that time the FSW is restarted, the IsHandleInvalid
// check will see a valid handle, unless we also null it out.
_directoryHandle.Dispose();
_directoryHandle = null;
}
private void FinalizeDispose()
{
// We must explicitly dispose the handle to ensure it gets closed before this object is finalized.
// Otherwise, it is possible that the GC will decide to finalize the handle after this,
// leaving a window of time where our callback could be invoked on a non-existent object.
if (!IsHandleInvalid(_directoryHandle))
_directoryHandle.Dispose();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// Current "session" ID to ignore old events whenever we stop then restart.
private int _currentSession;
// Unmanaged handle to monitored directory
private SafeFileHandle _directoryHandle;
private static bool IsHandleInvalid(SafeFileHandle handle)
{
return handle == null || handle.IsInvalid || handle.IsClosed;
}
/// <summary>
/// Initiates the next asynchronous read operation if monitoring is still desired.
/// If the directory handle has been closed due to an error or due to event monitoring
/// being disabled, this cleans up state associated with the operation.
/// </summary>
private unsafe void Monitor(AsyncReadState state)
{
// This method should only ever access the directory handle via the state object passed in, and not access it
// via _directoryHandle. While this function is executing asynchronously, another thread could set
// EnableRaisingEvents to false and then back to true, restarting the FSW and causing a new directory handle
// and thread pool binding to be stored. This function could then get into an inconsistent state by doing some
// operations against the old handles and some against the new.
NativeOverlapped* overlappedPointer = null;
bool continueExecuting = false;
try
{
// If shutdown has been requested, exit. The finally block will handle
// cleaning up the entire operation, as continueExecuting will remain false.
if (!_enabled || IsHandleInvalid(state.DirectoryHandle))
return;
// Get the overlapped pointer to use for this iteration.
overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped);
continueExecuting = Interop.Kernel32.ReadDirectoryChangesW(
state.DirectoryHandle,
state.Buffer, // the buffer is kept pinned for the duration of the sync and async operation by the PreAllocatedOverlapped
_internalBufferSize,
_includeSubdirectories,
(uint)_notifyFilters,
null,
overlappedPointer,
null);
}
catch (ObjectDisposedException)
{
// Ignore. Disposing of the handle is the mechanism by which the FSW communicates
// to the asynchronous operation to stop processing.
}
catch (ArgumentNullException)
{
//Ignore. The disposed handle could also manifest as an ArgumentNullException.
Debug.Assert(IsHandleInvalid(state.DirectoryHandle), "ArgumentNullException from something other than SafeHandle?");
}
finally
{
// At this point the operation has either been initiated and we'll let the callback
// handle things from here, or the operation has been stopped or failed, in which case
// we need to cleanup because we're no longer executing.
if (!continueExecuting)
{
// Clean up the overlapped pointer created for this iteration
if (overlappedPointer != null)
{
state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer);
}
// Clean up the thread pool binding created for the entire operation
state.PreAllocatedOverlapped.Dispose();
state.ThreadPoolBinding.Dispose();
// Finally, if the handle was for some reason changed or closed during this call,
// then don't throw an exception. Otherwise, it's a valid error.
if (!IsHandleInvalid(state.DirectoryHandle))
{
OnError(new ErrorEventArgs(new Win32Exception()));
}
}
}
}
/// <summary>Callback invoked when an asynchronous read on the directory handle completes.</summary>
private void ReadDirectoryChangesCallback(uint errorCode, uint numBytes, AsyncReadState state)
{
try
{
if (IsHandleInvalid(state.DirectoryHandle))
return;
if (errorCode != 0)
{
// Inside a service the first completion status is false;
// need to monitor again.
const int ERROR_OPERATION_ABORTED = 995;
if (errorCode != ERROR_OPERATION_ABORTED)
{
OnError(new ErrorEventArgs(new Win32Exception((int)errorCode)));
EnableRaisingEvents = false;
}
return;
}
// Ignore any events that occurred before this "session",
// so we don't get changed or error events after we
// told FSW to stop. Even with this check, though, there's a small
// race condition, as immediately after we do the check, raising
// events could be disabled.
if (state.Session != Volatile.Read(ref _currentSession))
return;
if (numBytes == 0)
{
NotifyInternalBufferOverflowEvent();
}
else
{
ParseEventBufferAndNotifyForEach(state.Buffer);
}
}
finally
{
// Call Monitor again to either start the next iteration or clean up the whole operation.
Monitor(state);
}
}
private unsafe void ParseEventBufferAndNotifyForEach(byte[] buffer)
{
Debug.Assert(buffer != null);
Debug.Assert(buffer.Length > 0);
fixed (byte* b = buffer)
{
Interop.Kernel32.FILE_NOTIFY_INFORMATION* info = (Interop.Kernel32.FILE_NOTIFY_INFORMATION*)b;
ReadOnlySpan<char> oldName = ReadOnlySpan<char>.Empty;
// Parse each event from the buffer and notify appropriate delegates
do
{
// A slightly convoluted piece of code follows. Here's what's happening:
//
// We wish to collapse the poorly done rename notifications from the
// ReadDirectoryChangesW API into a nice rename event. So to do that,
// it's assumed that a FILE_ACTION_RENAMED_OLD_NAME will be followed
// immediately by a FILE_ACTION_RENAMED_NEW_NAME in the buffer, which is
// all that the following code is doing.
//
// On a FILE_ACTION_RENAMED_OLD_NAME, it asserts that no previous one existed
// and saves its name. If there are no more events in the buffer, it'll
// assert and fire a RenameEventArgs with the Name field null.
//
// If a NEW_NAME action comes in with no previous OLD_NAME, we assert and fire
// a rename event with the OldName field null.
//
// If the OLD_NAME and NEW_NAME actions are indeed there one after the other,
// we'll fire the RenamedEventArgs normally and clear oldName.
//
// If the OLD_NAME is followed by another action, we assert and then fire the
// rename event with the Name field null and then fire the next action.
//
// In case it's not a OLD_NAME or NEW_NAME action, we just fire the event normally.
//
// (Phew!)
switch (info->Action)
{
case Interop.Kernel32.FileAction.FILE_ACTION_RENAMED_OLD_NAME:
// Action is renamed from, save the name of the file
oldName = info->FileName;
break;
case Interop.Kernel32.FileAction.FILE_ACTION_RENAMED_NEW_NAME:
// oldName may be empty if we didn't receive FILE_ACTION_RENAMED_OLD_NAME first
NotifyRenameEventArgs(
WatcherChangeTypes.Renamed,
info->FileName,
oldName);
oldName = ReadOnlySpan<char>.Empty;
break;
default:
if (!oldName.IsEmpty)
{
// Previous FILE_ACTION_RENAMED_OLD_NAME with no new name
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, ReadOnlySpan<char>.Empty, oldName);
oldName = ReadOnlySpan<char>.Empty;
}
switch (info->Action)
{
case Interop.Kernel32.FileAction.FILE_ACTION_ADDED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Created, info->FileName);
break;
case Interop.Kernel32.FileAction.FILE_ACTION_REMOVED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, info->FileName);
break;
case Interop.Kernel32.FileAction.FILE_ACTION_MODIFIED:
NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, info->FileName);
break;
default:
Debug.Fail($"Unknown FileSystemEvent action type! Value: {info->Action}");
break;
}
break;
}
info = info->NextEntryOffset == 0 ? null : (Interop.Kernel32.FILE_NOTIFY_INFORMATION*)((byte*)info + info->NextEntryOffset);
} while (info != null);
if (!oldName.IsEmpty)
{
// Previous FILE_ACTION_RENAMED_OLD_NAME with no new name
NotifyRenameEventArgs(WatcherChangeTypes.Renamed, ReadOnlySpan<char>.Empty, oldName);
}
} // fixed()
}
/// <summary>
/// State information used by the ReadDirectoryChangesW callback. A single instance of this is used
/// for an entire session, getting passed to each iterative call to ReadDirectoryChangesW.
/// </summary>
private sealed class AsyncReadState
{
internal AsyncReadState(int session, byte[] buffer, SafeFileHandle handle, ThreadPoolBoundHandle binding, FileSystemWatcher parent)
{
Debug.Assert(buffer != null);
Debug.Assert(buffer.Length > 0);
Debug.Assert(handle != null);
Debug.Assert(binding != null);
Session = session;
Buffer = buffer;
DirectoryHandle = handle;
ThreadPoolBinding = binding;
WeakWatcher = new WeakReference<FileSystemWatcher>(parent);
}
internal int Session { get; }
internal byte[] Buffer { get; }
internal SafeFileHandle DirectoryHandle { get; }
internal ThreadPoolBoundHandle ThreadPoolBinding { get; }
internal PreAllocatedOverlapped PreAllocatedOverlapped { get; set; }
internal WeakReference<FileSystemWatcher> WeakWatcher { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddUInt64()
{
var test = new SimpleBinaryOpTest__AddUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddUInt64 testClass)
{
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddUInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__AddUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Add(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddUInt64();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddUInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Insights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Composite Swagger for Insights Management Client
/// </summary>
public partial class InsightsManagementClient : Microsoft.Rest.ServiceClient<InsightsManagementClient>, IInsightsManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAutoscaleSettingsOperations.
/// </summary>
public virtual IAutoscaleSettingsOperations AutoscaleSettings { get; private set; }
/// <summary>
/// Gets the IServiceDiagnosticSettingsOperations.
/// </summary>
public virtual IServiceDiagnosticSettingsOperations ServiceDiagnosticSettings { get; private set; }
/// <summary>
/// Gets the IAlertRuleIncidentsOperations.
/// </summary>
public virtual IAlertRuleIncidentsOperations AlertRuleIncidents { get; private set; }
/// <summary>
/// Gets the IIncidentsOperations.
/// </summary>
public virtual IIncidentsOperations Incidents { get; private set; }
/// <summary>
/// Gets the IAlertRulesOperations.
/// </summary>
public virtual IAlertRulesOperations AlertRules { get; private set; }
/// <summary>
/// Gets the ILogProfilesOperations.
/// </summary>
public virtual ILogProfilesOperations LogProfiles { get; private set; }
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InsightsManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InsightsManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InsightsManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InsightsManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.AutoscaleSettings = new AutoscaleSettingsOperations(this);
this.ServiceDiagnosticSettings = new ServiceDiagnosticSettingsOperations(this);
this.AlertRuleIncidents = new AlertRuleIncidentsOperations(this);
this.Incidents = new IncidentsOperations(this);
this.AlertRules = new AlertRulesOperations(this);
this.LogProfiles = new LogProfilesOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleCondition>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleCondition>("odata.type"));
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleDataSource>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleDataSource>("odata.type"));
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleAction>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleAction>("odata.type"));
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
namespace NetGore.IO
{
/// <summary>
/// An implementation of an <see cref="IValueReader"/> that allows you to specify during the construction of the object
/// what format to use instead of specifying a specific <see cref="IValueReader"/> and <see cref="IValueWriter"/> directly.
/// The results are the exact same as if the underlying <see cref="IValueReader"/> and <see cref="IValueWriter"/> are
/// used directly. Because of this, you can, for example, use a <see cref="GenericValueReader"/> to read a file written with an
/// <see cref="XmlValueWriter"/> as long as the <see cref="GenericValueReader"/> can recognize the format. However, it is
/// recommended that you always use a <see cref="GenericValueReader"/> and <see cref="GenericValueWriter"/> directly when
/// possible to avoid any issues with format recognition and provide easier alteration of the used formats in the future.
/// </summary>
public class GenericValueReader : IValueReader
{
/// <summary>
/// The maximum length in chars of any of the headers. All formats must be identified using no more than this many chars.
/// </summary>
const int _maxHeaderLength = 8;
/// <summary>
/// Contains the bytes used to recognize an Xml header.
/// </summary>
static readonly char[] _xmlHeader = new char[] { '<', '?', 'x', 'm', 'l', ' ' };
readonly IValueReader _reader;
/// <summary>
/// Initializes the <see cref="GenericValueReader"/> class.
/// </summary>
static GenericValueReader()
{
// Make sure header identifiers are a valid length
Debug.Assert(_xmlHeader.Length <= _maxHeaderLength);
}
/// <summary>
/// Initializes a new instance of the <see cref="GenericValueReader"/> class.
/// </summary>
/// <param name="reader">The <see cref="IValueReader"/> to use to read.</param>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null or empty.</exception>
GenericValueReader(IValueReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
}
/// <summary>
/// Checks if the header bytes are equal to the expected bytes.
/// </summary>
/// <param name="header">The read header bytes.</param>
/// <param name="headerLength">The actual length of the header.</param>
/// <param name="expected">The expected bytes for the header.</param>
/// <returns>True if the <paramref name="header"/> matches the <paramref name="expected"/>; otherwise false.</returns>
static bool CheckFormatHeader(IList<char> header, int headerLength, IList<char> expected)
{
if (headerLength < expected.Count)
return false;
for (var i = 0; i < expected.Count; i++)
{
if (header[i] != expected[i])
return false;
}
return true;
}
/// <summary>
/// Checks if the header bytes are equal to the expected bytes.
/// </summary>
/// <param name="header">The read header bytes.</param>
/// <param name="headerLength">The actual length of the header.</param>
/// <param name="expected">The expected bytes for the header.</param>
/// <returns>True if the <paramref name="header"/> matches the <paramref name="expected"/>; otherwise false.</returns>
static bool CheckFormatHeader(string header, int headerLength, IList<char> expected)
{
if (headerLength < expected.Count)
return false;
for (var i = 0; i < expected.Count; i++)
{
if (header[i] != expected[i])
return false;
}
return true;
}
/// <summary>
/// Creates a <see cref="IValueReader"/> for reading the contents of a file.
/// </summary>
/// <param name="filePath">The path to the file to read.</param>
/// <param name="rootNodeName">The name of the root node. Not used by all formats, but should always be included anyways.</param>
/// <param name="useEnumNames">Whether or not enum names should be used. If true, enum names will always be used. If false, the
/// enum values will be used instead. If null, the default value for the underlying <see cref="IValueReader"/> will be used.</param>
/// <exception cref="ArgumentNullException"><paramref name="filePath"/> is null or empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="rootNodeName"/> is null or empty.</exception>
/// <exception cref="FileLoadException"><paramref name="filePath"/> contains an unsupported format.</exception>
public static IValueReader CreateFromFile(string filePath, string rootNodeName, bool? useEnumNames = null)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException("filePath");
if (string.IsNullOrEmpty(rootNodeName))
throw new ArgumentNullException("rootNodeName");
var reader = CreateReaderFromFile(filePath, rootNodeName, useEnumNames);
return new GenericValueReader(reader);
}
/// <summary>
/// Creates a <see cref="IValueReader"/> for reading the contents of a string.
/// </summary>
/// <param name="data">The string to read.</param>
/// <param name="rootNodeName">The name of the root node. Not used by all formats, but should always be included anyways.</param>
/// <param name="useEnumNames">Whether or not enum names should be used. If true, enum names will always be used. If false, the
/// enum values will be used instead. If null, the default value for the underlying <see cref="IValueReader"/> will be used.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is null or empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="rootNodeName"/> is null or empty.</exception>
public static IValueReader CreateFromString(string data, string rootNodeName, bool? useEnumNames = null)
{
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(rootNodeName))
throw new ArgumentNullException("rootNodeName");
var reader = CreateReaderFromString(data, rootNodeName, useEnumNames);
return new GenericValueReader(reader);
}
/// <summary>
/// Initializes the <see cref="GenericValueReader"/> for reading a file.
/// </summary>
/// <param name="filePath">The path to the file to read.</param>
/// <param name="rootNodeName">The name of the root node. Not used by all formats, but should always be included anyways.</param>
/// <param name="useEnumNames">Whether or not enum names should be used. If true, enum names will always be used. If false, the
/// enum values will be used instead. If null, the default value for the underlying <see cref="IValueReader"/> will be used.</param>
/// <exception cref="FileLoadException"><paramref name="filePath"/> contains an unsupported format.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "FindFileFormat")]
static IValueReader CreateReaderFromFile(string filePath, string rootNodeName, bool? useEnumNames = null)
{
// Discover the format
var format = FindContentFormatForFile(filePath);
Debug.Assert(EnumHelper<GenericValueIOFormat>.IsDefined(format));
// Create the IValueReader of the needed type
switch (format)
{
case GenericValueIOFormat.Binary:
if (useEnumNames.HasValue)
return BinaryValueReader.CreateFromFile(filePath, useEnumNames.Value);
else
return BinaryValueReader.CreateFromFile(filePath);
case GenericValueIOFormat.Xml:
if (useEnumNames.HasValue)
return XmlValueReader.CreateFromFile(filePath, rootNodeName, useEnumNames.Value);
else
return XmlValueReader.CreateFromFile(filePath, rootNodeName);
}
const string errmsg = "Ran into unsupported format `{0}`. Format value was acquired from FindFileFormat().";
Debug.Fail(string.Format(errmsg, format));
throw new FileLoadException(string.Format(errmsg, format));
}
/// <summary>
/// Initializes the <see cref="GenericValueReader"/> for reading a string.
/// </summary>
/// <param name="data">The string to read.</param>
/// <param name="rootNodeName">The name of the root node. Not used by all formats, but should always be included anyways.</param>
/// <param name="useEnumNames">Whether or not enum names should be used. If true, enum names will always be used. If false, the
/// enum values will be used instead. If null, the default value for the underlying <see cref="IValueReader"/> will be used.</param>
/// <exception cref="ArgumentException"><paramref name="data"/> is not formatted in a known format.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "FindFileFormat")]
static IValueReader CreateReaderFromString(string data, string rootNodeName, bool? useEnumNames = null)
{
// Discover the format
var format = FindContentFormatForString(data);
Debug.Assert(EnumHelper<GenericValueIOFormat>.IsDefined(format));
// Create the IValueReader of the needed type
switch (format)
{
case GenericValueIOFormat.Binary:
if (useEnumNames.HasValue)
return BinaryValueReader.CreateFromString(data, useEnumNames.Value);
else
return BinaryValueReader.CreateFromString(data);
case GenericValueIOFormat.Xml:
if (useEnumNames.HasValue)
return XmlValueReader.CreateFromString(data, rootNodeName, useEnumNames.Value);
else
return XmlValueReader.CreateFromString(data, rootNodeName);
}
const string errmsg = "Ran into unsupported format `{0}`. Format value was acquired from FindFileFormat().";
Debug.Fail(string.Format(errmsg, format));
throw new ArgumentException(string.Format(errmsg, format));
}
/// <summary>
/// Finds the <see cref="GenericValueIOFormat"/> is being used for a file.
/// </summary>
/// <param name="filePath">The path to the file to check.</param>
/// <returns>The <see cref="GenericValueIOFormat"/> being used for the content at the <paramref name="filePath"/>.</returns>
public static GenericValueIOFormat FindContentFormatForFile(string filePath)
{
// Grab enough characters from the file to determine the format
var header = new char[_maxHeaderLength];
int headerLength;
using (var fs = new StreamReader(filePath, true))
{
headerLength = fs.Read(header, 0, header.Length);
}
// Check for Xml
if (CheckFormatHeader(header, headerLength, _xmlHeader))
return GenericValueIOFormat.Xml;
// Assume everything else is binary
return GenericValueIOFormat.Binary;
}
/// <summary>
/// Finds the <see cref="GenericValueIOFormat"/> is being used for a string.
/// </summary>
/// <param name="str">The string to check.</param>
/// <returns>The <see cref="GenericValueIOFormat"/> being used for the content in the <paramref name="str"/>.</returns>
public static GenericValueIOFormat FindContentFormatForString(string str)
{
// Check for Xml
if (CheckFormatHeader(str, str.Length, _xmlHeader))
return GenericValueIOFormat.Xml;
// Assume everything else is binary
return GenericValueIOFormat.Binary;
}
#region IValueReader Members
/// <summary>
/// Gets if this <see cref="IValueReader"/> supports using the name field to look up values. If false,
/// values will have to be read back in the same order they were written and the name field will be ignored.
/// </summary>
public bool SupportsNameLookup
{
get { return _reader.SupportsNameLookup; }
}
/// <summary>
/// Gets if this <see cref="IValueReader"/> supports reading nodes. If false, any attempt to use nodes
/// in this IValueWriter will result in a NotSupportedException being thrown.
/// </summary>
public bool SupportsNodes
{
get { return _reader.SupportsNodes; }
}
/// <summary>
/// Gets if Enum I/O will be done with the Enum's name. If true, the name of the Enum value instead of the
/// underlying integer value will be used. If false, the underlying integer value will be used. This
/// only to Enum I/O that does not explicitly state which method to use.
/// </summary>
public bool UseEnumNames
{
get { return _reader.UseEnumNames; }
}
/// <summary>
/// Reads a boolean.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public bool ReadBool(string name)
{
return _reader.ReadBool(name);
}
/// <summary>
/// Reads a 8-bit unsigned integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public byte ReadByte(string name)
{
return _reader.ReadByte(name);
}
/// <summary>
/// Reads a 64-bit floating-point number.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public double ReadDouble(string name)
{
return _reader.ReadDouble(name);
}
/// <summary>
/// Reads an Enum of type <typeparamref name="T"/>. Whether to use the Enum's underlying integer value or the
/// name of the Enum value is determined from the <see cref="IValueReader.UseEnumNames"/> property.
/// </summary>
/// <typeparam name="T">The Type of Enum.</typeparam>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public T ReadEnum<T>(string name) where T : struct, IComparable, IConvertible, IFormattable
{
return _reader.ReadEnum<T>(name);
}
/// <summary>
/// Reads an Enum of type <typeparamref name="T"/> using the Enum's name instead of the value.
/// </summary>
/// <typeparam name="T">The Type of Enum.</typeparam>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public T ReadEnumName<T>(string name) where T : struct, IComparable, IConvertible, IFormattable
{
return _reader.ReadEnumName<T>(name);
}
/// <summary>
/// Reads an Enum of type <typeparamref name="T"/> using the Enum's value instead of the name.
/// </summary>
/// <typeparam name="T">The Type of Enum.</typeparam>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public T ReadEnumValue<T>(string name) where T : struct, IComparable, IConvertible, IFormattable
{
return _reader.ReadEnumValue<T>(name);
}
/// <summary>
/// Reads a 32-bit floating-point number.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public float ReadFloat(string name)
{
return _reader.ReadFloat(name);
}
/// <summary>
/// Reads a 32-bit signed integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public int ReadInt(string name)
{
return _reader.ReadInt(name);
}
/// <summary>
/// Reads a signed integer of up to 32 bits.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <param name="bits">Number of bits to read.</param>
/// <returns>Value read from the reader.</returns>
public int ReadInt(string name, int bits)
{
return _reader.ReadInt(name, bits);
}
/// <summary>
/// Reads a 64-bit signed integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public long ReadLong(string name)
{
return _reader.ReadLong(name);
}
/// <summary>
/// Reads multiple values that were written with WriteMany.
/// </summary>
/// <typeparam name="T">The Type of value to read.</typeparam>
/// <param name="nodeName">The name of the node containing the values.</param>
/// <param name="readHandler">Delegate that reads the values from the IValueReader.</param>
/// <returns>Array of the values read the IValueReader.</returns>
public T[] ReadMany<T>(string nodeName, ReadManyHandler<T> readHandler)
{
return _reader.ReadMany(nodeName, readHandler);
}
/// <summary>
/// Reads multiple nodes that were written with WriteMany.
/// </summary>
/// <typeparam name="T">The Type of nodes to read.</typeparam>
/// <param name="nodeName">The name of the root node containing the values.</param>
/// <param name="readHandler">Delegate that reads the values from the IValueReader.</param>
/// <returns>Array of the values read the IValueReader.</returns>
public T[] ReadManyNodes<T>(string nodeName, ReadManyNodesHandler<T> readHandler)
{
return _reader.ReadManyNodes(nodeName, readHandler);
}
/// <summary>
/// Reads multiple nodes that were written with WriteMany.
/// </summary>
/// <typeparam name="T">The Type of nodes to read.</typeparam>
/// <param name="nodeName">The name of the root node containing the values.</param>
/// <param name="readHandler">Delegate that reads the values from the IValueReader.</param>
/// <param name="handleMissingKey">Allows for handling when a key is missing or invalid instead of throwing
/// an <see cref="Exception"/>. This allows nodes to be read even if one or more of the expected
/// items are missing. The returned array will contain null for these indicies. The int contained in the
/// <see cref="Action{T}"/> contains the 0-based index of the index that failed. This parameter is only
/// valid when <see cref="IValueReader.SupportsNameLookup"/> and <see cref="IValueReader.SupportsNodes"/> are true.
/// Default is null.</param>
/// <returns>
/// Array of the values read from the IValueReader.
/// </returns>
public T[] ReadManyNodes<T>(string nodeName, ReadManyNodesHandler<T> readHandler, Action<int, Exception> handleMissingKey)
{
return _reader.ReadManyNodes(nodeName, readHandler, handleMissingKey);
}
/// <summary>
/// Reads a single child node, while enforcing the idea that there should only be one node
/// in the key. If there is more than one node for the given <paramref name="key"/>, an
/// ArgumentException will be thrown.
/// </summary>
/// <param name="key">The key of the child node to read.</param>
/// <returns>An IValueReader to read the child node.</returns>
/// <exception cref="ArgumentException">Zero or more than one values found for the given
/// <paramref name="key"/>.</exception>
public IValueReader ReadNode(string key)
{
return _reader.ReadNode(key);
}
/// <summary>
/// Reads one or more child nodes from the IValueReader.
/// </summary>
/// <param name="name">Name of the nodes to read.</param>
/// <param name="count">The number of nodes to read. If this value is 0, an empty IEnumerable of IValueReaders
/// will be returned, even if the key could not be found.</param>
/// <returns>An IEnumerable of IValueReaders used to read the nodes.</returns>
/// <exception cref="ArgumentOutOfRangeException">Count is less than 0.</exception>
public IEnumerable<IValueReader> ReadNodes(string name, int count)
{
return _reader.ReadNodes(name, count);
}
/// <summary>
/// Reads a 8-bit signed integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public sbyte ReadSByte(string name)
{
return _reader.ReadSByte(name);
}
/// <summary>
/// Reads a 16-bit signed integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public short ReadShort(string name)
{
return _reader.ReadShort(name);
}
/// <summary>
/// Reads a variable-length string of up to 65535 characters in length.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>String read from the reader.</returns>
public string ReadString(string name)
{
return _reader.ReadString(name);
}
/// <summary>
/// Reads a 32-bit unsigned integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public uint ReadUInt(string name)
{
return _reader.ReadUInt(name);
}
/// <summary>
/// Reads an unsigned integer of up to 32 bits.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <param name="bits">Number of bits to read.</param>
/// <returns>Value read from the reader.</returns>
public uint ReadUInt(string name, int bits)
{
return _reader.ReadUInt(name, bits);
}
/// <summary>
/// Reads a 64-bit unsigned integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public ulong ReadULong(string name)
{
return _reader.ReadULong(name);
}
/// <summary>
/// Reads a 16-bit unsigned integer.
/// </summary>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>Value read from the reader.</returns>
public ushort ReadUShort(string name)
{
return _reader.ReadUShort(name);
}
#endregion
}
}
| |
// -----------------------------------------------------------------------
// Licensed to The .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// -----------------------------------------------------------------------
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Tests.Kerberos.NET.Pac.Interop
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr PfnAllocate(int s);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PfnFree(IntPtr f);
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct MIDL_TYPE_PICKLING_INFO
{
public uint Version;
public uint Flags;
public fixed uint Reserved[3];
}
[StructLayout(LayoutKind.Sequential)]
internal struct RPC_VERSION
{
public ushort MajorVersion;
public ushort MinorVersion;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RPC_SYNTAX_IDENTIFIER
{
public Guid SyntaxGUID;
public RPC_VERSION SyntaxVersion;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RPC_CLIENT_INTERFACE
{
public uint Length;
public RPC_SYNTAX_IDENTIFIER InterfaceId;
public RPC_SYNTAX_IDENTIFIER TransferSyntax;
public IntPtr DispatchTable;
public uint RpcProtseqEndpointCount;
public IntPtr RpcProtseqEndpoint;
public uint Reserved;
public IntPtr InterpreterInfo;
public uint Flags;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MIDL_STUB_DESC
{
public IntPtr RpcInterfaceInformation;
public IntPtr PfnAllocate;
public IntPtr PfnFree;
public IntPtr PHandle;
public IntPtr ApfnNdrRundownRoutines;
public IntPtr AGenericBindingRoutinePairs;
public IntPtr ApfnExprEval;
public IntPtr AXmitQuintuple;
public IntPtr PFormatTypes;
public int FCheckBounds;
public uint Version;
public IntPtr PMallocFreeStruct;
public int MIDLVersion;
public IntPtr CommFaultOffsets;
public IntPtr AUserMarshalQuadruple;
public IntPtr NotifyRoutineTable;
public uint MFlags;
public IntPtr CsRoutineTables;
public IntPtr ProxyServerInfo;
public IntPtr PExprInfo;
}
internal unsafe sealed class PickleMarshaller : IDisposable
{
private const int RpcSOk = 0;
private static readonly PfnAllocate FnAllocator = new PfnAllocate(MIDL_user_allocate);
private static readonly PfnFree FnFree = new PfnFree(MIDL_user_free);
private static readonly MIDL_TYPE_PICKLING_INFO MIDLTypePicklingInfo = new MIDL_TYPE_PICKLING_INFO
{
Version = 0x33205054,
Flags = 0x3
};
private static readonly RPC_CLIENT_INTERFACE RpcClientInterface = new RPC_CLIENT_INTERFACE
{
Length = (uint)sizeof(RPC_CLIENT_INTERFACE),
InterfaceId = new RPC_SYNTAX_IDENTIFIER()
{
SyntaxGUID = new Guid(0x906B0CE0, 0xC70B, 0x1067, 0xB3, 0x17, 0x00, 0xDD, 0x01, 0x06, 0x62, 0xDA),
SyntaxVersion = new RPC_VERSION
{
MajorVersion = 1,
MinorVersion = 0
}
},
TransferSyntax = new RPC_SYNTAX_IDENTIFIER
{
SyntaxGUID = new Guid(0x8A885D04, 0x1CEB, 0x11C9, 0x9F, 0xE8, 0x08, 0x00, 0x2B, 0x10, 0x48, 0x60),
SyntaxVersion = new RPC_VERSION()
{
MajorVersion = 2,
MinorVersion = 0
}
}
};
private readonly int formatOffset;
private readonly MemoryHandle pTypeFormatString;
private readonly GCHandle pRpcInterface;
private bool disposed;
private MIDL_STUB_DESC stubDesc;
public unsafe PickleMarshaller(ReadOnlyMemory<byte> typeFormatString, int formatOffset)
{
this.pTypeFormatString = typeFormatString.Pin();
this.pRpcInterface = GCHandle.Alloc(RpcClientInterface, GCHandleType.Pinned);
this.formatOffset = formatOffset;
this.stubDesc = new MIDL_STUB_DESC
{
RpcInterfaceInformation = this.pRpcInterface.AddrOfPinnedObject(),
PfnAllocate = Marshal.GetFunctionPointerForDelegate(FnAllocator),
PfnFree = Marshal.GetFunctionPointerForDelegate(FnFree),
PFormatTypes = (IntPtr)this.pTypeFormatString.Pointer,
FCheckBounds = 1,
Version = 0x60000,
MIDLVersion = 0x8000000,
MFlags = 0x1
};
}
public unsafe SafeMarshalledHandle<T> Decode<T>(ReadOnlySpan<byte> buffer, Func<IntPtr, T> converter)
{
// WARNING: THIS IS DANGEROUS
//
// THIS CAN BE INCREDIBLY LEAKY BECAUSE IT DOESN'T FREE BUFFERS
// DO NOT FORGET TO FREE THE HANDLE AFTER YOU"VE USED IT
if (this.disposed)
{
throw new ObjectDisposedException(nameof(PickleMarshaller));
}
IntPtr pObj = IntPtr.Zero;
fixed (void* pBuf = &MemoryMarshal.GetReference(buffer))
{
var ret = MesDecodeBufferHandleCreate(
pBuf,
buffer.Length,
out IntPtr ndrHandle
);
if (ret != RpcSOk)
{
throw new Win32Exception(ret);
}
fixed (MIDL_TYPE_PICKLING_INFO* pPicklingInfo = &MIDLTypePicklingInfo)
{
NdrMesTypeDecode2(
ndrHandle,
pPicklingInfo,
ref this.stubDesc,
this.stubDesc.PFormatTypes + this.formatOffset,
ref pObj
);
}
if (pObj == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return new SafeMarshalledHandle<T>(converter(pObj), () => this.FreeNdr(ref ndrHandle, ref pObj));
}
}
private unsafe void FreeNdr(ref IntPtr ndrHandle, ref IntPtr pObj)
{
fixed (MIDL_TYPE_PICKLING_INFO* pPicklingInfo = &MIDLTypePicklingInfo)
{
NdrMesTypeFree2(
ndrHandle,
pPicklingInfo,
ref this.stubDesc,
this.stubDesc.PFormatTypes + this.formatOffset,
ref pObj
);
}
var ret = MesHandleFree(ndrHandle);
if (ret != RpcSOk)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
[DllImport("rpcrt4.dll")]
private static unsafe extern int MesDecodeBufferHandleCreate(
void* pBuffer,
int bufferSize,
out IntPtr pHandle
);
[DllImport("rpcrt4.dll")]
private static unsafe extern void NdrMesTypeDecode2(
IntPtr handle,
MIDL_TYPE_PICKLING_INFO* pPicklingInfo,
ref MIDL_STUB_DESC pStubDesc,
IntPtr pFormatString,
ref IntPtr pObject
);
[DllImport("rpcrt4.dll")]
private static unsafe extern void NdrMesTypeEncode2(
IntPtr handle,
MIDL_TYPE_PICKLING_INFO* pPicklingInfo,
ref MIDL_STUB_DESC pStubDesc,
IntPtr pFormatString,
ref void* pObject
);
[DllImport("rpcrt4.dll")]
private static unsafe extern void NdrMesTypeFree2(
IntPtr handle,
MIDL_TYPE_PICKLING_INFO* pPickingInfo,
ref MIDL_STUB_DESC pStubDesc,
IntPtr pFormatString,
ref IntPtr pObject
);
[DllImport("rpcrt4.dll")]
private static extern int MesHandleFree(IntPtr handle);
private static readonly ConcurrentDictionary<IntPtr, int> Allocations = new ConcurrentDictionary<IntPtr, int>();
private static IntPtr MIDL_user_allocate(int size)
{
var sizePlusPotentialOffset = size + 15;
var pAllocated = Marshal.AllocHGlobal(sizePlusPotentialOffset);
GC.AddMemoryPressure(size);
var pAligned = Align(pAllocated, 8);
if (pAligned == pAllocated)
{
pAligned = IntPtr.Add(pAllocated, 8);
}
var offset = (byte)CalculateOffset(pAligned, pAllocated);
Marshal.WriteByte(pAligned, -1, offset);
Allocations[pAllocated] = size;
return pAligned;
}
private static void MIDL_user_free(IntPtr f)
{
var offset = Marshal.ReadByte(IntPtr.Add(f, -1));
var pAllocated = IntPtr.Add(f, -offset);
Marshal.FreeHGlobal(pAllocated);
if (Allocations.TryRemove(pAllocated, out int allocSize))
{
GC.RemoveMemoryPressure(allocSize);
}
}
private static IntPtr CalculateOffset(IntPtr ptr1, IntPtr ptr2)
{
if (IntPtr.Size == sizeof(int))
{
return new IntPtr(ptr1.ToInt32() - ptr2.ToInt32());
}
if (IntPtr.Size == sizeof(long))
{
return new IntPtr(ptr1.ToInt64() - ptr2.ToInt64());
}
throw new NotSupportedException($"Unknown platform pointer size {IntPtr.Size}");
}
private static IntPtr Align(IntPtr ptr, int align)
{
align--;
if (IntPtr.Size == sizeof(int))
{
return new IntPtr((ptr.ToInt32() + align) & ~align);
}
if (IntPtr.Size == sizeof(long))
{
return new IntPtr((ptr.ToInt64() + align) & ~align);
}
throw new NotSupportedException($"Unknown platform pointer {IntPtr.Size}");
}
public void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.pTypeFormatString.Dispose();
this.pRpcInterface.Free();
}
this.disposed = true;
}
}
~PickleMarshaller()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Xml;
using NPOI.OpenXml4Net.Util;
using System.IO;
namespace NPOI.OpenXmlFormats.Dml
{
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
public enum ST_ShapeType
{
line,
lineInv,
triangle,
rtTriangle,
rect,
diamond,
parallelogram,
trapezoid,
nonIsoscelesTrapezoid,
pentagon,
hexagon,
heptagon,
octagon,
decagon,
dodecagon,
star4,
star5,
star6,
star7,
star8,
star10,
star12,
star16,
star24,
star32,
roundRect,
round1Rect,
round2SameRect,
round2DiagRect,
snipRoundRect,
snip1Rect,
snip2SameRect,
snip2DiagRect,
plaque,
ellipse,
teardrop,
homePlate,
chevron,
pieWedge,
pie,
blockArc,
donut,
noSmoking,
rightArrow,
leftArrow,
upArrow,
downArrow,
stripedRightArrow,
notchedRightArrow,
bentUpArrow,
leftRightArrow,
upDownArrow,
leftUpArrow,
leftRightUpArrow,
quadArrow,
leftArrowCallout,
rightArrowCallout,
upArrowCallout,
downArrowCallout,
leftRightArrowCallout,
upDownArrowCallout,
quadArrowCallout,
bentArrow,
uturnArrow,
circularArrow,
leftCircularArrow,
leftRightCircularArrow,
curvedRightArrow,
curvedLeftArrow,
curvedUpArrow,
curvedDownArrow,
swooshArrow,
cube,
can,
lightningBolt,
heart,
sun,
moon,
smileyFace,
irregularSeal1,
irregularSeal2,
foldedCorner,
bevel,
frame,
halfFrame,
corner,
diagStripe,
chord,
arc,
leftBracket,
rightBracket,
leftBrace,
rightBrace,
bracketPair,
bracePair,
straightConnector1,
bentConnector2,
bentConnector3,
bentConnector4,
bentConnector5,
curvedConnector2,
curvedConnector3,
curvedConnector4,
curvedConnector5,
callout1,
callout2,
callout3,
accentCallout1,
accentCallout2,
accentCallout3,
borderCallout1,
borderCallout2,
borderCallout3,
accentBorderCallout1,
accentBorderCallout2,
accentBorderCallout3,
wedgeRectCallout,
wedgeRoundRectCallout,
wedgeEllipseCallout,
cloudCallout,
cloud,
ribbon,
ribbon2,
ellipseRibbon,
ellipseRibbon2,
leftRightRibbon,
verticalScroll,
horizontalScroll,
wave,
doubleWave,
plus,
flowChartProcess,
flowChartDecision,
flowChartInputOutput,
flowChartPredefinedProcess,
flowChartInternalStorage,
flowChartDocument,
flowChartMultidocument,
flowChartTerminator,
flowChartPreparation,
flowChartManualInput,
flowChartManualOperation,
flowChartConnector,
flowChartPunchedCard,
flowChartPunchedTape,
flowChartSummingJunction,
flowChartOr,
flowChartCollate,
flowChartSort,
flowChartExtract,
flowChartMerge,
flowChartOfflineStorage,
flowChartOnlineStorage,
flowChartMagneticTape,
flowChartMagneticDisk,
flowChartMagneticDrum,
flowChartDisplay,
flowChartDelay,
flowChartAlternateProcess,
flowChartOffpageConnector,
actionButtonBlank,
actionButtonHome,
actionButtonHelp,
actionButtonInformation,
actionButtonForwardNext,
actionButtonBackPrevious,
actionButtonEnd,
actionButtonBeginning,
actionButtonReturn,
actionButtonDocument,
actionButtonSound,
actionButtonMovie,
gear6,
gear9,
funnel,
mathPlus,
mathMinus,
mathMultiply,
mathDivide,
mathEqual,
mathNotEqual,
cornerTabs,
squareTabs,
plaqueTabs,
chartX,
chartStar,
chartPlus,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
public enum ST_TextShapeType
{
textNoShape,
textPlain,
textStop,
textTriangle,
textTriangleInverted,
textChevron,
textChevronInverted,
textRingInside,
textRingOutside,
textArchUp,
textArchDown,
textCircle,
textButton,
textArchUpPour,
textArchDownPour,
textCirclePour,
textButtonPour,
textCurveUp,
textCurveDown,
textCanUp,
textCanDown,
textWave1,
textWave2,
textDoubleWave1,
textWave4,
textInflate,
textDeflate,
textInflateBottom,
textDeflateBottom,
textInflateTop,
textDeflateTop,
textDeflateInflate,
textDeflateInflateDeflate,
textFadeRight,
textFadeLeft,
textFadeUp,
textFadeDown,
textSlantUp,
textSlantDown,
textCascadeUp,
textCascadeDown,
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_GeomGuide
{
private string nameField;
private string fmlaField;
public static CT_GeomGuide Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_GeomGuide ctObj = new CT_GeomGuide();
ctObj.name = XmlHelper.ReadString(node.Attributes["name"]);
ctObj.fmla = XmlHelper.ReadString(node.Attributes["fmla"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "name", this.name);
XmlHelper.WriteAttribute(sw, "fmla", this.fmla);
sw.Write("/>");
}
[XmlAttribute(DataType = "token")]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
[XmlAttribute]
public string fmla
{
get
{
return this.fmlaField;
}
set
{
this.fmlaField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DCubicBezierTo
{
private CT_AdjPoint2D[] ptField;
[XmlElement("pt", Order = 0)]
public CT_AdjPoint2D[] pt
{
get
{
return this.ptField;
}
set
{
this.ptField = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_AdjPoint2D
{
private string xField;
private string yField;
public static CT_AdjPoint2D Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_AdjPoint2D ctObj = new CT_AdjPoint2D();
ctObj.x = XmlHelper.ReadString(node.Attributes["x"]);
ctObj.y = XmlHelper.ReadString(node.Attributes["y"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "x", this.x);
XmlHelper.WriteAttribute(sw, "y", this.y);
sw.Write(">");
sw.Write(string.Format("</a:{0}>", nodeName));
}
[XmlAttribute]
public string x
{
get
{
return this.xField;
}
set
{
this.xField = value;
}
}
[XmlAttribute]
public string y
{
get
{
return this.yField;
}
set
{
this.yField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DQuadBezierTo
{
private CT_AdjPoint2D[] ptField;
[XmlElement("pt", Order = 0)]
public CT_AdjPoint2D[] pt
{
get
{
return this.ptField;
}
set
{
this.ptField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_GeomGuideList
{
private List<CT_GeomGuide> gdField;
[XmlElement("gd", Order = 0)]
public List<CT_GeomGuide> gd
{
get
{
return this.gdField;
}
set
{
this.gdField = value;
}
}
internal static CT_GeomGuideList Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
CT_GeomGuideList avLst = new CT_GeomGuideList();
avLst.gdField = new List<CT_GeomGuide>();
if (node.ChildNodes != null)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "gd")
avLst.gdField.Add(CT_GeomGuide.Parse(childNode, namespaceManager));
}
}
return avLst;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write("<a:{0}>", nodeName);
if (this.gdField != null)
{
foreach (CT_GeomGuide gg in gdField)
{
gg.Write(sw, "gd");
}
}
sw.Write("</a:{0}>", nodeName);
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_GeomRect
{
private string lField;
private string tField;
private string rField;
private string bField;
public static CT_GeomRect Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_GeomRect ctObj = new CT_GeomRect();
ctObj.l = XmlHelper.ReadString(node.Attributes["l"]);
ctObj.t = XmlHelper.ReadString(node.Attributes["t"]);
ctObj.r = XmlHelper.ReadString(node.Attributes["r"]);
ctObj.b = XmlHelper.ReadString(node.Attributes["b"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "l", this.l);
XmlHelper.WriteAttribute(sw, "t", this.t);
XmlHelper.WriteAttribute(sw, "r", this.r);
XmlHelper.WriteAttribute(sw, "b", this.b);
sw.Write("/>");
}
[XmlAttribute]
public string l
{
get
{
return this.lField;
}
set
{
this.lField = value;
}
}
[XmlAttribute]
public string t
{
get
{
return this.tField;
}
set
{
this.tField = value;
}
}
[XmlAttribute]
public string r
{
get
{
return this.rField;
}
set
{
this.rField = value;
}
}
[XmlAttribute]
public string b
{
get
{
return this.bField;
}
set
{
this.bField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_XYAdjustHandle
{
private CT_AdjPoint2D posField;
private string gdRefXField;
private string minXField;
private string maxXField;
private string gdRefYField;
private string minYField;
private string maxYField;
[XmlElement(Order = 0)]
public CT_AdjPoint2D pos
{
get
{
return this.posField;
}
set
{
this.posField = value;
}
}
[XmlAttribute(DataType = "token")]
public string gdRefX
{
get
{
return this.gdRefXField;
}
set
{
this.gdRefXField = value;
}
}
[XmlAttribute]
public string minX
{
get
{
return this.minXField;
}
set
{
this.minXField = value;
}
}
[XmlAttribute]
public string maxX
{
get
{
return this.maxXField;
}
set
{
this.maxXField = value;
}
}
[XmlAttribute(DataType = "token")]
public string gdRefY
{
get
{
return this.gdRefYField;
}
set
{
this.gdRefYField = value;
}
}
[XmlAttribute]
public string minY
{
get
{
return this.minYField;
}
set
{
this.minYField = value;
}
}
[XmlAttribute]
public string maxY
{
get
{
return this.maxYField;
}
set
{
this.maxYField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_PolarAdjustHandle
{
private CT_AdjPoint2D posField;
private string gdRefRField;
private string minRField;
private string maxRField;
private string gdRefAngField;
private string minAngField;
private string maxAngField;
[XmlElement(Order = 0)]
public CT_AdjPoint2D pos
{
get
{
return this.posField;
}
set
{
this.posField = value;
}
}
[XmlAttribute(DataType = "token")]
public string gdRefR
{
get
{
return this.gdRefRField;
}
set
{
this.gdRefRField = value;
}
}
[XmlAttribute]
public string minR
{
get
{
return this.minRField;
}
set
{
this.minRField = value;
}
}
[XmlAttribute]
public string maxR
{
get
{
return this.maxRField;
}
set
{
this.maxRField = value;
}
}
[XmlAttribute(DataType = "token")]
public string gdRefAng
{
get
{
return this.gdRefAngField;
}
set
{
this.gdRefAngField = value;
}
}
[XmlAttribute]
public string minAng
{
get
{
return this.minAngField;
}
set
{
this.minAngField = value;
}
}
[XmlAttribute]
public string maxAng
{
get
{
return this.maxAngField;
}
set
{
this.maxAngField = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_ConnectionSite
{
private CT_AdjPoint2D posField;
private string angField;
public static CT_ConnectionSite Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_ConnectionSite ctObj = new CT_ConnectionSite();
ctObj.ang = XmlHelper.ReadString(node.Attributes["ang"]);
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "pos")
ctObj.pos = CT_AdjPoint2D.Parse(childNode, namespaceManager);
}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "ang", this.ang);
sw.Write(">");
if (this.pos != null)
this.pos.Write(sw, "pos");
sw.Write(string.Format("</a:{0}>", nodeName));
}
[XmlElement(Order = 0)]
public CT_AdjPoint2D pos
{
get
{
return this.posField;
}
set
{
this.posField = value;
}
}
[XmlAttribute]
public string ang
{
get
{
return this.angField;
}
set
{
this.angField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_AdjustHandleList
{
private object[] itemsField;
[XmlElement("ahPolar", typeof(CT_PolarAdjustHandle), Order = 0)]
[XmlElement("ahXY", typeof(CT_XYAdjustHandle), Order = 0)]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_ConnectionSiteList
{
private List<CT_ConnectionSite> cxnField;
//[XmlElement("cxn", Order = 0)]
public List<CT_ConnectionSite> cxn
{
get
{
return this.cxnField;
}
set
{
this.cxnField = value;
}
}
internal static CT_ConnectionSiteList Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
CT_ConnectionSiteList cxnLst = new CT_ConnectionSiteList();
cxnLst.cxnField = new List<CT_ConnectionSite>();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "cxn")
cxnLst.cxnField.Add(CT_ConnectionSite.Parse(childNode, namespaceManager));
}
return cxnLst;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write("<a:{0}>", nodeName);
if (this.cxnField != null)
{
foreach (CT_ConnectionSite gg in cxnField)
{
gg.Write(sw, "cxn");
}
}
sw.Write("</a:{0}>", nodeName);
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Connection
{
private uint idField;
private uint idxField;
public static CT_Connection Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_Connection ctObj = new CT_Connection();
ctObj.id = XmlHelper.ReadUInt(node.Attributes["id"]);
ctObj.idx = XmlHelper.ReadUInt(node.Attributes["idx"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "id", this.id);
XmlHelper.WriteAttribute(sw, "idx", this.idx);
sw.Write("/>");
}
[XmlAttribute]
public uint id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
[XmlAttribute]
public uint idx
{
get
{
return this.idxField;
}
set
{
this.idxField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DMoveTo
{
private CT_AdjPoint2D ptField;
public CT_Path2DMoveTo()
{
this.ptField = new CT_AdjPoint2D();
}
[XmlElement(Order = 0)]
public CT_AdjPoint2D pt
{
get
{
return this.ptField;
}
set
{
this.ptField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DLineTo
{
private CT_AdjPoint2D ptField;
public CT_Path2DLineTo()
{
this.ptField = new CT_AdjPoint2D();
}
[XmlElement(Order = 0)]
public CT_AdjPoint2D pt
{
get
{
return this.ptField;
}
set
{
this.ptField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DArcTo
{
private string wrField;
private string hrField;
private string stAngField;
private string swAngField;
[XmlAttribute]
public string wR
{
get
{
return this.wrField;
}
set
{
this.wrField = value;
}
}
[XmlAttribute]
public string hR
{
get
{
return this.hrField;
}
set
{
this.hrField = value;
}
}
[XmlAttribute]
public string stAng
{
get
{
return this.stAngField;
}
set
{
this.stAngField = value;
}
}
[XmlAttribute]
public string swAng
{
get
{
return this.swAngField;
}
set
{
this.swAngField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DClose
{
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
public enum ST_PathFillMode
{
none,
norm,
lighten,
lightenLess,
darken,
darkenLess,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2D
{
//private object[] itemsField;
private ItemsChoiceType[] itemsElementNameField;
private long wField;
private long hField;
private ST_PathFillMode fillField;
private bool strokeField;
private bool extrusionOkField;
public static CT_Path2D Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_Path2D ctObj = new CT_Path2D();
ctObj.w = XmlHelper.ReadLong(node.Attributes["w"]);
ctObj.h = XmlHelper.ReadLong(node.Attributes["h"]);
if (node.Attributes["fill"] != null)
ctObj.fill = (ST_PathFillMode)Enum.Parse(typeof(ST_PathFillMode), node.Attributes["fill"].Value);
ctObj.stroke = XmlHelper.ReadBool(node.Attributes["stroke"]);
ctObj.extrusionOk = XmlHelper.ReadBool(node.Attributes["extrusionOk"]);
//foreach(XmlNode childNode in node.ChildNodes)
//{
// if(childNode.LocalName == "ItemsElementName")
// ctObj.ItemsElementName = ItemsChoiceType[].Parse(childNode, namespaceManager);
//}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "w", this.w);
XmlHelper.WriteAttribute(sw, "h", this.h);
XmlHelper.WriteAttribute(sw, "fill", this.fill.ToString());
XmlHelper.WriteAttribute(sw, "stroke", this.stroke);
XmlHelper.WriteAttribute(sw, "extrusionOk", this.extrusionOk);
sw.Write(">");
//if (this.ItemsElementName != null)
// this.ItemsElementName.Write(sw, "ItemsElementName");
sw.Write(string.Format("</a:{0}>", nodeName));
}
public CT_Path2D()
{
this.wField = ((long)(0));
this.hField = ((long)(0));
this.fillField = ST_PathFillMode.norm;
this.strokeField = true;
this.extrusionOkField = true;
}
//[XmlElement("arcTo", typeof(CT_Path2DArcTo))]
//[XmlElement("close", typeof(CT_Path2DClose))]
//[XmlElement("cubicBezTo", typeof(CT_Path2DCubicBezierTo))]
//[XmlElement("lnTo", typeof(CT_Path2DLineTo))]
//[XmlElement("moveTo", typeof(CT_Path2DMoveTo))]
//[XmlElement("quadBezTo", typeof(CT_Path2DQuadBezierTo))]
//[XmlChoiceIdentifier("ItemsElementName")]
//public object[] Items
//{
// get
// {
// return this.itemsField;
// }
// set
// {
// this.itemsField = value;
// }
//}
//[XmlElement("ItemsElementName")]
//[XmlIgnore]
//public ItemsChoiceType[] ItemsElementName
//{
// get
// {
// return this.itemsElementNameField;
// }
// set
// {
// this.itemsElementNameField = value;
// }
//}
[XmlAttribute]
[DefaultValue(typeof(long), "0")]
public long w
{
get
{
return this.wField;
}
set
{
this.wField = value;
}
}
[XmlAttribute]
[DefaultValue(typeof(long), "0")]
public long h
{
get
{
return this.hField;
}
set
{
this.hField = value;
}
}
[XmlAttribute]
[DefaultValue(ST_PathFillMode.norm)]
public ST_PathFillMode fill
{
get
{
return this.fillField;
}
set
{
this.fillField = value;
}
}
[XmlAttribute]
[DefaultValue(true)]
public bool stroke
{
get
{
return this.strokeField;
}
set
{
this.strokeField = value;
}
}
[XmlAttribute]
[DefaultValue(true)]
public bool extrusionOk
{
get
{
return this.extrusionOkField;
}
set
{
this.extrusionOkField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IncludeInSchema = false)]
public enum ItemsChoiceType
{
arcTo,
close,
cubicBezTo,
lnTo,
moveTo,
quadBezTo,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_Path2DList
{
private List<CT_Path2D> pathField;
//[XmlElement("path", Order = 0)]
public List<CT_Path2D> path
{
get
{
return this.pathField;
}
set
{
this.pathField = value;
}
}
internal static CT_Path2DList Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
CT_Path2DList pathList = new CT_Path2DList();
pathList.path = new List<CT_Path2D>();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "path")
pathList.pathField.Add(CT_Path2D.Parse(childNode, namespaceManager));
}
return pathList;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write("<a:{0}>", nodeName);
if (this.pathField != null)
{
foreach (CT_Path2D gg in pathField)
{
gg.Write(sw, "path");
}
}
sw.Write("</a:{0}>", nodeName);
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_PresetGeometry2D
{
private CT_GeomGuideList avLstField;
private ST_ShapeType prstField;
public CT_GeomGuideList AddNewAvLst()
{
this.avLstField = new CT_GeomGuideList();
return this.avLstField;
}
public static CT_PresetGeometry2D Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_PresetGeometry2D ctObj = new CT_PresetGeometry2D();
if (node.Attributes["prst"] != null)
ctObj.prst = (ST_ShapeType)Enum.Parse(typeof(ST_ShapeType), node.Attributes["prst"].Value);
if (node.ChildNodes != null)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "avLst")
{
ctObj.avLstField = CT_GeomGuideList.Parse(childNode, namespaceManager);
}
}
}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "prst", this.prst.ToString());
sw.Write(">");
if (this.avLst != null)
{
avLst.Write(sw, "avLst");
}
sw.Write(string.Format("</a:{0}>", nodeName));
}
[XmlElement(Order = 0)]
public CT_GeomGuideList avLst
{
get
{
return this.avLstField;
}
set
{
this.avLstField =value;
}
}
[XmlAttribute]
public ST_ShapeType prst
{
get
{
return this.prstField;
}
set
{
this.prstField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_PresetTextShape
{
public static CT_PresetTextShape Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_PresetTextShape ctObj = new CT_PresetTextShape();
if (node.Attributes["prst"] != null)
ctObj.prst = (ST_TextShapeType)Enum.Parse(typeof(ST_TextShapeType), node.Attributes["prst"].Value);
ctObj.avLst = new List<CT_GeomGuide>();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "avLst")
ctObj.avLst.Add(CT_GeomGuide.Parse(childNode, namespaceManager));
}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "prst", this.prst.ToString());
sw.Write(">");
if (this.avLst != null)
{
foreach (CT_GeomGuide x in this.avLst)
{
x.Write(sw, "avLst");
}
}
sw.Write(string.Format("</a:{0}>", nodeName));
}
private List<CT_GeomGuide> avLstField;
private ST_TextShapeType prstField;
[XmlArray(Order = 0)]
[XmlArrayItem("gd", IsNullable = false)]
public List<CT_GeomGuide> avLst
{
get
{
return this.avLstField;
}
set
{
this.avLstField = value;
}
}
[XmlAttribute]
public ST_TextShapeType prst
{
get
{
return this.prstField;
}
set
{
this.prstField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_CustomGeometry2D
{
private CT_GeomGuideList avLstField;
private CT_GeomGuideList gdLstField;
private List<object> ahLstField;
private CT_ConnectionSiteList cxnLstField;
private CT_GeomRect rectField;
private CT_Path2DList pathLstField;
public static CT_CustomGeometry2D Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_CustomGeometry2D ctObj = new CT_CustomGeometry2D();
ctObj.ahLst = new List<Object>();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "rect")
ctObj.rect = CT_GeomRect.Parse(childNode, namespaceManager);
else if (childNode.LocalName == "avLst")
ctObj.avLst = CT_GeomGuideList.Parse(childNode, namespaceManager);
else if (childNode.LocalName == "gdLst")
ctObj.gdLst = CT_GeomGuideList.Parse(childNode, namespaceManager);
//else if (childNode.LocalName == "ahLst")
// ctObj.ahLst.Add(Object.Parse(childNode, namespaceManager));
else if (childNode.LocalName == "cxnLst")
ctObj.cxnLst = CT_ConnectionSiteList.Parse(childNode, namespaceManager);
else if (childNode.LocalName == "pathLst")
ctObj.pathLst = CT_Path2DList.Parse(childNode, namespaceManager);
}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
sw.Write(">");
if (this.rect != null)
this.rect.Write(sw, "rect");
if (this.avLst != null)
{
this.avLst.Write(sw, "avLst");
}
if (this.gdLst != null)
{
this.gdLst.Write(sw, "gdLst");
}
if (this.cxnLst != null)
{
this.cxnLstField.Write(sw, "cxnLst");
}
if (this.pathLst != null)
{
this.pathLstField.Write(sw, "pathLst");
}
sw.Write(string.Format("</a:{0}>", nodeName));
}
[XmlElement(Order = 0)]
//[XmlArrayItem("gd", IsNullable = false)]
public CT_GeomGuideList avLst
{
get
{
return this.avLstField;
}
set
{
this.avLstField = value;
}
}
[XmlElement(Order = 1)]
//[XmlArrayItem("gd", IsNullable = false)]
public CT_GeomGuideList gdLst
{
get
{
return this.gdLstField;
}
set
{
this.gdLstField = value;
}
}
[XmlArray(Order = 2)]
[XmlArrayItem("ahPolar", typeof(CT_PolarAdjustHandle), IsNullable = false)]
[XmlArrayItem("ahXY", typeof(CT_XYAdjustHandle), IsNullable = false)]
public List<object> ahLst
{
get
{
return this.ahLstField;
}
set
{
this.ahLstField = value;
}
}
[XmlElement(Order = 3)]
//[XmlArrayItem("cxn", IsNullable = false)]
public CT_ConnectionSiteList cxnLst
{
get
{
return this.cxnLstField;
}
set
{
this.cxnLstField = value;
}
}
[XmlElement(Order = 4)]
public CT_GeomRect rect
{
get
{
return this.rectField;
}
set
{
this.rectField = value;
}
}
[XmlElement(Order = 5)]
//[XmlArrayItem("path", IsNullable = false)]
public CT_Path2DList pathLst
{
get
{
return this.pathLstField;
}
set
{
this.pathLstField = value;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gctv = Google.Cloud.Translate.V3;
using sys = System;
namespace Google.Cloud.Translate.V3
{
/// <summary>Resource name for the <c>Glossary</c> resource.</summary>
public sealed partial class GlossaryName : gax::IResourceName, sys::IEquatable<GlossaryName>
{
/// <summary>The possible contents of <see cref="GlossaryName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </summary>
ProjectLocationGlossary = 1,
}
private static gax::PathTemplate s_projectLocationGlossary = new gax::PathTemplate("projects/{project}/locations/{location}/glossaries/{glossary}");
/// <summary>Creates a <see cref="GlossaryName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GlossaryName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static GlossaryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GlossaryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GlossaryName"/> with the pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="glossaryId">The <c>Glossary</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="GlossaryName"/> constructed from the provided ids.</returns>
public static GlossaryName FromProjectLocationGlossary(string projectId, string locationId, string glossaryId) =>
new GlossaryName(ResourceNameType.ProjectLocationGlossary, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), glossaryId: gax::GaxPreconditions.CheckNotNullOrEmpty(glossaryId, nameof(glossaryId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GlossaryName"/> with pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="glossaryId">The <c>Glossary</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GlossaryName"/> with pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string glossaryId) =>
FormatProjectLocationGlossary(projectId, locationId, glossaryId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GlossaryName"/> with pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="glossaryId">The <c>Glossary</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GlossaryName"/> with pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>.
/// </returns>
public static string FormatProjectLocationGlossary(string projectId, string locationId, string glossaryId) =>
s_projectLocationGlossary.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(glossaryId, nameof(glossaryId)));
/// <summary>Parses the given resource name string into a new <see cref="GlossaryName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/glossaries/{glossary}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="glossaryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GlossaryName"/> if successful.</returns>
public static GlossaryName Parse(string glossaryName) => Parse(glossaryName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GlossaryName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/glossaries/{glossary}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="glossaryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GlossaryName"/> if successful.</returns>
public static GlossaryName Parse(string glossaryName, bool allowUnparsed) =>
TryParse(glossaryName, allowUnparsed, out GlossaryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GlossaryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/glossaries/{glossary}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="glossaryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GlossaryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string glossaryName, out GlossaryName result) => TryParse(glossaryName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GlossaryName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/glossaries/{glossary}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="glossaryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GlossaryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string glossaryName, bool allowUnparsed, out GlossaryName result)
{
gax::GaxPreconditions.CheckNotNull(glossaryName, nameof(glossaryName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationGlossary.TryParseName(glossaryName, out resourceName))
{
result = FromProjectLocationGlossary(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(glossaryName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GlossaryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string glossaryId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
GlossaryId = glossaryId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GlossaryName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/glossaries/{glossary}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="glossaryId">The <c>Glossary</c> ID. Must not be <c>null</c> or empty.</param>
public GlossaryName(string projectId, string locationId, string glossaryId) : this(ResourceNameType.ProjectLocationGlossary, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), glossaryId: gax::GaxPreconditions.CheckNotNullOrEmpty(glossaryId, nameof(glossaryId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Glossary</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string GlossaryId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationGlossary: return s_projectLocationGlossary.Expand(ProjectId, LocationId, GlossaryId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GlossaryName);
/// <inheritdoc/>
public bool Equals(GlossaryName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GlossaryName a, GlossaryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GlossaryName a, GlossaryName b) => !(a == b);
}
public partial class TranslateTextRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DetectLanguageRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetSupportedLanguagesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class BatchTranslateTextRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class Glossary
{
/// <summary>
/// <see cref="gctv::GlossaryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::GlossaryName GlossaryName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::GlossaryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateGlossaryRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetGlossaryRequest
{
/// <summary>
/// <see cref="gctv::GlossaryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::GlossaryName GlossaryName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::GlossaryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteGlossaryRequest
{
/// <summary>
/// <see cref="gctv::GlossaryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::GlossaryName GlossaryName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::GlossaryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListGlossariesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class BatchTranslateDocumentRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Awards and Prizes Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGWDataSet : EduHubDataSet<KGW>
{
/// <inheritdoc />
public override string Name { get { return "KGW"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KGWDataSet(EduHubContext Context)
: base(Context)
{
Index_AWARD = new Lazy<Dictionary<string, KGW>>(() => this.ToDictionary(i => i.AWARD));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGW" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGW" /> fields for each CSV column header</returns>
internal override Action<KGW, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGW, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "AWARD":
mapper[i] = (e, v) => e.AWARD = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGW" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGW" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGW" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGW}"/> of entities</returns>
internal override IEnumerable<KGW> ApplyDeltaEntities(IEnumerable<KGW> Entities, List<KGW> DeltaEntities)
{
HashSet<string> Index_AWARD = new HashSet<string>(DeltaEntities.Select(i => i.AWARD));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.AWARD;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_AWARD.Remove(entity.AWARD);
if (entity.AWARD.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KGW>> Index_AWARD;
#endregion
#region Index Methods
/// <summary>
/// Find KGW by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find KGW</param>
/// <returns>Related KGW entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGW FindByAWARD(string AWARD)
{
return Index_AWARD.Value[AWARD];
}
/// <summary>
/// Attempt to find KGW by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find KGW</param>
/// <param name="Value">Related KGW entity</param>
/// <returns>True if the related KGW entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByAWARD(string AWARD, out KGW Value)
{
return Index_AWARD.Value.TryGetValue(AWARD, out Value);
}
/// <summary>
/// Attempt to find KGW by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find KGW</param>
/// <returns>Related KGW entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGW TryFindByAWARD(string AWARD)
{
KGW value;
if (Index_AWARD.Value.TryGetValue(AWARD, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGW table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGW]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGW](
[AWARD] varchar(10) NOT NULL,
[DESCRIPTION] varchar(30) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KGW_Index_AWARD] PRIMARY KEY CLUSTERED (
[AWARD] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KGWDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KGWDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGW"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGW"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGW> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_AWARD = new List<string>();
foreach (var entity in Entities)
{
Index_AWARD.Add(entity.AWARD);
}
builder.AppendLine("DELETE [dbo].[KGW] WHERE");
// Index_AWARD
builder.Append("[AWARD] IN (");
for (int index = 0; index < Index_AWARD.Count; index++)
{
if (index != 0)
builder.Append(", ");
// AWARD
var parameterAWARD = $"@p{parameterIndex++}";
builder.Append(parameterAWARD);
command.Parameters.Add(parameterAWARD, SqlDbType.VarChar, 10).Value = Index_AWARD[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGW data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGW data set</returns>
public override EduHubDataSetDataReader<KGW> GetDataSetDataReader()
{
return new KGWDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGW data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGW data set</returns>
public override EduHubDataSetDataReader<KGW> GetDataSetDataReader(List<KGW> Entities)
{
return new KGWDataReader(new EduHubDataSetLoadedReader<KGW>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGWDataReader : EduHubDataSetDataReader<KGW>
{
public KGWDataReader(IEduHubDataSetReader<KGW> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 5; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // AWARD
return Current.AWARD;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // LW_DATE
return Current.LW_DATE;
case 3: // LW_TIME
return Current.LW_TIME;
case 4: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // LW_DATE
return Current.LW_DATE == null;
case 3: // LW_TIME
return Current.LW_TIME == null;
case 4: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // AWARD
return "AWARD";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // LW_DATE
return "LW_DATE";
case 3: // LW_TIME
return "LW_TIME";
case 4: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "AWARD":
return 0;
case "DESCRIPTION":
return 1;
case "LW_DATE":
return 2;
case "LW_TIME":
return 3;
case "LW_USER":
return 4;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using Pathfinding;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/GraphUpdateScene")]
/** Helper class for easily updating graphs.
*
* \see \ref graph-updates
* for an explanation of how to use this class.
*/
public class GraphUpdateScene : GraphModifier {
/** Points which define the region to update */
public Vector3[] points;
/** Private cached convex hull of the #points */
private Vector3[] convexPoints;
[HideInInspector]
/** Use the convex hull (XZ space) of the points. */
public bool convex = true;
[HideInInspector]
/** Minumum height of the bounds of the resulting Graph Update Object.
* Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a
* zero height graph update object would usually result in no nodes being updated.
*/
public float minBoundsHeight = 1;
[HideInInspector]
/** Penalty to add to nodes.
* Be careful when setting negative values since if a node get's a negative penalty it will underflow and instead get
* really large. In most cases a warning will be logged if that happens.
*/
public int penaltyDelta = 0;
[HideInInspector]
/** Set to true to set all targeted nodese walkability to #setWalkability */
public bool modifyWalkability = false;
[HideInInspector]
/** See #modifyWalkability */
public bool setWalkability = false;
[HideInInspector]
/** Apply this graph update object on start */
public bool applyOnStart = true;
[HideInInspector]
/** Apply this graph update object whenever a graph is rescanned */
public bool applyOnScan = true;
/** Use world space for coordinates.
* If true, the shape will not follow when moving around the transform.
*
* \see #ToggleUseWorldSpace
*/
[HideInInspector]
public bool useWorldSpace = false;
/** Update node's walkability and connectivity using physics functions.
* For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph.
* If enabled for grid graphs, #modifyWalkability will be ignored.
*
* For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object
* using raycasts (if enabled).
*
*/
[HideInInspector]
public bool updatePhysics = false;
/** \copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics */
[HideInInspector]
public bool resetPenaltyOnPhysics = true;
/** \copydoc Pathfinding::GraphUpdateObject::updateErosion */
[HideInInspector]
public bool updateErosion = true;
[HideInInspector]
/** Lock all points to Y = #lockToYValue */
public bool lockToY = false;
[HideInInspector]
/** if #lockToY is enabled lock all points to this value */
public float lockToYValue = 0;
[HideInInspector]
/** If enabled, set all nodes' tags to #setTag */
public bool modifyTag = false;
[HideInInspector]
/** If #modifyTag is enabled, set all nodes' tags to this value */
public int setTag = 0;
/** Private cached inversion of #setTag.
* Used for InvertSettings() */
private int setTagInvert = 0;
/** Has apply been called yet.
* Used to prevent applying twice when both applyOnScan and applyOnStart are enabled */
private bool firstApplied = false;
/** Do some stuff at start */
public void Start () {
//If firstApplied is true, that means the graph was scanned during Awake.
//So we shouldn't apply it again because then we would end up applying it two times
if (!firstApplied && applyOnStart) {
Apply ();
}
}
public override void OnPostScan () {
if (applyOnScan) Apply ();
}
/** Inverts all invertable settings for this GUS.
* Namely: penalty delta, walkability, tags.
*
* Penalty delta will be changed to negative penalty delta.\n
* #setWalkability will be inverted.\n
* #setTag will be stored in a private variable, and the new value will be 0. When calling this function again, the saved
* value will be the new value.
*
* Calling this function an even number of times without changing any settings in between will be identical to no change in settings.
*/
public virtual void InvertSettings () {
setWalkability = !setWalkability;
penaltyDelta = -penaltyDelta;
if (setTagInvert == 0) {
setTagInvert = setTag;
setTag = 0;
} else {
setTag = setTagInvert;
setTagInvert = 0;
}
}
/** Recalculate convex points.
* Will not do anything if not #convex is enabled
*/
public void RecalcConvex () {
if (convex) convexPoints = Polygon.ConvexHull (points); else convexPoints = null;
}
/** Switches between using world space and using local space.
* Changes point coordinates to stay the same in world space after the change.
*
* \see #useWorldSpace
*/
public void ToggleUseWorldSpace () {
useWorldSpace = !useWorldSpace;
if (points == null) return;
convexPoints = null;
Matrix4x4 matrix = useWorldSpace ? transform.localToWorldMatrix : transform.worldToLocalMatrix;
for (int i=0;i<points.Length;i++) {
points[i] = matrix.MultiplyPoint3x4 (points[i]);
}
}
/** Lock all points to a specific Y value.
*
* \see lockToYValue
*/
public void LockToY () {
if (points == null) return;
for (int i=0;i<points.Length;i++)
points[i].y = lockToYValue;
}
/** Apply the update.
* Will only do anything if #applyOnScan is enabled */
public void Apply (AstarPath active) {
if (applyOnScan) {
Apply ();
}
}
/** Calculates the bounds for this component.
* This is a relatively expensive operation, it needs to go through all points and
* sometimes do matrix multiplications.
*/
public Bounds GetBounds () {
Bounds b;
if (points == null || points.Length == 0) {
var coll = GetComponent<Collider>();
var rend = GetComponent<Renderer>();
if (coll != null) b = coll.bounds;
else if (rend != null) b = rend.bounds;
else {
//Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached");
return new Bounds(Vector3.zero, Vector3.zero);
}
} else {
Matrix4x4 matrix = Matrix4x4.identity;
if (!useWorldSpace) {
matrix = transform.localToWorldMatrix;
}
Vector3 min = matrix.MultiplyPoint3x4(points[0]);
Vector3 max = matrix.MultiplyPoint3x4(points[0]);
for (int i=0;i<points.Length;i++) {
Vector3 p = matrix.MultiplyPoint3x4(points[i]);
min = Vector3.Min (min,p);
max = Vector3.Max (max,p);
}
b = new Bounds ((min+max)*0.5F,max-min);
}
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
return b;
}
/** Updates graphs with a created GUO.
* Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
* representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
* This will not update graphs directly. See AstarPath.UpdateGraph for more info.
*/
public void Apply () {
if (AstarPath.active == null) {
Debug.LogError ("There is no AstarPath object in the scene");
return;
}
GraphUpdateObject guo;
if (points == null || points.Length == 0) {
var coll = GetComponent<Collider>();
var rend = GetComponent<Renderer>();
Bounds b;
if (coll != null) b = coll.bounds;
else if (rend != null) b = rend.bounds;
else {
Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached");
return;
}
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
guo = new GraphUpdateObject (b);
} else {
Pathfinding.GraphUpdateShape shape = new Pathfinding.GraphUpdateShape ();
shape.convex = convex;
Vector3[] worldPoints = points;
if (!useWorldSpace) {
worldPoints = new Vector3[points.Length];
Matrix4x4 matrix = transform.localToWorldMatrix;
for (int i=0;i<worldPoints.Length;i++) worldPoints[i] = matrix.MultiplyPoint3x4 (points[i]);
}
shape.points = worldPoints;
Bounds b = shape.GetBounds ();
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
guo = new GraphUpdateObject (b);
guo.shape = shape;
}
firstApplied = true;
guo.modifyWalkability = modifyWalkability;
guo.setWalkability = setWalkability;
guo.addPenalty = penaltyDelta;
guo.updatePhysics = updatePhysics;
guo.updateErosion = updateErosion;
guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;
guo.modifyTag = modifyTag;
guo.setTag = setTag;
AstarPath.active.UpdateGraphs (guo);
}
/** Draws some gizmos */
public void OnDrawGizmos () {
OnDrawGizmos (false);
}
/** Draws some gizmos */
public void OnDrawGizmosSelected () {
OnDrawGizmos (true);
}
/** Draws some gizmos */
public void OnDrawGizmos (bool selected) {
Color c = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f);
if (selected) {
Gizmos.color = Color.Lerp (c, new Color (1,1,1,0.2f), 0.9f);
Bounds b = GetBounds ();
Gizmos.DrawCube (b.center, b.size);
Gizmos.DrawWireCube (b.center, b.size);
}
if (points == null) return;
if (convex) {
c.a *= 0.5f;
}
Gizmos.color = c;
Matrix4x4 matrix = useWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix;
if (convex) {
c.r -= 0.1f;
c.g -= 0.2f;
c.b -= 0.1f;
Gizmos.color = c;
}
if (selected || !convex) {
for (int i=0;i<points.Length;i++) {
Gizmos.DrawLine (matrix.MultiplyPoint3x4(points[i]),matrix.MultiplyPoint3x4(points[(i+1)%points.Length]));
}
}
if (convex) {
if (convexPoints == null) RecalcConvex ();
Gizmos.color = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f);
for (int i=0;i<convexPoints.Length;i++) {
Gizmos.DrawLine (matrix.MultiplyPoint3x4(convexPoints[i]),matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length]));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using OpenCV.Core;
using OpenCV.Android;
using Android.Util;
using Size = Android.Hardware.Camera.Size;
using Java.Text;
using Java.Util;
using Java.Lang;
using JavaObject = Java.Lang.Object;
namespace OpenCV.SDKDemo.CameraControl
{
[Activity(Label = "CameraControlActivity")]
public class CameraControlActivity : Activity, View.IOnTouchListener, CameraBridgeViewBase.ICvCameraViewListener2
{
public const string TAG = "OCVSample::Activity";
private CameraControlView mOpenCvCameraView;
private List<Size> mResolutionList;
private IMenuItem[] mEffectMenuItems;
private ISubMenu mColorEffectsMenu;
private IMenuItem[] mResolutionMenuItems;
private ISubMenu mResolutionMenu;
private BaseLoaderCallback mLoaderCallback;
public CameraControlActivity()
{
Log.Info(TAG, "Instantiated new " + GetType().ToString());
}
protected override void OnCreate(Bundle savedInstanceState)
{
Log.Info(TAG, "called onCreate");
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.tutorial3_surface_view);
mOpenCvCameraView = FindViewById<CameraControlView>(Resource.Id.tutorial3_activity_java_surface_view);
mOpenCvCameraView.Visibility = ViewStates.Visible;
mOpenCvCameraView.SetCvCameraViewListener2(this);
mLoaderCallback = new Callback(this, mOpenCvCameraView, this);
}
protected override void OnPause()
{
base.OnPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.DisableView();
}
protected override void OnResume()
{
base.OnResume();
if (!OpenCVLoader.InitDebug())
{
Log.Debug(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.InitAsync(OpenCVLoader.OpencvVersion300, this, mLoaderCallback);
}
else
{
Log.Debug(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.OnManagerConnected(LoaderCallbackInterface.Success);
}
}
protected override void OnDestroy()
{
base.OnDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.DisableView();
}
public void OnCameraViewStarted(int width, int height)
{
}
public void OnCameraViewStopped()
{
}
public Mat OnCameraFrame(CameraBridgeViewBase.ICvCameraViewFrame inputFrame)
{
return inputFrame.Rgba();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
IList<string> effects = mOpenCvCameraView.getEffectList();
if (effects == null)
{
Log.Error(TAG, "Color effects are not supported by device!");
return true;
}
mColorEffectsMenu = menu.AddSubMenu("Color Effect");
mEffectMenuItems = new IMenuItem[effects.Count];
int idx = 0;
foreach (var item in effects)
{
string element = item;
mEffectMenuItems[idx] = mColorEffectsMenu.Add(1, idx, Menu.None, element);
idx++;
}
mResolutionMenu = menu.AddSubMenu("Resolution");
mResolutionList = mOpenCvCameraView.getResolutionList();
mResolutionMenuItems = new IMenuItem[mResolutionList.Count];
idx = 0;
foreach (var item in mResolutionList)
{
Size element = item;
mResolutionMenuItems[idx] = mResolutionMenu.Add(2, idx, Menu.None,
element.Width.ToString() + "x" + element.Height.ToString());
idx++;
}
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
Log.Info(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item.GroupId == 1)
{
mOpenCvCameraView.setEffect((string)item.TitleFormatted.ToString());
Toast.MakeText(this, mOpenCvCameraView.getEffect(), ToastLength.Short).Show();
}
else if (item.GroupId == 2)
{
int id = item.ItemId;
Size resolution = mResolutionList[id];
mOpenCvCameraView.setResolution(resolution);
resolution = mOpenCvCameraView.getResolution();
string caption = resolution.Width.ToString() + "x" + resolution.Height.ToString();
Toast.MakeText(this, caption, ToastLength.Short).Show();
}
return true;
}
public bool OnTouch(View v, MotionEvent e)
{
Log.Info(TAG, "onTouch event");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
string currentDateandTime = sdf.Format(new Date());
string fileName = global::Android.OS.Environment.ExternalStorageDirectory.Path +
"/sample_picture_" + currentDateandTime + ".jpg";
mOpenCvCameraView.TakePicture(fileName);
Toast.MakeText(this, fileName + " saved", ToastLength.Short).Show();
return false;
}
}
class Callback : BaseLoaderCallback
{
private readonly Context _context;
private readonly CameraControlView mOpenCvCameraView;
private readonly View.IOnTouchListener _listener;
public Callback(Context context, CameraControlView view, View.IOnTouchListener listener)
: base(context)
{
_context = context;
mOpenCvCameraView = view;
_listener = listener;
}
public override void OnManagerConnected(int status)
{
switch (status)
{
case LoaderCallbackInterface.Success:
{
Log.Info(CameraControlActivity.TAG, "OpenCV loaded successfully");
mOpenCvCameraView.EnableView();
mOpenCvCameraView.SetOnTouchListener(_listener);
}
break;
default:
{
base.OnManagerConnected(status);
}
break;
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Runtime;
using System.Xml.XPath;
using System.Xml.Xsl;
class PushContextNodeOpcode : Opcode
{
internal PushContextNodeOpcode()
: base(OpcodeID.PushContextNode)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushContextSequenceFrame();
NodeSequence seq = context.CreateSequence();
seq.StartNodeset();
seq.Add(context.Processor.ContextNode);
seq.StopNodeset();
context.PushSequence(seq);
return this.next;
}
}
class PushContextPositionOpcode : Opcode
{
internal PushContextPositionOpcode()
: base(OpcodeID.PushPosition)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.TransferSequencePositions();
return this.next;
}
}
class PopSequenceToValueStackOpcode : Opcode
{
internal PopSequenceToValueStackOpcode()
: base(OpcodeID.PopSequenceToValueStack)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.PopSequenceFrameToValueStack();
return this.next;
}
}
class PopSequenceToSequenceStackOpcode : Opcode
{
internal PopSequenceToSequenceStackOpcode()
: base(OpcodeID.PopSequenceToSequenceStack)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushSequenceFrameFromValueStack();
return this.next;
}
}
#if NO
internal class PushContextCopy : Opcode
{
internal PushContextCopy()
: base(OpcodeID.PushContextCopy)
{
}
internal override Opcode Eval(ProcessingContext context)
{
NodeSequenceStack stack = context.SequenceStack;
StackFrame sequences = stack.TopArg;
stack.PushFrame();
for (int i = 0; i < sequences.count; ++i)
{
NodeSequence sourceSeq = stack.Sequences[sequences[i]];
sourceSeq.refCount++;
stack.Push(sourceSeq);
}
return this.next;
}
}
#endif
class PopContextNodes : Opcode
{
internal PopContextNodes()
: base(OpcodeID.PopContextNodes)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.PopContextSequenceFrame();
return this.next;
}
}
#if NO
internal class PopValueFrameOpcode : Opcode
{
internal PopValueFrameOpcode()
: base(OpcodeID.PopValueFrame)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.PopFrame();
return this.next;
}
}
#endif
class PushStringOpcode : Opcode
{
string literal;
internal PushStringOpcode(string literal)
: base(OpcodeID.PushString)
{
Fx.Assert(null != literal, "");
this.literal = literal;
this.flags |= OpcodeFlags.Literal;
}
internal override bool Equals(Opcode op)
{
if (base.Equals(op))
{
return (this.literal == ((PushStringOpcode)op).literal);
}
return false;
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushFrame();
int count = context.IterationCount;
if (count > 0)
{
context.Push(this.literal, count);
}
return this.next;
}
#if DEBUG_FILTER
public override string ToString()
{
return string.Format("{0} {1}", base.ToString(), this.literal);
}
#endif
}
class PushNumberOpcode : Opcode
{
double literal;
internal PushNumberOpcode(double literal)
: base(OpcodeID.PushDouble)
{
this.literal = literal;
this.flags |= OpcodeFlags.Literal;
}
internal override bool Equals(Opcode op)
{
if (base.Equals(op))
{
return (this.literal == ((PushNumberOpcode)op).literal);
}
return false;
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushFrame();
int count = context.IterationCount;
if (count > 0)
{
context.Push(this.literal, count);
}
return this.next;
}
#if DEBUG_FILTER
public override string ToString()
{
return string.Format("{0} {1}", base.ToString(), this.literal);
}
#endif
}
class PushBooleanOpcode : Opcode
{
bool literal;
internal PushBooleanOpcode(bool literal)
: base(OpcodeID.PushBool)
{
this.literal = literal;
this.flags |= OpcodeFlags.Literal;
}
internal override bool Equals(Opcode op)
{
if (base.Equals(op))
{
return (this.literal == ((PushBooleanOpcode)op).literal);
}
return false;
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushFrame();
int count = context.IterationCount;
if (count > 0)
{
context.Push(this.literal, count);
}
return this.next;
}
#if DEBUG_FILTER
public override string ToString()
{
return string.Format("{0} {1}", base.ToString(), this.literal);
}
#endif
}
class PushXsltVariableOpcode : Opcode
{
XsltContext xsltContext;
IXsltContextVariable variable;
ValueDataType type;
internal PushXsltVariableOpcode(XsltContext context, IXsltContextVariable variable)
: base(OpcodeID.PushXsltVariable)
{
Fx.Assert(null != context && null != variable, "");
this.xsltContext = context;
this.variable = variable;
this.type = XPathXsltFunctionExpr.ConvertTypeFromXslt(variable.VariableType);
// Make sure the type is supported
switch (this.type)
{
case ValueDataType.Boolean:
case ValueDataType.Double:
case ValueDataType.String:
case ValueDataType.Sequence:
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryCompileException(QueryCompileError.InvalidType, SR.GetString(SR.QueryVariableTypeNotSupported, this.variable.VariableType.ToString())));
}
}
internal override bool Equals(Opcode op)
{
if (base.Equals(op))
{
PushXsltVariableOpcode var = op as PushXsltVariableOpcode;
if (var != null)
{
return this.xsltContext == var.xsltContext && this.variable == var.variable;
}
}
return false;
}
internal override Opcode Eval(ProcessingContext context)
{
context.PushFrame();
int count = context.IterationCount;
if (count > 0)
{
object o = this.variable.Evaluate(this.xsltContext);
if (o == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryVariableNull)));
}
switch (this.type)
{
case ValueDataType.Boolean:
context.Push((bool)o, count);
break;
case ValueDataType.Double:
context.Push((double)o, count);
break;
case ValueDataType.String:
context.Push((string)o, count);
break;
case ValueDataType.Sequence:
XPathNodeIterator iter = (XPathNodeIterator)o;
NodeSequence seq = context.CreateSequence();
while (iter.MoveNext())
{
SeekableXPathNavigator nav = iter.Current as SeekableXPathNavigator;
if (nav != null)
{
seq.Add(nav);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryMustBeSeekable)));
}
}
context.Push(seq, count);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryVariableTypeNotSupported, this.variable.VariableType.ToString())));
}
}
return this.next;
}
#if DEBUG_FILTER
public override string ToString()
{
return string.Format("{0} IXsltContextVariable: {1}", base.ToString(), this.variable.ToString());
}
#endif
}
}
| |
/*
* Copyright 2010 Facebook, Inc.
* Copyright 2011 MercadoLibre, Inc.
*
* General purpose REST API based on FacebookAPI class.
* -User defined API Base URL
* -HTTP or JSON content types supported.
* -MercadoLibre API access token included in full path url.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using MercadoPagoSDK.IO;
namespace MercadoPagoSDK
{
public enum ContentType
{
HTTP,
JSON
}
enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
// This is the api call event delegate
public delegate void APICallEventHandler(object sender, APICallEventArgs e);
/// <summary>
/// Generic REST API util.
/// </summary>
public class RESTAPI
{
/// <summary>
/// The access token used to authenticate API calls.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// The API call event.
/// </summary>
public event APICallEventHandler APICall;
/// <summary>
/// Create a new instance of the API
/// </summary>
/// <param name="baseURL">The domain of the API URL
/// </param>
public RESTAPI(Uri baseURL)
{
_baseURL = baseURL;
}
/// <summary>
/// Create a new instance of the API, using the given token to
/// authenticate.
/// </summary>
/// <param name="baseURL">The domain of the API URL
/// </param>
/// <param name="token">The access token used for
/// authentication</param>
public RESTAPI(Uri baseURL, string token)
{
_baseURL = baseURL;
AccessToken = token;
}
/// <summary>
/// Makes a MercadoLibre API DELETE request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Delete(string relativePath)
{
return Call(relativePath, HttpVerb.DELETE, null, null);
}
/// <summary>
/// Makes a MercadoLibre API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Get(string relativePath)
{
return Call(relativePath, HttpVerb.GET, null, null);
}
/// <summary>
/// Makes a MercadoLibre API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="args">A Key/Value list of strings that
/// will get passed as query arguments.</param>
public JSONObject Get(string relativePath, List<KeyValuePair<string, string>> args)
{
return Call(relativePath, HttpVerb.GET, args, null, ContentType.HTTP);
}
/// <summary>
/// Makes a MercadoLibre API POST request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="json">A json object that
/// will get passed as the request body.</param>
/// <param name="contentType">The data format of the json to be written
/// in the request body.</param>
public JSONObject Post(string relativePath, JSONObject json, ContentType contentType = ContentType.JSON)
{
return Call(relativePath, HttpVerb.POST, null, json, contentType);
}
/// <summary>
/// Makes a MercadoLibre API PUT request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="json">A json object that
/// will get passed as the request body.</param>
/// <param name="contentType">The data format of the json to be written
/// in the request body.</param>
public JSONObject Put(string relativePath, JSONObject json, ContentType contentType = ContentType.JSON)
{
return Call(relativePath, HttpVerb.PUT, null, json, contentType);
}
/// <summary>
/// Creates a call back with the API call args.
/// </summary>
/// <param name="e">The API call event</param>
protected virtual void OnAPICall(APICallEventArgs e)
{
if (APICall != null)
{
// Invokes the delegates.
APICall(this, e);
}
}
#region "Private Members"
/// <summary>
/// The base URL used to complete relative path.
/// </summary>
private Uri _baseURL;
/// <summary>
/// Makes a MercadoLibre API Call.
/// </summary>
private JSONObject Call(string relativePath, HttpVerb httpVerb, List<KeyValuePair<string, string>> args, JSONObject body, ContentType contentType = ContentType.JSON)
{
Uri url = new Uri(_baseURL, relativePath);
JSONObject obj = JSONObject.CreateFromString(MakeRequest(url, httpVerb, args, body, contentType));
return obj;
}
/// <summary>
/// Encode a key/value list of arguments as a HTTP query string.
/// </summary>
private string EncodeArgs(List<KeyValuePair<string, string>> args)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in args)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
string str = kvp.Value.ToString();
if (str.Substring(0, 1) == "\"")
{
str = str.Substring(1, str.Length - 2); // rip "
}
sb.Append(HttpUtility.UrlEncode(str));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
return sb.ToString();
}
/// <summary>
/// Encode a json body as a json string or a http string.
/// </summary>
private string EncodeBody(JSONObject body, ContentType contentType = ContentType.JSON)
{
StringBuilder sb = new StringBuilder();
if (contentType == ContentType.JSON)
{
sb.Append(body.ToString());
}
else
{
foreach (KeyValuePair<string, JSONObject> kvp in body.Dictionary)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
string str = kvp.Value.ToString();
if (str.Substring(0, 1) == "\"")
{
str = str.Substring(1, str.Length - 2); // rip "
}
sb.Append(HttpUtility.UrlEncode(str));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
}
return sb.ToString();
}
/// <summary>
/// Make an HTTP request, with the given query args
/// </summary>
private string MakeRequest(Uri url, HttpVerb httpVerb, List<KeyValuePair<string, string>> args, JSONObject body, ContentType contentType = ContentType.JSON)
{
// Prepare HTTP url
url = PrepareUrl(url, AccessToken, args);
// Set request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = httpVerb.ToString();
if ((httpVerb == HttpVerb.POST) || (httpVerb == HttpVerb.PUT))
{
// Prepare HTTP body
string postData = EncodeBody(body, contentType);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
// Set content type & length
if (contentType == ContentType.JSON)
{
request.ContentType = "application/json";
}
else
{
request.ContentType = "application/x-www-form-urlencoded";
}
request.ContentLength = postDataBytes.Length;
// Call API
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
}
// Resolve the API response
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Read response data
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseBody = reader.ReadToEnd();
// Throw the API call event
APICallEventArgs apiCallEvent = new APICallEventArgs();
if (body != null)
{
apiCallEvent.Body = body.ToString();
}
apiCallEvent.Response = responseBody;
apiCallEvent.Url = url.ToString();
OnAPICall(apiCallEvent);
// Return API response body
return responseBody;
}
}
catch (WebException e)
{
JSONObject response = null;
try
{
// Try throwing a well-formed api error
Stream stream = e.Response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
response = JSONObject.CreateFromString(reader.ReadToEnd().Trim());
int status = Convert.ToInt16(response.GetJSONStringAttribute("status"));
string error = response.GetJSONStringAttribute("error");
string message = response.GetJSONStringAttribute("message");
// optional: cause
string cause = "";
try
{
cause = response.Dictionary["cause"].Dictionary["message"].String;
}
catch
{ }
throw new RESTAPIException(status, error, message, cause);
}
catch (RESTAPIException restEx)
{
throw restEx; // this is a well-formed error message
}
catch
{
throw new RESTAPIException(999, e.Status.ToString(), e.Message); // this is not a well-formed message
}
}
}
/// <summary>
/// Prepares API url including access token and extra parameters.
/// </summary>
private Uri PrepareUrl(Uri url, string accessToken, List<KeyValuePair<string, string>> args)
{
if ((!string.IsNullOrEmpty(accessToken)) && (args != null && args.Count > 0))
{
// url + token + params
url = new Uri(url.ToString() + "?access_token=" + accessToken + "&" + EncodeArgs(args));
}
else if ((!string.IsNullOrEmpty(accessToken)) && (args == null || args.Count == 0))
{
// just url + token
url = new Uri(url.ToString() + "?access_token=" + accessToken);
}
else if ((string.IsNullOrEmpty(accessToken)) && (args != null && args.Count > 0))
{
// just url + params
url = new Uri(url.ToString() + "?" + EncodeArgs(args));
}
else
{
// just url
}
return url;
}
#endregion
}
}
| |
//**************************************************************************
//
//
// National Institute Of Standards and Technology
// DTS Version 1.0
//
// Text Interface
//
// Written by: Carmelo Montanez
// Modified by: Mary Brady
//
// Ported to System.Xml by: Mizrahi Rafael rafim@mainsoft.com
// Mainsoft Corporation (c) 2003-2004
//**************************************************************************
using System;
using System.Xml;
using nist_dom;
using NUnit.Framework;
namespace nist_dom.fundamental
{
[TestFixture]
public class TextTest
{
public static int i = 2;
/*
public testResults[] RunTests()
{
testResults[] tests = new testResults[] {core0001T(), core0002T(), core0003T(),core0004T(),
core0005T(), core0006T(), core0007T(), core0008T(),
core0009T()};
return tests;
}
*/
//------------------------ test case core-0001T ------------------------
//
// Testing feature - If there is no markup inside an Element or Attr node
// content, then the text is contained in a single object
// implementing the Text interface that is the only child
// of the element.
//
// Testing approach - Retrieve the textual data from the second child of the
// third employee. That Text node contains a block of
// multiple text lines without markup, so they should be
// treated as a single Text node. The "nodeValue" attribute
// should contain the combination of the two lines.
//
// Semantic Requirements: 1
//
//----------------------------------------------------------------------------
[Test]
public void core0001T()
{
string computedValue = "";
string expectedValue = "Roger\n Jones";
System.Xml.XmlNode testNode = null;
System.Xml.XmlCharacterData testNodeData = null;
testResults results = new testResults("Core0001T");
try
{
results.description = "If there is no markup language in a block of text, " +
"then the content of the text is contained into " +
"an object implementing the Text interface that is " +
"the only child of the element.";
//
// Retrieve the second child of the second employee and access its
// textual data.
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
testNode.Normalize();
testNodeData = (System.Xml.XmlCharacterData)testNode.FirstChild;
computedValue = testNodeData.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0001T --------------------------
//
//-------------------------- test case core-0002T ----------------------------
//
// Testing feature - If there is markup inside the Text element content,
// then the text is parsed into a list of elements and text
// that forms the list of children of the element.
//
// Testing approach - Retrieve the textual data from the last child of the
// third employee. That node is composed of two
// EntityReferences nodes and two Text nodes. After the
// content of the node is parsed, the "address" Element
// should contain four children with each one of the
// EntityReferences containing one child in turn.
//
// Semantic Requirements: 2
//
//----------------------------------------------------------------------------
[Test]
public void core0002T()
{
string computedValue = "";
string expectedValue = "1900 Dallas Road Dallas, Texas\n 98554";
System.Xml.XmlNode testNode = null;
System.Xml.XmlNode textBlock1 = null;
System.Xml.XmlNode textBlock2 = null;
System.Xml.XmlNode textBlock3 = null;
System.Xml.XmlNode textBlock4 = null;
testResults results = new testResults("Core0002T");
try
{
results.description = "If there is markup language in the content of the " +
"element then the content is parsed into a " +
"list of elements and Text that are the children of " +
"the element";
//
// This last child of the second employee should now have four children,
// two Text nodes and two EntityReference nodes. Retrieve each one of them
// and in the case of EntityReferences retrieve their respective children.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
textBlock1 = testNode.ChildNodes.Item(util.FIRST).FirstChild;
textBlock2 = testNode.ChildNodes.Item(util.SECOND);
textBlock3 = testNode.ChildNodes.Item(util.THIRD).FirstChild;
textBlock4 = testNode.ChildNodes.Item(util.FOURTH);
computedValue += textBlock1.Value;
computedValue += textBlock2.Value;
computedValue += textBlock3.Value;
computedValue += textBlock4.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0002 --------------------------
//
//-------------------------- test case core-0003T ---------------------------
//
// Testing feature - The "splitText(offset)" method breaks the Text node
// into two Text nodes at the specified offset keeping
// each node as siblings in the tree.
//
// Testing approach - Retrieve the textual data from the second child of the
// third employee and invoke its "splitText(offset)" method.
// The method splits the Text node into two new sibling
// Text Nodes keeping both of them in the tree. This test
// checks the "nextSibling" attribute of the original node
// to ensure that the two nodes are indeed siblings.
//
// Semantic Requirements: 3
//
//----------------------------------------------------------------------------
[Test]
public void core0003T()
{
string computedValue = "";
string expectedValue = "Jones";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0003T");
try
{
results.description = "The \"splitText(offset)\" method breaks the Text node " +
"into two Text nodes at the specified offset, keeping each " +
"node in the tree as siblings.";
//
// Retrieve the targeted data.
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Split the two lines of text into two different Text nodes.
//
oldTextNode.SplitText(util.EIGHT);
computedValue = oldTextNode.NextSibling.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0003T --------------------------
//
//-------------------------- test case core-0004T ---------------------------
//
// Testing feature - After The "splitText(offset)" method breaks the Text node
// into two Text nodes, the original node contains all the
// content up to the offset point.
//
// Testing approach - Retrieve the textual data from the second child
// of the third employee and invoke the "splitText(offset)"
// method. The original Text node should contain all the
// content up to the offset point. The "nodeValue"
// attribute is invoke to check that indeed the original
// node now contains the first five characters
//
// Semantic Requirements: 4
//
//----------------------------------------------------------------------------
[Test]
public void core0004T()
{
string computedValue = "";
string expectedValue = "Roger";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0004T");
try
{
results.description = "After the \"splitText(offset)\" method is invoked, the " +
"original Text node contains all of the content up to the " +
"offset point.";
//
// Retrieve targeted data.
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Split the two lines of text into two different Text nodes.
//
oldTextNode.SplitText(util.SIXTH);
computedValue = oldTextNode.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0004T --------------------------
//
//-------------------------- test case core-0005T ---------------------------
//
// Testing feature - After The "splitText(offset)" method breaks the Text node
// into two Text nodes, the new Text node contains all the
// content at and after the offset point.
//
// Testing approach - Retrieve the textual data from the second child of the
// third employee and invoke the "splitText(offset)" method.
// The new Text node should contain all the content at
// and after the offset point. The "nodeValue" attribute
// is invoked to check that indeed the new node now
// contains the first characters at and after position
// seven (starting from 0).
//
// Semantic Requirements: 5
//
//----------------------------------------------------------------------------
[Test]
public void core0005T()
{
string computedValue = "";
string expectedValue = " Jones";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlText newTextNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0005T");
try
{
results.description = "After the \"splitText(offset)\" method is invoked, the " +
"new Text node contains all of the content from the offset " +
"point to the end of the text.";
//
// Retrieve the targeted data.
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Split the two lines of text into two different Text nodes.
//
newTextNode = oldTextNode.SplitText(util.SEVENTH);
computedValue = newTextNode.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0005T --------------------------
//
//-------------------------- test case core-0006T ---------------------------
//
// Testing feature - The "splitText(offset)" method returns the new Text
// node.
//
// Testing approach - Retrieve the textual data from the last child of the
// first employee and invoke its "splitText(offset)" method.
// The method should return the new Text node. The offset
// value used for this test is 30. The "nodeValue"
// attribute is invoked to check that indeed the new node
// now contains the characters at and after postion 30
// (counting from 0).
//
// Semantic Requirements: 6
//
//----------------------------------------------------------------------------
[Test]
public void core0006T()
{
string computedValue = "";
string expectedValue = "98551";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlText newTextNode = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0006T");
try
{
results.description = "The \"splitText(offset)\" method returns the " +
"new Text node.";
//
// Retrieve the targeted data.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Split the two lines of text into two different Text nodes.
//
newTextNode = oldTextNode.SplitText(30);
computedValue = newTextNode.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0006T --------------------------
//
//-------------------------- test case core-0007T ---------------------------
//
// Testing feature - The "splitText(offset)" method raises an INDEX_SIZE_ERR
// Exception if the specified offset is negative.
//
// Testing approach - Retrieve the textual data from the second child of
// the third employee and invoke its "splitText(offset)"
// method with "offset" equals to a negative number. It
// should raise the desired exception.
//
// Semantic Requirements: 7
//
//----------------------------------------------------------------------------
[Test]
public void core0007T()
{
string computedValue = "";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlText newTextNode = null;
System.Xml.XmlNode testNode = null;
string expectedValue = "System.ArgumentOutOfRangeException";//util.INDEX_SIZE_ERR;
testResults results = new testResults("Core0007T");
try
{
results.description = "The \"splitText(offset)\" method raises an " +
"INDEX_SIZE_ERR Exception if the specified " +
"offset is negative.";
//
// Retrieve the targeted data
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Call the "spitText(offset)" method with "offset" equal to a negative
// number should raise an exception.
//
try
{
oldTextNode.SplitText(-69);
}
catch(System.Exception ex)
{
computedValue = ex.GetType ().FullName;
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0007T --------------------------
//
//-------------------------- test case core-0008T ----------------------------
//
// Testing feature - The "splitText(offset)" method raises an
// ArgumentOutOfRangeException if the specified offset is greater than the
// number of 16-bit units in the Text node.
//
// Testing approach - Retrieve the textual data from the second child of
// third employee and invoke its "splitText(offset)"
// method with "offset" greater than the number of
// characters in the Text node. It should raise the
// desired exception.
//
// Semantic Requirements: 7
//
//----------------------------------------------------------------------------
[Test]
public void core0008T()
{
string computedValue = "";
System.Xml.XmlText oldTextNode = null;
System.Xml.XmlNode testNode = null;
string expectedValue = "System.ArgumentOutOfRangeException";
testResults results = new testResults("Core0008T");
try
{
results.description = "The \"splitText(offset)\" method raises an " +
"ArgumentOutOfRangeException if the specified " +
"offset is greater than the number of 16-bit units " +
"in the Text node.";
//
// Retrieve the targeted data.
//
testNode = util.nodeObject(util.THIRD,util.SECOND);
oldTextNode = (System.Xml.XmlText)testNode.FirstChild;
//
// Call the "spitText(offset)" method with "offset" greater than the numbers
// of characters in the Text node, it should raise an exception.
try
{
oldTextNode.SplitText(300);
}
catch(System.Exception ex)
{
computedValue = ex.GetType().ToString();
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0008T --------------------------
//
//-------------------------- test case core-0009T ----------------------------
//
// Testing feature - The "splitText(offset)" method raises a
// NO_MODIFICATION_ALLOWED_ERR Exception if
// the node is readonly.
//
// Testing approach - Retrieve the textual data from the first EntityReference
// inside the last child of the second employee and invoke
// its splitText(offset) method. Descendants of
// EntityReference nodes are readonly and therefore the
// desired exception should be raised.
//
// Semantic Requirements: 8
//
//----------------------------------------------------------------------------
[Test]
[Category ("NotDotNet")] // MS DOM is buggy
public void core0009T()
{
string computedValue = "";
System.Xml.XmlNode testNode = null;
System.Xml.XmlText readOnlyText = null;
string expectedValue = "System.ArgumentException";//util.NO_MODIFICATION_ALLOWED_ERR;
testResults results = new testResults("Core0009T");
try
{
results.description = "The \"splitText(offset)\" method raises a " +
"NO_MODIFICATION_ALLOWED_ERR Exception if the " +
"node is readonly.";
//
// Attempt to modify descendants of an EntityReference node should raise
// an exception.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
readOnlyText = (System.Xml.XmlText)testNode.ChildNodes.Item(util.FIRST).FirstChild;
try
{
readOnlyText.SplitText(5);
}
catch(ArgumentException ex)
{
computedValue = ex.GetType ().FullName;
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
Assert.AreEqual (results.expected, results.actual);
}
//------------------------ End test case core-0009T --------------------------
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.