context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// 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 BroadcastScalarToVector128UInt32()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128UInt32();
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();
if (Sse2.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 (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 class works
test.RunClassLclFldScenario();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 SimpleUnaryOpTest__BroadcastScalarToVector128UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.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<UInt32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__BroadcastScalarToVector128UInt32 testClass)
{
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__BroadcastScalarToVector128UInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar1;
private Vector128<UInt32> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__BroadcastScalarToVector128UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleUnaryOpTest__BroadcastScalarToVector128UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.BroadcastScalarToVector128(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.BroadcastScalarToVector128(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128UInt32();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128UInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(
Sse2.LoadVector128((UInt32*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<UInt32> op1, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((firstOp[0] != result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<UInt32>(Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// Follow solver positions an element in front of the of the tracked target (relative to its local forward axis).
/// The element can be loosely constrained (a.k.a. tag-along) so that it doesn't follow until the tracked target moves
/// beyond user defined bounds.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/Follow")]
public class Follow : Solver
{
[SerializeField]
[Tooltip("The desired orientation of this object")]
private SolverOrientationType orientationType = SolverOrientationType.FaceTrackedObject;
/// <summary>
/// The desired orientation of this object.
/// </summary>
public SolverOrientationType OrientationType
{
get => orientationType;
set => orientationType = value;
}
[SerializeField]
[Tooltip("The object will face the tracked object while the object is outside of the distance/direction bounds defined in this component.")]
private bool faceTrackedObjectWhileClamped = true;
/// <summary>
/// The object will face the tracked object while the object is outside of the distance/direction bounds defined in this component.
/// </summary>
public bool FaceTrackedObjectWhileClamped
{
get => faceTrackedObjectWhileClamped;
set => faceTrackedObjectWhileClamped = value;
}
[SerializeField]
[Tooltip("Face a user defined transform rather than using the solver orientation type.")]
private bool faceUserDefinedTargetTransform = false;
/// <summary>
/// Face a user defined transform rather than using the solver orientation type.
/// </summary>
public bool FaceUserDefinedTargetTransform
{
get => faceUserDefinedTargetTransform;
set => faceUserDefinedTargetTransform = value;
}
[SerializeField]
[Tooltip("Transform this object should face rather than using the solver orientation type.")]
private Transform targetToFace = null;
/// <summary>
/// Transform this object should face rather than using the solver orientation type.
/// </summary>
public Transform TargetToFace
{
get => targetToFace;
set => targetToFace = value;
}
[SerializeField]
[EnumFlags]
[Tooltip("Rotation axes used when facing target.")]
private AxisFlags pivotAxis = AxisFlags.XAxis | AxisFlags.YAxis | AxisFlags.ZAxis;
/// <summary>
/// Rotation axes used when facing target.
/// </summary>
public AxisFlags PivotAxis
{
get => pivotAxis;
set => pivotAxis = value;
}
[SerializeField]
[Tooltip("Min distance from eye to position element around, i.e. the sphere radius")]
private float minDistance = 0.3f;
/// <summary>
/// Min distance from eye to position element around, i.e. the sphere radius.
/// </summary>
public float MinDistance
{
get => minDistance;
set => minDistance = value;
}
[SerializeField]
[Tooltip("Max distance from eye to element")]
private float maxDistance = 0.9f;
/// <summary>
/// Max distance from eye to element.
/// </summary>
public float MaxDistance
{
get => maxDistance;
set => maxDistance = value;
}
[SerializeField]
[Tooltip("Default distance from eye to position element around, i.e. the sphere radius")]
private float defaultDistance = 0.7f;
/// <summary>
/// Initial placement distance. Should be between min and max.
/// </summary>
public float DefaultDistance
{
get => defaultDistance;
set => defaultDistance = value;
}
[SerializeField]
[Tooltip("The horizontal angle from the tracked target forward axis to this object will not exceed this value")]
private float maxViewHorizontalDegrees = 30f;
/// <summary>
/// The horizontal angle from the tracked target forward axis to this object will not exceed this value.
/// </summary>
public float MaxViewHorizontalDegrees
{
get => maxViewHorizontalDegrees;
set => maxViewHorizontalDegrees = value;
}
[SerializeField]
[Tooltip("The vertical angle from the tracked target forward axis to this object will not exceed this value")]
private float maxViewVerticalDegrees = 20f;
/// <summary>
/// The vertical angle from the tracked target forward axis to this object will not exceed this value.
/// </summary>
public float MaxViewVerticalDegrees
{
get => maxViewVerticalDegrees;
set => maxViewVerticalDegrees = value;
}
[SerializeField]
[Tooltip("The element will only reorient when the object is outside of the distance/direction bounds defined in this component.")]
private bool reorientWhenOutsideParameters = true;
/// <summary>
/// The element will only reorient when the object is outside of the distance/direction bounds above.
/// </summary>
public bool ReorientWhenOutsideParameters
{
get => reorientWhenOutsideParameters;
set => reorientWhenOutsideParameters = value;
}
[SerializeField]
[Tooltip("The element will not reorient until the angle between the forward vector and vector to the controller is greater then this value")]
private float orientToControllerDeadzoneDegrees = 60f;
/// <summary>
/// The element will not reorient until the angle between the forward vector and vector to the controller is greater then this value.
/// </summary>
public float OrientToControllerDeadzoneDegrees
{
get => orientToControllerDeadzoneDegrees;
set => orientToControllerDeadzoneDegrees = value;
}
[SerializeField]
[Tooltip("Option to ignore angle clamping")]
private bool ignoreAngleClamp = false;
/// <summary>
/// Option to ignore angle clamping.
/// </summary>
public bool IgnoreAngleClamp
{
get => ignoreAngleClamp;
set => ignoreAngleClamp = value;
}
[SerializeField]
[Tooltip("Option to ignore distance clamping")]
private bool ignoreDistanceClamp = false;
/// <summary>
/// Option to ignore distance clamping.
/// </summary>
public bool IgnoreDistanceClamp
{
get => ignoreDistanceClamp;
set => ignoreDistanceClamp = value;
}
[SerializeField]
[Tooltip("Option to ignore the pitch and roll of the reference target")]
private bool ignoreReferencePitchAndRoll = false;
/// <summary>
/// Option to ignore the pitch and roll of the reference target
/// </summary>
public bool IgnoreReferencePitchAndRoll
{
get => ignoreReferencePitchAndRoll;
set => ignoreReferencePitchAndRoll = value;
}
[SerializeField]
[Tooltip("Pitch offset from reference element (relative to Max Distance)")]
public float pitchOffset = 0;
/// <summary>
/// Pitch offset from reference element (relative to MaxDistance).
/// </summary>
public float PitchOffset
{
get => pitchOffset;
set => pitchOffset = value;
}
[SerializeField]
[Tooltip("Max vertical distance between element and reference")]
private float verticalMaxDistance = 0.0f;
/// <summary>
/// Max vertical distance between element and reference.
/// </summary>
public float VerticalMaxDistance
{
get => verticalMaxDistance;
set => verticalMaxDistance = value;
}
/// <summary>
/// Specifies the method used to ensure the refForward vector remains within the bounds set by the leashing parameters.
/// </summary>
public enum AngularClampType
{
/// <summary>
/// Locks the rotation with a viewing cone.
/// </summary>
ViewDegrees = 0,
/// <summary>
/// Locks the rotation to a specified number of steps around the tracked object.
/// </summary>
AngleStepping = 1,
/// <summary>
/// Uses the gameObject's renderer bounds to keep within the view frustum.
/// </summary>
RendererBounds = 2,
/// <summary>
/// Uses the gameObject's collider bounds to keep within the view frustum.
/// </summary>
ColliderBounds = 3,
}
[SerializeField]
[Tooltip("Specifies the method used to ensure the refForward vector remains within the bounds set by the leashing parameters.")]
private AngularClampType angularClampMode = AngularClampType.ViewDegrees;
/// <summary>
/// Accessors for specifying the method used to ensure the refForward vector remains within the bounds set by the leashing parameters.
/// </summary>
public AngularClampType AngularClampMode
{
get => angularClampMode;
set
{
angularClampMode = value;
RecalculateBoundsExtents();
}
}
[Range(2, 24)]
[SerializeField]
[Tooltip("The division of steps this object can tether to. Higher the number, the more snapping steps.")]
private int tetherAngleSteps = 6;
/// <summary>
/// The division of steps this object can tether to. Higher the number, the more snapping steps.
/// </summary>
public int TetherAngleSteps
{
get => tetherAngleSteps;
set => tetherAngleSteps = Mathf.Clamp(value, 2, 24);
}
[SerializeField]
[Tooltip("Scales the bounds to impose a larger or smaller bounds than the calculated bounds.")]
private float boundsScaler = 1.0f;
/// <summary>
/// Scales the bounds to impose a larger or smaller bounds than the calculated bounds.
/// </summary>
public float BoundsScaler
{
get => boundsScaler;
set
{
boundsScaler = value;
RecalculateBoundsExtents();
}
}
/// <summary>
/// Re-centers the target in the next update.
/// </summary>
public void Recenter()
{
recenterNextUpdate = true;
}
/// <summary>
/// Recalculates the bounds based on the angular clamp mode.
/// </summary>
public void RecalculateBoundsExtents()
{
Bounds bounds;
GetBounds(gameObject, angularClampMode, out bounds);
boundsExtents = bounds.extents * boundsScaler;
}
private Vector3 ReferencePosition => SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.position : Vector3.zero;
private Quaternion ReferenceRotation => SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.rotation : Quaternion.identity;
private Quaternion PreviousGoalRotation = Quaternion.identity;
private bool recenterNextUpdate = true;
private Vector3 boundsExtents = Vector3.one;
protected override void OnEnable()
{
base.OnEnable();
RecalculateBoundsExtents();
}
/// <inheritdoc />
public override void SolverUpdate()
{
Vector3 refPosition = Vector3.zero;
Quaternion refRotation = Quaternion.identity;
Vector3 refForward = Vector3.zero;
GetReferenceInfo(ref refPosition, ref refRotation, ref refForward);
// Determine the current position of the element
Vector3 currentPosition = WorkingPosition;
if (recenterNextUpdate)
{
currentPosition = refPosition + refForward * DefaultDistance;
}
bool wasClamped = false;
// Angular clamp to determine goal direction to place the element
Vector3 goalDirection = refForward;
if (!ignoreAngleClamp && !recenterNextUpdate)
{
wasClamped |= AngularClamp(refPosition, refRotation, currentPosition, ref goalDirection);
}
// Distance clamp to determine goal position to place the element
Vector3 goalPosition = currentPosition;
if (!ignoreDistanceClamp && !recenterNextUpdate)
{
wasClamped |= DistanceClamp(currentPosition, refPosition, goalDirection, ref goalPosition);
}
// Figure out goal rotation of the element based on orientation setting
Quaternion goalRotation = Quaternion.identity;
ComputeOrientation(goalPosition, wasClamped, ref goalRotation);
if (recenterNextUpdate)
{
PreviousGoalRotation = goalRotation;
SnapTo(goalPosition, goalRotation, WorkingScale);
recenterNextUpdate = false;
}
else
{
// Avoid drift by not updating the goal position when not clamped
if (wasClamped)
{
GoalPosition = goalPosition;
}
GoalRotation = goalRotation;
PreviousGoalRotation = goalRotation;
UpdateWorkingPositionToGoal();
UpdateWorkingRotationToGoal();
}
}
/// <summary>
/// Projects from and to on to the plane with given normal and gets the
/// angle between these projected vectors.
/// </summary>
/// <returns>Angle between project from and to in degrees</returns>
private float AngleBetweenOnPlane(Vector3 from, Vector3 to, Vector3 normal)
{
from.Normalize();
to.Normalize();
normal.Normalize();
Vector3 right = Vector3.Cross(normal, from);
Vector3 forward = Vector3.Cross(right, normal);
float angle = Mathf.Atan2(Vector3.Dot(to, right), Vector3.Dot(to, forward));
return SimplifyAngle(angle) * Mathf.Rad2Deg;
}
/// <summary>
/// Calculates the angle between vec and a plane described by normal. The angle returned
/// is signed.
/// </summary>
/// <returns>Signed angle between vec and the plane described by normal</returns>
private float AngleBetweenVectorAndPlane(Vector3 vec, Vector3 normal)
{
return 90 - (Mathf.Acos(Vector3.Dot(vec, normal)) * Mathf.Rad2Deg);
}
private float SimplifyAngle(float angle)
{
while (angle > Mathf.PI)
{
angle -= 2 * Mathf.PI;
}
while (angle < -Mathf.PI)
{
angle += 2 * Mathf.PI;
}
return angle;
}
/// <summary>
/// This method ensures that the refForward vector remains within the bounds set by the
/// leashing parameters. To do this, it determines the angles between toTarget and the reference
/// local xz and yz planes. If these angles fall within the leashing bounds, then we don't have
/// to modify refForward. Otherwise, we apply a correction rotation to bring it within bounds.
/// </summary>
private bool AngularClamp(Vector3 refPosition, Quaternion refRotation, Vector3 currentPosition, ref Vector3 refForward)
{
Vector3 toTarget = currentPosition - refPosition;
float currentDistance = toTarget.magnitude;
if (currentDistance <= 0)
{
// No need to clamp
return false;
}
toTarget.Normalize();
// Start off with a rotation towards the target. If it's within leashing bounds, we can leave it alone.
Quaternion rotation = Quaternion.LookRotation(toTarget, Vector3.up);
Vector3 currentRefForward = refRotation * Vector3.forward;
Vector3 refRight = refRotation * Vector3.right;
bool angularClamped = false;
// X-axis leashing
// Leashing around the reference's X axis only makes sense if the reference isn't gravity aligned.
if (IgnoreReferencePitchAndRoll)
{
float angle = AngleBetweenOnPlane(toTarget, currentRefForward, refRight);
rotation = Quaternion.AngleAxis(angle, refRight) * rotation;
}
else
{
float angle = -AngleBetweenOnPlane(toTarget, currentRefForward, refRight);
float minMaxAngle;
switch (angularClampMode)
{
default:
case AngularClampType.ViewDegrees:
case AngularClampType.AngleStepping:
{
minMaxAngle = MaxViewVerticalDegrees * 0.5f;
}
break;
case AngularClampType.RendererBounds:
case AngularClampType.ColliderBounds:
{
Vector3 top = refRotation * new Vector3(0.0f, boundsExtents.y, currentDistance);
minMaxAngle = AngleBetweenOnPlane(top, currentRefForward, refRight) * 2.0f;
}
break;
}
if (angle < -minMaxAngle)
{
rotation = Quaternion.AngleAxis(-minMaxAngle - angle, refRight) * rotation;
angularClamped = true;
}
else if (angle > minMaxAngle)
{
rotation = Quaternion.AngleAxis(minMaxAngle - angle, refRight) * rotation;
angularClamped = true;
}
}
// Y-axis leashing
switch (angularClampMode)
{
case AngularClampType.AngleStepping:
{
float stepAngle = 360f / tetherAngleSteps;
int numberOfSteps = Mathf.RoundToInt(SolverHandler.TransformTarget.transform.eulerAngles.y / stepAngle);
float newAngle = stepAngle * numberOfSteps;
rotation = Quaternion.Euler(rotation.eulerAngles.x, newAngle, rotation.eulerAngles.z);
}
break;
case AngularClampType.ViewDegrees:
case AngularClampType.RendererBounds:
case AngularClampType.ColliderBounds:
{
float angle = AngleBetweenVectorAndPlane(toTarget, refRight);
float minMaxAngle;
if (angularClampMode == AngularClampType.ViewDegrees)
{
minMaxAngle = MaxViewHorizontalDegrees * 0.5f;
}
else
{
Vector3 side = refRotation * new Vector3(boundsExtents.x, 0.0f, boundsExtents.z);
minMaxAngle = AngleBetweenVectorAndPlane(side, refRight) * 2.0f;
}
if (angle < -minMaxAngle)
{
rotation = Quaternion.AngleAxis(-minMaxAngle - angle, Vector3.up) * rotation;
angularClamped = true;
}
else if (angle > minMaxAngle)
{
rotation = Quaternion.AngleAxis(minMaxAngle - angle, Vector3.up) * rotation;
angularClamped = true;
}
}
break;
}
refForward = rotation * Vector3.forward;
return angularClamped;
}
/// <summary>
/// This method ensures that the distance from clampedPosition to the tracked target remains within
/// the bounds set by the leashing parameters. To do this, it clamps the current distance to these
/// bounds and then uses this clamped distance with refForward to calculate the new position. If
/// IgnoreReferencePitchAndRoll is true and we have a PitchOffset, we only apply these calculations
/// for xz.
/// </summary>
private bool DistanceClamp(Vector3 currentPosition, Vector3 refPosition, Vector3 refForward, ref Vector3 clampedPosition)
{
float clampedDistance;
float currentDistance = Vector3.Distance(currentPosition, refPosition);
Vector3 direction = refForward;
if (IgnoreReferencePitchAndRoll && PitchOffset != 0)
{
// If we don't account for pitch offset, the casted object will float up/down as the reference
// gets closer to it because we will still be casting in the direction of the pitched offset.
// To fix this, only modify the XZ position of the object.
Vector3 directionXZ = refForward;
directionXZ.y = 0;
directionXZ.Normalize();
Vector3 refToElementXZ = currentPosition - refPosition;
refToElementXZ.y = 0;
float desiredDistanceXZ = refToElementXZ.magnitude;
Vector3 minDistanceXZVector = refForward * MinDistance;
minDistanceXZVector.y = 0;
float minDistanceXZ = minDistanceXZVector.magnitude;
Vector3 maxDistanceXZVector = refForward * MaxDistance;
maxDistanceXZVector.y = 0;
float maxDistanceXZ = maxDistanceXZVector.magnitude;
desiredDistanceXZ = Mathf.Clamp(desiredDistanceXZ, minDistanceXZ, maxDistanceXZ);
Vector3 desiredPosition = refPosition + directionXZ * desiredDistanceXZ;
float desiredHeight = refPosition.y + refForward.y * MaxDistance;
desiredPosition.y = desiredHeight;
direction = desiredPosition - refPosition;
clampedDistance = direction.magnitude;
direction /= clampedDistance;
clampedDistance = Mathf.Max(MinDistance, clampedDistance);
}
else
{
clampedDistance = Mathf.Clamp(currentDistance, MinDistance, MaxDistance);
}
clampedPosition = refPosition + direction * clampedDistance;
// Apply vertical clamp on reference
if (VerticalMaxDistance > 0)
{
clampedPosition.y = Mathf.Clamp(clampedPosition.y, ReferencePosition.y - VerticalMaxDistance, ReferencePosition.y + VerticalMaxDistance);
}
return Vector3EqualEpsilon(clampedPosition, currentPosition, 0.0001f);
}
private void ComputeOrientation(Vector3 goalPosition, bool wasClamped, ref Quaternion orientation)
{
SolverOrientationType defaultOrientationType = OrientationType;
if (!wasClamped && reorientWhenOutsideParameters)
{
Vector3 nodeToCamera = goalPosition - ReferencePosition;
float angle = Mathf.Abs(AngleBetweenOnPlane(transform.forward, nodeToCamera, Vector3.up));
if (angle < OrientToControllerDeadzoneDegrees)
{
orientation = PreviousGoalRotation;
return;
}
}
if (FaceUserDefinedTargetTransform)
{
Vector3 directionToTarget = TargetToFace != null ? goalPosition - TargetToFace.position : Vector3.zero;
if (!PivotAxis.HasFlag(AxisFlags.XAxis))
{
directionToTarget.x = 0;
}
if (!PivotAxis.HasFlag(AxisFlags.YAxis))
{
directionToTarget.y = 0;
}
if (!PivotAxis.HasFlag(AxisFlags.ZAxis))
{
directionToTarget.z = 0;
}
if (directionToTarget.sqrMagnitude == 0)
{
orientation = Quaternion.identity;
return;
}
orientation = Quaternion.LookRotation(directionToTarget);
return;
}
if (wasClamped && FaceTrackedObjectWhileClamped)
{
defaultOrientationType = SolverOrientationType.FaceTrackedObject;
}
switch (defaultOrientationType)
{
case SolverOrientationType.YawOnly:
float targetYRotation = SolverHandler.TransformTarget != null ? SolverHandler.TransformTarget.eulerAngles.y : 0.0f;
orientation = Quaternion.Euler(0f, targetYRotation, 0f);
break;
case SolverOrientationType.Unmodified:
orientation = transform.rotation;
break;
case SolverOrientationType.CameraAligned:
orientation = CameraCache.Main.transform.rotation;
break;
case SolverOrientationType.FaceTrackedObject:
orientation = SolverHandler.TransformTarget != null ? Quaternion.LookRotation(goalPosition - ReferencePosition) : Quaternion.identity;
break;
case SolverOrientationType.CameraFacing:
orientation = SolverHandler.TransformTarget != null ? Quaternion.LookRotation(goalPosition - CameraCache.Main.transform.position) : Quaternion.identity;
break;
case SolverOrientationType.FollowTrackedObject:
orientation = SolverHandler.TransformTarget != null ? ReferenceRotation : Quaternion.identity;
break;
default:
Debug.LogError($"Invalid OrientationType for Orbital Solver on {gameObject.name}");
break;
}
}
private void GetReferenceInfo(ref Vector3 refPosition, ref Quaternion refRotation, ref Vector3 refForward)
{
refPosition = ReferencePosition;
refRotation = ReferenceRotation;
if (IgnoreReferencePitchAndRoll)
{
Vector3 forward = ReferenceRotation * Vector3.forward;
forward.y = 0;
refRotation = Quaternion.LookRotation(forward);
if (PitchOffset != 0)
{
Vector3 right = refRotation * Vector3.right;
forward = Quaternion.AngleAxis(PitchOffset, right) * forward;
refRotation = Quaternion.LookRotation(forward);
}
}
refForward = refRotation * Vector3.forward;
}
private bool Vector3EqualEpsilon(Vector3 x, Vector3 y, float eps)
{
float sqrMagnitude = (x - y).sqrMagnitude;
return sqrMagnitude > eps;
}
private static bool GetBounds(GameObject target, AngularClampType angularClampType, out Bounds bounds)
{
switch (angularClampType)
{
case AngularClampType.RendererBounds:
{
return BoundsExtensions.GetRenderBounds(target, out bounds, 0);
}
case AngularClampType.ColliderBounds:
{
return BoundsExtensions.GetColliderBounds(target, out bounds, 0);
}
}
bounds = new Bounds();
return false;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XsdDuration.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
#if SILVERLIGHT
[System.Runtime.CompilerServices.FriendAccessAllowed] // used by System.Runtime.Serialization.dll
#endif
internal struct XsdDuration {
private int years;
private int months;
private int days;
private int hours;
private int minutes;
private int seconds;
private uint nanoseconds; // High bit is used to indicate whether duration is negative
private const uint NegativeBit = 0x80000000;
private enum Parts {
HasNone = 0,
HasYears = 1,
HasMonths = 2,
HasDays = 4,
HasHours = 8,
HasMinutes = 16,
HasSeconds = 32,
}
public enum DurationType {
Duration,
YearMonthDuration,
DayTimeDuration,
};
/// <summary>
/// Construct an XsdDuration from component parts.
/// </summary>
public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) {
if (years < 0) throw new ArgumentOutOfRangeException("years");
if (months < 0) throw new ArgumentOutOfRangeException("months");
if (days < 0) throw new ArgumentOutOfRangeException("days");
if (hours < 0) throw new ArgumentOutOfRangeException("hours");
if (minutes < 0) throw new ArgumentOutOfRangeException("minutes");
if (seconds < 0) throw new ArgumentOutOfRangeException("seconds");
if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException("nanoseconds");
this.years = years;
this.months = months;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.nanoseconds = (uint) nanoseconds;
if (isNegative)
this.nanoseconds |= NegativeBit;
}
/// <summary>
/// Construct an XsdDuration from a TimeSpan value.
/// </summary>
public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) {
}
/// <summary>
/// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or
/// an xdt:yearMonthDuration.
/// </summary>
public XsdDuration(TimeSpan timeSpan, DurationType durationType) {
long ticks = timeSpan.Ticks;
ulong ticksPos;
bool isNegative;
if (ticks < 0) {
// Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case
isNegative = true;
ticksPos = (ulong) -ticks;
}
else {
isNegative = false;
ticksPos = (ulong) ticks;
}
if (durationType == DurationType.YearMonthDuration) {
int years = (int) (ticksPos / ((ulong) TimeSpan.TicksPerDay * 365));
int months = (int) ((ticksPos % ((ulong) TimeSpan.TicksPerDay * 365)) / ((ulong) TimeSpan.TicksPerDay * 30));
if (months == 12) {
// If remaining days >= 360 and < 365, then round off to year
years++;
months = 0;
}
this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0);
}
else {
Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration);
// Tick count is expressed in 100 nanosecond intervals
this.nanoseconds = (uint) (ticksPos % 10000000) * 100;
if (isNegative)
this.nanoseconds |= NegativeBit;
this.years = 0;
this.months = 0;
this.days = (int) (ticksPos / (ulong) TimeSpan.TicksPerDay);
this.hours = (int) ((ticksPos / (ulong) TimeSpan.TicksPerHour) % 24);
this.minutes = (int) ((ticksPos / (ulong) TimeSpan.TicksPerMinute) % 60);
this.seconds = (int) ((ticksPos / (ulong) TimeSpan.TicksPerSecond) % 60);
}
}
/// <summary>
/// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss
/// of fidelity (except in the case of overflow).
/// </summary>
public XsdDuration(string s) : this(s, DurationType.Duration) {
}
/// <summary>
/// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss
/// of fidelity (except in the case of overflow).
/// </summary>
public XsdDuration(string s, DurationType durationType) {
XsdDuration result;
Exception exception = TryParse(s, durationType, out result);
if (exception != null) {
throw exception;
}
this.years = result.Years;
this.months = result.Months;
this.days = result.Days;
this.hours = result.Hours;
this.minutes = result.Minutes;
this.seconds = result.Seconds;
this.nanoseconds = (uint)result.Nanoseconds;
if (result.IsNegative) {
this.nanoseconds |= NegativeBit;
}
return;
}
/// <summary>
/// Return true if this duration is negative.
/// </summary>
public bool IsNegative {
get { return (this.nanoseconds & NegativeBit) != 0; }
}
/// <summary>
/// Return number of years in this duration (stored in 31 bits).
/// </summary>
public int Years {
get { return this.years; }
}
/// <summary>
/// Return number of months in this duration (stored in 31 bits).
/// </summary>
public int Months {
get { return this.months; }
}
/// <summary>
/// Return number of days in this duration (stored in 31 bits).
/// </summary>
public int Days {
get { return this.days; }
}
/// <summary>
/// Return number of hours in this duration (stored in 31 bits).
/// </summary>
public int Hours {
get { return this.hours; }
}
/// <summary>
/// Return number of minutes in this duration (stored in 31 bits).
/// </summary>
public int Minutes {
get { return this.minutes; }
}
/// <summary>
/// Return number of seconds in this duration (stored in 31 bits).
/// </summary>
public int Seconds {
get { return this.seconds; }
}
/// <summary>
/// Return number of nanoseconds in this duration.
/// </summary>
public int Nanoseconds {
get { return (int) (this.nanoseconds & ~NegativeBit); }
}
#if !SILVERLIGHT
/// <summary>
/// Return number of microseconds in this duration.
/// </summary>
public int Microseconds {
get { return Nanoseconds / 1000; }
}
/// <summary>
/// Return number of milliseconds in this duration.
/// </summary>
public int Milliseconds {
get { return Nanoseconds / 1000000; }
}
/// <summary>
/// Normalize year-month part and day-time part so that month < 12, hour < 24, minute < 60, and second < 60.
/// </summary>
public XsdDuration Normalize() {
int years = Years;
int months = Months;
int days = Days;
int hours = Hours;
int minutes = Minutes;
int seconds = Seconds;
try {
checked {
if (months >= 12) {
years += months / 12;
months %= 12;
}
if (seconds >= 60) {
minutes += seconds / 60;
seconds %= 60;
}
if (minutes >= 60) {
hours += minutes / 60;
minutes %= 60;
}
if (hours >= 24) {
days += hours / 24;
hours %= 24;
}
}
}
catch (OverflowException) {
throw new OverflowException(Res.GetString(Res.XmlConvert_Overflow, ToString(), "Duration"));
}
return new XsdDuration(IsNegative, years, months, days, hours, minutes, seconds, Nanoseconds);
}
#endif
/// <summary>
/// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate
/// that there are 365 days in the year and 30 days in a month.
/// </summary>
public TimeSpan ToTimeSpan() {
return ToTimeSpan(DurationType.Duration);
}
/// <summary>
/// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate
/// that there are 365 days in the year and 30 days in a month.
/// </summary>
public TimeSpan ToTimeSpan(DurationType durationType) {
TimeSpan result;
Exception exception = TryToTimeSpan(durationType, out result);
if (exception != null) {
throw exception;
}
return result;
}
#if !SILVERLIGHT
internal Exception TryToTimeSpan(out TimeSpan result) {
return TryToTimeSpan(DurationType.Duration, out result);
}
#endif
internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result) {
Exception exception = null;
ulong ticks = 0;
// Throw error if result cannot fit into a long
try {
checked {
// Discard year and month parts if constructing TimeSpan for DayTimeDuration
if (durationType != DurationType.DayTimeDuration) {
ticks += ((ulong) this.years + (ulong) this.months / 12) * 365;
ticks += ((ulong) this.months % 12) * 30;
}
// Discard day and time parts if constructing TimeSpan for YearMonthDuration
if (durationType != DurationType.YearMonthDuration) {
ticks += (ulong) this.days;
ticks *= 24;
ticks += (ulong) this.hours;
ticks *= 60;
ticks += (ulong) this.minutes;
ticks *= 60;
ticks += (ulong) this.seconds;
// Tick count interval is in 100 nanosecond intervals (7 digits)
ticks *= (ulong) TimeSpan.TicksPerSecond;
ticks += (ulong) Nanoseconds / 100;
}
else {
// Multiply YearMonth duration by number of ticks per day
ticks *= (ulong) TimeSpan.TicksPerDay;
}
if (IsNegative) {
// Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow
if (ticks == (ulong) Int64.MaxValue + 1) {
result = new TimeSpan(Int64.MinValue);
}
else {
result = new TimeSpan(-((long) ticks));
}
}
else {
result = new TimeSpan((long) ticks);
}
return null;
}
}
catch (OverflowException) {
result = TimeSpan.MinValue;
exception = new OverflowException(Res.GetString(Res.XmlConvert_Overflow, durationType, "TimeSpan"));
}
return exception;
}
/// <summary>
/// Return the string representation of this Xsd duration.
/// </summary>
public override string ToString() {
return ToString(DurationType.Duration);
}
/// <summary>
/// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or
/// xdt:yearMonthDuration rules.
/// </summary>
internal string ToString(DurationType durationType) {
StringBuilder sb = new StringBuilder(20);
int nanoseconds, digit, zeroIdx, len;
if (IsNegative)
sb.Append('-');
sb.Append('P');
if (durationType != DurationType.DayTimeDuration) {
if (this.years != 0) {
sb.Append(XmlConvert.ToString(this.years));
sb.Append('Y');
}
if (this.months != 0) {
sb.Append(XmlConvert.ToString(this.months));
sb.Append('M');
}
}
if (durationType != DurationType.YearMonthDuration) {
if (this.days != 0) {
sb.Append(XmlConvert.ToString(this.days));
sb.Append('D');
}
if (this.hours != 0 || this.minutes != 0 || this.seconds != 0 || Nanoseconds != 0) {
sb.Append('T');
if (this.hours != 0) {
sb.Append(XmlConvert.ToString(this.hours));
sb.Append('H');
}
if (this.minutes != 0) {
sb.Append(XmlConvert.ToString(this.minutes));
sb.Append('M');
}
nanoseconds = Nanoseconds;
if (this.seconds != 0 || nanoseconds != 0) {
sb.Append(XmlConvert.ToString(this.seconds));
if (nanoseconds != 0) {
sb.Append('.');
len = sb.Length;
sb.Length += 9;
zeroIdx = sb.Length - 1;
for (int idx = zeroIdx; idx >= len; idx--) {
digit = nanoseconds % 10;
sb[idx] = (char) (digit + '0');
if (zeroIdx == idx && digit == 0)
zeroIdx--;
nanoseconds /= 10;
}
sb.Length = zeroIdx + 1;
}
sb.Append('S');
}
}
// Zero is represented as "PT0S"
if (sb[sb.Length - 1] == 'P')
sb.Append("T0S");
}
else {
// Zero is represented as "T0M"
if (sb[sb.Length - 1] == 'P')
sb.Append("0M");
}
return sb.ToString();
}
#if !SILVERLIGHT
internal static Exception TryParse(string s, out XsdDuration result) {
return TryParse(s, DurationType.Duration, out result);
}
#endif
internal static Exception TryParse(string s, DurationType durationType, out XsdDuration result) {
string errorCode;
int length;
int value, pos, numDigits;
Parts parts = Parts.HasNone;
result = new XsdDuration();
s = s.Trim();
length = s.Length;
pos = 0;
numDigits = 0;
if (pos >= length) goto InvalidFormat;
if (s[pos] == '-') {
pos++;
result.nanoseconds = NegativeBit;
}
else {
result.nanoseconds = 0;
}
if (pos >= length) goto InvalidFormat;
if (s[pos++] != 'P') goto InvalidFormat;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
if (s[pos] == 'Y') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasYears;
result.years = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'M') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasMonths;
result.months = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'D') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasDays;
result.days = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'T') {
if (numDigits != 0) goto InvalidFormat;
pos++;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
if (s[pos] == 'H') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasHours;
result.hours = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'M') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasMinutes;
result.minutes = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == '.') {
pos++;
parts |= Parts.HasSeconds;
result.seconds = value;
errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits);
if (errorCode != null) goto Error;
if (numDigits == 0) { //If there are no digits after the decimal point, assume 0
value = 0;
}
// Normalize to nanosecond intervals
for (; numDigits > 9; numDigits--)
value /= 10;
for (; numDigits < 9; numDigits++)
value *= 10;
result.nanoseconds |= (uint) value;
if (pos >= length) goto InvalidFormat;
if (s[pos] != 'S') goto InvalidFormat;
if (++pos == length) goto Done;
}
else if (s[pos] == 'S') {
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasSeconds;
result.seconds = value;
if (++pos == length) goto Done;
}
}
// Duration cannot end with digits
if (numDigits != 0) goto InvalidFormat;
// No further characters are allowed
if (pos != length) goto InvalidFormat;
Done:
// At least one part must be defined
if (parts == Parts.HasNone) goto InvalidFormat;
if (durationType == DurationType.DayTimeDuration) {
if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0)
goto InvalidFormat;
}
else if (durationType == DurationType.YearMonthDuration) {
if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0)
goto InvalidFormat;
}
return null;
InvalidFormat:
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, durationType));
Error:
return new OverflowException(Res.GetString(Res.XmlConvert_Overflow, s, durationType));
}
/// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is
/// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in
/// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32:
/// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits)
/// 2. If eatDigits is false, an overflow exception is thrown
private static string TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) {
int offsetStart = offset;
int offsetEnd = s.Length;
int digit;
result = 0;
numDigits = 0;
while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') {
digit = s[offset] - '0';
if (result > (Int32.MaxValue - digit) / 10) {
if (!eatDigits) {
return Res.XmlConvert_Overflow;
}
// Skip past any remaining digits
numDigits = offset - offsetStart;
while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') {
offset++;
}
return null;
}
result = result * 10 + digit;
offset++;
}
numDigits = offset - offsetStart;
return null;
}
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// 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.
#endregion Copyright
using System;
using System.Text.RegularExpressions;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using WatiN.Core.UnitTests.TestUtils;
namespace WatiN.Core.UnitTests
{
[TestFixture]
public class PageTests : BaseWithBrowserTests
{
[Test, Ignore("SF Bug 2866821: TODO for WatiN 2.1")]
// https://sourceforge.net/tracker/?func=detail&aid=2866821&group_id=167632&atid=843727
public void Should_fail_element_lookup_by_attribute_cause_we_are_on_the_wrong_page()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
browser.GoTo(AboutBlank);
var page = browser.Page<MainPage>();
// WHEN
try
{
var member = page.NameTextFieldUsingFindbyAttribute.Text;
Assert.Fail("Expected " + typeof(PageVerificationException).ToString());
}
catch (PageVerificationException)
{
// OK
}
catch(Exception e)
{
Assert.Fail("Unexpected exception: " + e.ToString());
}
// THEN expected exception
});
}
[Test, ExpectedException(ExceptionType = typeof(PageVerificationException))]
public void Should_fail_element_lookup_by_code_cause_we_are_on_the_wrong_page()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
browser.GoTo(AboutBlank);
var page = browser.Page<MainPage>();
// WHEN
var member = page.NameTextFieldUsingCode;
// THEN expected exception
});
}
[Test]
public void ShouldInitializeElementField()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var page = browser.Page<MainPage>();
// WHEN
var member = page.NameTextFieldUsingFindbyAttribute;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.Null);
Assert.That(member.Name, Is.EqualTo("textinput1"));
});
}
[Test]
public void ShouldInitializeElementPropertyWithDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var page = browser.Page<MainPage>();
// WHEN
var member = page.PopUpButton;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.EqualTo("Popup button."));
Assert.That(member.Id, Is.EqualTo("popupid"));
});
}
[Test]
public void ShouldInitializeControlFieldWithDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var page = browser.Page<MainPage>();
// WHEN
var member = page.NameTextFieldControl;
// THEN
Assert.That(member, Is.Not.Null);
Assert.That(member.Description, Is.EqualTo("Text field control."));
Assert.That(member.Id, Is.EqualTo("name"));
});
}
[Test]
public void ToStringWhenDescriptionIsNotSetShouldDescribePage()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
var page = browser.Page<MainPage>();
// WHEN
var description = page.Description;
var toString = page.ToString();
// THEN
Assert.That(description, Is.Null);
Assert.That(Regex.IsMatch(toString, @"MainPage \(file://.*\)"));
});
}
[Test]
public void ToStringWhenDescriptionIsSetShouldReturnDescription()
{
ExecuteTestWithAnyBrowser(browser =>
{
// GIVEN
#if !NET20
var page = browser.Page<MainPage>().WithDescription("foo");
#else
var page = browser.Page<MainPage>();
page.Description = "foo";
#endif
// WHEN
var description = page.Description;
var toString = page.ToString();
// THEN
Assert.That(description, Is.EqualTo("foo"));
Assert.That(toString, Is.EqualTo("foo"));
});
}
public override Uri TestPageUri
{
get { return MainURI; }
}
public class TextFieldControl : Control<TextField>
{
public string Text
{
get { return Element.Value; }
}
public string Id
{
get { return Element.Id; }
}
}
[Page(UrlRegex = "main.html$")]
public class MainPage : Page
{
[FindBy(Name = "textinput1")]
public TextField NameTextFieldUsingFindbyAttribute;
public TextField NameTextFieldUsingCode
{
get { return Document.TextField(Find.ByName("textinput1"));}
}
[FindBy(Id = "popupid")]
[Description("Popup button.")]
public Button PopUpButton { get; set; }
[FindBy(Name = "textinput1")]
[Description("Text field control.")]
internal TextFieldControl NameTextFieldControl = null; // intentionally non-public
}
}
[TestFixture]
public class GoogleTests
{
[Test, Ignore("SF Bug 2897406: TODO for WatiN 2.1")]
// https://sourceforge.net/tracker/?func=detail&aid=2897406&group_id=167632&atid=843727
public void Search_for_watin_on_google_using_page_class()
{
using (var browser = new IE("http://www.google.com"))
{
var searchPage = browser.Page<GoogleSearchPage>();
searchPage.SearchCriteria.TypeText("WatiN");
searchPage.SearchButton.Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
browser.Back();
//This line throws UnauthorizedAccessException.
searchPage.SearchCriteria.TypeText("Search Again");
searchPage.SearchButton.Click();
Assert.IsTrue(browser.ContainsText("Glenn"));
}
}
[Page(UrlRegex = "www.google.*")]
public class GoogleSearchPage : Page
{
[FindBy(Name = "q")]
public TextField SearchCriteria;
[FindBy(Name = "btnG")]
public Button SearchButton;
public void SearchFor(string searchCriteria)
{
SearchCriteria.TypeText("WatiN");
SearchButton.Click();
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TargetCore.cs
//
//
// The core implementation of a standard ITargetBlock<TInput>.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Threading.Tasks.Dataflow.Internal
{
// LOCK-LEVELING SCHEME
// --------------------
// TargetCore employs a single lock: IncomingLock. This lock must not be used when calling out to any targets,
// which TargetCore should not have, anyway. It also must not be held when calling back to any sources, except
// during calls to OfferMessage from that same source.
/// <summary>Options used to configure a target core.</summary>
[Flags]
internal enum TargetCoreOptions : byte
{
/// <summary>Synchronous completion, both a target and a source, etc.</summary>
None = 0x0,
/// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary>
UsesAsyncCompletion = 0x1,
/// <summary>
/// Whether the block containing this target core is just a target or also has a source side.
/// If it's just a target, then this target core's completion represents the entire block's completion.
/// </summary>
RepresentsBlockCompletion = 0x2
}
/// <summary>
/// Provides a core implementation of <see cref="ITargetBlock{TInput}"/>.</summary>
/// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
internal sealed class TargetCore<TInput>
{
// *** These fields are readonly and are initialized at AppDomain startup.
/// <summary>Caching the keep alive predicate.</summary>
private static readonly Common.KeepAlivePredicate<TargetCore<TInput>, KeyValuePair<TInput, long>> _keepAlivePredicate =
(TargetCore<TInput> thisTargetCore, out KeyValuePair<TInput, long> messageWithId) =>
thisTargetCore.TryGetNextAvailableOrPostponedMessage(out messageWithId);
// *** These fields are readonly and are initialized to new instances at construction.
/// <summary>A task representing the completion of the block.</summary>
private readonly TaskCompletionSource<VoidResult> _completionSource = new TaskCompletionSource<VoidResult>();
// *** These fields are readonly and are initialized by arguments to the constructor.
/// <summary>The target block using this helper.</summary>
private readonly ITargetBlock<TInput> _owningTarget;
/// <summary>The messages in this target.</summary>
/// <remarks>This field doubles as the IncomingLock.</remarks>
private readonly IProducerConsumerQueue<KeyValuePair<TInput, long>> _messages;
/// <summary>The options associated with this block.</summary>
private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions;
/// <summary>An action to invoke for every accepted message.</summary>
private readonly Action<KeyValuePair<TInput, long>> _callAction;
/// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary>
private readonly TargetCoreOptions _targetCoreOptions;
/// <summary>Bounding state for when the block is executing in bounded mode.</summary>
private readonly BoundingStateWithPostponed<TInput> _boundingState;
/// <summary>The reordering buffer used by the owner. May be null.</summary>
private readonly IReorderingBuffer _reorderingBuffer;
/// <summary>Gets the object used as the incoming lock.</summary>
private object IncomingLock { get { return _messages; } }
// *** These fields are mutated during execution.
/// <summary>Exceptions that may have occurred and gone unhandled during processing.</summary>
private List<Exception> _exceptions;
/// <summary>Whether to stop accepting new messages.</summary>
private bool _decliningPermanently;
/// <summary>The number of operations (including service tasks) currently running asynchronously.</summary>
/// <remarks>Must always be accessed from inside a lock.</remarks>
private int _numberOfOutstandingOperations;
/// <summary>The number of service tasks in async mode currently running.</summary>
/// <remarks>Must always be accessed from inside a lock.</remarks>
private int _numberOfOutstandingServiceTasks;
/// <summary>The next available ID we can assign to a message about to be processed.</summary>
private PaddedInt64 _nextAvailableInputMessageId; // initialized to 0... very important for a reordering buffer
/// <summary>A task has reserved the right to run the completion routine.</summary>
private bool _completionReserved;
/// <summary>This counter is set by the processing loop to prevent itself from trying to keep alive.</summary>
private int _keepAliveBanCounter;
/// <summary>Initializes the target core.</summary>
/// <param name="owningTarget">The target using this helper.</param>
/// <param name="callAction">An action to invoke for all accepted items.</param>
/// <param name="reorderingBuffer">The reordering buffer used by the owner; may be null.</param>
/// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param>
/// <param name="targetCoreOptions">Options for how the target core should behave.</param>
internal TargetCore(
ITargetBlock<TInput> owningTarget,
Action<KeyValuePair<TInput, long>> callAction,
IReorderingBuffer reorderingBuffer,
ExecutionDataflowBlockOptions dataflowBlockOptions,
TargetCoreOptions targetCoreOptions)
{
// Validate internal arguments
Contract.Requires(owningTarget != null, "Core must be associated with a target block.");
Contract.Requires(dataflowBlockOptions != null, "Options must be provided to configure the core.");
Contract.Requires(callAction != null, "Action to invoke for each item is required.");
// Store arguments and do additional initialization
_owningTarget = owningTarget;
_callAction = callAction;
_reorderingBuffer = reorderingBuffer;
_dataflowBlockOptions = dataflowBlockOptions;
_targetCoreOptions = targetCoreOptions;
_messages = (dataflowBlockOptions.MaxDegreeOfParallelism == 1) ?
(IProducerConsumerQueue<KeyValuePair<TInput, long>>)new SingleProducerSingleConsumerQueue<KeyValuePair<TInput, long>>() :
(IProducerConsumerQueue<KeyValuePair<TInput, long>>)new MultiProducerMultiConsumerQueue<KeyValuePair<TInput, long>>();
if (_dataflowBlockOptions.BoundedCapacity != System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded)
{
Debug.Assert(_dataflowBlockOptions.BoundedCapacity > 0, "Positive bounding count expected; should have been verified by options ctor");
_boundingState = new BoundingStateWithPostponed<TInput>(_dataflowBlockOptions.BoundedCapacity);
}
}
/// <summary>Internal Complete entry point with extra parameters for different contexts.</summary>
/// <param name="exception">If not null, the block will be faulted.</param>
/// <param name="dropPendingMessages">If true, any unprocessed input messages will be dropped.</param>
/// <param name="storeExceptionEvenIfAlreadyCompleting">If true, an exception will be stored after _decliningPermanently has been set to true.</param>
/// <param name="unwrapInnerExceptions">If true, exception will be treated as an AggregateException.</param>
/// <param name="revertProcessingState">Indicates whether the processing state is dirty and has to be reverted.</param>
internal void Complete(Exception exception, bool dropPendingMessages, bool storeExceptionEvenIfAlreadyCompleting = false,
bool unwrapInnerExceptions = false, bool revertProcessingState = false)
{
Contract.Requires(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
Contract.EndContractBlock();
// Ensure that no new messages may be added
lock (IncomingLock)
{
// Faulting from outside is allowed until we start declining permanently.
// Faulting from inside is allowed at any time.
if (exception != null && (!_decliningPermanently || storeExceptionEvenIfAlreadyCompleting))
{
Debug.Assert(_numberOfOutstandingOperations > 0 || !storeExceptionEvenIfAlreadyCompleting,
"Calls with storeExceptionEvenIfAlreadyCompleting==true may only be coming from processing task.");
#pragma warning disable 0420
Common.AddException(ref _exceptions, exception, unwrapInnerExceptions);
}
// Clear the messages queue if requested
if (dropPendingMessages)
{
KeyValuePair<TInput, long> dummy;
while (_messages.TryDequeue(out dummy)) ;
}
// Revert the dirty processing state if requested
if (revertProcessingState)
{
Debug.Assert(_numberOfOutstandingOperations > 0 && (!UsesAsyncCompletion || _numberOfOutstandingServiceTasks > 0),
"The processing state must be dirty when revertProcessingState==true.");
_numberOfOutstandingOperations--;
if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks--;
}
// Trigger completion
_decliningPermanently = true;
CompleteBlockIfPossible();
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, Boolean consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
Contract.EndContractBlock();
lock (IncomingLock)
{
// If we shouldn't be accepting more messages, don't.
if (_decliningPermanently)
{
CompleteBlockIfPossible();
return DataflowMessageStatus.DecliningPermanently;
}
// We can directly accept the message if:
// 1) we are not bounding, OR
// 2) we are bounding AND there is room available AND there are no postponed messages AND no messages are currently being transfered to the input queue.
// (If there were any postponed messages, we would need to postpone so that ordering would be maintained.)
// (Unlike all other blocks, TargetCore can accept messages while processing, because
// input message IDs are properly assigned and the correct order is preserved.)
if (_boundingState == null ||
(_boundingState.OutstandingTransfers == 0 && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0))
{
// Consume the message from the source if necessary
if (consumeToAccept)
{
Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true.");
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// Assign a message ID - strictly sequential, no gaps.
// Once consumed, enqueue the message with its ID and kick off asynchronous processing.
long messageId = _nextAvailableInputMessageId.Value++;
Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid.");
if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound
_messages.Enqueue(new KeyValuePair<TInput, long>(messageValue, messageId));
ProcessAsyncIfNecessary();
return DataflowMessageStatus.Accepted;
}
// Otherwise, we try to postpone if a source was provided
else if (source != null)
{
Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null,
"PostponedMessages must have been initialized during construction in non-greedy mode.");
// Store the message's info and kick off asynchronous processing
_boundingState.PostponedMessages.Push(source, messageHeader);
ProcessAsyncIfNecessary();
return DataflowMessageStatus.Postponed;
}
// We can't do anything else about this message
return DataflowMessageStatus.Declined;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
internal Task Completion { get { return _completionSource.Task; } }
/// <summary>Gets the number of items waiting to be processed by this target.</summary>
internal int InputCount { get { return _messages.GetCountSafe(IncomingLock); } }
/// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary>
internal void SignalOneAsyncMessageCompleted()
{
SignalOneAsyncMessageCompleted(boundingCountChange: 0);
}
/// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary>
/// <param name="boundingCountChange">The number of elements by which to change the bounding count, if bounding is occurring.</param>
internal void SignalOneAsyncMessageCompleted(int boundingCountChange)
{
lock (IncomingLock)
{
// We're no longer processing, so decrement the DOP counter
Debug.Assert(_numberOfOutstandingOperations > 0, "Operations may only be completed if any are outstanding.");
if (_numberOfOutstandingOperations > 0) _numberOfOutstandingOperations--;
// Fix up the bounding count if necessary
if (_boundingState != null && boundingCountChange != 0)
{
Debug.Assert(boundingCountChange <= 0 && _boundingState.CurrentCount + boundingCountChange >= 0,
"Expected a negative bounding change and not to drop below zero.");
_boundingState.CurrentCount += boundingCountChange;
}
// However, we may have given up early because we hit our own configured
// processing limits rather than because we ran out of work to do. If that's
// the case, make sure we spin up another task to keep going.
ProcessAsyncIfNecessary(repeat: true);
// If, however, we stopped because we ran out of work to do and we
// know we'll never get more, then complete.
CompleteBlockIfPossible();
}
}
/// <summary>Gets whether this instance has been constructed for async processing.</summary>
private bool UsesAsyncCompletion
{
get
{
return (_targetCoreOptions & TargetCoreOptions.UsesAsyncCompletion) != 0;
}
}
/// <summary>Gets whether there's room to launch more processing operations.</summary>
private bool HasRoomForMoreOperations
{
get
{
Contract.Requires(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative.");
Contract.Requires(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative.");
Contract.Requires(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations.");
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
// In async mode, we increment _numberOfOutstandingOperations before we start
// our own processing loop which should not count towards the MaxDOP.
return (_numberOfOutstandingOperations - _numberOfOutstandingServiceTasks) < _dataflowBlockOptions.ActualMaxDegreeOfParallelism;
}
}
/// <summary>Gets whether there's room to launch more service tasks for doing/launching processing operations.</summary>
private bool HasRoomForMoreServiceTasks
{
get
{
Contract.Requires(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative.");
Contract.Requires(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative.");
Contract.Requires(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations.");
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
if (!UsesAsyncCompletion)
{
// Sync mode:
// We don't count service tasks, because our tasks are counted as operations.
// Therefore, return HasRoomForMoreOperations.
return HasRoomForMoreOperations;
}
else
{
// Async mode:
// We allow up to MaxDOP true service tasks.
// Checking whether there is room for more processing operations is not necessary,
// but doing so will help us avoid spinning up a task that will go away without
// launching any processing operation.
return HasRoomForMoreOperations &&
_numberOfOutstandingServiceTasks < _dataflowBlockOptions.ActualMaxDegreeOfParallelism;
}
}
}
/// <summary>Called when new messages are available to be processed.</summary>
/// <param name="repeat">Whether this call is the continuation of a previous message loop.</param>
private void ProcessAsyncIfNecessary(bool repeat = false)
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
if (HasRoomForMoreServiceTasks)
{
ProcessAsyncIfNecessary_Slow(repeat);
}
}
/// <summary>
/// Slow path for ProcessAsyncIfNecessary.
/// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void ProcessAsyncIfNecessary_Slow(bool repeat)
{
Contract.Requires(HasRoomForMoreServiceTasks, "There must be room to process asynchronously.");
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
// Determine preconditions to launching a processing task
bool messagesAvailableOrPostponed =
!_messages.IsEmpty ||
(!_decliningPermanently && _boundingState != null && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count > 0);
// If all conditions are met, launch away
if (messagesAvailableOrPostponed && !CanceledOrFaulted)
{
// Any book keeping related to the processing task like incrementing the
// DOP counter or eventually recording the tasks reference must be done
// before the task starts. That is because the task itself will do the
// reverse operation upon its completion.
_numberOfOutstandingOperations++;
if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks++;
var taskForInputProcessing = new Task(thisTargetCore => ((TargetCore<TInput>)thisTargetCore).ProcessMessagesLoopCore(), this,
Common.GetCreationOptionsForTask(repeat));
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
_owningTarget, taskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages,
_messages.Count + (_boundingState != null ? _boundingState.PostponedMessages.Count : 0));
}
#endif
// Start the task handling scheduling exceptions
Exception exception = Common.StartTaskSafe(taskForInputProcessing, _dataflowBlockOptions.TaskScheduler);
if (exception != null)
{
// Get out from under currently held locks. Complete re-acquires the locks it needs.
Task.Factory.StartNew(exc => Complete(exception: (Exception)exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true,
unwrapInnerExceptions: false, revertProcessingState: true),
exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
}
}
/// <summary>Task body used to process messages.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ProcessMessagesLoopCore()
{
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
KeyValuePair<TInput, long> messageWithId = default(KeyValuePair<TInput, long>);
try
{
bool useAsyncCompletion = UsesAsyncCompletion;
bool shouldAttemptPostponedTransfer = _boundingState != null && _boundingState.BoundedCapacity > 1;
int numberOfMessagesProcessedByThisTask = 0;
int numberOfMessagesProcessedSinceTheLastKeepAlive = 0;
int maxMessagesPerTask = _dataflowBlockOptions.ActualMaxMessagesPerTask;
while (numberOfMessagesProcessedByThisTask < maxMessagesPerTask && !CanceledOrFaulted)
{
// If we're bounding, try to transfer a message from the postponed queue
// to the input queue. This enables us to more quickly unblock sources
// sending data to the block (otherwise, no postponed messages will be consumed
// until the input queue is entirely empty). If the bounded size is 1,
// there's no need to transfer, as attempting to get the next message will
// just go and consume the postponed message anyway, and we'll save
// the extra trip through the _messages queue.
KeyValuePair<TInput, long> transferMessageWithId;
if (shouldAttemptPostponedTransfer &&
TryConsumePostponedMessage(forPostponementTransfer: true, result: out transferMessageWithId))
{
lock (IncomingLock)
{
Debug.Assert(
_boundingState.OutstandingTransfers > 0
&& _boundingState.OutstandingTransfers <= _dataflowBlockOptions.ActualMaxDegreeOfParallelism,
"Expected TryConsumePostponedMessage to have incremented the count and for the count to not exceed the DOP.");
_boundingState.OutstandingTransfers--; // was incremented in TryConsumePostponedMessage
_messages.Enqueue(transferMessageWithId);
ProcessAsyncIfNecessary();
}
}
if (useAsyncCompletion)
{
// Get the next message if DOP is available.
// If we can't get a message or DOP is not available, bail out.
if (!TryGetNextMessageForNewAsyncOperation(out messageWithId)) break;
}
else
{
// Try to get a message for sequential execution, i.e. without checking DOP availability
if (!TryGetNextAvailableOrPostponedMessage(out messageWithId))
{
// Try to keep the task alive only if MaxDOP=1
if (_dataflowBlockOptions.MaxDegreeOfParallelism != 1) break;
// If this task has processed enough messages without being kept alive,
// it has served its purpose. Don't keep it alive.
if (numberOfMessagesProcessedSinceTheLastKeepAlive > Common.KEEP_ALIVE_NUMBER_OF_MESSAGES_THRESHOLD) break;
// If keep alive is banned, don't attempt it
if (_keepAliveBanCounter > 0)
{
_keepAliveBanCounter--;
break;
}
// Reset the keep alive counter. (Keep this line together with TryKeepAliveUntil.)
numberOfMessagesProcessedSinceTheLastKeepAlive = 0;
// Try to keep the task alive briefly until a new message arrives
if (!Common.TryKeepAliveUntil(_keepAlivePredicate, this, out messageWithId))
{
// Keep alive was unsuccessful.
// Therefore ban further attempts temporarily.
_keepAliveBanCounter = Common.KEEP_ALIVE_BAN_COUNT;
break;
}
}
}
// We have popped a message from the queue.
// So increment the counter of processed messages.
numberOfMessagesProcessedByThisTask++;
numberOfMessagesProcessedSinceTheLastKeepAlive++;
// Invoke the user action
_callAction(messageWithId);
}
}
catch (Exception exc)
{
Common.StoreDataflowMessageValueIntoExceptionData(exc, messageWithId.Key);
Complete(exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false);
}
finally
{
lock (IncomingLock)
{
// We incremented _numberOfOutstandingOperations before we launched this task.
// So we must decremented it before exiting.
// Note that each async task additionally incremented it before starting and
// is responsible for decrementing it prior to exiting.
Debug.Assert(_numberOfOutstandingOperations > 0, "Expected a positive number of outstanding operations, since we're completing one here.");
_numberOfOutstandingOperations--;
// If we are in async mode, we've also incremented _numberOfOutstandingServiceTasks.
// Now it's time to decrement it.
if (UsesAsyncCompletion)
{
Debug.Assert(_numberOfOutstandingServiceTasks > 0, "Expected a positive number of outstanding service tasks, since we're completing one here.");
_numberOfOutstandingServiceTasks--;
}
// However, we may have given up early because we hit our own configured
// processing limits rather than because we ran out of work to do. If that's
// the case, make sure we spin up another task to keep going.
ProcessAsyncIfNecessary(repeat: true);
// If, however, we stopped because we ran out of work to do and we
// know we'll never get more, then complete.
CompleteBlockIfPossible();
}
}
}
/// <summary>Retrieves the next message from the input queue for the useAsyncCompletion mode.</summary>
/// <param name="messageWithId">The next message retrieved.</param>
/// <returns>true if a message was found and removed; otherwise, false.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool TryGetNextMessageForNewAsyncOperation(out KeyValuePair<TInput, long> messageWithId)
{
Contract.Requires(UsesAsyncCompletion, "Only valid to use when in async mode.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
bool parallelismAvailable;
lock (IncomingLock)
{
// If we have room for another asynchronous operation, reserve it.
// If later it turns out that we had no work to fill the slot, we'll undo the addition.
parallelismAvailable = HasRoomForMoreOperations;
if (parallelismAvailable) ++_numberOfOutstandingOperations;
}
messageWithId = default(KeyValuePair<TInput, long>);
if (parallelismAvailable)
{
// If a parallelism slot was available, try to get an item.
// Be careful, because an exception may be thrown from ConsumeMessage
// and we have already incremented _numberOfOutstandingOperations.
bool gotMessage = false;
try
{
gotMessage = TryGetNextAvailableOrPostponedMessage(out messageWithId);
}
catch
{
// We have incremented the counter, but we didn't get a message.
// So we must undo the increment and eventually complete the block.
SignalOneAsyncMessageCompleted();
// Re-throw the exception. The processing loop will catch it.
throw;
}
// There may not be an error, but may have still failed to get a message.
// So we must undo the increment and eventually complete the block.
if (!gotMessage) SignalOneAsyncMessageCompleted();
return gotMessage;
}
// If there was no parallelism available, we didn't increment _numberOfOutstandingOperations.
// So there is nothing to do except to return false.
return false;
}
/// <summary>
/// Either takes the next available message from the input queue or retrieves a postponed
/// message from a source, based on whether we're in greedy or non-greedy mode.
/// </summary>
/// <param name="messageWithId">The retrieved item with its Id.</param>
/// <returns>true if a message could be removed and returned; otherwise, false.</returns>
private bool TryGetNextAvailableOrPostponedMessage(out KeyValuePair<TInput, long> messageWithId)
{
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// First try to get a message from our input buffer.
if (_messages.TryDequeue(out messageWithId))
{
return true;
}
// If we can't, but if we have any postponed messages due to bounding, then
// try to consume one of these postponed messages.
// Since we are not currently holding the lock, it is possible that new messages get queued up
// by the time we take the lock to manipulate _boundingState. So we have to double-check the
// input queue once we take the lock before we consider postponed messages.
else if (_boundingState != null && TryConsumePostponedMessage(forPostponementTransfer: false, result: out messageWithId))
{
return true;
}
// Otherwise, there's no message available.
else
{
messageWithId = default(KeyValuePair<TInput, long>);
return false;
}
}
/// <summary>Consumes a single postponed message.</summary>
/// <param name="forPostponementTransfer">
/// true if the method is being called to consume a message that'll then be stored into the input queue;
/// false if the method is being called to consume a message that'll be processed immediately.
/// If true, the bounding state's ForcePostponement will be updated.
/// If false, the method will first try (while holding the lock) to consume from the input queue before
/// consuming a postponed message.
/// </param>
/// <param name="result">The consumed message.</param>
/// <returns>true if a message was consumed; otherwise, false.</returns>
private bool TryConsumePostponedMessage(
bool forPostponementTransfer,
out KeyValuePair<TInput, long> result)
{
Contract.Requires(
_dataflowBlockOptions.BoundedCapacity !=
System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded, "Only valid to use when in bounded mode.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// Iterate until we either consume a message successfully or there are no more postponed messages.
bool countIncrementedExpectingToGetItem = false;
long messageId = Common.INVALID_REORDERING_ID;
while (true)
{
KeyValuePair<ISourceBlock<TInput>, DataflowMessageHeader> element;
lock (IncomingLock)
{
// If we are declining permanently, don't consume postponed messages.
if (_decliningPermanently) break;
// New messages may have been queued up while we weren't holding the lock.
// In particular, the input queue may have been filled up and messages may have
// gotten postponed. If we process such a postponed message, we would mess up the
// order. Therefore, we have to double-check the input queue first.
if (!forPostponementTransfer && _messages.TryDequeue(out result)) return true;
// We can consume a message to process if there's one to process and also if
// if we have logical room within our bound for the message.
if (!_boundingState.CountIsLessThanBound || !_boundingState.PostponedMessages.TryPop(out element))
{
if (countIncrementedExpectingToGetItem)
{
countIncrementedExpectingToGetItem = false;
_boundingState.CurrentCount -= 1;
}
break;
}
if (!countIncrementedExpectingToGetItem)
{
countIncrementedExpectingToGetItem = true;
messageId = _nextAvailableInputMessageId.Value++; // optimistically assign an ID
Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid.");
_boundingState.CurrentCount += 1; // optimistically take bounding space
if (forPostponementTransfer)
{
Debug.Assert(_boundingState.OutstandingTransfers >= 0, "Expected TryConsumePostponedMessage to not be negative.");
_boundingState.OutstandingTransfers++; // temporarily force postponement until we've successfully consumed the element
}
}
} // Must not call to source while holding lock
bool consumed;
TInput consumedValue = element.Key.ConsumeMessage(element.Value, _owningTarget, out consumed);
if (consumed)
{
result = new KeyValuePair<TInput, long>(consumedValue, messageId);
return true;
}
else
{
if (forPostponementTransfer)
{
// We didn't consume message so we need to decrement because we havent consumed the element.
_boundingState.OutstandingTransfers--;
}
}
}
// We optimistically acquired a message ID for a message that, in the end, we never got.
// So, we need to let the reordering buffer (if one exists) know that it should not
// expect an item with this ID. Otherwise, it would stall forever.
if (_reorderingBuffer != null && messageId != Common.INVALID_REORDERING_ID) _reorderingBuffer.IgnoreItem(messageId);
// Similarly, we optimistically increased the bounding count, expecting to get another message in.
// Since we didn't, we need to fix the bounding count back to what it should have been.
if (countIncrementedExpectingToGetItem) ChangeBoundingCount(-1);
// Inform the caller that no message could be consumed.
result = default(KeyValuePair<TInput, long>);
return false;
}
/// <summary>Gets whether the target has had cancellation requested or an exception has occurred.</summary>
private bool CanceledOrFaulted
{
get
{
return _dataflowBlockOptions.CancellationToken.IsCancellationRequested || Volatile.Read(ref _exceptions) != null;
}
}
/// <summary>Completes the block once all completion conditions are met.</summary>
private void CompleteBlockIfPossible()
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
bool noMoreMessages = _decliningPermanently && _messages.IsEmpty;
if (noMoreMessages || CanceledOrFaulted)
{
CompleteBlockIfPossible_Slow();
}
}
/// <summary>
/// Slow path for CompleteBlockIfPossible.
/// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined.
/// </summary>
private void CompleteBlockIfPossible_Slow()
{
Contract.Requires((_decliningPermanently && _messages.IsEmpty) || CanceledOrFaulted, "There must be no more messages.");
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
bool notCurrentlyProcessing = _numberOfOutstandingOperations == 0;
if (notCurrentlyProcessing && !_completionReserved)
{
// Make sure no one else tries to call CompleteBlockOncePossible
_completionReserved = true;
// Make sure the target is declining
_decliningPermanently = true;
// Get out from under currently held locks. This is to avoid
// invoking synchronous continuations off of _completionSource.Task
// while holding a lock.
Task.Factory.StartNew(state => ((TargetCore<TInput>)state).CompleteBlockOncePossible(),
this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
}
/// <summary>
/// Completes the block. This must only be called once, and only once all of the completion conditions are met.
/// As such, it must only be called from CompleteBlockIfPossible.
/// </summary>
private void CompleteBlockOncePossible()
{
// Since the lock is needed only for the Assert, we do this only in DEBUG mode
#if DEBUG
lock (IncomingLock) Debug.Assert(_numberOfOutstandingOperations == 0, "Everything must be done by now.");
#endif
// Release any postponed messages
if (_boundingState != null)
{
// Note: No locks should be held at this point.
Common.ReleaseAllPostponedMessages(_owningTarget, _boundingState.PostponedMessages, ref _exceptions);
}
// For good measure and help in preventing leaks, clear out the incoming message queue,
// which may still contain orphaned data if we were canceled or faulted. However,
// we don't reset the bounding count here, as the block as a whole may still be active.
KeyValuePair<TInput, long> ignored;
IProducerConsumerQueue<KeyValuePair<TInput, long>> messages = _messages;
while (messages.TryDequeue(out ignored)) ;
// If we completed with any unhandled exception, finish in an error state
if (Volatile.Read(ref _exceptions) != null)
{
// It's ok to read _exceptions' content here, because
// at this point no more exceptions can be generated and thus no one will
// be writing to it.
_completionSource.TrySetException(Volatile.Read(ref _exceptions));
}
// If we completed with cancellation, finish in a canceled state
else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested)
{
_completionSource.TrySetCanceled();
}
// Otherwise, finish in a successful state.
else
{
_completionSource.TrySetResult(default(VoidResult));
}
#if FEATURE_TRACING
// We only want to do tracing for block completion if this target core represents the whole block.
// If it only represents a part of the block (i.e. there's a source associated with it as well),
// then we shouldn't log just for the first half of the block; the source half will handle logging.
DataflowEtwProvider etwLog;
if ((_targetCoreOptions & TargetCoreOptions.RepresentsBlockCompletion) != 0 &&
(etwLog = DataflowEtwProvider.Log).IsEnabled())
{
etwLog.DataflowBlockCompleted(_owningTarget);
}
#endif
}
/// <summary>Gets whether the target core is operating in a bounded mode.</summary>
internal bool IsBounded { get { return _boundingState != null; } }
/// <summary>Increases or decreases the bounding count.</summary>
/// <param name="count">The incremental addition (positive to increase, negative to decrease).</param>
internal void ChangeBoundingCount(int count)
{
Contract.Requires(count != 0, "Should only be called when the count is actually changing.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
if (_boundingState != null)
{
lock (IncomingLock)
{
Debug.Assert(count > 0 || (count < 0 && _boundingState.CurrentCount + count >= 0),
"If count is negative, it must not take the total count negative.");
_boundingState.CurrentCount += count;
ProcessAsyncIfNecessary();
CompleteBlockIfPossible();
}
}
}
/// <summary>Gets the object to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _owningTarget as IDebuggerDisplay;
return string.Format("Block=\"{0}\"",
displayTarget != null ? displayTarget.Content : _owningTarget);
}
}
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } }
/// <summary>Gets information about this helper to be used for display in a debugger.</summary>
/// <returns>Debugging information about this target.</returns>
internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); }
/// <summary>Provides a wrapper for commonly needed debugging information.</summary>
internal sealed class DebuggingInformation
{
/// <summary>The target being viewed.</summary>
private readonly TargetCore<TInput> _target;
/// <summary>Initializes the debugging helper.</summary>
/// <param name="target">The target being viewed.</param>
internal DebuggingInformation(TargetCore<TInput> target) { _target = target; }
/// <summary>Gets the number of messages waiting to be processed.</summary>
internal int InputCount { get { return _target._messages.Count; } }
/// <summary>Gets the messages waiting to be processed.</summary>
internal IEnumerable<TInput> InputQueue { get { return _target._messages.Select(kvp => kvp.Key).ToList(); } }
/// <summary>Gets any postponed messages.</summary>
internal QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages
{
get { return _target._boundingState != null ? _target._boundingState.PostponedMessages : null; }
}
/// <summary>Gets the current number of outstanding input processing operations.</summary>
internal Int32 CurrentDegreeOfParallelism { get { return _target._numberOfOutstandingOperations - _target._numberOfOutstandingServiceTasks; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
internal bool IsCompleted { get { return _target.Completion.IsCompleted; } }
}
}
}
| |
using System;
using TidyNet.Dom;
namespace TidyNet
{
/// <summary>
/// DomDocumentImpl
///
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.cs for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
///
/// </summary>
/// <author>Dave Raggett <[email protected]></author>
/// <author>Andy Quick <[email protected]> (translation to Java)</author>
/// <author>Seth Yates <[email protected]> (translation to C#)</author>
/// <version>1.4, 1999/09/04 DOM support</version>
/// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version>
/// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version>
/// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version>
/// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version>
/// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version>
/// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version>
/// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version>
internal class DomDocumentImpl : DomNodeImpl, IDocument
{
protected internal DomDocumentImpl(Node Adaptee) : base(Adaptee)
{
tt = new TagTable();
}
virtual public TagTable TagTable
{
set
{
this.tt = value;
}
}
override public string NodeName
{
get
{
return "#document";
}
}
override public NodeType NodeType
{
get
{
return NodeType.DOCUMENT_NODE;
}
}
virtual public IDocumentType Doctype
{
get
{
Node node = Adaptee.Content;
while (node != null)
{
if (node.Type == Node.DocTypeTag)
{
break;
}
node = node.Next;
}
if (node != null)
{
return (IDocumentType) node.Adapter;
}
else
{
return null;
}
}
}
virtual public IDomImplementation Implementation
{
get
{
// NOT SUPPORTED
return null;
}
}
virtual public IElement DocumentElement
{
get
{
Node node = Adaptee.Content;
while (node != null)
{
if (node.Type == Node.StartTag || node.Type == Node.StartEndTag)
{
break;
}
node = node.Next;
}
if (node != null)
{
return (IElement) node.Adapter;
}
else
{
return null;
}
}
}
public virtual IElement CreateElement(string tagName)
{
Node node = new Node(Node.StartEndTag, null, 0, 0, tagName, tt);
if (node != null)
{
if (node.Tag == null)
{
// Fix Bug 121206
node.Tag = tt.XmlTags;
}
return (IElement) node.Adapter;
}
else
{
return null;
}
}
public virtual IDocumentFragment CreateDocumentFragment()
{
// NOT SUPPORTED
return null;
}
public virtual IText CreateTextNode(string data)
{
byte[] textarray = Lexer.GetBytes(data);
Node node = new Node(Node.TextNode, textarray, 0, textarray.Length);
if (node != null)
{
return (IText) node.Adapter;
}
else
{
return null;
}
}
public virtual IComment CreateComment(string data)
{
byte[] textarray = Lexer.GetBytes(data);
Node node = new Node(Node.CommentTag, textarray, 0, textarray.Length);
if (node != null)
{
return (IComment) node.Adapter;
}
else
{
return null;
}
}
public virtual ICdataSection CreateCdataSection(string data)
{
// NOT SUPPORTED
return null;
}
public virtual IProcessingInstruction CreateProcessingInstruction(string target, string data)
{
throw new DomException(DomException.NotSupported, "HTML document");
}
public virtual IAttr CreateAttribute(string name)
{
AttVal av = new AttVal(null, null, (int) '"', name, null);
if (av != null)
{
av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(av);
return (IAttr) av.Adapter;
}
else
{
return null;
}
}
public virtual IEntityReference CreateEntityReference(string name)
{
// NOT SUPPORTED
return null;
}
public virtual INodeList GetElementsByTagName(string tagname)
{
return new DomNodeListByTagNameImpl(this.Adaptee, tagname);
}
/// <summary> DOM2 - not implemented. </summary>
public virtual INode ImportNode(INode importedNode, bool deep)
{
return null;
}
/// <summary> DOM2 - not implemented. </summary>
public virtual IAttr CreateAttributeNS(string namespaceURI, string qualifiedName)
{
return null;
}
/// <summary> DOM2 - not implemented. </summary>
public virtual IElement CreateElementNS(string namespaceURI, string qualifiedName)
{
return null;
}
/// <summary> DOM2 - not implemented. </summary>
public virtual INodeList GetElementsByTagNameNS(string namespaceURI, string localName)
{
return null;
}
/// <summary> DOM2 - not implemented. </summary>
public virtual IElement GetElementById(string elementId)
{
return null;
}
private TagTable tt;
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.Text;
namespace gView.Framework.system
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class JSON
{
public const int TOKEN_NONE = 0;
public const int TOKEN_CURLY_OPEN = 1;
public const int TOKEN_CURLY_CLOSE = 2;
public const int TOKEN_SQUARED_OPEN = 3;
public const int TOKEN_SQUARED_CLOSE = 4;
public const int TOKEN_COLON = 5;
public const int TOKEN_COMMA = 6;
public const int TOKEN_STRING = 7;
public const int TOKEN_NUMBER = 8;
public const int TOKEN_TRUE = 9;
public const int TOKEN_FALSE = 10;
public const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json)
{
bool success = true;
return JsonDecode(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json, ref bool success)
{
success = true;
if (json != null)
{
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
}
else
{
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string JsonEncode(object json)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(json, builder);
return (success ? builder.ToString() : null);
}
protected static Hashtable ParseObject(char[] json, ref int index, ref bool success)
{
Hashtable table = new Hashtable();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done)
{
token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE)
{
success = false;
return null;
}
else if (token == JSON.TOKEN_COMMA)
{
NextToken(json, ref index);
}
else if (token == JSON.TOKEN_CURLY_CLOSE)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != JSON.TOKEN_COLON)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
{
ArrayList array = new ArrayList();
// [
NextToken(json, ref index);
bool done = false;
while (!done)
{
int token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE)
{
success = false;
return null;
}
else if (token == JSON.TOKEN_COMMA)
{
NextToken(json, ref index);
}
else if (token == JSON.TOKEN_SQUARED_CLOSE)
{
NextToken(json, ref index);
break;
}
else
{
object value = ParseValue(json, ref index, ref success);
if (!success)
{
return null;
}
array.Add(value);
}
}
return array;
}
protected static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index))
{
case JSON.TOKEN_STRING:
return ParseString(json, ref index, ref success);
case JSON.TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case JSON.TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case JSON.TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case JSON.TOKEN_TRUE:
NextToken(json, ref index);
return true;
case JSON.TOKEN_FALSE:
NextToken(json, ref index);
return false;
case JSON.TOKEN_NULL:
NextToken(json, ref index);
return null;
case JSON.TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete)
{
if (index == json.Length)
{
break;
}
c = json[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == json.Length)
{
break;
}
c = json[index++];
if (c == '"')
{
s.Append('"');
}
else if (c == '\\')
{
s.Append('\\');
}
else if (c == '/')
{
s.Append('/');
}
else if (c == 'b')
{
s.Append('\b');
}
else if (c == 'f')
{
s.Append('\f');
}
else if (c == 'n')
{
s.Append('\n');
}
else if (c == 'r')
{
s.Append('\r');
}
else if (c == 't')
{
s.Append('\t');
}
else if (c == 'u')
{
int remainingLength = json.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
{
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
s.Append(c);
}
}
if (!complete)
{
success = false;
return null;
}
return s.ToString();
}
protected static double ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
double number;
success = Double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
index = lastIndex + 1;
return number;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++)
{
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1)
{
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++)
{
if (" \t\n\r".IndexOf(json[index]) == -1)
{
break;
}
}
}
protected static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
protected static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length)
{
return JSON.TOKEN_NONE;
}
char c = json[index];
index++;
switch (c)
{
case '{':
return JSON.TOKEN_CURLY_OPEN;
case '}':
return JSON.TOKEN_CURLY_CLOSE;
case '[':
return JSON.TOKEN_SQUARED_OPEN;
case ']':
return JSON.TOKEN_SQUARED_CLOSE;
case ',':
return JSON.TOKEN_COMMA;
case '"':
return JSON.TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return JSON.TOKEN_NUMBER;
case ':':
return JSON.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e')
{
index += 5;
return JSON.TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e')
{
index += 4;
return JSON.TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l')
{
index += 4;
return JSON.TOKEN_NULL;
}
}
return JSON.TOKEN_NONE;
}
protected static bool SerializeValue(object value, StringBuilder builder)
{
bool success = true;
if (value is string)
{
success = SerializeString((string)value, builder);
}
else if (value is Hashtable)
{
success = SerializeObject((Hashtable)value, builder);
}
else if (value is ArrayList)
{
success = SerializeArray((ArrayList)value, builder);
}
else if (IsNumeric(value))
{
success = SerializeNumber(Convert.ToDouble(value), builder);
}
else if ((value is Boolean) && ((Boolean)value == true))
{
builder.Append("true");
}
else if ((value is Boolean) && ((Boolean)value == false))
{
builder.Append("false");
}
else if (value == null)
{
builder.Append("null");
}
else
{
success = false;
}
return success;
}
protected static bool SerializeObject(Hashtable anObject, StringBuilder builder)
{
builder.Append("{");
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while (e.MoveNext())
{
string key = e.Key.ToString();
object value = e.Value;
if (!first)
{
builder.Append(", ");
}
SerializeString(key, builder);
builder.Append(":");
if (!SerializeValue(value, builder))
{
return false;
}
first = false;
}
builder.Append("}");
return true;
}
protected static bool SerializeArray(ArrayList anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
for (int i = 0; i < anArray.Count; i++)
{
object value = anArray[i];
if (!first)
{
builder.Append(", ");
}
if (!SerializeValue(value, builder))
{
return false;
}
first = false;
}
builder.Append("]");
return true;
}
protected static bool SerializeString(string aString, StringBuilder builder)
{
builder.Append("\"");
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
if (c == '"')
{
builder.Append("\\\"");
}
else if (c == '\\')
{
builder.Append("\\\\");
}
else if (c == '\b')
{
builder.Append("\\b");
}
else if (c == '\f')
{
builder.Append("\\f");
}
else if (c == '\n')
{
builder.Append("\\n");
}
else if (c == '\r')
{
builder.Append("\\r");
}
else if (c == '\t')
{
builder.Append("\\t");
}
else
{
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126))
{
builder.Append(c);
}
else
{
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
}
}
builder.Append("\"");
return true;
}
protected static bool SerializeNumber(double number, StringBuilder builder)
{
builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture));
return true;
}
/// <summary>
/// Determines if a given object is numeric in any way
/// (can be integer, double, null, etc).
///
/// Thanks to mtighe for pointing out Double.TryParse to me.
/// </summary>
protected static bool IsNumeric(object o)
{
double result;
return (o == null) ? false : Double.TryParse(o.ToString(), out result);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullableMultiplyTests
{
#region Test methods
[Fact]
public static void CheckNullableByteMultiplyTest()
{
byte?[] array = { 0, 1, byte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSByteMultiplyTest()
{
sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteMultiply(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortMultiplyTest(bool useInterpreter)
{
ushort?[] array = { 0, 1, ushort.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortMultiply(array[i], array[j], useInterpreter);
VerifyNullableUShortMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortMultiplyTest(bool useInterpreter)
{
short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortMultiply(array[i], array[j], useInterpreter);
VerifyNullableShortMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntMultiplyTest(bool useInterpreter)
{
uint?[] array = { 0, 1, uint.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntMultiply(array[i], array[j], useInterpreter);
VerifyNullableUIntMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntMultiplyTest(bool useInterpreter)
{
int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntMultiply(array[i], array[j], useInterpreter);
VerifyNullableIntMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongMultiplyTest(bool useInterpreter)
{
ulong?[] array = { 0, 1, ulong.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongMultiply(array[i], array[j], useInterpreter);
VerifyNullableULongMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongMultiplyTest(bool useInterpreter)
{
long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongMultiply(array[i], array[j], useInterpreter);
VerifyNullableLongMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatMultiplyTest(bool useInterpreter)
{
float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatMultiply(array[i], array[j], useInterpreter);
VerifyNullableFloatMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleMultiplyTest(bool useInterpreter)
{
double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleMultiply(array[i], array[j], useInterpreter);
VerifyNullableDoubleMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalMultiplyTest(bool useInterpreter)
{
decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalMultiply(array[i], array[j], useInterpreter);
VerifyNullableDecimalMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckNullableCharMultiplyTest()
{
char?[] array = { '\0', '\b', 'A', '\uffff', null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharMultiply(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteMultiply(byte? a, byte? b)
{
Expression aExp = Expression.Constant(a, typeof(byte?));
Expression bExp = Expression.Constant(b, typeof(byte?));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp));
}
private static void VerifyNullableSByteMultiply(sbyte? a, sbyte? b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte?));
Expression bExp = Expression.Constant(b, typeof(sbyte?));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp));
}
private static void VerifyNullableUShortMultiply(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Multiply(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal((ushort?)(a * b), f());
}
private static void VerifyNullableUShortMultiplyOvf(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
ushort? expected;
try
{
expected = checked((ushort?)(a * b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableShortMultiply(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Multiply(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal((short?)(a * b), f());
}
private static void VerifyNullableShortMultiplyOvf(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
short? expected;
try
{
expected = checked((short?)(a * b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableUIntMultiply(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Multiply(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableUIntMultiplyOvf(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
uint? expected;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableIntMultiply(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Multiply(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableIntMultiplyOvf(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
int? expected;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableULongMultiply(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Multiply(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableULongMultiplyOvf(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
ulong? expected;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableLongMultiply(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Multiply(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableLongMultiplyOvf(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
long? expected;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableFloatMultiply(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Multiply(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableFloatMultiplyOvf(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableDoubleMultiply(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Multiply(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableDoubleMultiplyOvf(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyNullableDecimalMultiply(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Multiply(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected;
try
{
expected = a * b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableDecimalMultiplyOvf(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected;
try
{
expected = a * b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableCharMultiply(char? a, char? b)
{
Expression aExp = Expression.Constant(a, typeof(char?));
Expression bExp = Expression.Constant(b, typeof(char?));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp));
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using XSerializer.Encryption;
namespace XSerializer
{
/// <summary>
/// A representation of a JSON object. Provides an advanced dynamic API as well as a standard
/// object API.
/// </summary>
public sealed class JsonObject : DynamicObject, IDictionary<string, object>
{
private static readonly string[] _definedProjections =
{
"AsByte",
"AsSByte",
"AsInt16",
"AsUInt16",
"AsInt32",
"AsUInt32",
"AsInt64",
"AsUInt64",
"AsDouble",
"AsSingle",
"AsDecimal",
"AsString",
"AsDateTime",
"AsDateTimeOffset",
"AsGuid"
};
private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
private readonly Dictionary<string, string> _numericStringValues = new Dictionary<string, string>();
private readonly Dictionary<string, object> _projections = new Dictionary<string, object>();
private readonly IJsonSerializeOperationInfo _info;
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class.
/// </summary>
public JsonObject()
: this(null, null, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class.
/// </summary>
/// <param name="dateTimeHandler">The object that determines how date time values are parsed.</param>
/// <param name="encryptionMechanism">The object the performs encryption operations.</param>
/// <param name="encryptKey">A key optionally used by the encryption mechanism during encryption operations.</param>
/// <param name="serializationState">An object optionally used by the encryption mechanism to carry state across multiple encryption operations.</param>
public JsonObject(
IDateTimeHandler dateTimeHandler = null,
IEncryptionMechanism encryptionMechanism = null,
object encryptKey = null,
SerializationState serializationState = null)
: this(new JsonSerializeOperationInfo
{
DateTimeHandler = dateTimeHandler ?? DateTimeHandler.Default,
EncryptionMechanism = encryptionMechanism,
EncryptKey = encryptKey,
SerializationState = serializationState ?? new SerializationState()
})
{
}
internal JsonObject(IJsonSerializeOperationInfo info)
{
_info = info;
}
/// <summary>
/// Add a property to the JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
/// <exception cref="ArgumentNullException">If <paramref name="name"/> is null.</exception>
public void Add(string name, object value)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
AddImpl(name, GuardValue(value));
}
private void AddImpl(string name, object value)
{
var jsonNumber = value as JsonNumber;
if (jsonNumber != null)
{
_values.Add(name, jsonNumber.DoubleValue);
_numericStringValues.Add(name, jsonNumber.StringValue);
}
else
{
_values.Add(name, value);
}
}
/// <summary>
/// Gets or sets the value associated with the specified property name.
/// </summary>
/// <param name="name">The name of the property</param>
/// <exception cref="KeyNotFoundException">When getting the value, if no property exists with the specified name.</exception>
public object this[string name]
{
get
{
object value;
if (TryGetValue(name, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
value = GuardValue(value);
if (!TrySetValueImpl(name, value))
{
AddImpl(name, value);
}
}
}
bool IDictionary<string, object>.ContainsKey(string key)
{
object dummy;
return TryGetValue(key, out dummy);
}
bool IDictionary<string, object>.Remove(string key)
{
if (_values.Remove(key))
{
RemoveProjections(key);
return true;
}
return false;
}
ICollection<string> IDictionary<string, object>.Keys
{
get { return _values.Keys; }
}
ICollection<object> IDictionary<string, object>.Values
{
get { return _values.Values; }
}
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
Add(item.Key, item.Value);
}
void ICollection<KeyValuePair<string, object>>.Clear()
{
_values.Clear();
_numericStringValues.Clear();
_projections.Clear();
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
object value;
return TryGetValue(item.Key, out value) && Equals(item.Value, value);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<string, object>>)_values).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
if (((ICollection<KeyValuePair<string, object>>)_values).Remove(item))
{
RemoveProjections(item.Key);
return true;
}
return false;
}
int ICollection<KeyValuePair<string, object>>.Count
{
get { return _values.Count; }
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Decrypts the specified property, changing its value in place.
/// </summary>
/// <param name="name">The name of the property to decrypt.</param>
/// <returns>This instance of <see cref="JsonObject"/>.</returns>
public JsonObject Decrypt(string name)
{
if (_info.EncryptionMechanism != null)
{
object value;
if (_values.TryGetValue(name, out value)
&& value is string)
{
var decryptedJson = _info.EncryptionMechanism.Decrypt(
(string)value, _info.EncryptKey, _info.SerializationState);
using (var stringReader = new StringReader(decryptedJson))
{
using (var reader = new JsonReader(stringReader, _info))
{
value = DynamicJsonSerializer.Get(false, JsonMappings.Empty).DeserializeObject(reader, _info, name);
if (value == null
|| value is bool
|| value is string
|| value is JsonArray
|| value is JsonObject)
{
_values[name] = value;
return this;
}
var jsonNumber = value as JsonNumber;
if (jsonNumber != null)
{
_values[name] = jsonNumber.DoubleValue;
_numericStringValues[name] = jsonNumber.StringValue;
return this;
}
throw new NotSupportedException("Unsupported value type: " + value.GetType());
}
}
}
}
return this;
}
/// <summary>
/// Encrypts the specified property, changing its value in place.
/// </summary>
/// <param name="name">The name of the property to encrypt.</param>
/// <returns>This instance of <see cref="JsonObject"/>.</returns>
public JsonObject Encrypt(string name)
{
if (_info.EncryptionMechanism != null)
{
object value;
if (_values.TryGetValue(name, out value)
&& value != null)
{
var sb = new StringBuilder();
using (var stringwriter = new StringWriter(sb))
{
using (var writer = new JsonWriter(stringwriter, _info))
{
DynamicJsonSerializer.Get(false, JsonMappings.Empty).SerializeObject(writer, value, _info);
}
}
value = _info.EncryptionMechanism.Encrypt(sb.ToString(), _info.EncryptKey, _info.SerializationState);
_values[name] = value;
}
}
return this;
}
/// <summary>
/// Gets the value of the specified property.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="result">
/// When this method returns, contains the value of the property, if the name exists; otherwise, null.
/// </param>
/// <returns>True if the JSON object contains the specified property; otherwise false.</returns>
public bool TryGetValue(string name, out object result)
{
if (_values.TryGetValue(name, out result)
|| _projections.TryGetValue(name, out result))
{
return true;
}
return TryGetProjection(name, ref result);
}
/// <summary>
/// Set the value of the specified property.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
/// <returns>True if the JSON object contains the specified property; otherwise false.</returns>
public bool TrySetValue(string name, object value)
{
return TrySetValueImpl(name, GuardValue(value));
}
private bool TrySetValueImpl(string name, object value)
{
if (_values.ContainsKey(name))
{
var jsonNumber = value as JsonNumber;
if (jsonNumber != null)
{
_values[name] = jsonNumber.DoubleValue;
_numericStringValues[name] = jsonNumber.StringValue;
}
else
{
_values[name] = value;
_numericStringValues.Remove(name);
}
RemoveProjections(name);
return true;
}
return false;
}
private static object GuardValue(object value)
{
if (value == null
|| value is bool
|| value is string
|| value is JsonNumber
|| value is JsonObject
|| value is JsonArray)
{
return value;
}
if (value is int
|| value is double
|| value is byte
|| value is long
|| value is decimal
|| value is uint
|| value is ulong
|| value is short
|| value is float
|| value is ushort
|| value is sbyte)
{
return new JsonNumber(value.ToString());
}
if (value is Guid)
{
var guid = (Guid)value;
return guid.ToString("D");
}
if (value is DateTime)
{
var dateTime = (DateTime)value;
return dateTime.ToString("O");
}
if (value is DateTimeOffset)
{
var dateTimeOffset = (DateTimeOffset)value;
return dateTimeOffset.ToString("O");
}
throw new XSerializerException("Invalid value for JsonObject member: " + value.GetType().FullName);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_values).GetEnumerator();
}
/// <summary>
/// Determines whether the specified <see cref="object"/> is equal to the current <see cref="object"/>.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare with the current <see cref="object"/>.</param>
/// <returns>
/// true if the specified <see cref="object"/> is equal to the current <see cref="object"/>; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as JsonObject;
if (other == null)
{
return false;
}
foreach (var item in _values)
{
if (!other._values.ContainsKey(item.Key))
{
return false;
}
object value;
object otherValue;
if (_numericStringValues.ContainsKey(item.Key))
{
if (!other._numericStringValues.ContainsKey(item.Key))
{
return false;
}
value = _numericStringValues[item.Key];
otherValue = other._numericStringValues[item.Key];
}
else
{
value = _values[item.Key];
otherValue = other._values[item.Key];
}
if (!Equals(value, otherValue))
{
return false;
}
}
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="object"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = typeof(JsonObject).GetHashCode();
foreach (var item in _values.OrderBy(x => x.Key))
{
hashCode = (hashCode * 397) ^ item.Key.GetHashCode();
hashCode = (hashCode * 397) ^ (item.Value != null ? item.Value.GetHashCode() : 0);
}
return hashCode;
}
}
/// <summary>
/// Provides the implementation for operations that get member values.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation.</param>
/// <param name="result">The result of the get operation.</param>
/// <returns>
/// true if the operation is successful; otherwise, false.
/// </returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return TryGetValue(binder.Name, out result);
}
/// <summary>
/// Provides the implementation for operations that set member values.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation.</param>
/// <param name="value">The value to set to the member.</param>
/// <returns>
/// true if the operation is successful; otherwise, false.
/// </returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this[binder.Name] = value;
return true;
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>
/// A sequence that contains dynamic member names.
/// </returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
return _values.Keys;
}
private bool TryGetProjection(string name, ref object result)
{
string modifiedName;
if (EndsWith(name, "AsByte", out modifiedName))
{
return AsByte(ref result, modifiedName, name);
}
if (EndsWith(name, "AsSByte", out modifiedName))
{
return AsSByte(ref result, modifiedName, name);
}
if (EndsWith(name, "AsInt16", out modifiedName))
{
return AsInt16(ref result, modifiedName, name);
}
if (EndsWith(name, "AsUInt16", out modifiedName))
{
return AsUInt16(ref result, modifiedName, name);
}
if (EndsWith(name, "AsInt32", out modifiedName))
{
return AsInt32(ref result, modifiedName, name);
}
if (EndsWith(name, "AsUInt32", out modifiedName))
{
return AsUInt32(ref result, modifiedName, name);
}
if (EndsWith(name, "AsInt64", out modifiedName))
{
return AsInt64(ref result, modifiedName, name);
}
if (EndsWith(name, "AsUInt64", out modifiedName))
{
return AsUInt64(ref result, modifiedName, name);
}
if (EndsWith(name, "AsDouble", out modifiedName))
{
return AsDouble(ref result, modifiedName);
}
if (EndsWith(name, "AsSingle", out modifiedName))
{
return AsSingle(ref result, modifiedName);
}
if (EndsWith(name, "AsDecimal", out modifiedName))
{
return AsDecimal(ref result, modifiedName, name);
}
if (EndsWith(name, "AsString", out modifiedName))
{
return AsString(ref result, modifiedName, name);
}
if (EndsWith(name, "AsDateTime", out modifiedName))
{
return AsDateTime(ref result, modifiedName, name);
}
if (EndsWith(name, "AsDateTimeOffset", out modifiedName))
{
return AsDateTimeOffset(ref result, modifiedName, name);
}
if (EndsWith(name, "AsGuid", out modifiedName))
{
return AsGuid(ref result, modifiedName, name);
}
return false;
}
private void RemoveProjections(string name)
{
var toRemove =
from projectionName in _projections.Keys
where projectionName.StartsWith(name) && _definedProjections.Any(projectionName.EndsWith)
select projectionName;
foreach (var key in toRemove)
{
_projections.Remove(key);
}
}
private static bool EndsWith(string binderName, string suffix, out string name)
{
if (binderName.EndsWith(suffix, StringComparison.InvariantCulture))
{
name = binderName.Substring(
0, binderName.LastIndexOf(suffix, StringComparison.InvariantCulture));
return true;
}
name = null;
return false;
}
private bool AsByte(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
byte byteResult;
if (byte.TryParse(value, out byteResult))
{
result = byteResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsSByte(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
sbyte sbyteResult;
if (sbyte.TryParse(value, out sbyteResult))
{
result = sbyteResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsInt16(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
short shortResult;
if (short.TryParse(value, out shortResult))
{
result = shortResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsUInt16(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
ushort ushortResult;
if (ushort.TryParse(value, out ushortResult))
{
result = ushortResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsInt32(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
int intResult;
if (int.TryParse(value, out intResult))
{
result = intResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsUInt32(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
uint uintResult;
if (uint.TryParse(value, out uintResult))
{
result = uintResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsInt64(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
long longResult;
if (long.TryParse(value, out longResult))
{
result = longResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsUInt64(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
TruncateNumber(ref value);
ulong ulongResult;
if (ulong.TryParse(value, out ulongResult))
{
result = ulongResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsDouble(ref object result, string name)
{
object value;
if (_values.TryGetValue(name, out value)
&& value is double)
{
result = value;
return true;
}
return false;
}
private bool AsSingle(ref object result, string name)
{
object value;
if (_values.TryGetValue(name, out value)
&& value is double)
{
result = (float)((double)value);
return true;
}
return false;
}
private bool AsDecimal(ref object result, string name, string binderName)
{
string value;
if (_numericStringValues.TryGetValue(name, out value))
{
decimal decimalResult;
if (decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out decimalResult))
{
result = decimalResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsString(ref object result, string name, string binderName)
{
object value;
if (_values.TryGetValue(name, out value))
{
if (value == null)
{
result = null;
_projections.Add(binderName, result);
return true;
}
var stringValue = value as string;
if (stringValue != null)
{
result = stringValue;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private bool AsDateTime(ref object result, string name, string binderName)
{
object value;
if (_values.TryGetValue(name, out value))
{
if (value == null)
{
result = null;
_projections.Add(binderName, result);
return true;
}
var stringValue = value as string;
if (stringValue != null)
{
try
{
result = _info.DateTimeHandler.ParseDateTime(stringValue);
_projections.Add(binderName, result);
return true;
}
catch
{
return false;
}
}
}
return false;
}
private bool AsDateTimeOffset(ref object result, string name, string binderName)
{
object value;
if (_values.TryGetValue(name, out value))
{
if (value == null)
{
result = null;
_projections.Add(binderName, result);
return true;
}
var stringValue = value as string;
if (stringValue != null)
{
try
{
result = _info.DateTimeHandler.ParseDateTimeOffset(stringValue);
_projections.Add(binderName, result);
return true;
}
catch
{
return false;
}
}
}
return false;
}
private bool AsGuid(ref object result, string name, string binderName)
{
object value;
if (_values.TryGetValue(name, out value)
&& value is string)
{
Guid guidResult;
if (Guid.TryParse((string)value, out guidResult))
{
result = guidResult;
_projections.Add(binderName, result);
return true;
}
}
return false;
}
private static void TruncateNumber(ref string value)
{
if (value.Contains('.') || value.Contains('e') || value.Contains('E'))
{
var d = double.Parse(value);
d = Math.Truncate(d);
value = d.ToString(NumberFormatInfo.InvariantInfo);
}
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetCompletedJobsSpectraS3Request : Ds3Request
{
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private JobChunkClientProcessingOrderGuarantee? _chunkClientProcessingOrderGuarantee;
public JobChunkClientProcessingOrderGuarantee? ChunkClientProcessingOrderGuarantee
{
get { return _chunkClientProcessingOrderGuarantee; }
set { WithChunkClientProcessingOrderGuarantee(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private Priority? _priority;
public Priority? Priority
{
get { return _priority; }
set { WithPriority(value); }
}
private DateTime? _rechunked;
public DateTime? Rechunked
{
get { return _rechunked; }
set { WithRechunked(value); }
}
private JobRequestType? _requestType;
public JobRequestType? RequestType
{
get { return _requestType; }
set { WithRequestType(value); }
}
private bool? _truncated;
public bool? Truncated
{
get { return _truncated; }
set { WithTruncated(value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { WithUserId(value); }
}
public GetCompletedJobsSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithChunkClientProcessingOrderGuarantee(JobChunkClientProcessingOrderGuarantee? chunkClientProcessingOrderGuarantee)
{
this._chunkClientProcessingOrderGuarantee = chunkClientProcessingOrderGuarantee;
if (chunkClientProcessingOrderGuarantee != null)
{
this.QueryParams.Add("chunk_client_processing_order_guarantee", chunkClientProcessingOrderGuarantee.ToString());
}
else
{
this.QueryParams.Remove("chunk_client_processing_order_guarantee");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithPriority(Priority? priority)
{
this._priority = priority;
if (priority != null)
{
this.QueryParams.Add("priority", priority.ToString());
}
else
{
this.QueryParams.Remove("priority");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithRechunked(DateTime? rechunked)
{
this._rechunked = rechunked;
if (rechunked != null)
{
this.QueryParams.Add("rechunked", rechunked.ToString());
}
else
{
this.QueryParams.Remove("rechunked");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithRequestType(JobRequestType? requestType)
{
this._requestType = requestType;
if (requestType != null)
{
this.QueryParams.Add("request_type", requestType.ToString());
}
else
{
this.QueryParams.Remove("request_type");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithTruncated(bool? truncated)
{
this._truncated = truncated;
if (truncated != null)
{
this.QueryParams.Add("truncated", truncated.ToString());
}
else
{
this.QueryParams.Remove("truncated");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithUserId(Guid? userId)
{
this._userId = userId.ToString();
if (userId != null)
{
this.QueryParams.Add("user_id", userId.ToString());
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetCompletedJobsSpectraS3Request WithUserId(string userId)
{
this._userId = userId;
if (userId != null)
{
this.QueryParams.Add("user_id", userId);
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetCompletedJobsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/completed_job";
}
}
}
}
| |
// 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 CompareEqualUInt32()
{
var test = new SimpleBinaryOpTest__CompareEqualUInt32();
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 SimpleBinaryOpTest__CompareEqualUInt32
{
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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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 Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualUInt32 testClass)
{
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualUInt32 testClass)
{
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqualUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public SimpleBinaryOpTest__CompareEqualUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.CompareEqual(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_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 = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.CompareEqual(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_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(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(pClsVar1)),
Avx.LoadVector256((UInt32*)(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<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqualUInt32();
var result = Avx2.CompareEqual(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__CompareEqualUInt32();
fixed (Vector256<UInt32>* pFld1 = &test._fld1)
fixed (Vector256<UInt32>* pFld2 = &test._fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(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 = Avx2.CompareEqual(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 = Avx2.CompareEqual(
Avx.LoadVector256((UInt32*)(&test._fld1)),
Avx.LoadVector256((UInt32*)(&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(Vector256<UInt32> op1, Vector256<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] == right[0]) ? unchecked((uint)(-1)) : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((uint)(-1)) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {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;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
using System.Data;
namespace EarLab.ReaderWriters
{
/// <summary>
/// Summary description for ReaderWriterXMLVersion.
/// </summary>
public class ReaderWriterXMLVersion
{
public static DataSet Read(string fileName)
{
XmlTextReader xmlTextReader = new XmlTextReader(fileName);
XmlValidatingReader xmlValidatingReader = new XmlValidatingReader(xmlTextReader);
xmlValidatingReader.ValidationType = ValidationType.Schema;
Stream schemaStream = GetXMLSchemaStream();
XmlSchema versionSchema = XmlSchema.Read(schemaStream, new System.Xml.Schema.ValidationEventHandler(xmlValidatingReader_ValidationEventHandler));
versionSchema.TargetNamespace = "http://eardev.bu.edu/software/specifications/schemas/EarLabVersion.xsd";
xmlValidatingReader.Schemas.Add(versionSchema);
xmlValidatingReader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(xmlValidatingReader_ValidationEventHandler);
try
{
while (xmlValidatingReader.Read()){}
DataSet xmlDataSet = new DataSet();
schemaStream.Position = 0;
xmlDataSet.ReadXmlSchema(schemaStream);
schemaStream.Close();
xmlDataSet.ReadXml(fileName, XmlReadMode.IgnoreSchema);
// we need to establish a relationship between the Module and Version for later use (tricky me!)
//if (destinationDataSet.Tables["Version"].Columns["ModuleLSID"] == null)
//xmlDataSet.Tables["Version"].Columns["VersionLSID"].Unique = true;
//xmlDataSet.Tables["Version"].PrimaryKey = new DataColumn[] {xmlDataSet.Tables["Version"].Columns["VersionLSID"]};
//destinationDataSet.Tables["Version"].Columns.Add("ModuleLSID", typeof(string));
//destinationDataSet.Tables["Version"].Rows[0]["ModuleLSID"] = destinationDataSet.Tables["Module"].Rows[0]["ModuleLSID"];
//xmlDataSet.Relations.Add("ModuleVersion", xmlDataSet.Tables["Module"].Columns["ModuleLSID"], xmlDataSet.Tables["Version"].Columns["ModuleLSID"], true);
//xmlDataSet.Tables["Version"].Rows[0].SetParentRow(xmlDataSet.Tables["Module"].Rows[0], xmlDataSet.Relations["ModuleVersion"]);
//xmlDataSet.AcceptChanges();
//return true;
return xmlDataSet;
}
catch //(System.Exception e)
{
//System.Diagnostics.Debug.WriteLine(e.Message.ToString());
return null;
}
finally
{
schemaStream.Close();
xmlTextReader.Close();
}
}
private static Stream GetXMLSchemaStream()
{
return System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("EarLab.Schemas.EarLabVersion.xsd");
}
public static bool ConvertToXML(string saveDirectory, string zipFilename, DataSet versionDataSet)
{
if (versionDataSet.Tables["tblVersion"].Rows[0]["fldExecutableFile"].ToString() != "")
{
DataSet xmlDataSet = new DataSet();
xmlDataSet.ReadXmlSchema(GetXMLSchemaStream());
DataRow moduleRow = xmlDataSet.Tables["Module"].NewRow();
moduleRow["ModuleLSID"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleLSID"];
moduleRow["Name"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleName"];
moduleRow["Description"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleDescription"];
xmlDataSet.Tables["Module"].Rows.Add(moduleRow);
DataRow versionRow = xmlDataSet.Tables["Version"].NewRow();
versionRow["VersionLSID"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionLSID"];
versionRow["VersionNumber"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionNumber"];
versionRow["ReleaseDate"] = DateTime.Parse(versionDataSet.Tables["tblVersion"].Rows[0]["fldReleaseDate"].ToString());
versionRow["NeuralEntity"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldNeuralEntity"];
versionRow["Abstract"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldAbstract"];
versionRow["Description"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldDescription"];
versionRow["Design"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldDesign"];
versionRow["Implementation"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldImplementation"];
versionRow["Interface"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldInterface"];
versionRow["Evaluation"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldEvaluation"];
versionRow["Prerequisite"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldPrerequisite"];
versionRow["Note"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldNote"];
xmlDataSet.Tables["Version"].Rows.Add(versionRow);
string[] groupTable = new string[] { "Languages", "OSes", "Compliances", "Histories",
"References", "Bugs", "Restrictions" };
string[] singleTable = new string[] { "Language", "OS", "Compliance", "History",
"Reference", "Bug", "Restriction" };
string[] dataTable = new string[] { "tblVersionLanguage", "tblVersionOS", "tblVersionCompliance", "tblHistory",
"tblReference", "tblBug", "tblRestriction" };
string[] fieldTable = new string[] { "fldLanguage", "fldOS", "fldCompliance", "fldItem",
"fldItem", "fldItem", "fldItem" };
for(int i=0; i<groupTable.Length; i++)
{
if (versionDataSet.Tables[dataTable[i]].Rows.Count > 0)
{
DataRow groupRow = xmlDataSet.Tables[groupTable[i]].NewRow();
groupRow.SetParentRow(versionRow, xmlDataSet.Relations["Version_" + groupTable[i]]);
xmlDataSet.Tables[groupTable[i]].Rows.Add(groupRow);
foreach (DataRow row in versionDataSet.Tables[dataTable[i]].Rows)
{
DataRow singleRow = xmlDataSet.Tables[singleTable[i]].NewRow();
singleRow.SetParentRow(groupRow, xmlDataSet.Relations[groupTable[i] + "_" + singleTable[i]]);
singleRow[singleTable[i] + "_Column"] = row[fieldTable[i]];
xmlDataSet.Tables[singleTable[i]].Rows.Add(singleRow);
}
}
}
if (versionDataSet.Tables["tblClassification"].Rows.Count > 0)
{
DataRow classificationsRow = xmlDataSet.Tables["Classifications"].NewRow();
classificationsRow.SetParentRow(versionRow, xmlDataSet.Relations["Version_Classifications"]);
xmlDataSet.Tables["Classifications"].Rows.Add(classificationsRow);
foreach (DataRow row in versionDataSet.Tables["tblClassification"].Rows)
{
DataRow classificationRow = xmlDataSet.Tables["Classification"].NewRow();
classificationRow.SetParentRow(classificationsRow, xmlDataSet.Relations["Classifications_Classification"]);
classificationRow["Structure"] = row["fldStructure"];
classificationRow["Substructure"] = row["fldSubstructure"];
classificationRow["CellType"] = row["fldCellType"];
xmlDataSet.Tables["Classification"].Rows.Add(classificationRow);
}
}
if (versionDataSet.Tables["tblVersionDataType"].Rows.Count > 0)
{
DataRow datatypesRow = xmlDataSet.Tables["DataTypes"].NewRow();
xmlDataSet.Tables["DataTypes"].Rows.Add(datatypesRow);
foreach (DataRow row in versionDataSet.Tables["tblVersionDataType"].Rows)
{
DataRow datatypeRow = xmlDataSet.Tables["DataType"].NewRow();
datatypeRow.SetParentRow(datatypesRow, xmlDataSet.Relations["DataTypes_DataType"]);
datatypeRow["Name"] = row["fldName"];
datatypeRow["Index"] = row["fldIndex"];
datatypeRow["Description"] = row["fldDescription"];
datatypeRow["Direction"] = row["fldDirection"];
datatypeRow["Type"] = row["fldDataType"];
xmlDataSet.Tables["DataType"].Rows.Add(datatypeRow);
}
}
if (versionDataSet.Tables["tblParameter"].Rows.Count > 0)
{
DataRow parametersRow = xmlDataSet.Tables["Parameters"].NewRow();
xmlDataSet.Tables["Parameters"].Rows.Add(parametersRow);
foreach (DataRow row in versionDataSet.Tables["tblParameter"].Rows)
{
DataRow parameterRow = xmlDataSet.Tables["Parameter"].NewRow();
parameterRow.SetParentRow(parametersRow, xmlDataSet.Relations["Parameters_Parameter"]);
parameterRow["Name"] = row["fldName"];
parameterRow["Description"] = row["fldDescription"];
parameterRow["Type"] = row["fldParameterType"];
parameterRow["Minimum"] = row["fldMinimum"];
parameterRow["Maximum"] = row["fldMaximum"];
xmlDataSet.Tables["Parameter"].Rows.Add(parameterRow);
}
}
string xmlName = saveDirectory + "\\" + versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionLSID"].ToString().Replace(':','_') + ".xml";
xmlDataSet.WriteXml(xmlName, XmlWriteMode.IgnoreSchema);
string dllName = saveDirectory + "\\" + versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionLSID"].ToString().Replace(':','_') + ".dll";
File.Copy(versionDataSet.Tables["tblVersion"].Rows[0]["fldExecutableFile"].ToString(), dllName);
EarLab.Utilities.Zip.ZipFiles(new string[] { xmlName, dllName }, saveDirectory + "\\" + zipFilename);
File.Delete(xmlName);
File.Delete(dllName);
return true;
}
else
return false;
}
public static DataSet ConvertToXML(DataSet versionDataSet)
{
if (versionDataSet.Tables["tblVersion"].Rows[0]["fldExecutableFile"].ToString() != "")
{
DataSet xmlDataSet = new DataSet();
xmlDataSet.ReadXmlSchema(GetXMLSchemaStream());
DataRow moduleRow = xmlDataSet.Tables["Module"].NewRow();
moduleRow["ModuleLSID"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleLSID"];
moduleRow["Name"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleName"];
moduleRow["Description"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldModuleDescription"];
xmlDataSet.Tables["Module"].Rows.Add(moduleRow);
DataRow versionRow = xmlDataSet.Tables["Version"].NewRow();
versionRow["VersionLSID"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionLSID"];
versionRow["VersionNumber"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionNumber"];
versionRow["ReleaseDate"] = DateTime.Parse(versionDataSet.Tables["tblVersion"].Rows[0]["fldReleaseDate"].ToString());
versionRow["NeuralEntity"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldNeuralEntity"];
versionRow["Abstract"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldAbstract"];
versionRow["Description"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldDescription"];
versionRow["Design"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldDesign"];
versionRow["Implementation"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldImplementation"];
versionRow["Interface"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldInterface"];
versionRow["Evaluation"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldEvaluation"];
versionRow["Prerequisite"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldPrerequisite"];
versionRow["Note"] = versionDataSet.Tables["tblVersion"].Rows[0]["fldNote"];
xmlDataSet.Tables["Version"].Rows.Add(versionRow);
string[] groupTable = new string[] { "Languages", "OSes", "Compliances", "Histories",
"References", "Bugs", "Restrictions" };
string[] singleTable = new string[] { "Language", "OS", "Compliance", "History",
"Reference", "Bug", "Restriction" };
string[] dataTable = new string[] { "tblVersionLanguage", "tblVersionOS", "tblVersionCompliance", "tblHistory",
"tblReference", "tblBug", "tblRestriction" };
string[] fieldTable = new string[] { "fldLanguage", "fldOS", "fldCompliance", "fldItem",
"fldItem", "fldItem", "fldItem" };
for(int i=0; i<groupTable.Length; i++)
{
if (versionDataSet.Tables[dataTable[i]].Rows.Count > 0)
{
DataRow groupRow = xmlDataSet.Tables[groupTable[i]].NewRow();
groupRow.SetParentRow(versionRow, xmlDataSet.Relations["Version_" + groupTable[i]]);
xmlDataSet.Tables[groupTable[i]].Rows.Add(groupRow);
foreach (DataRow row in versionDataSet.Tables[dataTable[i]].Rows)
{
DataRow singleRow = xmlDataSet.Tables[singleTable[i]].NewRow();
singleRow.SetParentRow(groupRow, xmlDataSet.Relations[groupTable[i] + "_" + singleTable[i]]);
singleRow[singleTable[i] + "_Column"] = row[fieldTable[i]];
xmlDataSet.Tables[singleTable[i]].Rows.Add(singleRow);
}
}
}
if (versionDataSet.Tables["tblClassification"].Rows.Count > 0)
{
DataRow classificationsRow = xmlDataSet.Tables["Classifications"].NewRow();
classificationsRow.SetParentRow(versionRow, xmlDataSet.Relations["Version_Classifications"]);
xmlDataSet.Tables["Classifications"].Rows.Add(classificationsRow);
foreach (DataRow row in versionDataSet.Tables["tblClassification"].Rows)
{
DataRow classificationRow = xmlDataSet.Tables["Classification"].NewRow();
classificationRow.SetParentRow(classificationsRow, xmlDataSet.Relations["Classifications_Classification"]);
classificationRow["Structure"] = row["fldStructure"];
classificationRow["Substructure"] = row["fldSubstructure"];
classificationRow["CellType"] = row["fldCellType"];
xmlDataSet.Tables["Classification"].Rows.Add(classificationRow);
}
}
if (versionDataSet.Tables["tblVersionDataType"].Rows.Count > 0)
{
DataRow datatypesRow = xmlDataSet.Tables["DataTypes"].NewRow();
xmlDataSet.Tables["DataTypes"].Rows.Add(datatypesRow);
foreach (DataRow row in versionDataSet.Tables["tblVersionDataType"].Rows)
{
DataRow datatypeRow = xmlDataSet.Tables["DataType"].NewRow();
datatypeRow.SetParentRow(datatypesRow, xmlDataSet.Relations["DataTypes_DataType"]);
datatypeRow["Name"] = row["fldName"];
datatypeRow["Index"] = row["fldIndex"];
datatypeRow["Description"] = row["fldDescription"];
datatypeRow["Direction"] = row["fldDirection"];
datatypeRow["Type"] = row["fldDataType"];
xmlDataSet.Tables["DataType"].Rows.Add(datatypeRow);
}
}
if (versionDataSet.Tables["tblParameter"].Rows.Count > 0)
{
DataRow parametersRow = xmlDataSet.Tables["Parameters"].NewRow();
xmlDataSet.Tables["Parameters"].Rows.Add(parametersRow);
foreach (DataRow row in versionDataSet.Tables["tblParameter"].Rows)
{
DataRow parameterRow = xmlDataSet.Tables["Parameter"].NewRow();
parameterRow.SetParentRow(parametersRow, xmlDataSet.Relations["Parameters_Parameter"]);
parameterRow["Name"] = row["fldName"];
parameterRow["Description"] = row["fldDescription"];
parameterRow["Type"] = row["fldParameterType"];
parameterRow["Minimum"] = row["fldMinimum"];
parameterRow["Maximum"] = row["fldMaximum"];
xmlDataSet.Tables["Parameter"].Rows.Add(parameterRow);
}
}
return xmlDataSet;
}
else
return null;
}
private static void xmlValidatingReader_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
{
throw new Exception(e.Message);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="COM2ExtendedTypeConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms.ComponentModel.Com2Interop {
using System.Diagnostics;
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using Microsoft.Win32;
using System.Globalization;
using System.Collections;
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter"]/*' />
/// <devdoc>
/// Base class for value editors that extend basic functionality.
/// calls will be delegated to the "base value editor".
/// </devdoc>
internal class Com2ExtendedTypeConverter : TypeConverter {
private TypeConverter innerConverter;
public Com2ExtendedTypeConverter(TypeConverter innerConverter) {
this.innerConverter = innerConverter;
}
public Com2ExtendedTypeConverter(Type baseType) {
this.innerConverter = TypeDescriptor.GetConverter(baseType);
}
public TypeConverter InnerConverter {
get {
return innerConverter;
}
}
public TypeConverter GetWrappedConverter(Type t) {
TypeConverter converter = innerConverter;
while (converter != null) {
if (t.IsInstanceOfType(converter)) {
return converter;
}
if (converter is Com2ExtendedTypeConverter) {
converter = ((Com2ExtendedTypeConverter)converter).InnerConverter;
}
else {
break;
}
}
return null;
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (innerConverter != null) {
return innerConverter.CanConvertFrom(context, sourceType);
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.CanConvertTo"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object to the given destination
/// type.
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (innerConverter != null) {
return innerConverter.CanConvertTo(context, destinationType);
}
return base.CanConvertTo(context, destinationType);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (innerConverter != null) {
return innerConverter.ConvertFrom(context, culture, value);
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (innerConverter != null) {
return innerConverter.ConvertTo(context, culture, value, destinationType);
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.CreateInstance"]/*' />
/// <devdoc>
/// Creates an instance of this type given a set of property values
/// for the object. This is useful for objects that are immutable, but still
/// want to provide changable properties.
/// </devdoc>
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) {
if (innerConverter != null) {
return innerConverter.CreateInstance(context, propertyValues);
}
return base.CreateInstance(context, propertyValues);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetCreateInstanceSupported"]/*' />
/// <devdoc>
/// Determines if changing a value on this object should require a call to
/// CreateInstance to create a new value.
/// </devdoc>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
if (innerConverter != null) {
return innerConverter.GetCreateInstanceSupported(context);
}
return base.GetCreateInstanceSupported(context);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetProperties"]/*' />
/// <devdoc>
/// Retrieves the set of properties for this type. By default, a type has
/// does not return any properties. An easy implementation of this method
/// can just call TypeDescriptor.GetProperties for the correct data type.
/// </devdoc>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
if (innerConverter != null) {
return innerConverter.GetProperties(context, value, attributes);
}
return base.GetProperties(context, value, attributes);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetPropertiesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports properties. By default, this
/// is false.
/// </devdoc>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
if (innerConverter != null) {
return innerConverter.GetPropertiesSupported(context);
}
return base.GetPropertiesSupported(context);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetStandardValues"]/*' />
/// <devdoc>
/// Retrieves a collection containing a set of standard values
/// for the data type this validator is designed for. This
/// will return null if the data type does not support a
/// standard set of values.
/// </devdoc>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
if (innerConverter != null) {
return innerConverter.GetStandardValues(context);
}
return base.GetStandardValues(context);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetStandardValuesExclusive"]/*' />
/// <devdoc>
/// Determines if the list of standard values returned from
/// GetStandardValues is an exclusive list. If the list
/// is exclusive, then no other values are valid, such as
/// in an enum data type. If the list is not exclusive,
/// then there are other valid values besides the list of
/// standard values GetStandardValues provides.
/// </devdoc>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
if (innerConverter != null) {
return innerConverter.GetStandardValuesExclusive(context);
}
return base.GetStandardValuesExclusive(context);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.GetStandardValuesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports a standard set of values
/// that can be picked from a list.
/// </devdoc>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
if (innerConverter != null) {
return innerConverter.GetStandardValuesSupported(context);
}
return base.GetStandardValuesSupported(context);
}
/// <include file='doc\COM2ExtendedTypeConverter.uex' path='docs/doc[@for="Com2ExtendedTypeConverter.IsValid"]/*' />
/// <devdoc>
/// Determines if the given object value is valid for this type.
/// </devdoc>
public override bool IsValid(ITypeDescriptorContext context, object value) {
if (innerConverter != null) {
return innerConverter.IsValid(context, value);
}
return base.IsValid(context, value);
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\RectLightComponent.h:20
namespace UnrealEngine
{
[ManageType("ManageRectLightComponent")]
public partial class ManageRectLightComponent : URectLightComponent, IManageWrapper
{
public ManageRectLightComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_UpdateLightGUIDs(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__URectLightComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Update/reset light GUIDs.
/// </summary>
public override void UpdateLightGUIDs()
=> E__Supper__URectLightComponent_UpdateLightGUIDs(this);
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__URectLightComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__URectLightComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__URectLightComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__URectLightComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__URectLightComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__URectLightComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__URectLightComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__URectLightComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__URectLightComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__URectLightComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__URectLightComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__URectLightComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__URectLightComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__URectLightComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__URectLightComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__URectLightComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__URectLightComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__URectLightComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__URectLightComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__URectLightComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__URectLightComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__URectLightComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__URectLightComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__URectLightComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__URectLightComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__URectLightComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__URectLightComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__URectLightComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__URectLightComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__URectLightComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__URectLightComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__URectLightComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__URectLightComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__URectLightComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__URectLightComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__URectLightComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__URectLightComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__URectLightComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__URectLightComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__URectLightComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__URectLightComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__URectLightComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__URectLightComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__URectLightComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__URectLightComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__URectLightComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__URectLightComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageRectLightComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageRectLightComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageRectLightComponent>(PtrDesc);
}
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Runtime.InteropServices;
namespace System.Data.SqlTypes
{
/// <devdoc>
/// <para>
/// Represents a 32-bit signed integer to be stored in
/// or retrieved from a database.
/// </para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public struct SqlInt32 : INullable, IComparable
{
private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null
private int _value;
private static readonly long s_iIntMin = Int32.MinValue; // minimum (signed) int value
private static readonly long s_lBitNotIntMax = ~(long)(Int32.MaxValue);
// constructor
// construct a Null
private SqlInt32(bool fNull)
{
_fNotNull = false;
_value = 0;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlInt32(int value)
{
_value = value;
_fNotNull = true;
}
// INullable
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Value
{
get
{
if (IsNull)
throw new SqlNullValueException();
else
return _value;
}
}
// Implicit conversion from int to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt32(int x)
{
return new SqlInt32(x);
}
// Explicit conversion from SqlInt32 to int. Throw exception if x is Null.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator int (SqlInt32 x)
{
return x.Value;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override String ToString()
{
return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 Parse(String s)
{
if (s == SQLResource.NullString)
return SqlInt32.Null;
else
return new SqlInt32(Int32.Parse(s, (IFormatProvider)null));
}
// Unary operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator -(SqlInt32 x)
{
return x.IsNull ? Null : new SqlInt32(-x._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator ~(SqlInt32 x)
{
return x.IsNull ? Null : new SqlInt32(~x._value);
}
// Binary operators
// Arithmetic operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator +(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = x._value + y._value;
if (SameSignInt(x._value, y._value) && !SameSignInt(x._value, iResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32(iResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator -(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return Null;
int iResult = x._value - y._value;
if (!SameSignInt(x._value, y._value) && SameSignInt(y._value, iResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32(iResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator *(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return Null;
long lResult = (long)x._value * (long)y._value;
long lTemp = lResult & s_lBitNotIntMax;
if (lTemp != 0 && lTemp != s_lBitNotIntMax)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32((int)lResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator /(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
if ((x._value == s_iIntMin) && (y._value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt32(x._value / y._value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator %(SqlInt32 x, SqlInt32 y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value != 0)
{
if ((x._value == s_iIntMin) && (y._value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt32(x._value % y._value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
// Bitwise operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator &(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt32(x._value & y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator |(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt32(x._value | y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt32 operator ^(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt32(x._value ^ y._value);
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlBoolean x)
{
return x.IsNull ? Null : new SqlInt32((int)x.ByteValue);
}
// Implicit conversion from SqlByte to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt32(SqlByte x)
{
return x.IsNull ? Null : new SqlInt32(x.Value);
}
// Implicit conversion from SqlInt16 to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt32(SqlInt16 x)
{
return x.IsNull ? Null : new SqlInt32(x.Value);
}
// Explicit conversions
// Explicit conversion from SqlInt64 to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlInt64 x)
{
if (x.IsNull)
return Null;
long value = x.Value;
if (value > (long)Int32.MaxValue || value < (long)Int32.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32((int)value);
}
// Explicit conversion from SqlSingle to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlSingle x)
{
if (x.IsNull)
return Null;
float value = x.Value;
if (value > (float)Int32.MaxValue || value < (float)Int32.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32((int)value);
}
// Explicit conversion from SqlDouble to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlDouble x)
{
if (x.IsNull)
return Null;
double value = x.Value;
if (value > (double)Int32.MaxValue || value < (double)Int32.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt32((int)value);
}
// Explicit conversion from SqlMoney to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlMoney x)
{
return x.IsNull ? Null : new SqlInt32(x.ToInt32());
}
// Explicit conversion from SqlDecimal to SqlInt32
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlDecimal x)
{
if (x.IsNull)
return SqlInt32.Null;
x.AdjustScale(-x.Scale, true);
long ret = (long)x.m_data1;
if (!x.IsPositive)
ret = -ret;
if (x.m_bLen > 1 || ret > (long)Int32.MaxValue || ret < (long)Int32.MinValue)
throw new OverflowException(SQLResource.ConversionOverflowMessage);
return new SqlInt32((int)ret);
}
// Explicit conversion from SqlString to SqlInt
// Throws FormatException or OverflowException if necessary.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt32(SqlString x)
{
return x.IsNull ? SqlInt32.Null : new SqlInt32(Int32.Parse(x.Value, (IFormatProvider)null));
}
// Utility functions
private static bool SameSignInt(int x, int y)
{
return ((x ^ y) & 0x80000000) == 0;
}
// Overloading comparison operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator ==(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator !=(SqlInt32 x, SqlInt32 y)
{
return !(x == y);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <=(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >=(SqlInt32 x, SqlInt32 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlInt32 OnesComplement(SqlInt32 x)
{
return ~x;
}
// Alternative method for operator +
public static SqlInt32 Add(SqlInt32 x, SqlInt32 y)
{
return x + y;
}
// Alternative method for operator -
public static SqlInt32 Subtract(SqlInt32 x, SqlInt32 y)
{
return x - y;
}
// Alternative method for operator *
public static SqlInt32 Multiply(SqlInt32 x, SqlInt32 y)
{
return x * y;
}
// Alternative method for operator /
public static SqlInt32 Divide(SqlInt32 x, SqlInt32 y)
{
return x / y;
}
// Alternative method for operator %
public static SqlInt32 Mod(SqlInt32 x, SqlInt32 y)
{
return x % y;
}
public static SqlInt32 Modulus(SqlInt32 x, SqlInt32 y)
{
return x % y;
}
// Alternative method for operator &
public static SqlInt32 BitwiseAnd(SqlInt32 x, SqlInt32 y)
{
return x & y;
}
// Alternative method for operator |
public static SqlInt32 BitwiseOr(SqlInt32 x, SqlInt32 y)
{
return x | y;
}
// Alternative method for operator ^
public static SqlInt32 Xor(SqlInt32 x, SqlInt32 y)
{
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlInt32 x, SqlInt32 y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlInt32 x, SqlInt32 y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlInt32 x, SqlInt32 y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlInt32 x, SqlInt32 y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlInt32 x, SqlInt32 y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlInt32 x, SqlInt32 y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int CompareTo(Object value)
{
if (value is SqlInt32)
{
SqlInt32 i = (SqlInt32)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlInt32));
}
public int CompareTo(SqlInt32 value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(Object value)
{
if (!(value is SqlInt32))
{
return false;
}
SqlInt32 i = (SqlInt32)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt32 Null = new SqlInt32(true);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt32 Zero = new SqlInt32(0);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt32 MinValue = new SqlInt32(Int32.MinValue);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt32 MaxValue = new SqlInt32(Int32.MaxValue);
} // SqlInt32
} // namespace System.Data.SqlTypes
| |
// 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 System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Implements an assembly loader for interactive compiler and REPL.
/// </summary>
/// <remarks>
/// <para>
/// The class is thread-safe.
/// </para>
/// </remarks>
public sealed partial class InteractiveAssemblyLoader : IDisposable
{
private class LoadedAssembly
{
public bool LoadedExplicitly { get; set; }
/// <summary>
/// The original path of the assembly before it was shadow-copied.
/// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them.
/// </summary>
public string OriginalPath { get; set; }
}
private readonly AssemblyLoaderImpl _runtimeAssemblyLoader;
private readonly MetadataShadowCopyProvider _shadowCopyProvider;
// Synchronizes assembly reference tracking.
// Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader.
private readonly object _referencesLock = new object();
// loaded assembly -> loaded assembly info
private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation;
// { original full path -> assembly }
// Note, that there might be multiple entries for a single GAC'd assembly.
private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath;
// simple name -> loaded assemblies
private readonly Dictionary<string, List<Assembly>> _loadedAssembliesBySimpleName;
// simple name -> identity and location of a known dependency
private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName;
[SuppressMessage("Performance", "RS0008", Justification = "Equality not actually implemented")]
private struct AssemblyIdentityAndLocation
{
public readonly AssemblyIdentity Identity;
public readonly string Location;
public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location)
{
Debug.Assert(identity != null && location != null);
this.Identity = identity;
this.Location = location;
}
public override int GetHashCode()
{
throw ExceptionUtilities.Unreachable;
}
public override bool Equals(object obj)
{
throw ExceptionUtilities.Unreachable;
}
public override string ToString()
{
return Identity + " @ " + Location;
}
}
public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null)
{
_shadowCopyProvider = shadowCopyProvider;
_assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>();
_assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>();
_loadedAssembliesBySimpleName = new Dictionary<string, List<Assembly>>(AssemblyIdentityComparer.SimpleNameComparer);
_dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>();
_runtimeAssemblyLoader = AssemblyLoaderImpl.Create(this);
}
public void Dispose()
{
_runtimeAssemblyLoader.Dispose();
}
internal Assembly LoadAssemblyFromStream(Stream peStream, Stream pdbStream)
{
Assembly assembly = _runtimeAssemblyLoader.LoadFromStream(peStream, pdbStream);
RegisterDependency(assembly);
return assembly;
}
private AssemblyAndLocation Load(string reference)
{
MetadataShadowCopy copy = null;
try
{
if (_shadowCopyProvider != null)
{
// All modules of the assembly has to be copied at once to keep the metadata consistent.
// This API copies the xml doc file and keeps the memory-maps of the metadata.
// We don't need that here but presumably the provider is shared with the compilation API that needs both.
// Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map.
copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly);
}
var result = _runtimeAssemblyLoader.LoadFromPath((copy != null) ? copy.PrimaryModule.FullPath : reference);
if (_shadowCopyProvider != null && result.GlobalAssemblyCache)
{
_shadowCopyProvider.SuppressShadowCopy(reference);
}
return result;
}
catch (FileNotFoundException)
{
return default(AssemblyAndLocation);
}
finally
{
// copy holds on the file handle, we need to keep the handle
// open until the file is locked by the CLR assembly loader:
copy?.DisposeFileHandles();
}
}
/// <summary>
/// Loads an assembly from path.
/// </summary>
/// <param name="path">Absolute assembly file path.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing assembly file path.</exception>
/// <exception cref="TargetInvocationException">The assembly resolver threw an exception.</exception>
public AssemblyLoadResult LoadFromPath(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path));
}
try
{
return LoadFromPathInternal(FileUtilities.NormalizeAbsolutePath(path));
}
catch (TargetInvocationException)
{
throw;
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(path), e);
}
}
/// <summary>
/// Notifies the assembly loader about a dependency that might be loaded in future.
/// </summary>
/// <param name="dependency">Assembly identity.</param>
/// <param name="path">Assembly location.</param>
/// <remarks>
/// Associates a full assembly name with its location. The association is used when an assembly
/// is being loaded and its name needs to be resolved to a location.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception>
public void RegisterDependency(AssemblyIdentity dependency, string path)
{
if (dependency == null)
{
throw new ArgumentNullException(nameof(dependency));
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path));
}
lock (_referencesLock)
{
RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path));
}
}
/// <summary>
/// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context.
/// </summary>
/// <param name="dependency">Assembly identity.</param>
/// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception>
/// <remarks>
/// When another in-memory assembly references the <paramref name="dependency"/> the loader
/// responds with the specified dependency if the assembly identity matches the requested one.
/// </remarks>
public void RegisterDependency(Assembly dependency)
{
if (dependency == null)
{
throw new ArgumentNullException(nameof(dependency));
}
lock (_referencesLock)
{
RegisterLoadedAssemblySimpleNameNoLock(dependency);
}
}
private AssemblyLoadResult LoadFromPathInternal(string fullPath)
{
AssemblyAndLocation assembly;
lock (_referencesLock)
{
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(fullPath, out assembly))
{
LoadedAssembly loadedAssembly = _assembliesLoadedFromLocation[assembly.Assembly];
if (loadedAssembly.LoadedExplicitly)
{
return AssemblyLoadResult.CreateAlreadyLoaded(assembly.Location, loadedAssembly.OriginalPath);
}
else
{
loadedAssembly.LoadedExplicitly = true;
return AssemblyLoadResult.CreateSuccessful(assembly.Location, loadedAssembly.OriginalPath);
}
}
}
AssemblyLoadResult result;
assembly = ShadowCopyAndLoadAssembly(fullPath, out result);
if (assembly.IsDefault)
{
throw new FileNotFoundException(message: null, fileName: fullPath);
}
return result;
}
private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly)
{
List<Assembly> sameSimpleNameAssemblies;
string simpleName = assembly.GetName().Name;
if (_loadedAssembliesBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblies))
{
sameSimpleNameAssemblies.Add(assembly);
}
else
{
_loadedAssembliesBySimpleName.Add(simpleName, new List<Assembly> { assembly });
}
}
private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency)
{
List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities;
string simpleName = dependency.Identity.Name;
if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities))
{
sameSimpleNameAssemblyIdentities.Add(dependency);
}
else
{
_dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency });
}
}
internal Assembly ResolveAssembly(string assemblyDisplayName, Assembly requestingAssemblyOpt)
{
AssemblyIdentity identity;
if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity))
{
return null;
}
string loadDirectoryOpt;
lock (_referencesLock)
{
LoadedAssembly loadedAssembly;
if (requestingAssemblyOpt != null &&
_assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly))
{
loadDirectoryOpt = Path.GetDirectoryName(loadedAssembly.OriginalPath);
}
else
{
loadDirectoryOpt = null;
}
}
return ResolveAssembly(identity, loadDirectoryOpt);
}
internal Assembly ResolveAssembly(AssemblyIdentity identity, string loadDirectoryOpt)
{
// if the referring assembly is already loaded by our loader, load from its directory:
if (loadDirectoryOpt != null)
{
string pathWithoutExtension = Path.Combine(loadDirectoryOpt, identity.Name);
string originalDllPath = pathWithoutExtension + ".dll";
string originalExePath = pathWithoutExtension + ".exe";
lock (_referencesLock)
{
AssemblyAndLocation assembly;
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(originalDllPath, out assembly) ||
_assembliesLoadedFromLocationByFullPath.TryGetValue(originalExePath, out assembly))
{
return assembly.Assembly;
}
}
// Copy & load both .dll and .exe, this is not a common scenario we would need to optimize for.
// Remember both loaded assemblies for the next time, even though their versions might not match the current request
// they might match the next one and we don't want to load them again.
Assembly dll = ShadowCopyAndLoadDependency(originalDllPath).Assembly;
Assembly exe = ShadowCopyAndLoadDependency(originalExePath).Assembly;
if (dll == null ^ exe == null)
{
return dll ?? exe;
}
if (dll != null && exe != null)
{
// .dll and an .exe of the same name might have different versions,
// one of which might match the requested version.
// Prefer .dll if they are both the same.
return FindHighestVersionOrFirstMatchingIdentity(identity, new[] { dll, exe });
}
}
return GetOrLoadKnownAssembly(identity);
}
private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity)
{
Assembly assembly = null;
string assemblyFileToLoad = null;
// Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one.
lock (_referencesLock)
{
// already loaded assemblies:
List<Assembly> sameSimpleNameAssemblies;
if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameAssemblies))
{
assembly = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameAssemblies);
if (assembly != null)
{
return assembly;
}
}
// names:
List<AssemblyIdentityAndLocation> sameSimpleNameIdentities;
if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
{
var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities);
if (identityAndLocation.Identity != null)
{
assemblyFileToLoad = identityAndLocation.Location;
AssemblyAndLocation assemblyAndLocation;
if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation))
{
return assemblyAndLocation.Assembly;
}
}
}
}
if (assemblyFileToLoad != null)
{
assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly;
}
return assembly;
}
private AssemblyAndLocation ShadowCopyAndLoadAssembly(string originalPath, out AssemblyLoadResult result)
{
return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: true);
}
private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath)
{
AssemblyLoadResult result;
return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: false);
}
private AssemblyAndLocation ShadowCopyAndLoadAndAddEntry(string originalPath, out AssemblyLoadResult result, bool explicitLoad)
{
AssemblyAndLocation assemblyAndLocation = Load(originalPath);
if (assemblyAndLocation.IsDefault)
{
result = default(AssemblyLoadResult);
return default(AssemblyAndLocation);
}
lock (_referencesLock)
{
// Always remember the path. The assembly might have been loaded from another path or not loaded yet.
_assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation;
LoadedAssembly loadedAssembly;
if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly))
{
// The same assembly may have been loaded from a different path already,
// or the assembly has been loaded while we were copying the file and loading the copy;
// Use the existing assembly record.
if (loadedAssembly.LoadedExplicitly)
{
result = AssemblyLoadResult.CreateAlreadyLoaded(assemblyAndLocation.Location, loadedAssembly.OriginalPath);
}
else
{
loadedAssembly.LoadedExplicitly = explicitLoad;
result = AssemblyLoadResult.CreateSuccessful(assemblyAndLocation.Location, loadedAssembly.OriginalPath);
}
return assemblyAndLocation;
}
else
{
result = AssemblyLoadResult.CreateSuccessful(
assemblyAndLocation.Location,
assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath);
_assembliesLoadedFromLocation.Add(
assemblyAndLocation.Assembly,
new LoadedAssembly { LoadedExplicitly = explicitLoad, OriginalPath = result.OriginalPath });
}
RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly);
}
return assemblyAndLocation;
}
private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<Assembly> assemblies)
{
Assembly candidate = null;
Version candidateVersion = null;
foreach (var assembly in assemblies)
{
var assemblyIdentity = AssemblyIdentity.FromAssemblyDefinition(assembly);
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assemblyIdentity))
{
if (candidate == null || candidateVersion < assemblyIdentity.Version)
{
candidate = assembly;
candidateVersion = assemblyIdentity.Version;
}
}
}
return candidate;
}
private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies)
{
var candidate = default(AssemblyIdentityAndLocation);
foreach (var assembly in assemblies)
{
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity))
{
if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version)
{
candidate = assembly;
}
}
}
return candidate;
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Cassandra.Requests;
using Cassandra.Serialization;
namespace Cassandra
{
/// <summary>
/// A simple <see cref="IStatement"/> implementation built directly from a query string.
/// </summary>
public class SimpleStatement : RegularStatement
{
private static readonly Logger Logger = new Logger(typeof(SimpleStatement));
private string _query;
private volatile RoutingKey _routingKey;
private object[] _routingValues;
private string _keyspace;
/// <summary>
/// Gets the query string.
/// </summary>
public override string QueryString
{
get { return _query; }
}
/// <summary>
/// Gets the routing key for the query.
/// <para>
/// Routing key can be provided using the <see cref="SetRoutingValues"/> method.
/// </para>
/// </summary>
public override RoutingKey RoutingKey
{
get
{
if (_routingKey != null)
{
return _routingKey;
}
if (_routingValues == null)
{
return null;
}
var serializer = Serializer;
if (serializer == null)
{
serializer = Serializer.Default;
Logger.Warning("Calculating routing key before executing is not supporting for SimpleStatements, " +
"using default serializer.");
}
//Calculate the routing key
return RoutingKey.Compose(
_routingValues
.Select(value => new RoutingKey(serializer.Serialize(value)))
.ToArray());
}
}
/// <summary>
/// Returns the keyspace this query operates on, as set using <see cref="SetKeyspace(string)"/>
/// <para>
/// The keyspace returned is used as a hint for token-aware routing.
/// </para>
/// </summary>
/// <remarks>
/// Consider using a <see cref="ISession"/> connected to single keyspace using
/// <see cref="ICluster.Connect(string)"/>.
/// </remarks>
public override string Keyspace
{
get { return _keyspace; }
}
/// <summary>
/// Creates a new instance of <see cref="SimpleStatement"/> without any query string or parameters.
/// </summary>
public SimpleStatement()
{
}
/// <summary>
/// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query.
/// </summary>
/// <param name="query">The cql query string.</param>
public SimpleStatement(string query)
{
_query = query;
}
/// <summary>
/// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query and values provided.
/// </summary>
/// <param name="query">The cql query string.</param>
/// <param name="values">Parameter values required for the execution of <c>query</c>.</param>
/// <example>
/// Using positional parameters:
/// <code>
/// const string query = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)";
/// var statement = new SimpleStatement(query, id, name, email);
/// </code>
/// Using named parameters (using anonymous objects):
/// <code>
/// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)";
/// var statement = new SimpleStatement(query, new { id, name, email } );
/// </code>
/// </example>
public SimpleStatement(string query, params object[] values) : this(query)
{
// ReSharper disable once DoNotCallOverridableMethodsInConstructor
SetValues(values);
}
/// <summary>
/// Creates a new instance of <see cref="SimpleStatement"/> using a dictionary of parameters and a query with
/// named parameters.
/// </summary>
/// <param name="valuesDictionary">
/// A dictionary containing the query parameters values using the parameter name as keys.
/// </param>
/// <param name="query">The cql query string.</param>
/// <remarks>
/// This constructor is valid for dynamically-sized named parameters, consider using anonymous types for
/// fixed-size named parameters.
/// </remarks>
/// <example>
/// <code>
/// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)";
/// var parameters = new Dictionary<string, object>
/// {
/// { "id", id },
/// { "name", name },
/// { "email", email },
/// };
/// var statement = new SimpleStatement(parameters, query);
/// </code>
/// </example>
/// <seealso cref="SimpleStatement(string, object[])"/>
public SimpleStatement(IDictionary<string, object> valuesDictionary, string query)
{
if (valuesDictionary == null)
{
throw new ArgumentNullException("valuesDictionary");
}
if (query == null)
{
throw new ArgumentNullException("query");
}
//The order of the keys and values is unspecified, but is guaranteed to be both in the same order.
SetParameterNames(valuesDictionary.Keys);
base.SetValues(valuesDictionary.Values.ToArray());
_query = query;
}
/// <summary>
/// Set the routing key for this query. <p> This method allows to manually
/// provide a routing key for this query. It is thus optional since the routing
/// key is only an hint for token aware load balancing policy but is never
/// mandatory. </p><p> If the partition key for the query is composite, use the
/// <link>#setRoutingKey(ByteBuffer...)</link> method instead to build the
/// routing key.</p>
/// </summary>
/// <param name="routingKeyComponents"> the raw (binary) values to compose to
/// obtain the routing key.
/// </param>
/// <returns>this <c>SimpleStatement</c> object. <see>Query#getRoutingKey</see></returns>
public SimpleStatement SetRoutingKey(params RoutingKey[] routingKeyComponents)
{
_routingKey = RoutingKey.Compose(routingKeyComponents);
return this;
}
/// <summary>
/// Sets the partition key values in order to route the query to the correct replicas.
/// <para>For simple partition keys, set the partition key value.</para>
/// <para>For composite partition keys, set the multiple the partition key values in correct order.</para>
/// </summary>
public SimpleStatement SetRoutingValues(params object[] keys)
{
_routingValues = keys;
return this;
}
public SimpleStatement SetQueryString(string queryString)
{
_query = queryString;
return this;
}
/// <summary>
/// Sets the parameter values for the query.
/// <para>
/// The same amount of values must be provided as parameter markers in the query.
/// </para>
/// <para>
/// Specify the parameter values by the position of the markers in the query or by name,
/// using a single instance of an anonymous type, with property names as parameter names.
/// </para>
/// </summary>
[Obsolete("The method Bind() is deprecated, use SimpleStatement constructor parameters to provide query values")]
public SimpleStatement Bind(params object[] values)
{
SetValues(values);
return this;
}
[Obsolete("The method BindObject() is deprecated, use SimpleStatement constructor parameters to provide query values")]
public SimpleStatement BindObjects(object[] values)
{
return Bind(values);
}
/// <summary>
/// Sets the keyspace of this <see cref="SimpleStatement"/> to be used as a hint for token-aware routing.
/// </summary>
/// <param name="name">The keyspace name</param>
public SimpleStatement SetKeyspace(string name)
{
_keyspace = name;
return this;
}
internal override IQueryRequest CreateBatchRequest(ProtocolVersion protocolVersion)
{
// Use the default query options as the individual options of the query will be ignored
var options = QueryProtocolOptions.CreateForBatchItem(this);
return new QueryRequest(protocolVersion, QueryString, IsTracing, options);
}
internal override void SetValues(object[] values)
{
if (values != null && values.Length == 1 && Utils.IsAnonymousType(values[0]))
{
var keyValues = Utils.GetValues(values[0]);
SetParameterNames(keyValues.Keys);
values = keyValues.Values.ToArray();
}
base.SetValues(values);
}
private void SetParameterNames(IEnumerable<string> names)
{
//Force named values to lowercase as identifiers are lowercased in Cassandra
QueryValueNames = names.Select(k => k.ToLowerInvariant()).ToList();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
using System;
using System.Diagnostics.Contracts;
using System.Threading;
using DotNetty.Buffers;
using DotNetty.Common;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Utilities;
public sealed class ChannelOutboundBuffer
{
#pragma warning disable 420 // all volatile fields are used with referenced in Interlocked methods only
//static readonly ThreadLocal<IByteBuffer[]> NIO_BUFFERS = new ThreadLocal<IByteBuffer[]>(() => new IByteBuffer[1024]);
readonly IChannel channel;
// Entry(flushedEntry) --> ... Entry(unflushedEntry) --> ... Entry(tailEntry)
//
// The Entry that is the first in the linked-list structure that was flushed
Entry flushedEntry;
// The Entry which is the first unflushed in the linked-list structure
Entry unflushedEntry;
// The Entry which represents the tail of the buffer
Entry tailEntry;
// The number of flushed entries that are not written yet
int flushed;
//int nioBufferCount;
//long nioBufferSize;
bool inFail;
long totalPendingSize;
volatile int unwritable;
internal ChannelOutboundBuffer(IChannel channel)
{
this.channel = channel;
}
/// <summary>
/// Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once
/// the message was written.
/// </summary>
public void AddMessage(object msg, int size, TaskCompletionSource promise)
{
Entry entry = Entry.NewInstance(msg, size, Total(msg), promise);
if (this.tailEntry == null)
{
this.flushedEntry = null;
this.tailEntry = entry;
}
else
{
Entry tail = this.tailEntry;
tail.Next = entry;
this.tailEntry = entry;
}
if (this.unflushedEntry == null)
{
this.unflushedEntry = entry;
}
// increment pending bytes after adding message to the unflushed arrays.
// See https://github.com/netty/netty/issues/1619
this.IncrementPendingOutboundBytes(size, false);
}
/// <summary>
/// Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed
/// and so you will be able to handle them.
/// </summary>
public void AddFlush()
{
// There is no need to process all entries if there was already a flush before and no new messages
// where added in the meantime.
//
// See https://github.com/netty/netty/issues/2577
Entry entry = this.unflushedEntry;
if (entry != null)
{
if (this.flushedEntry == null)
{
// there is no flushedEntry yet, so start with the entry
this.flushedEntry = entry;
}
do
{
this.flushed++;
if (!entry.Promise.setUncancellable())
{
// Was cancelled so make sure we free up memory and notify about the freed bytes
int pending = entry.Cancel();
this.DecrementPendingOutboundBytes(pending, false, true);
}
entry = entry.Next;
}
while (entry != null);
// All flushed so reset unflushedEntry
this.unflushedEntry = null;
}
}
/// <summary>
/// Increment the pending bytes which will be written at some point.
/// This method is thread-safe!
/// </summary>
internal void IncrementPendingOutboundBytes(long size)
{
this.IncrementPendingOutboundBytes(size, true);
}
void IncrementPendingOutboundBytes(long size, bool invokeLater)
{
if (size == 0)
{
return;
}
long newWriteBufferSize = Interlocked.Add(ref this.totalPendingSize, size);
if (newWriteBufferSize >= this.channel.Configuration.WriteBufferHighWaterMark)
{
this.SetUnwritable(invokeLater);
}
}
/// <summary>
/// Decrement the pending bytes which will be written at some point.
/// This method is thread-safe!
/// </summary>
internal void DecrementPendingOutboundBytes(long size)
{
this.DecrementPendingOutboundBytes(size, true, true);
}
void DecrementPendingOutboundBytes(long size, bool invokeLater, bool notifyWritability)
{
if (size == 0)
{
return;
}
long newWriteBufferSize = Interlocked.Add(ref this.totalPendingSize, -size);
if (notifyWritability && (newWriteBufferSize == 0
|| newWriteBufferSize <= this.channel.Configuration.WriteBufferLowWaterMark))
{
this.SetWritable(invokeLater);
}
}
static long Total(object msg)
{
if (msg is IByteBuffer)
{
return ((IByteBuffer)msg).ReadableBytes;
}
// todo: FileRegion support
//if (msg is FileRegion)
//{
// return ((FileRegion)msg).count();
//}
// todo: IByteBufferHolder support
//if (msg is IByteBufferHolder)
//{
// return ((ByteBufHolder)msg).content().readableBytes();
//}
return -1;
}
/// <summary>
/// Return the current message to write or {@code null} if nothing was flushed before and so is ready to be written.
/// </summary>
public object Current
{
get
{
Entry entry = this.flushedEntry;
if (entry == null)
{
return null;
}
return entry.Message;
}
}
/// <summary>
/// Notify the {@link ChannelPromise} of the current message about writing progress.
/// </summary>
public void Progress(long amount)
{
// todo: support progress report?
//Entry e = this.flushedEntry;
//Contract.Assert(e != null);
//var p = e.promise;
//if (p is ChannelProgressivePromise)
//{
// long progress = e.progress + amount;
// e.progress = progress;
// ((ChannelProgressivePromise)p).tryProgress(progress, e.Total);
//}
}
/// <summary>
/// Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no
/// flushed message exists at the time this method is called it will return {@code false} to signal that no more
/// messages are ready to be handled.
/// </summary>
public bool Remove()
{
Entry e = this.flushedEntry;
if (e == null)
{
return false;
}
object msg = e.Message;
TaskCompletionSource promise = e.Promise;
int size = e.PendingSize;
this.RemoveEntry(e);
if (!e.Cancelled)
{
// only release message, notify and decrement if it was not canceled before.
ReferenceCountUtil.SafeRelease(msg);
Util.SafeSetSuccess(promise);
this.DecrementPendingOutboundBytes(size, false, true);
}
// recycle the entry
e.Recycle();
return true;
}
/// <summary>
/// Will remove the current message, mark its {@link ChannelPromise} as failure using the given {@link Exception}
/// and return {@code true}. If no flushed message exists at the time this method is called it will return
/// {@code false} to signal that no more messages are ready to be handled.
/// </summary>
public bool Remove(Exception cause)
{
return this.Remove0(cause, true);
}
bool Remove0(Exception cause, bool notifyWritability)
{
Entry e = this.flushedEntry;
if (e == null)
{
return false;
}
object msg = e.Message;
TaskCompletionSource promise = e.Promise;
int size = e.PendingSize;
this.RemoveEntry(e);
if (!e.Cancelled)
{
// only release message, fail and decrement if it was not canceled before.
ReferenceCountUtil.SafeRelease(msg);
Util.SafeSetFailure(promise, cause);
if (promise != TaskCompletionSource.Void && !promise.TrySetException(cause))
{
ChannelEventSource.Log.Warning(string.Format("Failed to mark a promise as failure because it's done already: {0}", promise), cause);
}
this.DecrementPendingOutboundBytes(size, false, notifyWritability);
}
// recycle the entry
e.Recycle();
return true;
}
void RemoveEntry(Entry e)
{
if (-- this.flushed == 0)
{
// processed everything
this.flushedEntry = null;
if (e == this.tailEntry)
{
this.tailEntry = null;
this.unflushedEntry = null;
}
}
else
{
this.flushedEntry = e.Next;
}
}
/// <summary>
/// Removes the fully written entries and update the reader index of the partially written entry.
/// This operation assumes all messages in this buffer is {@link ByteBuf}.
/// </summary>
public void RemoveBytes(long writtenBytes)
{
for (;;)
{
object msg = this.Current;
if (!(msg is IByteBuffer))
{
Contract.Assert(writtenBytes == 0);
break;
}
var buf = (IByteBuffer)msg;
int readerIndex = buf.ReaderIndex;
int readableBytes = buf.WriterIndex - readerIndex;
if (readableBytes <= writtenBytes)
{
if (writtenBytes != 0)
{
this.Progress(readableBytes);
writtenBytes -= readableBytes;
}
this.Remove();
}
else
{
// readableBytes > writtenBytes
if (writtenBytes != 0)
{
buf.SetReaderIndex(readerIndex + (int)writtenBytes);
this.Progress(writtenBytes);
}
break;
}
}
}
/// <summary>
/// Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only.
/// {@link #NioBufferCount} and {@link #NioBufferSize} will return the number of NIO buffers in the returned
/// array and the total number of readable bytes of the NIO buffers respectively.
/// <p>
/// Note that the returned array is reused and thus should not escape
/// {@link AbstractChannel#doWrite(ChannelOutboundBuffer)}.
/// Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example.
/// </p>
/// </summary>
//public IByteBuffer[] nioBuffers()
//{
// long nioBufferSize = 0;
// int nioBufferCount = 0;
// IByteBuffer[] nioBuffers = NIO_BUFFERS.Value; // todo: review FastThreadLocal here
// Entry entry = this.flushedEntry;
// while (this.isFlushedEntry(entry) && entry.msg is IByteBuffer)
// {
// if (!entry.cancelled)
// {
// var buf = (IByteBuffer)entry.msg;
// int readerIndex = buf.ReaderIndex;
// int readableBytes = buf.WriterIndex - readerIndex;
// if (readableBytes > 0)
// {
// nioBufferSize += readableBytes;
// int count = entry.count;
// if (count == -1)
// {
// //noinspection ConstantValueVariableUse
// entry.count = count = buf.NioBufferCount;
// }
// int neededSpace = nioBufferCount + count;
// if (neededSpace > nioBuffers.Length)
// {
// nioBuffers = expandNioBufferArray(nioBuffers, neededSpace, nioBufferCount);
// NIO_BUFFERS.Value = nioBuffers;
// }
// if (count == 1)
// {
// IByteBuffer nioBuf = entry.buf;
// if (nioBuf == null)
// {
// // cache ByteBuffer as it may need to create a new ByteBuffer instance if its a
// // derived buffer
// entry.buf = nioBuf = buf.internalNioBuffer(readerIndex, readableBytes);
// }
// nioBuffers[nioBufferCount++] = nioBuf;
// }
// else
// {
// IByteBuffer[] nioBufs = entry.bufs;
// if (nioBufs == null)
// {
// // cached ByteBuffers as they may be expensive to create in terms
// // of Object allocation
// entry.bufs = nioBufs = buf.nioBuffers();
// }
// nioBufferCount = fillBufferArray(nioBufs, nioBuffers, nioBufferCount);
// }
// }
// }
// entry = entry.next;
// }
// this.nioBufferCount = nioBufferCount;
// this.nioBufferSize = nioBufferSize;
// return nioBuffers;
//}
//static int FillBufferArray(IByteBuffer[] nioBufs, IByteBuffer[] nioBuffers, int nioBufferCount)
//{
// foreach (IByteBuffer nioBuf in nioBufs)
// {
// if (nioBuf == null)
// {
// break;
// }
// nioBuffers[nioBufferCount++] = nioBuf;
// }
// return nioBufferCount;
//}
//static IByteBuffer[] ExpandNioBufferArray(IByteBuffer[] array, int neededSpace, int size)
//{
// int newCapacity = array.Length;
// do
// {
// // double capacity until it is big enough
// // See https://github.com/netty/netty/issues/1890
// newCapacity <<= 1;
// if (newCapacity < 0)
// {
// throw new InvalidOperationException();
// }
// }
// while (neededSpace > newCapacity);
// var newArray = new IByteBuffer[newCapacity];
// Array.Copy(array, 0, newArray, 0, size);
// return newArray;
//}
// /// <summary>
//* Returns the number of {@link ByteBuffer} that can be written out of the {@link ByteBuffer} array that was
//* obtained via {@link #nioBuffers()}. This method <strong>MUST</strong> be called after {@link #nioBuffers()}
//* was called.
///// </summary>
// public int NioBufferCount
// {
// get { return this.nioBufferCount; }
// }
// /// <summary>
//* Returns the number of bytes that can be written out of the {@link ByteBuffer} array that was
//* obtained via {@link #nioBuffers()}. This method <strong>MUST</strong> be called after {@link #nioBuffers()}
//* was called.
///// </summary>
// public long NioBufferSize
// {
// get { return this.nioBufferSize; }
// }
/// <summary>
/// Returns {@code true} if and only if {@linkplain #totalPendingWriteBytes() the total number of pending bytes} did
/// not exceed the write watermark of the {@link Channel} and
/// no {@linkplain #SetUserDefinedWritability(int, bool) user-defined writability flag} has been set to
/// {@code false}.
/// </summary>
public bool IsWritable
{
get { return this.unwritable == 0; }
}
/// <summary>
/// Returns {@code true} if and only if the user-defined writability flag at the specified index is set to
/// {@code true}.
/// </summary>
public bool GetUserDefinedWritability(int index)
{
return (this.unwritable & WritabilityMask(index)) == 0;
}
/// <summary>
/// Sets a user-defined writability flag at the specified index.
/// </summary>
public void SetUserDefinedWritability(int index, bool writable)
{
if (writable)
{
this.SetUserDefinedWritability(index);
}
else
{
this.ClearUserDefinedWritability(index);
}
}
void SetUserDefinedWritability(int index)
{
int mask = ~WritabilityMask(index);
while (true)
{
int oldValue = this.unwritable;
int newValue = oldValue & mask;
if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue)
{
if (oldValue != 0 && newValue == 0)
{
this.FireChannelWritabilityChanged(true);
}
break;
}
}
}
void ClearUserDefinedWritability(int index)
{
int mask = WritabilityMask(index);
while (true)
{
int oldValue = this.unwritable;
int newValue = oldValue | mask;
if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue)
{
if (oldValue == 0 && newValue != 0)
{
this.FireChannelWritabilityChanged(true);
}
break;
}
}
}
static int WritabilityMask(int index)
{
if (index < 1 || index > 31)
{
throw new InvalidOperationException("index: " + index + " (expected: 1~31)");
}
return 1 << index;
}
void SetWritable(bool invokeLater)
{
while (true)
{
int oldValue = this.unwritable;
int newValue = oldValue & ~1;
if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue)
{
if (oldValue != 0 && newValue == 0)
{
this.FireChannelWritabilityChanged(invokeLater);
}
break;
}
}
}
void SetUnwritable(bool invokeLater)
{
while (true)
{
int oldValue = this.unwritable;
int newValue = oldValue | 1;
if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue)
{
if (oldValue == 0 && newValue != 0)
{
this.FireChannelWritabilityChanged(invokeLater);
}
break;
}
}
}
void FireChannelWritabilityChanged(bool invokeLater)
{
IChannelPipeline pipeline = this.channel.Pipeline;
if (invokeLater)
{
// todo: allocation check
this.channel.EventLoop.Execute(p => ((IChannelPipeline)p).FireChannelWritabilityChanged(), pipeline);
}
else
{
pipeline.FireChannelWritabilityChanged();
}
}
/// <summary>
/// Returns the number of flushed messages in this {@link ChannelOutboundBuffer}.
/// </summary>
public int Count
{
get { return this.flushed; }
}
/// <summary>
/// Returns {@code true} if there are flushed messages in this {@link ChannelOutboundBuffer} or {@code false}
/// otherwise.
/// </summary>
public bool IsEmpty
{
get { return this.flushed == 0; }
}
internal void FailFlushed(Exception cause, bool notify)
{
// Make sure that this method does not reenter. A listener added to the current promise can be notified by the
// current thread in the tryFailure() call of the loop below, and the listener can trigger another fail() call
// indirectly (usually by closing the channel.)
//
// See https://github.com/netty/netty/issues/1501
if (this.inFail)
{
return;
}
try
{
this.inFail = true;
for (;;)
{
if (!this.Remove0(cause, notify))
{
break;
}
}
}
finally
{
this.inFail = false;
}
}
internal void Close(ClosedChannelException cause)
{
if (this.inFail)
{
this.channel.EventLoop.Execute((buf, ex) => ((ChannelOutboundBuffer)buf).Close((ClosedChannelException)ex),
this, cause);
return;
}
this.inFail = true;
if (this.channel.Open)
{
throw new InvalidOperationException("close() must be invoked after the channel is closed.");
}
if (!this.IsEmpty)
{
throw new InvalidOperationException("close() must be invoked after all flushed writes are handled.");
}
// Release all unflushed messages.
try
{
Entry e = this.unflushedEntry;
while (e != null)
{
// Just decrease; do not trigger any events via DecrementPendingOutboundBytes()
int size = e.PendingSize;
Interlocked.Add(ref this.totalPendingSize, -size);
if (!e.Cancelled)
{
ReferenceCountUtil.SafeRelease(e.Message);
Util.SafeSetFailure(e.Promise, cause);
if (e.Promise != TaskCompletionSource.Void && !e.Promise.TrySetException(cause))
{
ChannelEventSource.Log.Warning(string.Format("Failed to mark a promise as failure because it's done already: {0}", e.Promise), cause);
}
}
e = e.RecycleAndGetNext();
}
}
finally
{
this.inFail = false;
}
}
public long TotalPendingWriteBytes()
{
return Thread.VolatileRead(ref this.totalPendingSize);
}
/// <summary>
/// Call {@link IMessageProcessor#processMessage(Object)} for each flushed message
/// in this {@link ChannelOutboundBuffer} until {@link IMessageProcessor#processMessage(Object)}
/// returns {@code false} or there are no more flushed messages to process.
/// </summary>
bool IsFlushedEntry(Entry e)
{
return e != null && e != this.unflushedEntry;
}
sealed class Entry
{
static readonly ThreadLocalPool<Entry> Pool = new ThreadLocalPool<Entry>(h => new Entry(h));
readonly ThreadLocalPool.Handle handle;
public Entry Next;
public object Message;
public IByteBuffer[] Buffers;
public IByteBuffer Buffer;
public TaskCompletionSource Promise;
public long Progress;
public long Total;
public int PendingSize;
public int Count = -1;
public bool Cancelled;
Entry(ThreadLocalPool.Handle handle)
{
this.handle = handle;
}
public static Entry NewInstance(object msg, int size, long total, TaskCompletionSource promise)
{
Entry entry = Pool.Take();
entry.Message = msg;
entry.PendingSize = size;
entry.Total = total;
entry.Promise = promise;
return entry;
}
public int Cancel()
{
if (!this.Cancelled)
{
this.Cancelled = true;
int pSize = this.PendingSize;
// release message and replace with an empty buffer
ReferenceCountUtil.SafeRelease(this.Message);
this.Message = Unpooled.Empty;
this.PendingSize = 0;
this.Total = 0;
this.Progress = 0;
this.Buffers = null;
this.Buffer = null;
return pSize;
}
return 0;
}
public void Recycle()
{
this.Next = null;
this.Buffers = null;
this.Buffer = null;
this.Message = null;
this.Promise = null;
this.Progress = 0;
this.Total = 0;
this.PendingSize = 0;
this.Count = -1;
this.Cancelled = false;
this.handle.Release(this);
}
public Entry RecycleAndGetNext()
{
Entry next = this.Next;
this.Recycle();
return next;
}
}
}
}
| |
// <copyright file="GPGSUpgrader.cs" company="Google Inc.">
// Copyright (C) 2014 Google 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.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.Editor
{
using System.IO;
using UnityEditor;
using UnityEngine;
/// <summary>
/// GPGS upgrader handles performing and upgrade tasks.
/// </summary>
[InitializeOnLoad]
public class GPGSUpgrader
{
/// <summary>
/// Initializes static members of the <see cref="GooglePlayGames.GPGSUpgrader"/> class.
/// </summary>
static GPGSUpgrader()
{
string prevVer = GPGSProjectSettings.Instance.Get(GPGSUtil.LASTUPGRADEKEY, "00000");
if (!prevVer.Equals(PluginVersion.VersionKey))
{
// if this is a really old version, upgrade to 911 first, then 915
if (!prevVer.Equals(PluginVersion.VersionKeyCPP))
{
prevVer = Upgrade911(prevVer);
}
prevVer = Upgrade915(prevVer);
prevVer = Upgrade927Patch(prevVer);
// Upgrade to remove gpg version of jar resolver
prevVer = Upgrade928(prevVer);
prevVer = Upgrade930(prevVer);
prevVer = Upgrade931(prevVer);
prevVer = Upgrade935(prevVer);
// there is no migration needed to 930+
if (!prevVer.Equals(PluginVersion.VersionKey))
{
Debug.Log("Upgrading from format version " + prevVer + " to " + PluginVersion.VersionKey);
prevVer = PluginVersion.VersionKey;
}
string msg = GPGSStrings.PostInstall.Text.Replace(
"$VERSION",
PluginVersion.VersionString);
EditorUtility.DisplayDialog(GPGSStrings.PostInstall.Title, msg, "OK");
}
GPGSProjectSettings.Instance.Set(GPGSUtil.LASTUPGRADEKEY, prevVer);
GPGSProjectSettings.Instance.Set(GPGSUtil.PLUGINVERSIONKEY,
PluginVersion.VersionString);
GPGSProjectSettings.Instance.Save();
// clean up duplicate scripts if Unity 5+
int ver = GPGSUtil.GetUnityMajorVersion();
if (ver >= 5)
{
string[] paths =
{
"Assets/GooglePlayGames",
"Assets/Plugins/Android",
"Assets/PlayServicesResolver"
};
foreach (string p in paths)
{
CleanDuplicates(p);
}
// remove support lib from old location.
string jarFile =
"Assets/Plugins/Android/libs/android-support-v4.jar";
if (File.Exists(jarFile))
{
File.Delete(jarFile);
}
// remove the massive play services client lib
string clientDir = "Assets/Plugins/Android/google-play-services_lib";
GPGSUtil.DeleteDirIfExists(clientDir);
}
// Check that there is a AndroidManifest.xml file
if (!GPGSUtil.AndroidManifestExists())
{
GPGSUtil.GenerateAndroidManifest();
}
AssetDatabase.Refresh();
}
/// <summary>
/// Cleans the duplicate files. There should not be any since
/// we are keeping track of the .meta files.
/// </summary>
/// <param name="root">Root of the directory to clean.</param>
private static void CleanDuplicates(string root)
{
string[] subDirs = Directory.GetDirectories(root);
// look for .1 and .2
string[] dups = Directory.GetFiles(root, "* 1.*");
foreach (string d in dups)
{
Debug.Log("Deleting duplicate file: " + d);
File.Delete(d);
}
dups = Directory.GetFiles(root, "* 2.*");
foreach (string d in dups)
{
Debug.Log("Deleting duplicate file: " + d);
File.Delete(d);
}
// recurse
foreach (string s in subDirs)
{
CleanDuplicates(s);
}
}
/// <summary>
/// Upgrade to 0.9.35
/// </summary>
/// <remarks>
/// This cleans up some unused files mostly related to the improved jar resolver.
/// </remarks>
/// <param name="prevVer">Previous ver.</param>
private static string Upgrade935(string prevVer)
{
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/Editor/CocoaPodHelper.cs",
"Assets/GooglePlayGames/Editor/CocoaPodHelper.cs.meta",
"Assets/GooglePlayGames/Editor/GPGSInstructionWindow.cs",
"Assets/GooglePlayGames/Editor/GPGSInstructionWindow.cs.meta",
"Assets/GooglePlayGames/Editor/Podfile.txt",
"Assets/GooglePlayGames/Editor/Podfile.txt.meta",
"Assets/GooglePlayGames/Editor/cocoapod_instructions",
"Assets/GooglePlayGames/Editor/cocoapod_instructions.meta",
"Assets/GooglePlayGames/Editor/ios_instructions",
"Assets/GooglePlayGames/Editor/ios_instructions.meta",
"Assets/PlayServicesResolver/Editor/DefaultResolver.cs",
"Assets/PlayServicesResolver/Editor/DefaultResolver.cs.meta",
"Assets/PlayServicesResolver/Editor/IResolver.cs",
"Assets/PlayServicesResolver/Editor/IResolver.cs.meta",
"Assets/PlayServicesResolver/Editor/JarResolverLib.dll",
"Assets/PlayServicesResolver/Editor/JarResolverLib.dll.meta",
"Assets/PlayServicesResolver/Editor/PlayServicesResolver.cs",
"Assets/PlayServicesResolver/Editor/PlayServicesResolver.cs.meta",
"Assets/PlayServicesResolver/Editor/ResolverVer1_1.cs",
"Assets/PlayServicesResolver/Editor/ResolverVer1_1.cs.meta",
"Assets/PlayServicesResolver/Editor/SampleDependencies.cs",
"Assets/PlayServicesResolver/Editor/SampleDependencies.cs.meta",
"Assets/PlayServicesResolver/Editor/SettingsDialog.cs",
"Assets/PlayServicesResolver/Editor/SettingsDialog.cs.meta",
"Assets/Plugins/Android/play-services-plus-8.4.0.aar",
"Assets/PlayServicesResolver/Editor/play-services-plus-8.4.0.aar.meta",
// not an obsolete file, but delete the cache since the schema changed.
"ProjectSettings/GoogleDependencyGooglePlayGames.xml"
};
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
return PluginVersion.VersionKey;
}
/// <summary>
/// Upgrade to 0.9.31
/// </summary>
/// <remarks>
/// This cleans up some unused files.
/// </remarks>
/// <param name="prevVer">Previous ver.</param>
private static string Upgrade931(string prevVer)
{
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/Editor/GPGSExportPackageUI.cs",
"Assets/GooglePlayGames/Editor/GPGSExportPackageUI.cs.meta"
};
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
return PluginVersion.VersionKey;
}
/// <summary>
/// Upgrade to 930 from the specified prevVer.
/// </summary>
/// <param name="prevVer">Previous ver.</param>
/// <returns>the version string upgraded to.</returns>
private static string Upgrade930(string prevVer)
{
Debug.Log("Upgrading from format version " + prevVer + " to " + PluginVersion.VersionKeyNativeCRM);
// As of 930, the CRM API is handled by the Native SDK, not GmsCore.
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Games.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Games.cs.meta",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/LoadPlayerStatsResultObject.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/LoadPlayerStatsResultObject.cs.meta",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/PlayerStats.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/PlayerStats.cs.meta",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/PlayerStatsObject.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/PlayerStatsObject.cs.meta",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/Stats.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/Stats.cs.meta",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/StatsObject.cs",
"Assets/GooglePlayGames/Platforms/Android/Gms/Games/Stats/StatsObject.cs.meta"
};
// only delete these if we are not version 0.9.34
if (string.Compare(PluginVersion.VersionKey, PluginVersion.VersionKeyJNIStats,
System.StringComparison.Ordinal) <= 0)
{
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
}
return PluginVersion.VersionKeyNativeCRM;
}
private static string Upgrade928(string prevVer)
{
//remove the jar resolver and if found, then
// warn the user that restarting the editor is required.
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/Editor/JarResolverLib.dll",
"Assets/GooglePlayGames/Editor/JarResolverLib.dll.meta",
"Assets/GooglePlayGames/Editor/BackgroundResolution.cs",
"Assets/GooglePlayGames/Editor/BackgroundResolution.cs.meta"
};
bool found = File.Exists(obsoleteFiles[0]);
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
if (found)
{
GPGSUtil.Alert("This update made changes that requires that you restart the editor");
}
Debug.Log("Upgrading from version " + prevVer + " to " + PluginVersion.VersionKeyJarResolver);
return PluginVersion.VersionKeyJarResolver;
}
/// <summary>
/// Upgrade to 0.9.27a.
/// </summary>
/// <remarks>This removes the GPGGizmo class, which broke the editor</remarks>
/// <returns>The patched version</returns>
/// <param name="prevVer">Previous version</param>
private static string Upgrade927Patch(string prevVer)
{
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/Editor/GPGGizmo.cs",
"Assets/GooglePlayGames/Editor/GPGGizmo.cs.meta",
"Assets/GooglePlayGames/BasicApi/OnStateLoadedListener.cs",
"Assets/GooglePlayGames/BasicApi/OnStateLoadedListener.cs.meta",
"Assets/GooglePlayGames/Platforms/Native/AndroidAppStateClient.cs",
"Assets/GooglePlayGames/Platforms/Native/AndroidAppStateClient.cs.meta",
"Assets/GooglePlayGames/Platforms/Native/UnsupportedAppStateClient.cs",
"Assets/GooglePlayGames/Platforms/Native/UnsupportedAppStateClient.cs.meta"
};
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
return PluginVersion.VersionKey27Patch;
}
/// <summary>
/// Upgrade to 915 from the specified prevVer.
/// </summary>
/// <param name="prevVer">Previous ver.</param>
/// <returns>the version string upgraded to.</returns>
private static string Upgrade915(string prevVer)
{
Debug.Log("Upgrading from format version " + prevVer + " to " + PluginVersion.VersionKeyU5);
// all that was done was moving the Editor files to be in GooglePlayGames/Editor
string[] obsoleteFiles =
{
"Assets/Editor/GPGSAndroidSetupUI.cs",
"Assets/Editor/GPGSAndroidSetupUI.cs.meta",
"Assets/Editor/GPGSDocsUI.cs",
"Assets/Editor/GPGSDocsUI.cs.meta",
"Assets/Editor/GPGSIOSSetupUI.cs",
"Assets/Editor/GPGSIOSSetupUI.cs.meta",
"Assets/Editor/GPGSInstructionWindow.cs",
"Assets/Editor/GPGSInstructionWindow.cs.meta",
"Assets/Editor/GPGSPostBuild.cs",
"Assets/Editor/GPGSPostBuild.cs.meta",
"Assets/Editor/GPGSProjectSettings.cs",
"Assets/Editor/GPGSProjectSettings.cs.meta",
"Assets/Editor/GPGSStrings.cs",
"Assets/Editor/GPGSStrings.cs.meta",
"Assets/Editor/GPGSUpgrader.cs",
"Assets/Editor/GPGSUpgrader.cs.meta",
"Assets/Editor/GPGSUtil.cs",
"Assets/Editor/GPGSUtil.cs.meta",
"Assets/Editor/GameInfo.template",
"Assets/Editor/GameInfo.template.meta",
"Assets/Editor/PlistBuddyHelper.cs",
"Assets/Editor/PlistBuddyHelper.cs.meta",
"Assets/Editor/PostprocessBuildPlayer",
"Assets/Editor/PostprocessBuildPlayer.meta",
"Assets/Editor/ios_instructions",
"Assets/Editor/ios_instructions.meta",
"Assets/Editor/projsettings.txt",
"Assets/Editor/projsettings.txt.meta",
"Assets/Editor/template-AndroidManifest.txt",
"Assets/Editor/template-AndroidManifest.txt.meta",
"Assets/Plugins/Android/libs/armeabi/libgpg.so",
"Assets/Plugins/Android/libs/armeabi/libgpg.so.meta",
"Assets/Plugins/iOS/GPGSAppController 1.h",
"Assets/Plugins/iOS/GPGSAppController 1.h.meta",
"Assets/Plugins/iOS/GPGSAppController 1.mm",
"Assets/Plugins/iOS/GPGSAppController 1.mm.meta"
};
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
return PluginVersion.VersionKeyU5;
}
/// <summary>
/// Upgrade to 911 from the specified prevVer.
/// </summary>
/// <param name="prevVer">Previous ver.</param>
/// <returns>the version string upgraded to.</returns>
private static string Upgrade911(string prevVer)
{
Debug.Log("Upgrading from format version " + prevVer + " to " + PluginVersion.VersionKeyCPP);
// delete obsolete files, if they are there
string[] obsoleteFiles =
{
"Assets/GooglePlayGames/OurUtils/Utils.cs",
"Assets/GooglePlayGames/OurUtils/Utils.cs.meta",
"Assets/GooglePlayGames/OurUtils/MyClass.cs",
"Assets/GooglePlayGames/OurUtils/MyClass.cs.meta",
"Assets/Plugins/GPGSUtils.dll",
"Assets/Plugins/GPGSUtils.dll.meta",
};
foreach (string file in obsoleteFiles)
{
if (File.Exists(file))
{
Debug.Log("Deleting obsolete file: " + file);
File.Delete(file);
}
}
// delete obsolete directories, if they are there
string[] obsoleteDirectories =
{
"Assets/Plugins/Android/BaseGameUtils"
};
foreach (string directory in obsoleteDirectories)
{
if (Directory.Exists(directory))
{
Debug.Log("Deleting obsolete directory: " + directory);
Directory.Delete(directory, true);
}
}
Debug.Log("Done upgrading from format version " + prevVer + " to " + PluginVersion.VersionKeyCPP);
return PluginVersion.VersionKeyCPP;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace NDatabase.TypeResolution
{
/// <summary>
/// Holder for the generic arguments when using type parameters.
/// </summary>
/// <remarks>
/// <p>
/// Type parameters can be applied to classes, interfaces,
/// structures, methods, delegates, etc...
/// </p>
/// </remarks>
internal sealed class GenericArgumentsHolder
{
private static readonly Regex ClrPattern = new Regex(
"^"
+ @"(?'name'\w[\w\d\.]+)"
+ @"`\d+\s*\["
+ @"(?'args'(?>[^\[\]]+|\[(?<DEPTH>)|\](?<-DEPTH>))*(?(DEPTH)(?!)))"
+ @"\]"
+ @"(?'remainder'.*)"
+ @"$"
, RegexOptions.CultureInvariant | RegexOptions.Compiled
);
private static readonly Regex CSharpPattern = new Regex(
"^"
+ @"(?'name'\w[\w\d\.]+)"
+ @"<"
+ @"(?'args'.*)"
+ @">"
+ @"(?'remainder'.*)"
+ @"$"
, RegexOptions.CultureInvariant | RegexOptions.Compiled
);
private string _arrayDeclaration;
private string[] _unresolvedGenericArguments;
private string _unresolvedGenericTypeName;
/// <summary>
/// Creates a new instance of the GenericArgumentsHolder class.
/// </summary>
/// <param name="value">
/// The string value to parse looking for a generic definition
/// and retrieving its generic arguments.
/// </param>
public GenericArgumentsHolder(string value)
{
ParseGenericTypeDeclaration(value);
}
/// <summary>
/// The (unresolved) generic type name portion
/// of the original value when parsing a generic type.
/// </summary>
public string GetGenericTypeName()
{
return _unresolvedGenericTypeName;
}
/// <summary>
/// Is the string value contains generic arguments ?
/// </summary>
/// <remarks>
/// <p>
/// A generic argument can be a type parameter or a type argument.
/// </p>
/// </remarks>
public bool ContainsGenericArguments
{
get
{
return (_unresolvedGenericArguments != null &&
_unresolvedGenericArguments.Length > 0);
}
}
/// <summary>
/// Is generic arguments only contains type parameters ?
/// </summary>
public bool IsGenericDefinition
{
get { return _unresolvedGenericArguments != null && _unresolvedGenericArguments.All(arg => arg.Length <= 0); }
}
/// <summary>
/// Is this an array type definition?
/// </summary>
public bool IsArrayDeclaration
{
get { return _arrayDeclaration != null; }
}
/// <summary>
/// Returns the array declaration portion of the definition, e.g. "[,]"
/// </summary>
/// <returns></returns>
public string GetArrayDeclaration()
{
return _arrayDeclaration;
}
/// <summary>
/// Returns an array of unresolved generic arguments types.
/// </summary>
/// <remarks>
/// <p>
/// A empty string represents a type parameter that
/// did not have been substituted by a specific type.
/// </p>
/// </remarks>
/// <returns>
/// An array of strings that represents the unresolved generic
/// arguments types or an empty array if not generic.
/// </returns>
public string[] GetGenericArguments()
{
return _unresolvedGenericArguments ?? Enumerable.Empty<string>().ToArray();
}
private void ParseGenericTypeDeclaration(string originalString)
{
if (originalString.IndexOf('[') == -1 && originalString.IndexOf('<') == -1)
{
// nothing to do
_unresolvedGenericTypeName = originalString;
return;
}
originalString = originalString.Trim();
var isClrStyleNotation = originalString.IndexOf('`') > -1;
var match = (isClrStyleNotation)
? ClrPattern.Match(originalString)
: CSharpPattern.Match(originalString);
if (!match.Success)
{
_unresolvedGenericTypeName = originalString;
return;
}
var @group = match.Groups["args"];
_unresolvedGenericArguments = ParseGenericArgumentList(@group.Value);
var name = match.Groups["name"].Value;
var remainder = match.Groups["remainder"].Value.Trim();
// check, if we're dealing with an array type declaration
if (remainder.Length > 0 && remainder.IndexOf('[') > -1)
{
var remainderParts = Split(remainder, ",", false, false, "[]");
var arrayPart = remainderParts[0].Trim();
if (arrayPart[0] == '[' && arrayPart[arrayPart.Length - 1] == ']')
{
_arrayDeclaration = arrayPart;
remainder = ", " + string.Join(",", remainderParts, 1, remainderParts.Length - 1);
}
}
_unresolvedGenericTypeName = name + "`" + _unresolvedGenericArguments.Length + remainder;
}
private static string[] ParseGenericArgumentList(string originalArgs)
{
var args = Split(originalArgs, ",", true, false, "[]<>");
// remove quotes if necessary
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.Length > 1 && arg[0] == '[')
{
args[i] = arg.Substring(1, arg.Length - 2);
}
}
return args;
}
/// <summary>
/// Tokenize the given <see cref="System.String" /> into a
/// <see cref="System.String" /> array.
/// </summary>
/// <remarks>
/// <p>
/// If <paramref name="s" /> is <see langword="null" />, returns an empty
/// <see cref="System.String" /> array.
/// </p>
/// <p>
/// If <paramref name="delimiters" /> is <see langword="null" /> or the empty
/// <see cref="System.String" />, returns a <see cref="System.String" /> array with one
/// element: <paramref name="s" /> itself.
/// </p>
/// </remarks>
/// <param name="s">
/// The <see cref="System.String" /> to tokenize.
/// </param>
/// <param name="delimiters">
/// The delimiter characters, assembled as a <see cref="System.String" />.
/// </param>
/// <param name="trimTokens">
/// Trim the tokens via <see cref="System.String.Trim()" />.
/// </param>
/// <param name="ignoreEmptyTokens">
/// Omit empty tokens from the result array.
/// </param>
/// <param name="quoteChars">
/// Pairs of quote characters. <paramref name="delimiters" /> within a pair of quotes are ignored
/// </param>
/// <returns>An array of the tokens.</returns>
private static string[] Split(
string s, string delimiters, bool trimTokens, bool ignoreEmptyTokens, string quoteChars)
{
if (s == null)
return new string[0];
if (string.IsNullOrEmpty(delimiters))
return new[] {s};
if (quoteChars == null)
quoteChars = string.Empty;
if (quoteChars.Length%2 != 0)
throw new ArgumentException("the number of quote characters must be even", "quoteChars");
var delimiterChars = delimiters.ToCharArray();
// scan separator positions
var delimiterPositions = new int[s.Length];
var count = MakeDelimiterPositionList(s, delimiterChars, quoteChars, delimiterPositions);
var tokens = new List<string>(count + 1);
var startIndex = 0;
for (var ixSep = 0; ixSep < count; ixSep++)
{
var token = s.Substring(startIndex, delimiterPositions[ixSep] - startIndex);
if (trimTokens)
{
token = token.Trim();
}
if (!(ignoreEmptyTokens && token.Length == 0))
{
tokens.Add(token);
}
startIndex = delimiterPositions[ixSep] + 1;
}
// add remainder
if (startIndex < s.Length)
{
var token = s.Substring(startIndex);
if (trimTokens)
{
token = token.Trim();
}
if (!(ignoreEmptyTokens && token.Length == 0))
{
tokens.Add(token);
}
}
else if (startIndex == s.Length)
{
if (!(ignoreEmptyTokens))
{
tokens.Add(string.Empty);
}
}
return tokens.ToArray();
}
private static int MakeDelimiterPositionList(string s, char[] delimiters, string quoteChars,
int[] delimiterPositions)
{
var count = 0;
var quoteNestingDepth = 0;
var expectedQuoteOpenChar = '\0';
var expectedQuoteCloseChar = '\0';
for (var ixCurChar = 0; ixCurChar < s.Length; ixCurChar++)
{
var curChar = s[ixCurChar];
foreach (var token in delimiters)
{
if (token == curChar)
{
if (quoteNestingDepth == 0)
{
delimiterPositions[count] = ixCurChar;
count++;
break;
}
}
if (quoteNestingDepth == 0)
{
// check, if we're facing an opening char
for (var ixCurQuoteChar = 0; ixCurQuoteChar < quoteChars.Length; ixCurQuoteChar += 2)
{
if (quoteChars[ixCurQuoteChar] == curChar)
{
quoteNestingDepth++;
expectedQuoteOpenChar = curChar;
expectedQuoteCloseChar = quoteChars[ixCurQuoteChar + 1];
break;
}
}
}
else
{
// check if we're facing an expected open or close char
if (curChar == expectedQuoteOpenChar)
{
quoteNestingDepth++;
}
else if (curChar == expectedQuoteCloseChar)
{
quoteNestingDepth--;
}
}
}
}
return count;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.IO;
namespace LMI
{
public class Kernel
{
[STAThread]
static void Main(string[] args)
{
Kernel myLMI = new Kernel();
Console.WriteLine(myLMI.GetProcesses());
while (true)
{
string query = Console.ReadLine();
foreach(string s in myLMI.GetCollectionHw(query))
Console.WriteLine(s);
}
}
private XmlDocument xmldoc;
public Kernel()
{
xmldoc = new XmlDocument();
Console.Write("Load XML: ");
xmldoc.Load(Console.ReadLine());
}
#region PUBLIC
public string[] GetCollectionHw(string query)
{
string[] toret = null;
string temp = GetValueHw(query);
if (temp.IndexOf("|") > 0)
toret = temp.Substring(0, temp.Length-1).Split('|');
else
{
toret = new string[1];
toret[0] = "-";
}
return toret;
}
public string GetValueHw(string query)
{
string temp = string.Empty;
switch (query)
{
case "Processor":
foreach (XmlNode xnodem in xmldoc.ChildNodes[2].ChildNodes)
if(xnodem.Name == "node")
foreach (XmlNode xnode in xnodem.ChildNodes)
if(xnode.Name == "node" && xnode.HasChildNodes && xnode.Attributes["class"].InnerText == "processor")
{
string name = "";
string speed = "0";
foreach (XmlNode xnode2 in xnode.ChildNodes)
{
if (xnode2.Name == "product")
name = xnode2.InnerText;
if (xnode2.Name == "size")
speed = xnode2.InnerText;
}
temp += name+" "+ formatSpeed(Convert.ToInt64(speed)/1000000) +"|";
}
break;
case "Video":
foreach (XmlNode xnodem in xmldoc.ChildNodes[2].ChildNodes)
if(xnodem.Name == "node")
foreach (XmlNode xnode in xnodem.ChildNodes)
if(xnode.Name == "node" && xnode.HasChildNodes && xnode.Attributes["class"].InnerText == "bridge")
foreach (XmlNode xnode2 in xnode.ChildNodes)
if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "display")
{
temp += xnode2.ChildNodes[2].InnerText+" "+xnode2.ChildNodes[1].InnerText+"|";
}
else if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "bridge")
{
foreach (XmlNode xnode3 in xnode2.ChildNodes)
if (xnode3.Name == "node" && xnode3.Attributes["class"].InnerText == "display")
temp += xnode3.ChildNodes[2].InnerText+" "+xnode3.ChildNodes[1].InnerText+"|";
}
break;
case "NIC":
foreach (XmlNode xnodem in xmldoc.ChildNodes[2].ChildNodes)
if(xnodem.Name == "node")
foreach (XmlNode xnode in xnodem.ChildNodes)
if(xnode.Name == "node" && xnode.HasChildNodes && xnode.Attributes["class"].InnerText == "bridge")
foreach (XmlNode xnode2 in xnode.ChildNodes)
if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "network")
{// Fix to add mac address
temp += xnode2.ChildNodes[2].InnerText+" "+xnode2.ChildNodes[1].InnerText+" ("+ xnode2.ChildNodes[3].InnerText +")|";
}
else if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "bridge")
{
foreach (XmlNode xnode3 in xnode2.ChildNodes)
if (xnode3.Name == "node" && xnode3.Attributes["class"].InnerText == "network")
temp += xnode3.ChildNodes[2].InnerText+" "+xnode3.ChildNodes[1].InnerText+" ("+ xnode3.ChildNodes[3].InnerText +")|";
}
break;
case "CDROMDrive":
foreach (XmlNode xnodem in xmldoc.ChildNodes[2].ChildNodes)
if(xnodem.Name == "node")
foreach (XmlNode xnode in xnodem.ChildNodes)
if(xnode.Name == "node" && xnode.HasChildNodes && xnode.Attributes["class"].InnerText == "bridge")
foreach (XmlNode xnode2 in xnode.ChildNodes)
if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "storage")
foreach (XmlNode xnode3 in xnode2.ChildNodes)
if (xnode3.Name == "node" && xnode3.Attributes["class"].InnerText == "bus")
foreach (XmlNode xnode4 in xnode3.ChildNodes)
if (xnode4.Name == "node" && xnode4.Attributes["class"].InnerText == "disk" && xnode4.Attributes["id"].InnerText.Substring(0, 1) == "c")
temp += xnode4.ChildNodes[1].InnerText+"|";
break;
case "HardDrive":
foreach (XmlNode xnodem in xmldoc.ChildNodes[2].ChildNodes)
if(xnodem.Name == "node")
foreach (XmlNode xnode in xnodem.ChildNodes)
if(xnode.Name == "node" && xnode.HasChildNodes && xnode.Attributes["class"].InnerText == "bridge")
foreach (XmlNode xnode2 in xnode.ChildNodes)
if (xnode2.Name == "node" && xnode2.Attributes["class"].InnerText == "storage")
foreach (XmlNode xnode3 in xnode2.ChildNodes)
if (xnode3.Name == "node" && xnode3.Attributes["class"].InnerText == "bus")
foreach (XmlNode xnode4 in xnode3.ChildNodes)
if (xnode4.Name == "node" && xnode4.Attributes["class"].InnerText == "disk" && xnode4.Attributes["id"].InnerText.Substring(0, 1) == "d")
temp += xnode4.ChildNodes[1].InnerText+"|";
break;
case "System.Model":
foreach (XmlNode xnode in xmldoc.ChildNodes[2].ChildNodes)
if(xnode.Name == "product")
temp = xnode.InnerText+"|";
break;
case "System.Manufacturer":
foreach (XmlNode xnode in xmldoc.ChildNodes[2].ChildNodes)
if(xnode.Name == "vendor")
temp = xnode.InnerText+"|";
break;
case "System.SerialNumber":
foreach (XmlNode xnode in xmldoc.ChildNodes[2].ChildNodes)
if(xnode.Name == "serial")
temp = xnode.InnerText+"|";
break;
}
return temp;
}
public string GetProcesses()
{
// ProcessStartInfo psi = new ProcessStartInfo("c:\\do.bat"); // FOR WINDOWS
// psi.WindowStyle = ProcessWindowStyle.Hidden; // FOR WINDOWS =S
// ProcessStartInfo psi = new ProcessStartInfo("sh", "/usr/bin/CWD/pss.sh"); // FOR LINUX
// psi.UseShellExecute = false; // FOR MONO =S
// Process.Start(psi);
FileStream fs = new FileStream("c:\\temp.lst",FileMode.Open); // FOR WINDOWS
// FileStream fs = new FileStream("/tmp/temp.lst",FileMode.Open); // FOR LINUX
byte[] buf = new byte[fs.Length];
fs.Read(buf,0,buf.Length);
string[] prs = System.Text.ASCIIEncoding.ASCII.GetString(buf).Split('\n');
string toret = string.Empty;
foreach (string tprs in prs)
{
string tp = tprs;
tp = tp.TrimEnd(' ');
if(tp.Length > 50)
{
//XML output
toret += "<user>" + tp.Substring(0, 10).Trim() + "</user><pid>" + tp.Substring(11,4).Trim() + "</pid><name>" + tp.Substring(48, tp.Length-51).Trim() + "</name>\n";
//toret += tp.Substring(0, 10).Trim() + "|" + tp.Substring(11,4).Trim() + "|" + tp.Substring(48, tp.Length-51).Trim() + "&";
}
}
return toret;
}
/* public string[] GetCollectionPr()
{
string[] stmp;
string[] toret = null;
string temp = GetProcesses();
if (temp.IndexOf("&") > 0)
stmp = temp.Substring(0, temp.Length-1).Split('|');
// toret =
else
{
toret[0] = "-";
}
return toret;
}*/
#endregion
#region PRIVATE
private string formatSize(Int64 lSize, bool booleanFormatOnly)
{
string stringSize = "";
NumberFormatInfo myNfi = new NumberFormatInfo();
Int64 lKBSize = 0;
if (lSize < 1024 )
{
if (lSize == 0)
stringSize = "0";
else
stringSize = "1";
}
else
{
if (booleanFormatOnly == false)
lKBSize = lSize / 1024;
else
lKBSize = lSize;
stringSize = lKBSize.ToString("n",myNfi);
stringSize = stringSize.Replace(".00", "");
}
return stringSize + " KB";
}
private string formatSpeed(Int64 lSpeed)
{
float floatSpeed = 0;
string stringSpeed = "";
NumberFormatInfo myNfi = new NumberFormatInfo();
if (lSpeed < 1000 )
{
stringSpeed = lSpeed.ToString() + "MHz";
}
else
{
floatSpeed = (float) lSpeed / 1000;
stringSpeed = floatSpeed.ToString() + "GHz";
}
return stringSpeed;
}
#endregion
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public interface IAssemblyResolver : IDisposable {
AssemblyDefinition Resolve (AssemblyNameReference name);
AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters);
}
public interface IMetadataResolver {
TypeDefinition Resolve (TypeReference type);
FieldDefinition Resolve (FieldReference field);
MethodDefinition Resolve (MethodReference method);
}
#if !NET_CORE
[Serializable]
#endif
public sealed class ResolutionException : Exception {
readonly MemberReference member;
public MemberReference Member {
get { return member; }
}
public IMetadataScope Scope {
get {
var type = member as TypeReference;
if (type != null)
return type.Scope;
var declaring_type = member.DeclaringType;
if (declaring_type != null)
return declaring_type.Scope;
throw new NotSupportedException ();
}
}
public ResolutionException (MemberReference member)
: base ("Failed to resolve " + member.FullName)
{
if (member == null)
throw new ArgumentNullException ("member");
this.member = member;
}
public ResolutionException (MemberReference member, Exception innerException)
: base ("Failed to resolve " + member.FullName, innerException)
{
if (member == null)
throw new ArgumentNullException ("member");
this.member = member;
}
#if !NET_CORE
ResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
public class MetadataResolver : IMetadataResolver {
readonly IAssemblyResolver assembly_resolver;
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
}
public MetadataResolver (IAssemblyResolver assemblyResolver)
{
if (assemblyResolver == null)
throw new ArgumentNullException ("assemblyResolver");
assembly_resolver = assemblyResolver;
}
public virtual TypeDefinition Resolve (TypeReference type)
{
Mixin.CheckType (type);
type = type.GetElementType ();
var scope = type.Scope;
if (scope == null)
return null;
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
var assembly = assembly_resolver.Resolve ((AssemblyNameReference) scope);
if (assembly == null)
return null;
return GetType (assembly.MainModule, type);
case MetadataScopeType.ModuleDefinition:
return GetType ((ModuleDefinition) scope, type);
case MetadataScopeType.ModuleReference:
if (type.Module.Assembly == null)
return null;
var modules = type.Module.Assembly.Modules;
var module_ref = (ModuleReference) scope;
for (int i = 0; i < modules.Count; i++) {
var netmodule = modules [i];
if (netmodule.Name == module_ref.Name)
return GetType (netmodule, type);
}
break;
}
throw new NotSupportedException ();
}
static TypeDefinition GetType (ModuleDefinition module, TypeReference reference)
{
var type = GetTypeDefinition (module, reference);
if (type != null)
return type;
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++) {
var exported_type = exported_types [i];
if (exported_type.Name != reference.Name)
continue;
if (exported_type.Namespace != reference.Namespace)
continue;
return exported_type.Resolve ();
}
return null;
}
static TypeDefinition GetTypeDefinition (ModuleDefinition module, TypeReference type)
{
if (!type.IsNested)
return module.GetType (type.Namespace, type.Name);
var declaring_type = type.DeclaringType.Resolve ();
if (declaring_type == null)
return null;
return declaring_type.GetNestedType (type.TypeFullName ());
}
public virtual FieldDefinition Resolve (FieldReference field)
{
Mixin.CheckField (field);
var type = Resolve (field.DeclaringType);
if (type == null)
return null;
if (!type.HasFields)
return null;
return GetField (type, field);
}
FieldDefinition GetField (TypeDefinition type, FieldReference reference)
{
while (type != null) {
var field = GetField (type.Fields, reference);
if (field != null)
return field;
if (type.BaseType == null)
return null;
type = Resolve (type.BaseType);
}
return null;
}
static FieldDefinition GetField (Collection<FieldDefinition> fields, FieldReference reference)
{
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (field.Name != reference.Name)
continue;
if (!AreSame (field.FieldType, reference.FieldType))
continue;
return field;
}
return null;
}
public virtual MethodDefinition Resolve (MethodReference method)
{
Mixin.CheckMethod (method);
var type = Resolve (method.DeclaringType);
if (type == null)
return null;
method = method.GetElementMethod ();
if (!type.HasMethods)
return null;
return GetMethod (type, method);
}
MethodDefinition GetMethod (TypeDefinition type, MethodReference reference)
{
while (type != null) {
var method = GetMethod (type.Methods, reference);
if (method != null)
return method;
if (type.BaseType == null)
return null;
type = Resolve (type.BaseType);
}
return null;
}
public static MethodDefinition GetMethod (Collection<MethodDefinition> methods, MethodReference reference)
{
for (int i = 0; i < methods.Count; i++) {
var method = methods [i];
if (method.Name != reference.Name)
continue;
if (method.HasGenericParameters != reference.HasGenericParameters)
continue;
if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)
continue;
if (!AreSame (method.ReturnType, reference.ReturnType))
continue;
if (method.IsVarArg () != reference.IsVarArg ())
continue;
if (method.IsVarArg () && IsVarArgCallTo (method, reference))
return method;
if (method.HasParameters != reference.HasParameters)
continue;
if (!method.HasParameters && !reference.HasParameters)
return method;
if (!AreSame (method.Parameters, reference.Parameters))
continue;
return method;
}
return null;
}
static bool AreSame (Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)
{
var count = a.Count;
if (count != b.Count)
return false;
if (count == 0)
return true;
for (int i = 0; i < count; i++)
if (!AreSame (a [i].ParameterType, b [i].ParameterType))
return false;
return true;
}
static bool IsVarArgCallTo (MethodDefinition method, MethodReference reference)
{
if (method.Parameters.Count >= reference.Parameters.Count)
return false;
if (reference.GetSentinelPosition () != method.Parameters.Count)
return false;
for (int i = 0; i < method.Parameters.Count; i++)
if (!AreSame (method.Parameters [i].ParameterType, reference.Parameters [i].ParameterType))
return false;
return true;
}
static bool AreSame (TypeSpecification a, TypeSpecification b)
{
if (!AreSame (a.ElementType, b.ElementType))
return false;
if (a.IsGenericInstance)
return AreSame ((GenericInstanceType) a, (GenericInstanceType) b);
if (a.IsRequiredModifier || a.IsOptionalModifier)
return AreSame ((IModifierType) a, (IModifierType) b);
if (a.IsArray)
return AreSame ((ArrayType) a, (ArrayType) b);
return true;
}
static bool AreSame (ArrayType a, ArrayType b)
{
if (a.Rank != b.Rank)
return false;
// TODO: dimensions
return true;
}
static bool AreSame (IModifierType a, IModifierType b)
{
return AreSame (a.ModifierType, b.ModifierType);
}
static bool AreSame (GenericInstanceType a, GenericInstanceType b)
{
if (a.GenericArguments.Count != b.GenericArguments.Count)
return false;
for (int i = 0; i < a.GenericArguments.Count; i++)
if (!AreSame (a.GenericArguments [i], b.GenericArguments [i]))
return false;
return true;
}
static bool AreSame (GenericParameter a, GenericParameter b)
{
return a.Position == b.Position;
}
static bool AreSame (TypeReference a, TypeReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null || b == null)
return false;
if (a.etype != b.etype)
return false;
if (a.IsGenericParameter)
return AreSame ((GenericParameter) a, (GenericParameter) b);
if (a.IsTypeSpecification ())
return AreSame ((TypeSpecification) a, (TypeSpecification) b);
if (a.Name != b.Name || a.Namespace != b.Namespace)
return false;
//TODO: check scope
return AreSame (a.DeclaringType, b.DeclaringType);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Order Product
///<para>SObject Name: OrderItem</para>
///<para>Custom Object: False</para>
///</summary>
public class SfOrderItem : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "OrderItem"; }
}
///<summary>
/// Order Product ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Product ID
/// <para>Name: Product2Id</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "product2Id")]
[Updateable(false), Createable(true)]
public string Product2Id { get; set; }
///<summary>
/// ReferenceTo: Product2
/// <para>RelationshipName: Product2</para>
///</summary>
[JsonProperty(PropertyName = "product2")]
[Updateable(false), Createable(false)]
public SfProduct2 Product2 { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Order ID
/// <para>Name: OrderId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "orderId")]
[Updateable(false), Createable(true)]
public string OrderId { get; set; }
///<summary>
/// ReferenceTo: Order
/// <para>RelationshipName: Order</para>
///</summary>
[JsonProperty(PropertyName = "order")]
[Updateable(false), Createable(false)]
public SfOrder Order { get; set; }
///<summary>
/// Price Book Entry ID
/// <para>Name: PricebookEntryId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "pricebookEntryId")]
[Updateable(false), Createable(true)]
public string PricebookEntryId { get; set; }
///<summary>
/// ReferenceTo: PricebookEntry
/// <para>RelationshipName: PricebookEntry</para>
///</summary>
[JsonProperty(PropertyName = "pricebookEntry")]
[Updateable(false), Createable(false)]
public SfPricebookEntry PricebookEntry { get; set; }
///<summary>
/// Original Order Item ID
/// <para>Name: OriginalOrderItemId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "originalOrderItemId")]
[Updateable(false), Createable(true)]
public string OriginalOrderItemId { get; set; }
///<summary>
/// ReferenceTo: OrderItem
/// <para>RelationshipName: OriginalOrderItem</para>
///</summary>
[JsonProperty(PropertyName = "originalOrderItem")]
[Updateable(false), Createable(false)]
public SfOrderItem OriginalOrderItem { get; set; }
///<summary>
/// Available Quantity
/// <para>Name: AvailableQuantity</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "availableQuantity")]
[Updateable(false), Createable(false)]
public double? AvailableQuantity { get; set; }
///<summary>
/// Quantity
/// <para>Name: Quantity</para>
/// <para>SF Type: double</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "quantity")]
public double? Quantity { get; set; }
///<summary>
/// Unit Price
/// <para>Name: UnitPrice</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "unitPrice")]
public decimal? UnitPrice { get; set; }
///<summary>
/// List Price
/// <para>Name: ListPrice</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "listPrice")]
[Updateable(false), Createable(true)]
public decimal? ListPrice { get; set; }
///<summary>
/// Total Price
/// <para>Name: TotalPrice</para>
/// <para>SF Type: currency</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "totalPrice")]
[Updateable(false), Createable(false)]
public decimal? TotalPrice { get; set; }
///<summary>
/// Start Date
/// <para>Name: ServiceDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "serviceDate")]
public DateTime? ServiceDate { get; set; }
///<summary>
/// End Date
/// <para>Name: EndDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "endDate")]
public DateTime? EndDate { get; set; }
///<summary>
/// Line Description
/// <para>Name: Description</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Order Product Number
/// <para>Name: OrderItemNumber</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "orderItemNumber")]
[Updateable(false), Createable(false)]
public string OrderItemNumber { get; set; }
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A Job Release task to run on job completion on any compute node where the job has run.
/// </summary>
public partial class JobReleaseTask : ITransportObjectProvider<Models.JobReleaseTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<TimeSpan?> MaxWallClockTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<TimeSpan?> RetentionTimeProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.MaxWallClockTimeProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(MaxWallClockTime), BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write);
this.RetentionTimeProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(RetentionTime), BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobReleaseTask protocolObject) : base(BindingState.Bound)
{
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
nameof(CommandLine),
BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()),
nameof(ContainerSettings),
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
nameof(EnvironmentSettings),
BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read | BindingAccess.Write);
this.MaxWallClockTimeProperty = this.CreatePropertyAccessor(
protocolObject.MaxWallClockTime,
nameof(MaxWallClockTime),
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
nameof(ResourceFiles),
BindingAccess.Read | BindingAccess.Write);
this.RetentionTimeProperty = this.CreatePropertyAccessor(
protocolObject.RetentionTime,
nameof(RetentionTime),
BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)),
nameof(UserIdentity),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobReleaseTask"/> class.
/// </summary>
/// <param name='commandLine'>The command line of the task.</param>
public JobReleaseTask(
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.CommandLine = commandLine;
}
internal JobReleaseTask(Models.JobReleaseTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobReleaseTask
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If the command line
/// refers to file paths, it should use a relative path (relative to the task working directory), or use the Batch
/// provided environment variables (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables).
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets the settings for the container under which the task runs.
/// </summary>
/// <remarks>
/// When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch
/// directories on the node) are mapped into the container, all task environment variables are mapped into the container,
/// and the task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR
/// might not be reflected to the host disk, meaning that Batch file APIs will not be able to access them.
/// </remarks>
public TaskContainerSettings ContainerSettings
{
get { return this.propertyContainer.ContainerSettingsProperty.Value; }
set { this.propertyContainer.ContainerSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the collection of EnvironmentSetting instances.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets the maximum duration of time for which a task is allowed to run from the time it is created.
/// </summary>
public TimeSpan? MaxWallClockTime
{
get { return this.propertyContainer.MaxWallClockTimeProperty.Value; }
set { this.propertyContainer.MaxWallClockTimeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
/// <remarks>
/// There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail
/// and the response error code will be RequestEntityTooLarge. If this occurs, the collection of resource files must
/// be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.
/// </remarks>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the duration of time for which files in the task's working directory are retained, from the time
/// it completes execution. After this duration, the task's working directory is reclaimed.
/// </summary>
/// <remarks>
/// The default is 7 days, i.e. the task directory will be retained for 7 days unless the compute node is removed
/// or the job is deleted.
/// </remarks>
public TimeSpan? RetentionTime
{
get { return this.propertyContainer.RetentionTimeProperty.Value; }
set { this.propertyContainer.RetentionTimeProperty.Value = value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // JobReleaseTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobReleaseTask ITransportObjectProvider<Models.JobReleaseTask>.GetTransportObject()
{
Models.JobReleaseTask result = new Models.JobReleaseTask()
{
CommandLine = this.CommandLine,
ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()),
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
Id = this.Id,
MaxWallClockTime = this.MaxWallClockTime,
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RetentionTime = this.RetentionTime,
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory6.CSharp.Analysis;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using System;
namespace ICSharpCode.NRefactory6.CSharp.Diagnostics
{
public abstract class AccessToClosureDiagnosticAnalyzer : GatherVisitorCodeIssueProvider
{
public string Title
{ get; private set; }
protected AccessToClosureIssue(string title)
{
Title = title;
}
protected override IGatherVisitor CreateVisitor(BaseSemanticModel context)
{
var unit = context.RootNode as SyntaxTree;
if (unit == null)
return null;
return new GatherVisitor(context, unit, this);
}
protected virtual bool IsTargetVariable(IVariable variable)
{
return true;
}
protected abstract NodeKind GetNodeKind(AstNode node);
protected virtual bool CanReachModification(ControlFlowNode node, Statement start,
IDictionary<Statement, IList<Node>> modifications)
{
return node.NextStatement != null && node.NextStatement != start &&
modifications.ContainsKey(node.NextStatement);
}
protected abstract IEnumerable<CodeAction> GetFixes(BaseSemanticModel context, Node env,
string variableName);
#region GatherVisitor
class GatherVisitor : GatherVisitorBase<AccessToClosureIssue>
{
readonly ControlFlowGraphBuilder cfgBuilder = new ControlFlowGraphBuilder();
string title;
public GatherVisitor(BaseSemanticModel context, SyntaxTree unit,
AccessToClosureIssue qualifierDirectiveEvidentIssueProvider)
: base(context, qualifierDirectiveEvidentIssueProvider)
{
this.title = context.TranslateString(qualifierDirectiveEvidentIssueProvider.Title);
}
public override void VisitVariableInitializer(VariableInitializer variableInitializer)
{
var variableDecl = variableInitializer.Parent as VariableDeclarationStatement;
if (variableDecl != null)
CheckVariable(GetVariable(ctx.Resolve(variableInitializer)),
variableDecl.GetParent<Statement>());
base.VisitVariableInitializer(variableInitializer);
}
public override void VisitForeachStatement(ForeachStatement foreachStatement)
{
CheckVariable(GetVariable(ctx.Resolve(foreachStatement.VariableNameToken)),
foreachStatement);
base.VisitForeachStatement(foreachStatement);
}
public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
{
var parent = parameterDeclaration.Parent;
Statement body = null;
if (parent is MethodDeclaration)
{
body = ((MethodDeclaration)parent).Body;
}
else if (parent is AnonymousMethodExpression)
{
body = ((AnonymousMethodExpression)parent).Body;
}
else if (parent is LambdaExpression)
{
body = ((LambdaExpression)parent).Body as Statement;
}
else if (parent is ConstructorDeclaration)
{
body = ((ConstructorDeclaration)parent).Body;
}
else if (parent is OperatorDeclaration)
{
body = ((OperatorDeclaration)parent).Body;
}
if (body != null)
{
var lrr = ctx.Resolve(parameterDeclaration) as LocalResolveResult;
if (lrr != null)
CheckVariable(lrr.Variable, body);
}
base.VisitParameterDeclaration(parameterDeclaration);
}
IVariable GetVariable(ResolveResult rr)
{
var lrr = rr as LocalResolveResult;
return lrr != null ? lrr.Variable : null;
}
void CheckVariable(IVariable variable, Statement env)
{
if (variable == null)
return;
if (!issueProvider.IsTargetVariable(variable))
return;
var root = new Environment(env, env);
var envLookup = new Dictionary<AstNode, Environment>();
envLookup[env] = root;
foreach (var result in ctx.FindReferences(env, variable))
{
AddNode(envLookup, new Node(result.Node, issueProvider.GetNodeKind(result.Node)));
}
root.SortChildren();
CollectIssues(root, variable.Name);
}
void CollectIssues(Environment env, string variableName)
{
IList<ControlFlowNode> cfg = null;
IDictionary<Statement, IList<Node>> modifications = null;
if (env.Body != null)
{
try
{
cfg = cfgBuilder.BuildControlFlowGraph(env.Body);
}
catch (Exception)
{
return;
}
modifications = new Dictionary<Statement, IList<Node>>();
foreach (var node in env.Children)
{
if (node.Kind == NodeKind.Modification || node.Kind == NodeKind.ReferenceAndModification)
{
IList<Node> nodes;
if (!modifications.TryGetValue(node.ContainingStatement, out nodes))
modifications[node.ContainingStatement] = nodes = new List<Node>();
nodes.Add(node);
}
}
}
foreach (var child in env.GetChildEnvironments())
{
if (!child.IssueCollected && cfg != null &&
CanReachModification(cfg, child, modifications))
CollectAllIssues(child, variableName);
CollectIssues(child, variableName);
}
}
void CollectAllIssues(Environment env, string variableName)
{
var fixes = issueProvider.GetFixes(ctx, env, variableName).ToArray();
env.IssueCollected = true;
foreach (var child in env.Children)
{
if (child is Environment)
{
CollectAllIssues((Environment)child, variableName);
}
else
{
if (child.Kind != NodeKind.Modification)
AddDiagnosticAnalyzer(new CodeIssue(child.AstNode, title, fixes));
// stop marking references after the variable is modified in current environment
if (child.Kind != NodeKind.Reference)
break;
}
}
}
void AddNode(IDictionary<AstNode, Environment> envLookup, Node node)
{
var astParent = node.AstNode.Parent;
var path = new List<AstNode>();
while (astParent != null)
{
Environment parent;
if (envLookup.TryGetValue(astParent, out parent))
{
parent.Children.Add(node);
return;
}
if (astParent is LambdaExpression)
{
parent = new Environment(astParent, ((LambdaExpression)astParent).Body as Statement);
}
else if (astParent is AnonymousMethodExpression)
{
parent = new Environment(astParent, ((AnonymousMethodExpression)astParent).Body);
}
path.Add(astParent);
if (parent != null)
{
foreach (var astNode in path)
envLookup[astNode] = parent;
path.Clear();
parent.Children.Add(node);
node = parent;
}
astParent = astParent.Parent;
}
}
bool CanReachModification(IEnumerable<ControlFlowNode> cfg, Environment env,
IDictionary<Statement, IList<Node>> modifications)
{
if (modifications.Count == 0)
return false;
var start = env.ContainingStatement;
if (modifications.ContainsKey(start) &&
modifications[start].Any(v => v.AstNode.StartLocation > env.AstNode.EndLocation))
return true;
var stack = new Stack<ControlFlowNode>(cfg.Where(node => node.NextStatement == start));
var visitedNodes = new HashSet<ControlFlowNode>(stack);
while (stack.Count > 0)
{
var node = stack.Pop();
if (issueProvider.CanReachModification(node, start, modifications))
return true;
foreach (var edge in node.Outgoing)
{
if (visitedNodes.Add(edge.To))
stack.Push(edge.To);
}
}
return false;
}
}
#endregion
#region Node
protected enum NodeKind
{
Reference,
Modification,
ReferenceAndModification,
Environment,
}
protected class Node
{
public AstNode AstNode
{ get; private set; }
public NodeKind Kind
{ get; private set; }
public Statement ContainingStatement
{ get; private set; }
public Node(AstNode astNode, NodeKind kind)
{
AstNode = astNode;
Kind = kind;
ContainingStatement = astNode.GetParent<Statement>();
}
public virtual IEnumerable<Node> GetAllReferences()
{
yield return this;
}
}
protected class Environment : Node
{
public Statement Body
{ get; private set; }
public bool IssueCollected
{ get; set; }
public List<Node> Children
{ get; private set; }
public Environment(AstNode astNode, Statement body)
: base(astNode, NodeKind.Environment)
{
Body = body;
Children = new List<Node>();
}
public override IEnumerable<Node> GetAllReferences()
{
return Children.SelectMany(child => child.GetAllReferences());
}
public IEnumerable<Environment> GetChildEnvironments()
{
return from child in Children
where child is Environment
select (Environment)child;
}
public void SortChildren()
{
Children.Sort((x, y) => x.AstNode.StartLocation.CompareTo(y.AstNode.StartLocation));
foreach (var env in GetChildEnvironments())
env.SortChildren();
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=InputScope.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: class for input scope definition
//
// Please refer to the design specfication http://avalon/Cicero/Specifications/Stylable%20InputScope.mht
//
// History:
// 5/7/2004 : yutakan - created
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows.Input;
using System.Windows.Markup;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using MS.Internal.PresentationCore;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Input
{
///<summary>
/// InputScope class is a type which InputScope property holds. FrameworkElement.IputScope returns the current inherited InputScope
/// instance for the element
///</summary>
/// <speclink>http://avalon/Cicero/Specifications/Stylable%20InputScope.mht</speclink>
[TypeConverter("System.Windows.Input.InputScopeConverter, PresentationCore, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")]
public class InputScope
{
//
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public System.Collections.IList Names
{
get
{
return (System.Collections.IList)_scopeNames;
}
}
///<summary>
/// SrgsMarkup is currently speech specific. Will be used in non-speech
/// input methods in the near future too
///</summary>
[DefaultValue(null)]
public String SrgsMarkup
{
get
{
return _srgsMarkup;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_srgsMarkup = value;
}
}
///<summary>
/// RegularExpression is used as a suggested input text pattern
/// for input processors.
///</summary>
[DefaultValue(null)]
public String RegularExpression
{
get
{
return _regexString;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_regexString = value;
}
}
///<summary>
/// PhraseList is a collection of suggested input patterns.
/// Each phrase is of type InputScopePhrase
///</summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public System.Collections.IList PhraseList
{
get
{
return (System.Collections.IList)_phraseList;
}
}
private IList<InputScopeName> _scopeNames = new List<InputScopeName>();
private IList<InputScopePhrase> _phraseList = new List<InputScopePhrase>();
private String _regexString;
private String _srgsMarkup;
}
///<summary>
/// InputScopePhrase is a class that implements InputScopePhrase tag
/// Each InputScopePhrase represents a suggested input text pattern and ususally used to
/// form a list
///</summary>
[ContentProperty("NameValue")]
[TypeConverter("System.Windows.Input.InputScopeNameConverter, PresentationCore, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")]
public class InputScopeName : IAddChild
{
// NOTE: this is a class rather than a simple string so that we can add more hint information
// for input phrase such as typing stroke, pronouciation etc.
// should be enhanced as needed.
//---------------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------------
#region Public Methods
///<summary>
/// Default Constructor necesary for parser
///</summary>
public InputScopeName()
{
}
///<summary>
/// Constructor that takes name
///</summary>
public InputScopeName(InputScopeNameValue nameValue)
{
_nameValue = nameValue;
}
#region implementation of IAddChild
///<summary>
/// Called to Add the object as a Child. For InputScopePhrase tag this is ignored
///</summary>
///<param name="value">
/// Object to add as a child
///</param>
public void AddChild(object value)
{
throw new System.NotImplementedException();
}
/// <summary>
/// if text is present between InputScopePhrase tags, the text is added as a phrase name
/// </summary>
///<param name="name">
/// Text string to add
///</param>
public void AddText(string name)
{
// throw new System.NotImplementedException();
}
#endregion IAddChild
#endregion Public Methods
#region class public properties
///<summary>
/// Name property - this is used when accessing the string that is set to InputScopePhrase
///</summary>
public InputScopeNameValue NameValue
{
get { return _nameValue; }
set
{
if (!IsValidInputScopeNameValue(value))
{
throw new ArgumentException(SR.Get(SRID.InputScope_InvalidInputScopeName, "value"));
}
_nameValue = value;
}
}
#endregion class public properties
///<summary>
/// This validates the value for InputScopeName.
///</summary>
private bool IsValidInputScopeNameValue(InputScopeNameValue name)
{
switch (name)
{
case InputScopeNameValue.Default : break; // = 0, // IS_DEFAULT
case InputScopeNameValue.Url : break; // = 1, // IS_URL
case InputScopeNameValue.FullFilePath : break; // = 2, // IS_FILE_FULLFILEPATH
case InputScopeNameValue.FileName : break; // = 3, // IS_FILE_FILENAME
case InputScopeNameValue.EmailUserName : break; // = 4, // IS_EMAIL_USERNAME
case InputScopeNameValue.EmailSmtpAddress : break; // = 5, // IS_EMAIL_SMTPEMAILADDRESS
case InputScopeNameValue.LogOnName : break; // = 6, // IS_LOGINNAME
case InputScopeNameValue.PersonalFullName : break; // = 7, // IS_PERSONALNAME_FULLNAME
case InputScopeNameValue.PersonalNamePrefix : break; // = 8, // IS_PERSONALNAME_PREFIX
case InputScopeNameValue.PersonalGivenName : break; // = 9, // IS_PERSONALNAME_GIVENNAME
case InputScopeNameValue.PersonalMiddleName : break; // = 10, // IS_PERSONALNAME_MIDDLENAME
case InputScopeNameValue.PersonalSurname : break; // = 11, // IS_PERSONALNAME_SURNAME
case InputScopeNameValue.PersonalNameSuffix : break; // = 12, // IS_PERSONALNAME_SUFFIX
case InputScopeNameValue.PostalAddress : break; // = 13, // IS_ADDRESS_FULLPOSTALADDRESS
case InputScopeNameValue.PostalCode : break; // = 14, // IS_ADDRESS_POSTALCODE
case InputScopeNameValue.AddressStreet : break; // = 15, // IS_ADDRESS_STREET
case InputScopeNameValue.AddressStateOrProvince : break; // = 16, // IS_ADDRESS_STATEORPROVINCE
case InputScopeNameValue.AddressCity : break; // = 17, // IS_ADDRESS_CITY
case InputScopeNameValue.AddressCountryName : break; // = 18, // IS_ADDRESS_COUNTRYNAME
case InputScopeNameValue.AddressCountryShortName : break; // = 19, // IS_ADDRESS_COUNTRYSHORTNAME
case InputScopeNameValue.CurrencyAmountAndSymbol : break; // = 20, // IS_CURRENCY_AMOUNTANDSYMBOL
case InputScopeNameValue.CurrencyAmount : break; // = 21, // IS_CURRENCY_AMOUNT
case InputScopeNameValue.Date : break; // = 22, // IS_DATE_FULLDATE
case InputScopeNameValue.DateMonth : break; // = 23, // IS_DATE_MONTH
case InputScopeNameValue.DateDay : break; // = 24, // IS_DATE_DAY
case InputScopeNameValue.DateYear : break; // = 25, // IS_DATE_YEAR
case InputScopeNameValue.DateMonthName : break; // = 26, // IS_DATE_MONTHNAME
case InputScopeNameValue.DateDayName : break; // = 27, // IS_DATE_DAYNAME
case InputScopeNameValue.Digits : break; // = 28, // IS_DIGITS
case InputScopeNameValue.Number : break; // = 29, // IS_NUMBER
case InputScopeNameValue.OneChar : break; // = 30, // IS_ONECHAR
case InputScopeNameValue.Password : break; // = 31, // IS_PASSWORD
case InputScopeNameValue.TelephoneNumber : break; // = 32, // IS_TELEPHONE_FULLTELEPHONENUMBER
case InputScopeNameValue.TelephoneCountryCode : break; // = 33, // IS_TELEPHONE_COUNTRYCODE
case InputScopeNameValue.TelephoneAreaCode : break; // = 34, // IS_TELEPHONE_AREACODE
case InputScopeNameValue.TelephoneLocalNumber : break; // = 35, // IS_TELEPHONE_LOCALNUMBER
case InputScopeNameValue.Time : break; // = 36, // IS_TIME_FULLTIME
case InputScopeNameValue.TimeHour : break; // = 37, // IS_TIME_HOUR
case InputScopeNameValue.TimeMinorSec : break; // = 38, // IS_TIME_MINORSEC
case InputScopeNameValue.NumberFullWidth : break; // = 39, // IS_NUMBER_FULLWIDTH
case InputScopeNameValue.AlphanumericHalfWidth : break; // = 40, // IS_ALPHANUMERIC_HALFWIDTH
case InputScopeNameValue.AlphanumericFullWidth : break; // = 41, // IS_ALPHANUMERIC_FULLWIDTH
case InputScopeNameValue.CurrencyChinese : break; // = 42, // IS_CURRENCY_CHINESE
case InputScopeNameValue.Bopomofo : break; // = 43, // IS_BOPOMOFO
case InputScopeNameValue.Hiragana : break; // = 44, // IS_HIRAGANA
case InputScopeNameValue.KatakanaHalfWidth : break; // = 45, // IS_KATAKANA_HALFWIDTH
case InputScopeNameValue.KatakanaFullWidth : break; // = 46, // IS_KATAKANA_FULLWIDTH
case InputScopeNameValue.Hanja : break; // = 47, // IS_HANJA
case InputScopeNameValue.PhraseList : break; // = -1, // IS_PHRASELIST
case InputScopeNameValue.RegularExpression : break; // = -2, // IS_REGULAREXPRESSION
case InputScopeNameValue.Srgs : break; // = -3, // IS_SRGS
case InputScopeNameValue.Xml : break; // = -4, // IS_XML
default:
return false;
}
return true;
}
private InputScopeNameValue _nameValue;
}
///<summary>
/// InputScopePhrase is a class that implements InputScopePhrase tag
/// Each InputScopePhrase represents a suggested input text pattern and ususally used to
/// form a list
///</summary>
[ContentProperty("Name")]
public class InputScopePhrase : IAddChild
{
// NOTE: this is a class rather than a simple string so that we can add more hint information
// for input phrase such as typing stroke, pronouciation etc.
// should be enhanced as needed.
//---------------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------------
#region Public Methods
///<summary>
/// Default Constructor necesary for parser
///</summary>
public InputScopePhrase()
{
}
///<summary>
/// Constructor that takes name
///</summary>
public InputScopePhrase(String name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
_phraseName = name;
}
#region implementation of IAddChild
///<summary>
/// Called to Add the object as a Child. For InputScopePhrase tag this is ignored
///</summary>
///<param name="value">
/// Object to add as a child
///</param>
public void AddChild(object value)
{
throw new System.NotImplementedException();
}
/// <summary>
/// if text is present between InputScopePhrase tags, the text is added as a phrase name
/// </summary>
///<param name="name">
/// Text string to add
///</param>
public void AddText(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
_phraseName = name;
}
#endregion IAddChild
#endregion Public Methods
#region class public properties
///<summary>
/// Name property - this is used when accessing the string that is set to InputScopePhrase
///</summary>
public String Name
{
get { return _phraseName; }
set { _phraseName = value; }
}
#endregion class public properties
private String _phraseName;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml;
using System.Text;
using System;
namespace System.Xml
{
// Specifies the context that the XmLReader will use for xml fragment
public class XmlParserContext
{
private XmlNameTable _nt = null;
private XmlNamespaceManager _nsMgr = null;
private String _docTypeName = String.Empty;
private String _pubId = String.Empty;
private String _sysId = String.Empty;
private String _internalSubset = String.Empty;
private String _xmlLang = String.Empty;
private XmlSpace _xmlSpace;
private String _baseURI = String.Empty;
private Encoding _encoding = null;
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, null, null, null, null, String.Empty, xmlLang, xmlSpace)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String xmlLang, XmlSpace xmlSpace, Encoding enc)
: this(nt, nsMgr, null, null, null, null, String.Empty, xmlLang, xmlSpace, enc)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
String pubId, String sysId, String internalSubset, String baseURI,
String xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, docTypeName, pubId, sysId, internalSubset, baseURI, xmlLang, xmlSpace, null)
{
// Intentionally Empty
}
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName,
String pubId, String sysId, String internalSubset, String baseURI,
String xmlLang, XmlSpace xmlSpace, Encoding enc)
{
if (nsMgr != null)
{
if (nt == null)
{
_nt = nsMgr.NameTable;
}
else
{
if ((object)nt != (object)nsMgr.NameTable)
{
throw new XmlException(SR.Xml_NotSameNametable, string.Empty);
}
_nt = nt;
}
}
else
{
_nt = nt;
}
_nsMgr = nsMgr;
_docTypeName = (null == docTypeName ? String.Empty : docTypeName);
_pubId = (null == pubId ? String.Empty : pubId);
_sysId = (null == sysId ? String.Empty : sysId);
_internalSubset = (null == internalSubset ? String.Empty : internalSubset);
_baseURI = (null == baseURI ? String.Empty : baseURI);
_xmlLang = (null == xmlLang ? String.Empty : xmlLang);
_xmlSpace = xmlSpace;
_encoding = enc;
}
public XmlNameTable NameTable
{
get
{
return _nt;
}
set
{
_nt = value;
}
}
public XmlNamespaceManager NamespaceManager
{
get
{
return _nsMgr;
}
set
{
_nsMgr = value;
}
}
public String DocTypeName
{
get
{
return _docTypeName;
}
set
{
_docTypeName = (null == value ? String.Empty : value);
}
}
public String PublicId
{
get
{
return _pubId;
}
set
{
_pubId = (null == value ? String.Empty : value);
}
}
public String SystemId
{
get
{
return _sysId;
}
set
{
_sysId = (null == value ? String.Empty : value);
}
}
public String BaseURI
{
get
{
return _baseURI;
}
set
{
_baseURI = (null == value ? String.Empty : value);
}
}
public String InternalSubset
{
get
{
return _internalSubset;
}
set
{
_internalSubset = (null == value ? String.Empty : value);
}
}
public String XmlLang
{
get
{
return _xmlLang;
}
set
{
_xmlLang = (null == value ? String.Empty : value);
}
}
public XmlSpace XmlSpace
{
get
{
return _xmlSpace;
}
set
{
_xmlSpace = value;
}
}
public Encoding Encoding
{
get
{
return _encoding;
}
set
{
_encoding = value;
}
}
internal bool HasDtdInfo
{
get
{
return (_internalSubset != string.Empty || _pubId != string.Empty || _sysId != string.Empty);
}
}
} // class XmlContext
} // namespace System.Xml
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Microsoft.WindowsAPICodePack.DirectX;
using Microsoft.WindowsAPICodePack.DirectX.Direct3D;
using Microsoft.WindowsAPICodePack.DirectX.Direct3D10;
using Microsoft.WindowsAPICodePack.DirectX.Graphics;
using System.Windows.Media.Media3D;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities
{
/// <summary>
///
/// </summary>
public class XMesh : IDisposable
{
RasterizerDescription rDescription = new RasterizerDescription()
{
FillMode = FillMode.Solid,
CullMode = CullMode.Back,
FrontCounterclockwise = false,
DepthBias = 0,
DepthBiasClamp = 0,
SlopeScaledDepthBias = 0,
DepthClipEnable = true,
ScissorEnable = false,
MultisampleEnable = true,
AntiAliasedLineEnable = true,
};
#region public methods
/// <summary>
/// Renders the mesh with the specified transformation
/// </summary>
/// <param name="modelTransform"></param>
public void Render(Matrix4x4F modelTransform)
{
rDescription.FillMode = wireFrame ? FillMode.Wireframe : FillMode.Solid;
// setup rasterization
using (RasterizerState rState = this.manager.device.CreateRasterizerState(rDescription))
{
this.manager.device.RS.State = rState;
this.manager.brightnessVariable.AsSingle = this.lightIntensity;
if (rootParts != null)
{
Matrix3D transform = modelTransform.ToMatrix3D();
foreach (Part part in rootParts)
{
RenderPart(part, transform, null);
}
}
// Note: see comment regarding input layout in RenderPart()
// method; the same thing applies to the render state of the
// rasterizer stage of the pipeline.
this.manager.device.RS.State = null;
}
}
#endregion
#region public properties
/// <summary>
/// Displays the unshaded wireframe if true
/// </summary>
public bool ShowWireFrame
{
get { return wireFrame; }
set { wireFrame = value; }
}
private bool wireFrame = false;
/// <summary>
/// Sets the intensity of the light used in rendering.
/// </summary>
public float LightIntensity
{
get { return lightIntensity; }
set { lightIntensity = value; }
}
private float lightIntensity = 1.0f;
#endregion
#region virtual methods
protected virtual Matrix3D PartAnimation(string partName)
{
return Matrix3D.Identity;
}
internal virtual ShaderResourceView UpdateRasterizerStateForPart(Part part)
{
return null;
}
#endregion
#region implementation
internal XMesh()
{
}
internal void Load(string path, XMeshManager manager)
{
this.manager = manager;
XMeshTextLoader loader = new XMeshTextLoader(this.manager.device);
rootParts = loader.XMeshFromFile(path);
}
private void RenderPart(Part part, Matrix3D parentMatrix, ShaderResourceView parentTextureOverride)
{
// set part transform
Transform3DGroup partGroup = new Transform3DGroup();
partGroup.Children.Add(new MatrixTransform3D(PartAnimation(part.name)));
partGroup.Children.Add(new MatrixTransform3D(part.partTransform.ToMatrix3D()));
partGroup.Children.Add(new MatrixTransform3D(parentMatrix));
parentMatrix = partGroup.Value;
ShaderResourceView textureOverride = UpdateRasterizerStateForPart(part);
if (textureOverride == null)
{
textureOverride = parentTextureOverride;
}
else
{
parentTextureOverride = textureOverride;
}
if (part.vertexBuffer != null)
{
EffectTechnique technique;
if (textureOverride != null)
{
technique = this.manager.techniqueRenderTexture;
this.manager.diffuseVariable.Resource = textureOverride;
}
else if (part.material == null)
{
technique = this.manager.techniqueRenderVertexColor;
}
else
{
if (part.material.textureResource != null)
{
technique = this.manager.techniqueRenderTexture;
this.manager.diffuseVariable.Resource = part.material.textureResource;
}
else
{
technique = this.manager.techniqueRenderMaterialColor;
this.manager.materialColorVariable.FloatVector = part.material.materialColor;
}
}
this.manager.worldVariable.Matrix = parentMatrix.ToMatrix4x4F();
//set up vertex buffer and index buffer
uint stride = (uint)Marshal.SizeOf(typeof(XMeshVertex));
uint offset = 0;
this.manager.device.IA.SetVertexBuffers(0, new D3DBuffer[]
{ part.vertexBuffer },
new uint[] { stride },
new uint[] { offset });
//Set primitive topology
this.manager.device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;
TechniqueDescription techDesc = technique.Description;
for (uint p = 0; p < techDesc.Passes; ++p)
{
technique.GetPassByIndex(p).Apply();
PassDescription passDescription = technique.GetPassByIndex(p).Description;
using (InputLayout inputLayout = this.manager.device.CreateInputLayout(
part.dataDescription,
passDescription.InputAssemblerInputSignature,
passDescription.InputAssemblerInputSignatureSize))
{
// set vertex layout
this.manager.device.IA.InputLayout = inputLayout;
// draw part
this.manager.device.Draw((uint)part.vertexCount, 0);
// Note: In Direct3D 10, the device will not retain a reference
// to the input layout, so it's important to reset the device's
// input layout before disposing the object. Were this code
// using Direct3D 11, the device would in fact retain a reference
// and so it would be safe to go ahead and dispose the input
// layout without resetting it; in that case, there could be just
// a single assignment to null outside the 'for' loop, or even
// no assignment at all.
this.manager.device.IA.InputLayout = null;
}
}
}
foreach (Part childPart in part.parts)
{
RenderPart(childPart, parentMatrix, parentTextureOverride);
}
}
/// <summary>
/// The root part of this mesh
/// </summary>
internal IEnumerable<Part> rootParts;
/// <summary>
/// The object that manages the XMeshes
/// </summary>
internal XMeshManager manager;
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool disposed;
private void DisposePart(Part part)
{
if (part.vertexBuffer != null)
{
part.vertexBuffer.Dispose();
part.vertexBuffer = null;
}
if ((part.material != null) && (part.material.textureResource != null))
{
part.material.textureResource.Dispose();
part.material.textureResource = null;
}
foreach (Part childPart in part.parts)
{
DisposePart(childPart);
}
part.parts = null;
}
/// <summary>
/// Releases resources no longer needed.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!disposed && rootParts != null)
{
foreach (Part part in rootParts)
{
DisposePart(part);
}
rootParts = null;
disposed = true;
}
}
#endregion
}
}
| |
//
// HttpURLConnection.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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.
//
/*
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. 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. 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.
*/
//
// HttpURLConnection.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2010 Novell, Inc (http://www.novell.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.Net;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace Sharpen
{
internal class URLConnection
{
}
internal class HttpsURLConnection: HttpURLConnection
{
internal HttpsURLConnection (Uri uri, Proxy p): base (uri, p)
{
}
internal void SetSSLSocketFactory (object factory)
{
// TODO
}
}
internal class HttpURLConnection: URLConnection
{
public const int HTTP_OK = 200;
public const int HTTP_NOT_FOUND = 404;
public const int HTTP_FORBIDDEN = 403;
public const int HTTP_UNAUTHORIZED = 401;
HttpWebRequest request;
HttpWebResponse reqResponse;
Uri url;
internal HttpURLConnection (Uri uri, Proxy p)
{
url = uri;
request = (HttpWebRequest) HttpWebRequest.Create (uri);
}
HttpWebResponse Response {
get {
if (reqResponse == null)
{
try
{
reqResponse = (HttpWebResponse) request.GetResponse ();
}
catch (WebException ex)
{
reqResponse = (HttpWebResponse) ex.Response;
if (reqResponse == null) {
if (this is HttpsURLConnection)
throw new WebException ("A secure connection could not be established", ex);
throw;
}
}
}
return reqResponse;
}
}
public void SetRequestInputStream (IEnumerable<byte> bais)
{
var bytes = bais.ToArray();
using (var stream = request.GetRequestStream())
{
var bytesWritten = 0;
while (bytesWritten < bytes.Length)
{
// stream.Write doesn't support a length of Int64,
// we need to write in chunk of up to Int32.MaxValue.
stream.Write(bytes, 0, bytes.Length);
bytesWritten += bytes.Length;
}
}
}
public void SetUseCaches (bool u)
{
if (u)
request.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.Default);
else
request.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.BypassCache);
}
public void SetRequestMethod (string method)
{
request.Method = method;
}
public string GetRequestMethod ()
{
return request.Method;
}
public void SetInstanceFollowRedirects (bool redirects)
{
request.AllowAutoRedirect = redirects;
}
public void SetDoOutput (bool dooutput)
{
// Not required?
}
public void SetFixedLengthStreamingMode (int len)
{
request.SendChunked = false;
}
public void SetChunkedStreamingMode (int n)
{
request.SendChunked = true;
}
public void SetRequestProperty (string key, string value)
{
switch (key.ToLower ()) {
case "user-agent": request.UserAgent = value; break;
case "content-length": request.ContentLength = long.Parse (value); break;
case "content-type": request.ContentType = value; break;
case "expect": request.Expect = value; break;
case "referer": request.Referer = value; break;
case "transfer-encoding": request.TransferEncoding = value; break;
case "accept": request.Accept = value; break;
default: request.Headers.Set (key, value); break;
}
}
public IDictionary<String, Object> GetRequestProperties()
{
var props = new Dictionary<String, Object>()
{
{ "user-agent", request.UserAgent },
{ "content-length", request.ContentLength },
{ "content-type", request.ContentType },
{ "expect", request.Expect },
{ "referer", request.Referer },
{ "transfer-encoding", request.TransferEncoding },
{ "accept", request.Accept }
};
for(var i = 0; i < request.Headers.Count; i++)
{
props.Add(request.Headers.GetKey(i), request.Headers.Get(i));
}
return props;
}
public string GetResponseMessage ()
{
return Response.StatusDescription;
}
public void SetConnectTimeout (int ms)
{
if (ms == 0)
ms = -1;
request.Timeout = ms;
}
public void SetReadTimeout (int ms)
{
// Not available
}
public Stream GetInputStream ()
{
return Response.GetResponseStream ();
}
public Stream GetOutputStream ()
{
return request.GetRequestStream ();
}
public string GetHeaderField (string header)
{
return Response.GetResponseHeader (header);
}
public string GetContentType ()
{
return Response.ContentType;
}
public int GetContentLength ()
{
return (int) Response.ContentLength;
}
public int GetResponseCode ()
{
return (int) Response.StatusCode;
}
public Uri GetURL ()
{
return url;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.MDS;
using Microsoft.Msagl.Core;
namespace Microsoft.Msagl.Layout.Incremental {
/// <summary>
///
/// </summary>
public class ProcrustesCircleConstraint : IConstraint {
Node[] V;
int n;
Point[] X;
Point[] Y;
/// <summary>
/// Create a circle constraint with variable radius
/// </summary>
/// <param name="nodes"></param>
public ProcrustesCircleConstraint(IEnumerable<Node> nodes) {
V = nodes.ToArray();
n = V.Length;
X = new Point[n];
Y = new Point[n];
double angle = 2.0 * Math.PI / (double)n;
double r = 10*(double)n; // we make our circle a reasonable size to aid numerical precision
for (int i = 0; i < n; ++i) {
double theta = angle * (double)i;
Y[i] = new Point(r * Math.Cos(theta), r * Math.Sin(theta));
}
}
/// <summary>
/// A procrustes constraint with arbitrary target shape
/// </summary>
/// <param name="nodes"></param>
/// <param name="targetConfiguration"></param>
public ProcrustesCircleConstraint(IEnumerable<Node> nodes, IEnumerable<Point> targetConfiguration)
{
ValidateArg.IsNotNull(nodes, "nodes");
ValidateArg.IsNotNull(targetConfiguration, "targetConfiguration");
V = nodes.ToArray();
n = V.Length;
X = new Point[n];
Y = new Point[n];
int i = 0;
Point yc = new Point();
foreach (var p in targetConfiguration) {
Y[i++] = p;
yc += p;
}
yc /= n;
for (i = 0; i < n; ++i) {
Y[i] -= yc;
}
}
#region IConstraint Members
/// <summary>
/// matrix product: A'B
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns>2X2 matrix</returns>
private static Point[] matrixProduct(Point[] A, Point[] B) {
Point[] R = new Point[2];
double x0 = 0, y0 = 0, x1 = 0, y1 = 0;
for (int i = 0; i < A.Length; ++i)
{
x0 += A[i].X * B[i].X;
y0 += A[i].X * B[i].Y;
x1 += A[i].Y * B[i].X;
y1 += A[i].Y * B[i].Y;
}
R[0] = new Point(x0, y0);
R[1] = new Point(x1, y1);
return R;
}
/// <summary>
/// matrix product of two 2x2 matrices with no transpose, i.e.: AB
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns>2X2 matrix</returns>
private static Point[] matrixProductNoTranspose(Point[] A, Point[] B) {
Point[] R = new Point[2];
R[0] = new Point(A[0].X*B[0].X+A[0].Y*B[1].X, A[0].X*B[0].Y + A[0].Y*B[1].Y);
R[1] = new Point(A[1].X*B[0].X+A[1].Y*B[1].X, A[1].X*B[0].Y + A[1].Y*B[1].Y);
return R;
}
private static Point MatrixTimesVector(Point[] A, Point v) {
double a = A[0].X, b = A[0].Y, c = A[1].X, d = A[1].Y;
return new Point(a * v.X + b * v.Y, c * v.X + d * v.Y);
}
private static Point eigenSystem2(Point[] B, out Point[] Q) {
double[][] b = new double[B.Length][];
for (int i = 0; i < B.Length; i++) {
b[i] = new double[2];
b[i][0] = B[i].X;
b[i][1] = B[i].Y;
}
double lambda1;
double[] q1;
double lambda2;
double[] q2;
MultidimensionalScaling.SpectralDecomposition(b, out q1, out lambda1, out q2, out lambda2,300,1e-8);
Q = new Point[] { new Point(q1[0], q1[1]), new Point(q2[0], q2[1]) };
return new Point(lambda1, lambda2);
}
/// <summary>
/// Compute singular value decomposition of a 2X2 matrix X=PSQ'
/// </summary>
/// <param name="X">input 2x2 matrix</param>
/// <param name="P">left singular vectors</param>
/// <param name="Q">right singular vectors (eigenvectors of X'X)</param>
/// <returns>Singular values (Sqrt of eigenvalues of X'X)</returns>
private static Point SingularValueDecomposition(Point[] X, out Point[] P, out Point[] Q) {
Point[] XX = matrixProduct(X, X);
Point l = eigenSystem2(XX, out Q);
/*
Point[] Q0;
Point l0 = eigenSystem3(XX, out Q0);
Q0 = new Point[] { Q0[1], Q0[0] };
Q0 = Transpose(Q0);
Q0 = new Point[] { -Q0[0], -Q0[1] };
double tmp = l0.X;
l0.X = l0.Y;
l0.Y = tmp;
if (!cmpEigenSystem(Q0, Q, l0, l)) {
System.Console.Write("XX=");
printMatrix(XX);
System.Console.Write("Q0=");
printMatrix(Q0);
System.Console.WriteLine("l0=" + l0 + ";");
System.Console.Write("Q=");
printMatrix(Q);
System.Console.WriteLine("l=" + l + ";");
}
l = l0;
Q = Q0;
System.Console.Write("Q=");
printMatrix(Q);
System.Console.WriteLine("l=" + l + ";");
*/
Point s = new Point(Math.Sqrt(l.X), Math.Sqrt(l.Y));
P = matrixProductNoTranspose(X, Q);
P = matrixProductNoTranspose(P,new Point[]{new Point(1.0/s.X,0), new Point(0,1.0/s.Y)});
return s;
}
#if OLDPROJECT
/// <summary>
///
/// </summary>
/// <returns></returns>
public double Project() {
Point barycenter = Barycenter();
Point[] X = new Point[ni];
Point[] Y = new Point[ni];
double angle = 2.0 * Math.PI / nd;
double r = 0;
int i = 0;
foreach(var v in nodes) {
X[i] = v.Center - barycenter;
r += X[i].LengthSquared;
++i;
}
r = Math.Sqrt(r / nd);
i = 0;
foreach (var v in nodes) {
double theta = angle * (double)i;
Y[i] = new Point(r * Math.Cos(theta), r * Math.Sin(theta));
++i;
}
Point[] C = matrixProduct(Y, X);
Point[] P, Q;
SingularValueDecomposition(C, out P, out Q);
Point[] T = matrixProductNoTranspose(Q, Transpose(P));
/*
Point[] XY = matrixProduct(X, Y);
Point[] XYT = matrixProductNoTranspose(XY, T);
Point[] YY = matrixProduct(Y, Y);
double s = XYT[0].X + XYT[1].Y;
s /= YY[0].X + YY[1].Y;
for (int i = 0; i < nodes.Count; ++i) {
Y[i] = Y[i] * s;
}
*/
i = 0;
foreach (var v in nodes) {
v.Center = barycenter + MatrixTimesVector(T, Y[i++]);
}
return 0;
}
#endif
/// <summary>
///
/// </summary>
/// <returns></returns>
public double Project() {
for (int i = 0; i < n; ++i)
{
X[i] = V[i].Center;
}
Point[] T;
double s;
Point t;
FindTransform(X, Y, out T, out s, out t);
//System.Console.WriteLine("X=");
//printMatrix(X);
//System.Console.WriteLine("Y=");
//printMatrix(Y);
//System.Console.WriteLine("T=");
//printMatrix(T);
//System.Console.WriteLine("s="+s);
//System.Console.WriteLine("t="+t);
Point[] TT = Transpose(T);
double displacement = 0;
for (int i = 0; i < n; ++i)
{
var v = V[i];
v.Center = double.IsNaN(s) ? Y[i] : s * MatrixTimesVector(TT, Y[i]) + t;
displacement += (v.Center - X[i]).Length;
}
return displacement;
}
/// <summary>
/// output an n*2 point matrix in Mathematica format
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.Write(System.String,System.Object,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.Write(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String)")]
public static void PrintMatrix(Point[] points) {
ValidateArg.IsNotNull(points, "points");
System.Console.Write("{");
for (int i = 0; i < points.Length;) {
System.Console.Write("{{{0},{1}}}", points[i].X, points[i].Y);
if (++i != points.Length) {
System.Console.Write(",");
}
}
System.Console.WriteLine("};");
}
private static Point[] Transpose(Point[] X) {
return new Point[] { new Point(X[0].X, X[1].X), new Point(X[0].Y, X[1].Y) };
}
//// <summary>
////
//// </summary>
//public static void Test1() {
// Random rand = new Random();
// Point[] X = new Point[] { new Point(rand.NextDouble(), rand.NextDouble()), new Point(rand.NextDouble(), rand.NextDouble()) };
// System.Console.Write("X="); printMatrix(X);
// Point[] P, Q;
// Point s = SingularValueDecomposition(X, out P, out Q);
// Point[] S = new Point[] { new Point(s.X, 0), new Point(0, s.Y) };
// System.Console.Write("S="); printMatrix(S);
// System.Console.Write("Q="); printMatrix(Q);
// System.Console.Write("P="); printMatrix(P);
// Point[] R = matrixProductNoTranspose(P, S);
// System.Console.Write("PS="); printMatrix(R);
// R = matrixProductNoTranspose(R, Transpose(Q));
// System.Console.Write("R="); printMatrix(R);
// Debug.Assert(Math.Abs(R[0].X - X[0].X) < 0.01);
// Debug.Assert(Math.Abs(R[0].Y - X[0].Y) < 0.01);
// Debug.Assert(Math.Abs(R[1].X - X[1].X) < 0.01);
// Debug.Assert(Math.Abs(R[1].Y - X[1].Y) < 0.01);
//}
//// <summary>
////
//// </summary>
// public static void Test() {
// double[,] XX = {{-0.342439, -0.815696}, {-0.772753, -0.807363}, {-0.264356,
//0.847908}, {-0.524064, 0.826169}, {0.615021, -0.762655}};
// List<Microsoft.Msagl.Node> vs = new List<Microsoft.Msagl.Node>();
// for (int i = 0; i < XX.Length/2; ++i) {
// var v = new Microsoft.Msagl.Node();
// v.Center = new Point(XX[i,0], XX[i,1]);
// vs.Add(v);
// }
// ProcrustesCircleConstraint c = new ProcrustesCircleConstraint(vs);
// c.Project();
// }
///<summary>
///</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Body"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String,System.Object,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.Write(System.String)")]
public static void Test() {
double[,] XX = { { 1, 2 }, { -1, 2 }, { -1, -2 }, { 1, -2 } },
YY = { { 0.07, 2.62 }, { 0.93, 3.12 }, { 1.93, 1.38 }, { 1.07, 0.88 } };
int ni = 4;
Point[] X = new Point[ni];
Point[] Y = new Point[ni];
for (int i = 0; i < ni; ++i) {
X[i] = new Point(XX[i, 0], XX[i, 1]);
Y[i] = new Point(YY[i, 0], YY[i, 1]);
}
Point[] XY = matrixProduct(X, Y);
System.Console.Write("XY=");
PrintMatrix(XY);
Point[] P, Q;
SingularValueDecomposition(XY, out P, out Q);
PrintMatrix(P);
PrintMatrix(Q);
Point[] T;
double s;
Point t;
FindTransform(X, Y, out T, out s, out t);
PrintMatrix(T);
System.Console.WriteLine("s={0}", s);
System.Console.WriteLine("t=({0},{1})", t.X,t.Y);
}
private static void FindTransform(Point[] X, Point[] Y,
out Point[] T, out double s, out Point t) {
int ni = X.Length;
Point[] C = matrixProduct(X, Y);
Point[] P, Q;
SingularValueDecomposition(C, out P, out Q);
T = matrixProductNoTranspose(Q, Transpose(P));
Point[] XYT = matrixProductNoTranspose(C, T);
Point[] Y2 = matrixProduct(Y, Y);
s = XYT[0].X + XYT[1].Y;
s /= Y2[0].X + Y2[1].Y;
t = new Point();
for (int i = 0; i < ni; ++i) {
t += X[i] - s * MatrixTimesVector(T, Y[i]);
}
t /= ni;
}
/// <summary>
///
/// </summary>
public int Level {
get {
return 1;
}
}
/// <summary>
/// Get the list of nodes involved in the constraint
/// </summary>
public IEnumerable<Node> Nodes { get { return V.AsEnumerable(); } }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.AzureUtils.Utilities;
using Orleans.AzureUtils;
using Orleans.Reminders.AzureStorage;
namespace Orleans.Runtime.ReminderService
{
internal class ReminderTableEntry : TableEntity
{
public string GrainReference { get; set; } // Part of RowKey
public string ReminderName { get; set; } // Part of RowKey
public string ServiceId { get; set; } // Part of PartitionKey
public string DeploymentId { get; set; }
public string StartAt { get; set; }
public string Period { get; set; }
public string GrainRefConsistentHash { get; set; } // Part of PartitionKey
public static string ConstructRowKey(GrainReference grainRef, string reminderName)
{
var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName);
return AzureStorageUtils.SanitizeTableProperty(key);
}
public static string ConstructPartitionKey(Guid serviceId, GrainReference grainRef)
{
return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode());
}
public static string ConstructPartitionKey(Guid serviceId, uint number)
{
// IMPORTANT NOTE: Other code using this return data is very sensitive to format changes,
// so take great care when making any changes here!!!
// this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly
// the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now,
// when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative
// string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number);
var grainHash = String.Format("{0:X8}", number);
return String.Format("{0}_{1}", ConstructServiceIdStr(serviceId), grainHash);
}
public static string ConstructServiceIdStr(Guid serviceId)
{
return serviceId.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("Reminder [");
sb.Append(" PartitionKey=").Append(PartitionKey);
sb.Append(" RowKey=").Append(RowKey);
sb.Append(" GrainReference=").Append(GrainReference);
sb.Append(" ReminderName=").Append(ReminderName);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" ServiceId=").Append(ServiceId);
sb.Append(" StartAt=").Append(StartAt);
sb.Append(" Period=").Append(Period);
sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash);
sb.Append("]");
return sb.ToString();
}
}
internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry>
{
private const string REMINDERS_TABLE_NAME = "OrleansReminders";
public Guid ServiceId { get; private set; }
public string DeploymentId { get; private set; }
private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public static async Task<RemindersTableManager> GetManager(Guid serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory)
{
var singleton = new RemindersTableManager(serviceId, clusterId, storageConnectionString, loggerFactory);
try
{
singleton.Logger.Info("Creating RemindersTableManager for service id {0} and clusterId {1}.", serviceId, clusterId);
await singleton.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}";
singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_38, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}";
singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_39, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return singleton;
}
private RemindersTableManager(Guid serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory)
: base(REMINDERS_TABLE_NAME, storageConnectionString, loggerFactory)
{
DeploymentId = clusterId;
ServiceId = serviceId;
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end)
{
// TODO: Determine whether or not a single query could be used here while avoiding a table scan
string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin);
string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end);
string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(ServiceId);
string filterOnServiceIdStr = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, serviceIdStr + '_'),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual,
serviceIdStr + (char)('_' + 1)));
if (begin < end)
{
string filterBetweenBeginAndEnd = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual,
sEnd));
string query = TableQuery.CombineFilters(filterOnServiceIdStr, TableOperators.And, filterBetweenBeginAndEnd);
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
if (begin == end)
{
var queryResults = await ReadTableEntriesAndEtagsAsync(filterOnServiceIdStr);
return queryResults.ToList();
}
// (begin > end)
string queryOnSBegin = TableQuery.CombineFilters(
filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin));
string queryOnSEnd = TableQuery.CombineFilters(
filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd));
var resultsOnSBeginQuery = ReadTableEntriesAndEtagsAsync(queryOnSBegin);
var resultsOnSEndQuery = ReadTableEntriesAndEtagsAsync(queryOnSEnd);
IEnumerable<Tuple<ReminderTableEntry, string>>[] results = await Task.WhenAll(resultsOnSBeginQuery, resultsOnSEndQuery);
return results[0].Concat(results[1]).ToList();
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef)
{
var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string filter = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.GreaterThan, grainRef.ToKeyString() + '-'),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.LessThanOrEqual,
grainRef.ToKeyString() + (char)('-' + 1)));
string query =
TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.Equal, partitionKey),
TableOperators.And,
filter);
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName)
{
string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName);
return await ReadSingleTableEntryAsync(partitionKey, rowKey);
}
private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries()
{
return FindReminderEntries(0, 0);
}
internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry)
{
try
{
return await UpsertTableEntryAsync(reminderEntry);
}
catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false;
}
throw;
}
}
internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag)
{
try
{
await DeleteTableEntryAsync(reminderEntry, eTag);
return true;
}catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
}
throw;
}
}
#region Table operations
internal async Task DeleteTableEntries()
{
if (ServiceId.Equals(Guid.Empty) && DeploymentId == null)
{
await DeleteTableAsync();
}
else
{
List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries();
// return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed
// group by grain hashcode so each query goes to different partition
var tasks = new List<Task>();
var groupedByHash = entries
.Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId)))
.Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId.
.GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList());
foreach (var entriesPerPartition in groupedByHash.Values)
{
foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(DeleteTableEntriesAsync(batch));
}
}
await Task.WhenAll(tasks);
}
}
#endregion
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK 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 UnityEngine;
/// <summary>
/// Controls the player's movement in virtual reality.
/// </summary>
[RequireComponent(typeof(CharacterController))]
public class OVRPlayerController : MonoBehaviour
{
/// <summary>
/// The rate acceleration during movement.
/// </summary>
public float Acceleration = 0.1f;
/// <summary>
/// The rate of damping on movement.
/// </summary>
public float Damping = 0.3f;
/// <summary>
/// The rate of additional damping when moving sideways or backwards.
/// </summary>
public float BackAndSideDampen = 0.5f;
/// <summary>
/// The force applied to the character when jumping.
/// </summary>
public float JumpForce = 0.3f;
/// <summary>
/// The rate of rotation when using a gamepad.
/// </summary>
public float RotationAmount = 1.5f;
/// <summary>
/// The rate of rotation when using the keyboard.
/// </summary>
public float RotationRatchet = 45.0f;
/// <summary>
/// The player will rotate in fixed steps if Snap Rotation is enabled.
/// </summary>
[Tooltip("The player will rotate in fixed steps if Snap Rotation is enabled.")]
public bool SnapRotation = true;
/// <summary>
/// How many fixed speeds to use with linear movement? 0=linear control
/// </summary>
[Tooltip("How many fixed speeds to use with linear movement? 0=linear control")]
public int FixedSpeedSteps;
/// <summary>
/// If true, reset the initial yaw of the player controller when the Hmd pose is recentered.
/// </summary>
public bool HmdResetsY = true;
/// <summary>
/// If true, tracking data from a child OVRCameraRig will update the direction of movement.
/// </summary>
public bool HmdRotatesY = true;
/// <summary>
/// Modifies the strength of gravity.
/// </summary>
public float GravityModifier = 0.379f;
/// <summary>
/// If true, each OVRPlayerController will use the player's physical height.
/// </summary>
public bool useProfileData = true;
/// <summary>
/// The CameraHeight is the actual height of the HMD and can be used to adjust the height of the character controller, which will affect the
/// ability of the character to move into areas with a low ceiling.
/// </summary>
[NonSerialized]
public float CameraHeight;
/// <summary>
/// This event is raised after the character controller is moved. This is used by the OVRAvatarLocomotion script to keep the avatar transform synchronized
/// with the OVRPlayerController.
/// </summary>
public event Action<Transform> TransformUpdated;
/// <summary>
/// This bool is set to true whenever the player controller has been teleported. It is reset after every frame. Some systems, such as
/// CharacterCameraConstraint, test this boolean in order to disable logic that moves the character controller immediately
/// following the teleport.
/// </summary>
[NonSerialized] // This doesn't need to be visible in the inspector.
public bool Teleported;
/// <summary>
/// This event is raised immediately after the camera transform has been updated, but before movement is updated.
/// </summary>
public event Action CameraUpdated;
/// <summary>
/// This event is raised right before the character controller is actually moved in order to provide other systems the opportunity to
/// move the character controller in response to things other than user input, such as movement of the HMD. See CharacterCameraConstraint.cs
/// for an example of this.
/// </summary>
public event Action PreCharacterMove;
/// <summary>
/// When true, user input will be applied to linear movement. Set this to false whenever the player controller needs to ignore input for
/// linear movement.
/// </summary>
public bool EnableLinearMovement = true;
/// <summary>
/// When true, user input will be applied to rotation. Set this to false whenever the player controller needs to ignore input for rotation.
/// </summary>
public bool EnableRotation = true;
/// <summary>
/// Rotation defaults to secondary thumbstick. You can allow either here. Note that this won't behave well if EnableLinearMovement is true.
/// </summary>
public bool RotationEitherThumbstick = false;
protected CharacterController Controller = null;
protected OVRCameraRig CameraRig = null;
private float MoveScale = 1.0f;
private Vector3 MoveThrottle = Vector3.zero;
private float FallSpeed = 0.0f;
private OVRPose? InitialPose;
public float InitialYRotation { get; private set; }
private float MoveScaleMultiplier = 1.0f;
private float RotationScaleMultiplier = 1.0f;
private bool SkipMouseRotation = true; // It is rare to want to use mouse movement in VR, so ignore the mouse by default.
private bool HaltUpdateMovement = false;
private bool prevHatLeft = false;
private bool prevHatRight = false;
private float SimulationRate = 60f;
private float buttonRotation = 0f;
private bool ReadyToSnapTurn; // Set to true when a snap turn has occurred, code requires one frame of centered thumbstick to enable another snap turn.
private bool playerControllerEnabled = false;
void Start()
{
// Add eye-depth as a camera offset from the player controller
var p = CameraRig.transform.localPosition;
p.z = OVRManager.profile.eyeDepth;
CameraRig.transform.localPosition = p;
}
void Awake()
{
Controller = gameObject.GetComponent<CharacterController>();
if (Controller == null)
Debug.LogWarning("OVRPlayerController: No CharacterController attached.");
// We use OVRCameraRig to set rotations to cameras,
// and to be influenced by rotation
OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>();
if (CameraRigs.Length == 0)
Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached.");
else if (CameraRigs.Length > 1)
Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached.");
else
CameraRig = CameraRigs[0];
InitialYRotation = transform.rotation.eulerAngles.y;
}
void OnEnable()
{
}
void OnDisable()
{
if (playerControllerEnabled)
{
OVRManager.display.RecenteredPose -= ResetOrientation;
if (CameraRig != null)
{
CameraRig.UpdatedAnchors -= UpdateTransform;
}
playerControllerEnabled = false;
}
}
void Update()
{
if (!playerControllerEnabled)
{
if (OVRManager.OVRManagerinitialized)
{
OVRManager.display.RecenteredPose += ResetOrientation;
if (CameraRig != null)
{
CameraRig.UpdatedAnchors += UpdateTransform;
}
playerControllerEnabled = true;
}
else
return;
}
//Use keys to ratchet rotation
if (Input.GetKeyDown(KeyCode.Q))
buttonRotation -= RotationRatchet;
if (Input.GetKeyDown(KeyCode.E))
buttonRotation += RotationRatchet;
}
protected virtual void UpdateController()
{
if (useProfileData)
{
if (InitialPose == null)
{
// Save the initial pose so it can be recovered if useProfileData
// is turned off later.
InitialPose = new OVRPose()
{
position = CameraRig.transform.localPosition,
orientation = CameraRig.transform.localRotation
};
}
var p = CameraRig.transform.localPosition;
if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.EyeLevel)
{
p.y = OVRManager.profile.eyeHeight - (0.5f * Controller.height) + Controller.center.y;
}
else if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.FloorLevel)
{
p.y = -(0.5f * Controller.height) + Controller.center.y;
}
CameraRig.transform.localPosition = p;
}
else if (InitialPose != null)
{
// Return to the initial pose if useProfileData was turned off at runtime
CameraRig.transform.localPosition = InitialPose.Value.position;
CameraRig.transform.localRotation = InitialPose.Value.orientation;
InitialPose = null;
}
CameraHeight = CameraRig.centerEyeAnchor.localPosition.y;
if (CameraUpdated != null)
{
CameraUpdated();
}
UpdateMovement();
Vector3 moveDirection = Vector3.zero;
float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime));
MoveThrottle.x /= motorDamp;
MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y;
MoveThrottle.z /= motorDamp;
moveDirection += MoveThrottle * SimulationRate * Time.deltaTime;
// Gravity
if (Controller.isGrounded && FallSpeed <= 0)
FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f)));
else
FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime);
moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime;
if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f)
{
// Offset correction for uneven ground
float bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude);
moveDirection -= bumpUpOffset * Vector3.up;
}
if (PreCharacterMove != null)
{
PreCharacterMove();
Teleported = false;
}
Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1));
// Move contoller
Controller.Move(moveDirection);
Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1));
if (predictedXZ != actualXZ)
MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime);
}
public virtual void UpdateMovement()
{
if (HaltUpdateMovement)
return;
if (EnableLinearMovement)
{
bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);
bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow);
bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow);
bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow);
bool dpad_move = false;
if (OVRInput.Get(OVRInput.Button.DpadUp))
{
moveForward = true;
dpad_move = true;
}
if (OVRInput.Get(OVRInput.Button.DpadDown))
{
moveBack = true;
dpad_move = true;
}
MoveScale = 1.0f;
if ((moveForward && moveLeft) || (moveForward && moveRight) ||
(moveBack && moveLeft) || (moveBack && moveRight))
MoveScale = 0.70710678f;
// No positional movement if we are in the air
if (!Controller.isGrounded)
MoveScale = 0.0f;
MoveScale *= SimulationRate * Time.deltaTime;
// Compute this for key movement
float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
// Run!
if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
moveInfluence *= 2.0f;
Quaternion ort = transform.rotation;
Vector3 ortEuler = ort.eulerAngles;
ortEuler.z = ortEuler.x = 0f;
ort = Quaternion.Euler(ortEuler);
if (moveForward)
MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward);
if (moveBack)
MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back);
if (moveLeft)
MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left);
if (moveRight)
MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right);
moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
#if !UNITY_ANDROID // LeftTrigger not avail on Android game pad
moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);
#endif
Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
// If speed quantization is enabled, adjust the input to the number of fixed speed steps.
if (FixedSpeedSteps > 0)
{
primaryAxis.y = Mathf.Round(primaryAxis.y * FixedSpeedSteps) / FixedSpeedSteps;
primaryAxis.x = Mathf.Round(primaryAxis.x * FixedSpeedSteps) / FixedSpeedSteps;
}
if (primaryAxis.y > 0.0f)
MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward);
if (primaryAxis.y < 0.0f)
MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence *
BackAndSideDampen * Vector3.back);
if (primaryAxis.x < 0.0f)
MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence *
BackAndSideDampen * Vector3.left);
if (primaryAxis.x > 0.0f)
MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen *
Vector3.right);
}
if (EnableRotation)
{
Vector3 euler = transform.rotation.eulerAngles;
float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier;
bool curHatLeft = OVRInput.Get(OVRInput.Button.PrimaryShoulder);
if (curHatLeft && !prevHatLeft)
euler.y -= RotationRatchet;
prevHatLeft = curHatLeft;
bool curHatRight = OVRInput.Get(OVRInput.Button.SecondaryShoulder);
if (curHatRight && !prevHatRight)
euler.y += RotationRatchet;
prevHatRight = curHatRight;
euler.y += buttonRotation;
buttonRotation = 0f;
#if !UNITY_ANDROID || UNITY_EDITOR
if (!SkipMouseRotation)
euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f;
#endif
if (SnapRotation)
{
if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickLeft) ||
(RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickLeft)))
{
if (ReadyToSnapTurn)
{
euler.y -= RotationRatchet;
ReadyToSnapTurn = false;
}
}
else if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickRight) ||
(RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickRight)))
{
if (ReadyToSnapTurn)
{
euler.y += RotationRatchet;
ReadyToSnapTurn = false;
}
}
else
{
ReadyToSnapTurn = true;
}
}
else
{
Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
if (RotationEitherThumbstick)
{
Vector2 altSecondaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
if (secondaryAxis.sqrMagnitude < altSecondaryAxis.sqrMagnitude)
{
secondaryAxis = altSecondaryAxis;
}
}
euler.y += secondaryAxis.x * rotateInfluence;
}
transform.rotation = Quaternion.Euler(euler);
}
}
/// <summary>
/// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player.
/// </summary>
public void UpdateTransform(OVRCameraRig rig)
{
Transform root = CameraRig.trackingSpace;
Transform centerEye = CameraRig.centerEyeAnchor;
if (HmdRotatesY && !Teleported)
{
Vector3 prevPos = root.position;
Quaternion prevRot = root.rotation;
transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f);
root.position = prevPos;
root.rotation = prevRot;
}
UpdateController();
if (TransformUpdated != null)
{
TransformUpdated(root);
}
}
/// <summary>
/// Jump! Must be enabled manually.
/// </summary>
public bool Jump()
{
if (!Controller.isGrounded)
return false;
MoveThrottle += new Vector3(0, transform.lossyScale.y * JumpForce, 0);
return true;
}
/// <summary>
/// Stop this instance.
/// </summary>
public void Stop()
{
Controller.Move(Vector3.zero);
MoveThrottle = Vector3.zero;
FallSpeed = 0.0f;
}
/// <summary>
/// Gets the move scale multiplier.
/// </summary>
/// <param name="moveScaleMultiplier">Move scale multiplier.</param>
public void GetMoveScaleMultiplier(ref float moveScaleMultiplier)
{
moveScaleMultiplier = MoveScaleMultiplier;
}
/// <summary>
/// Sets the move scale multiplier.
/// </summary>
/// <param name="moveScaleMultiplier">Move scale multiplier.</param>
public void SetMoveScaleMultiplier(float moveScaleMultiplier)
{
MoveScaleMultiplier = moveScaleMultiplier;
}
/// <summary>
/// Gets the rotation scale multiplier.
/// </summary>
/// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier)
{
rotationScaleMultiplier = RotationScaleMultiplier;
}
/// <summary>
/// Sets the rotation scale multiplier.
/// </summary>
/// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
public void SetRotationScaleMultiplier(float rotationScaleMultiplier)
{
RotationScaleMultiplier = rotationScaleMultiplier;
}
/// <summary>
/// Gets the allow mouse rotation.
/// </summary>
/// <param name="skipMouseRotation">Allow mouse rotation.</param>
public void GetSkipMouseRotation(ref bool skipMouseRotation)
{
skipMouseRotation = SkipMouseRotation;
}
/// <summary>
/// Sets the allow mouse rotation.
/// </summary>
/// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param>
public void SetSkipMouseRotation(bool skipMouseRotation)
{
SkipMouseRotation = skipMouseRotation;
}
/// <summary>
/// Gets the halt update movement.
/// </summary>
/// <param name="haltUpdateMovement">Halt update movement.</param>
public void GetHaltUpdateMovement(ref bool haltUpdateMovement)
{
haltUpdateMovement = HaltUpdateMovement;
}
/// <summary>
/// Sets the halt update movement.
/// </summary>
/// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param>
public void SetHaltUpdateMovement(bool haltUpdateMovement)
{
HaltUpdateMovement = haltUpdateMovement;
}
/// <summary>
/// Resets the player look rotation when the device orientation is reset.
/// </summary>
public void ResetOrientation()
{
if (HmdResetsY && !HmdRotatesY)
{
Vector3 euler = transform.rotation.eulerAngles;
euler.y = InitialYRotation;
transform.rotation = Quaternion.Euler(euler);
}
}
}
| |
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace FluentAssertions.Json
{
[TestClass]
// ReSharper disable InconsistentNaming
public class JTokenAssertionsSpecs
{
[TestMethod]
public void When_both_values_are_the_same_or_equal_Be_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":1}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Be(a);
b.Should().Be(b);
a.Should().Be(b);
}
[TestMethod]
public void When_values_differ_NotBe_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":2}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().NotBeNull();
a.Should().NotBe(null);
a.Should().NotBe(b);
}
[TestMethod]
public void When_values_are_equal_or_equivalent_NotBe_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var a = JToken.Parse("{\"id\":1}");
var b = JToken.Parse("{\"id\":1}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Invoking(x => x.Should().NotBe(b))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document not to be {_formatter.ToString(b)}.");
}
[TestMethod]
public void When_both_values_are_equal_BeEquivalentTo_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}", "{friends:[{name:\"Corby Page\",id:123},{id:456,name:\"Carter Page\"}]}" },
{ "{id:2,admin:true}", "{admin:true,id:2}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().BeEquivalentTo(b);
}
}
[TestMethod]
public void When_values_differ_NotBeEquivalentTo_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().NotBeEquivalentTo(b);
}
}
[TestMethod]
public void When_values_differ_Be_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1}", "{id:2}" }
, { "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
var expectedMessage =
$"Expected JSON document to be {_formatter.ToString(b)}, but found {_formatter.ToString(a)}.";
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Invoking(x => x.Be(b))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
}
[TestMethod]
public void When_values_differ_BeEquivalentTo_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var testCases = new Dictionary<string, string>
{
{ "{id:1,admin:true}", "{id:1,admin:false}" }
};
foreach (var testCase in testCases)
{
var actualJson = testCase.Key;
var expectedJson = testCase.Value;
var a = JToken.Parse(actualJson);
var b = JToken.Parse(expectedJson);
var expectedMessage = GetNotEquivalentMessage(a, b);
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
a.Should().Invoking(x => x.BeEquivalentTo(b))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
}
[TestMethod]
public void Fail_with_descriptive_message_when_child_element_differs()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{child:{subject:'foo'}}");
var expected = JToken.Parse("{child:{expected:'bar'}}");
var expectedMessage = GetNotEquivalentMessage(subject, expected, "we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().Invoking(x => x.BeEquivalentTo(expected, "we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage(expectedMessage);
}
[TestMethod]
public void When_jtoken_has_value_HaveValue_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject["id"].Should().HaveValue("42");
}
[TestMethod]
public void When_jtoken_not_has_value_HaveValue_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject["id"].Should().Invoking(x => x.HaveValue("43", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected JSON property \"id\" to have value \"43\" because foo, but found \"42\".");
}
[TestMethod]
public void When_jtoken_has_element_HaveElement_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().HaveElement("id");
subject.Should().Invoking(x => x.HaveElement("name", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found.");
}
[TestMethod]
public void When_jtoken_not_has_element_HaveElement_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = JToken.Parse("{ 'id':42}");
//-----------------------------------------------------------------------------------------------------------
// Act & Assert
//-----------------------------------------------------------------------------------------------------------
subject.Should().Invoking(x => x.HaveElement("name", "because foo"))
.ShouldThrow<AssertFailedException>()
.WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found.");
}
private static readonly JTokenFormatter _formatter = new JTokenFormatter();
private static string GetNotEquivalentMessage(JToken actual, JToken expected,
string reason = null, params object[] reasonArgs)
{
var diff = ObjectDiffPatch.GenerateDiff(actual, expected);
var key = diff.NewValues?.First ?? diff.OldValues?.First;
var because = string.Empty;
if (!string.IsNullOrWhiteSpace(reason))
because = " because " + string.Format(reason, reasonArgs);
var expectedMessage = $"Expected JSON document {_formatter.ToString(actual)}" +
$" to be equivalent to {_formatter.ToString(expected)}" +
$"{because}, but differs at {_formatter.ToString(key)}.";
return expectedMessage;
}
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - [email protected]
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Configuration;
using HtmlAgilityPack;
using Magix.Core;
namespace Magix.web
{
/*
* web helper core
*/
internal sealed class HttpCore : ActiveController
{
/*
* return the given http get parameter
*/
[ActiveEvent(Name = "magix.web.get-parameter")]
private void magix_web_get_parameter(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.get-parameter-dox].value");
AppendCodeFromResource(
ip,
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.get-parameter-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("name"))
throw new ArgumentException("no [name] given to [magix.web.get-parameter]");
string name = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false);
if (HttpContext.Current.Request.Params[name] != null)
ip["value"].Value = HttpUtility.UrlDecode(HttpContext.Current.Request.Params[name]);
}
/*
* transfer a file to client
*/
[ActiveEvent(Name = "magix.web.get-url")]
private void magix_web_get_url(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.get-url-dox].value");
AppendCodeFromResource(
ip,
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.get-url-sample]");
return;
}
ip["url"].Value = HttpUtility.UrlDecode(HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower().Replace("default.aspx", ""));
}
/*
* transfer a file to client
*/
[ActiveEvent(Name = "magix.web.transfer-file")]
private void magix_web_transfer_file(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.transfer-file-dox].value");
AppendCodeFromResource(
ip,
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.transfer-file-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("file"))
throw new ArgumentException("no [file] given to [magix.web.transfer-file]");
string file = Page.Server.MapPath(Expressions.GetExpressionValue<string>(ip["file"].Get<string>(), dp, ip, false));
FileInfo fileInfo = new FileInfo(file);
string fileAs = fileInfo.Name;
if (ip.ContainsValue("as"))
fileAs = Expressions.GetExpressionValue<string>(ip["as"].Get<string>(), dp, ip, false);
// transmitting file
Page.Response.Filter = null; // ditching magix ux filter rendering ...
Page.Response.ClearContent();
Page.Response.ClearHeaders();
Page.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileAs));
Page.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Page.Response.ContentType = GetContentType(fileInfo.Extension.ToLower());
Page.Response.TransmitFile(file);
Page.Response.Flush();
Page.Response.End();
}
/*
* helper for above
*/
private string GetContentType(string extension)
{
switch (extension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
default:
return "application/octet-stream";
}
}
/*
* strips html from node
*/
[ActiveEvent(Name = "magix.web.strip-html")]
private void magix_web_strip_html(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.strip-html-dox].value");
AppendCodeFromResource(
ip,
"Magix.web",
"Magix.web.hyperlisp.inspect.hl",
"[magix.web.strip-html-sample]");
return;
}
Node dp = Dp(e.Params);
string html = Expressions.GetExpressionValue<string>(ip["value"].Get<string>(), dp, ip, false);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
ip["result"].Value = doc.DocumentNode.InnerText;
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap 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 Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using NetTopologySuite.Geometries;
using SharpMap.CoordinateSystems;
using SharpMap.Rendering.Exceptions;
using SharpMap.Web.Wms;
using Common.Logging;
namespace SharpMap.Layers
{
/// <summary>
/// Web Map Service layer
/// </summary>
/// <remarks>
/// The WmsLayer is currently very basic and doesn't support automatic fetching of the WMS Service Description.
/// Instead you would have to add the necessary parameters to the URL,
/// and the WmsLayer will set the remaining BoundingBox property and proper requests that changes between the requests.
/// See the example below.
/// </remarks>
/// <example>
/// The following example creates a map with a WMS layer the Demis WMS Server
/// <code lang="C#">
/// myMap = new SharpMap.Map(new System.Drawing.Size(500,250);
/// string wmsUrl = "http://www2.demis.nl/mapserver/request.asp";
/// SharpMap.Layers.WmsLayer myLayer = new SharpMap.Layers.WmsLayer("Demis WMS", myLayer);
/// myLayer.AddLayer("Bathymetry");
/// myLayer.AddLayer("Countries");
/// myLayer.AddLayer("Topography");
/// myLayer.AddLayer("Hillshading");
/// myLayer.SetImageFormat(layWms.OutputFormats[0]);
/// myLayer.SRID = 4326;
/// myMap.Layers.Add(myLayer);
/// myMap.Center = new NetTopologySuite.Geometries.Coordinate(0, 0);
/// myMap.Zoom = 360;
/// myMap.MaximumZoom = 360;
/// myMap.MinimumZoom = 0.1;
/// </code>
/// </example>
[Serializable]
public class WmsLayer : Layer
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(WmsLayer));
private Boolean _continueOnError;
//private ICredentials _credentials;
[NonSerialized]
private ImageAttributes _imageAttributes;
private float _opacity = 1.0f;
private readonly Collection<string> _layerList;
private string _mimeType = "";
//private IWebProxy _proxy;
private readonly Collection<string> _stylesList;
//private int _timeOut;
private readonly Client _wmsClient;
private bool _transparent = true;
private Color _bgColor = Color.White;
//private readonly string _capabilitiesUrl;
private Envelope _envelope;
/// <summary>
/// Initializes a new layer, and downloads and parses the service description
/// </summary>
/// <remarks>In and ASP.NET application the service description is automatically cached for 24 hours when not specified</remarks>
/// <param name="layername">Layername</param>
/// <param name="url">Url of WMS server</param>
public WmsLayer(string layername, string url)
: this(layername, url, new TimeSpan(24, 0, 0))
{
}
/// <summary>
/// Initializes a new layer, and downloads and parses the service description
/// </summary>
/// <param name="layername">Layername</param>
/// <param name="url">Url of WMS server</param>
/// <param name="cachetime">Time for caching Service Description (ASP.NET only)</param>
public WmsLayer(string layername, string url, TimeSpan cachetime)
: this(layername, url, cachetime, null)
{
}
/// <summary>
/// Initializes a new layer, and downloads and parses the service description
/// </summary>
/// <remarks>In and ASP.NET application the service description is automatically cached for 24 hours when not specified</remarks>
/// <param name="layername">Layername</param>
/// <param name="url">Url of WMS server</param>
/// <param name="proxy">Proxy</param>
public WmsLayer(string layername, string url, IWebProxy proxy)
: this(layername, url, new TimeSpan(24, 0, 0), proxy)
{
}
/// <summary>
/// Initializes a new layer, and downloads and parses the service description
/// </summary>
/// <param name="layername">Layername</param>
/// <param name="url">Url of WMS server</param>
/// <param name="cachetime">Time for caching Service Description (ASP.NET only)</param>
/// <param name="proxy">Proxy</param>
public WmsLayer(string layername, string url, TimeSpan cachetime, IWebProxy proxy)
: this(layername, url, cachetime, proxy, null)
{
}
/// <summary>
/// Initializes a new layer, and downloads and parses the service description
/// </summary>
/// <param name="layername">Layername</param>
/// <param name="url">Url of WMS server</param>
/// <param name="cachetime">Time for caching Service Description (ASP.NET only)</param>
/// <param name="proxy">Proxy</param>
/// <param name="credentials"></param>
public WmsLayer(string layername, string url, TimeSpan cachetime, IWebProxy proxy,
ICredentials credentials)
:this(layername, GetClient(url, proxy, credentials, cachetime))
{
}
private static Client GetClient(string capabilitiesUrl, IWebProxy proxy, ICredentials credentials, TimeSpan cacheTime)
{
if (!Web.HttpCacheUtility.TryGetValue("SharpMap_WmsClient_" + capabilitiesUrl, out Client result))
{
if (Logger.IsDebugEnabled)
Logger.Debug("Creating new client for url " + capabilitiesUrl);
result = new Client(capabilitiesUrl, proxy, credentials);
if (!Web.HttpCacheUtility.TryAddValue("SharpMap_WmsClient_" + capabilitiesUrl, result, cacheTime))
{
if (Logger.IsDebugEnabled)
Logger.Debug("Adding client to Cache for url " + capabilitiesUrl + " failed");
}
}
else
{
if (Logger.IsDebugEnabled)
Logger.Debug("Created client from Cache for url " + capabilitiesUrl);
}
return result;
}
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="layername"></param>
/// <param name="wmsClient"></param>
public WmsLayer(string layername, Client wmsClient)
{
_wmsClient = wmsClient;
_continueOnError = true;
LayerName = layername;
//Set default mimetype - We prefer compressed formats
if (OutputFormats.Contains("image/jpeg")) _mimeType = "image/jpeg";
else if (OutputFormats.Contains("image/png")) _mimeType = "image/png";
else if (OutputFormats.Contains("image/gif")) _mimeType = "image/gif";
else //None of the default formats supported - Look for the first supported output format
{
bool formatSupported = false;
foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
if (OutputFormats.Contains(encoder.MimeType.ToLower()))
{
formatSupported = true;
_mimeType = encoder.MimeType;
break;
}
if (!formatSupported)
throw new ArgumentException(
"GDI+ doesn't not support any of the mimetypes supported by this WMS service");
}
_layerList = new Collection<string>();
_stylesList = new Collection<string>();
}
/// <summary>
/// Can be used to force the OnlineResourceUrl for services that return incorrect (often internal) onlineresources
/// </summary>
/// <param name="url">Url without any OGC specific parameters</param>
public void ForceOnlineResourceUrl(string url)
{
for (int i = 0; i < _wmsClient.GetMapRequests.Length; i++)
{
_wmsClient.GetMapRequests[i].OnlineResource = url;
}
}
/// <summary>
/// Gets the list of enabled layers
/// </summary>
public Collection<string> LayerList
{
get { return _layerList; }
}
/// <summary>
/// Gets the list of enabled styles
/// </summary>
public Collection<string> StylesList
{
get { return _stylesList; }
}
/// <summary>
/// Gets the hierarchical list of available WMS layers from this service
/// </summary>
public Client.WmsServerLayer RootLayer
{
get { return _wmsClient.Layer; }
}
/// <summary>
/// Gets the list of available formats
/// </summary>
public Collection<string> OutputFormats
{
get { return _wmsClient.GetMapOutputFormats; }
}
/// <summary>
/// Sets the optional transparancy. The WMS server might ignore this when not implemented and will ignore if the imageformat is jpg
/// </summary>
[Obsolete("Use Transparent")]
public bool Transparancy
{
get { return Transparent; }
set { Transparent = value; }
}
/// <summary>
/// Sets if the image should have transparent background. The WMS server might ignore this when not implemented and will ignore if the imageformat is jpg
/// </summary>
public bool Transparent
{
get { return _transparent; }
set { _transparent = value; }
}
/// <summary>
/// Gets or sets a value indicating the opacity degree
/// 1.0 = No transparency (Default)
/// 0.0 = full transparency
/// </summary>
public float Opacity
{
get { return _opacity; }
set
{
if (value < 0f) value = 0f;
if (value > 1f) value = 1f;
_opacity = value;
if (_imageAttributes != null)
_imageAttributes.Dispose();
if (_opacity < 1f)
{
_imageAttributes = new ImageAttributes();
_imageAttributes.SetColorMatrix(new ColorMatrix { Matrix33 = _opacity },
ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
}
}
}
/// <summary>
/// Set the opacity on the drawn image, this method updates the ImageAttributes with opacity-values and is used when sharpmap draws the image, the the wms-server
/// 1.0 = No transparency
/// 0.0 = full transparency
/// </summary>
/// <param name="opacity"></param>
public void SetOpacity(float opacity)
{
Opacity = opacity;
}
/// <summary>
/// Sets the optional backgroundcolor.
/// </summary>
public Color BgColor
{
get { return _bgColor; }
set { _bgColor = value; }
}
/// <summary>
/// Gets the service description from this server
/// </summary>
public Capabilities.WmsServiceDescription ServiceDescription
{
get { return _wmsClient.ServiceDescription; }
}
/// <summary>
/// Gets or sets the WMS Server version of this service
/// </summary>
public string Version
{
get { return _wmsClient.Version; }
set { _wmsClient.Version = value; }
}
/// <summary>
/// Gets a value indicating the URL for the 'GetCapablities' request
/// </summary>
public string CapabilitiesUrl
{
get { return _wmsClient.CapabilitiesUrl; }
}
/// <summary>
/// When specified, applies image attributes at image (fx. make WMS layer semi-transparent)
/// </summary>
/// <remarks>
/// <para>You can make the WMS layer semi-transparent by settings a up a ColorMatrix,
/// or scale/translate the colors in any other way you like.</para>
/// <example>
/// Setting the WMS layer to be semi-transparent.
/// <code lang="C#">
/// float[][] colorMatrixElements = {
/// new float[] {1, 0, 0, 0, 0},
/// new float[] {0, 1, 0, 0, 0},
/// new float[] {0, 0, 1, 0, 0},
/// new float[] {0, 0, 0, 0.5, 0},
/// new float[] {0, 0, 0, 0, 1}};
/// ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
/// ImageAttributes imageAttributes = new ImageAttributes();
/// imageAttributes.SetColorMatrix(
/// colorMatrix,
/// ColorMatrixFlag.Default,
/// ColorAdjustType.Bitmap);
/// myWmsLayer.ImageAttributes = imageAttributes;
/// </code>
/// </example>
/// </remarks>
[Obsolete("Use transparency instead")]
public ImageAttributes ImageAttributes
{
get { return _imageAttributes; }
set { _imageAttributes = value; }
}
/// <summary>
/// Returns the extent of the layer
/// </summary>
/// <returns>Bounding box corresponding to the extent of the features in the layer</returns>
public override Envelope Envelope
{
get
{
return _envelope ?? (_envelope = GetEnvelope());
}
}
public override int SRID
{
get { return base.SRID; }
set
{
base.SRID = value;
_envelope = null;
}
}
/// <summary>
/// Specifies whether to throw an exception if the Wms request failed, or to just skip rendering the layer
/// </summary>
public Boolean ContinueOnError
{
get { return _continueOnError; }
set { _continueOnError = value; }
}
/// <summary>
/// Provides the base authentication interface for retrieving credentials for Web client authentication.
/// </summary>
public ICredentials Credentials
{
get { return _wmsClient.Credentials; }
set { _wmsClient.Credentials = value; }
}
/// <summary>
/// Gets or sets the proxy used for requesting a webresource
/// </summary>
public IWebProxy Proxy
{
get { return _wmsClient.Proxy; }
set { _wmsClient.Proxy = value; }
}
/// <summary>
/// Timeout of webrequest in milliseconds. Defaults to 10 seconds
/// </summary>
public int TimeOut
{
get { return _wmsClient.TimeOut; }
set { _wmsClient.TimeOut = value; }
}
/// <summary>
/// Adds a layer to WMS request
/// </summary>
/// <remarks>Layer names are case sensitive.</remarks>
/// <param name="name">Name of layer</param>
/// <exception cref="System.ArgumentException">Throws an exception is an unknown layer is added</exception>
public void AddLayer(string name)
{
if (!LayerExists(_wmsClient.Layer, name))
throw new ArgumentException("Cannot add WMS Layer - Unknown layername");
_layerList.Add(name);
}
/// <summary>
/// Recursive method for checking whether a layername exists
/// </summary>
/// <param name="wmsServerLayer">The WMS Server layer</param>
/// <param name="name">The name of the desired layer</param>
/// <returns></returns>
private static bool LayerExists(Client.WmsServerLayer wmsServerLayer, string name)
{
if (name == wmsServerLayer.Name)
{
return true;
}
foreach (Client.WmsServerLayer childlayer in wmsServerLayer.ChildLayers)
{
if (LayerExists(childlayer, name)) return true;
}
return false;
}
/// <summary>
/// Removes a layer from the layer list
/// </summary>
/// <param name="name">Name of layer to remove</param>
public void RemoveLayer(string name)
{
_layerList.Remove(name);
}
/// <summary>
/// Removes the layer at the specified index
/// </summary>
/// <param name="index"></param>
public void RemoveLayerAt(int index)
{
_layerList.RemoveAt(index);
}
/// <summary>
/// Removes all layers
/// </summary>
public void RemoveAllLayers()
{
_layerList.Clear();
}
/// <summary>
/// Adds a style to the style collection
/// </summary>
/// <param name="name">Name of style</param>
/// <exception cref="System.ArgumentException">Throws an exception is an unknown layer is added</exception>
public void AddStyle(string name)
{
if (!StyleExists(_wmsClient.Layer, name))
throw new ArgumentException("Cannot add WMS Layer - Unknown layername");
_stylesList.Add(name);
}
/// <summary>
/// Recursive method for checking whether a layername exists
/// </summary>
/// <param name="layer">layer</param>
/// <param name="name">name of style</param>
/// <returns>True of style exists</returns>
private static bool StyleExists(Client.WmsServerLayer layer, string name)
{
foreach (Client.WmsLayerStyle style in layer.Style)
{
if (name == style.Name) return true;
}
foreach (Client.WmsServerLayer childlayer in layer.ChildLayers)
{
if (StyleExists(childlayer, name)) return true;
}
return false;
}
/// <summary>
/// Removes a style from the collection
/// </summary>
/// <param name="name">Name of style</param>
public void RemoveStyle(string name)
{
_stylesList.Remove(name);
}
/// <summary>
/// Removes a style at specified index
/// </summary>
/// <param name="index">Index</param>
public void RemoveStyleAt(int index)
{
_stylesList.RemoveAt(index);
}
/// <summary>
/// Removes all styles from the list
/// </summary>
public void RemoveAllStyles()
{
_stylesList.Clear();
}
/// <summary>
/// Sets the image type to use when requesting images from the WMS server
/// </summary>
/// <remarks>
/// <para>See the <see cref="OutputFormats"/> property for a list of available mime types supported by the WMS server</para>
/// </remarks>
/// <exception cref="ArgumentException">Throws an exception if either the mime type isn't offered by the WMS
/// or GDI+ doesn't support this mime type.</exception>
/// <param name="mimeType">Mime type of image format</param>
public void SetImageFormat(string mimeType)
{
if (!OutputFormats.Contains(mimeType))
throw new ArgumentException("WMS service doesn't not offer mimetype '" + mimeType + "'");
//Check whether SharpMap supports the specified mimetype
bool formatSupported = false;
foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
if (encoder.MimeType.ToLower() == mimeType.ToLower())
{
formatSupported = true;
break;
}
if (!formatSupported)
throw new ArgumentException("GDI+ doesn't not support mimetype '" + mimeType + "'");
_mimeType = mimeType;
}
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="g">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
public override void Render(Graphics g, MapViewport map)
{
if (Logger.IsDebugEnabled)
Logger.Debug("Rendering wmslayer: " + LayerName);
Client.WmsOnlineResource resource = GetPreferredMethod();
var myUri = new Uri(GetRequestUrl(map.Envelope, map.Size));
if (Logger.IsDebugEnabled)
Logger.Debug("Url: " + myUri);
var myWebRequest = WebRequest.Create(myUri);
myWebRequest.Method = resource.Type;
myWebRequest.Timeout = TimeOut;
if (myWebRequest is HttpWebRequest)
{
(myWebRequest as HttpWebRequest).Accept = _mimeType;
(myWebRequest as HttpWebRequest).KeepAlive = false;
(myWebRequest as HttpWebRequest).UserAgent = "SharpMap-WMSLayer";
}
if (Credentials != null)
{
myWebRequest.Credentials = Credentials;
myWebRequest.PreAuthenticate = true;
}
else
myWebRequest.Credentials = CredentialCache.DefaultCredentials;
if (Proxy != null)
myWebRequest.Proxy = Proxy;
try
{
if (Logger.IsDebugEnabled)
Logger.Debug("Beginning request");
using(var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
{
if (Logger.IsDebugEnabled)
Logger.Debug("Got response");
using (var dataStream = myWebResponse.GetResponseStream())
{
if (dataStream != null && myWebResponse.ContentType.StartsWith("image"))
{
if (Logger.IsDebugEnabled)
Logger.Debug("Reading image from stream");
var cLength = (int) myWebResponse.ContentLength;
if (Logger.IsDebugEnabled)
Logger.Debug("Content-Length: " + cLength);
Image img;
using (var ms = new MemoryStream())
{
var buf = new byte[50000];
int numRead = 0;
DateTime lastTimeGotData = DateTime.Now;
var moreToRead = true;
do
{
try
{
int nr = dataStream.Read(buf, 0, buf.Length);
ms.Write(buf, 0, nr);
numRead += nr;
if (nr == 0)
{
int testByte = dataStream.ReadByte();
if (testByte == -1)
{
//moreToRead = false;
break;
}
if ((DateTime.Now - lastTimeGotData).TotalSeconds > TimeOut)
{
if (Logger.IsInfoEnabled)
Logger.Info("Did not get any data for " + TimeOut +
" seconds, aborting");
return;
}
if (Logger.IsDebugEnabled)
Logger.Debug("No data to read. Have received: " +
numRead + " of " + cLength);
//Did not get data... sleep for a while to not spin
System.Threading.Thread.Sleep(10);
}
else
{
lastTimeGotData = DateTime.Now;
}
}
catch (IOException /*ee*/)
{
//This can be valid since in some cases .NET failed to parse 0-sized chunks in responses..
//For now, just safely ignore the exception and assume we read all data...
//Either way we will get an error later if we did not..
moreToRead = false;
}
catch (Exception ee)
{
Logger.Error("Error reading from WMS-server..", ee);
throw;
}
} while (moreToRead);
if (Logger.IsDebugEnabled)
Logger.Debug("Have received: " + numRead);
ms.Seek(0, SeekOrigin.Begin);
img = Image.FromStream(ms);
}
if (Logger.IsDebugEnabled)
Logger.Debug("Image read.. Drawing");
if (_imageAttributes != null)
g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0,
img.Width, img.Height, GraphicsUnit.Pixel, _imageAttributes);
else
g.DrawImage(img, Rectangle.FromLTRB(0, 0, map.Size.Width, map.Size.Height));
if (Logger.IsDebugEnabled)
Logger.Debug("Draw complete");
dataStream.Close();
}
}
myWebResponse.Close();
}
}
catch (WebException webEx)
{
if (!_continueOnError)
throw (new RenderException(
"There was a problem connecting to the WMS server when rendering layer '" + LayerName + "'",
webEx));
Logger.Error("There was a problem connecting to the WMS server when rendering layer '" + LayerName +
"'", webEx);
}
catch (Exception ex)
{
if (!_continueOnError)
throw (new RenderException("There was a problem rendering layer '" + LayerName + "'", ex));
Logger.Error("There was a problem connecting to the WMS server when rendering layer '" + LayerName +
"'", ex);
}
base.Render(g, map);
}
/// <summary>
/// Gets the URL for a map request base on current settings, the image size and boundingbox
/// </summary>
/// <param name="box">Area the WMS request should cover</param>
/// <param name="size">Size of image</param>
/// <returns>URL for WMS request</returns>
public virtual string GetRequestUrl(Envelope box, Size size)
{
Client.WmsOnlineResource resource = GetPreferredMethod();
var strReq = new StringBuilder(resource.OnlineResource);
if (!resource.OnlineResource.Contains("?"))
strReq.Append("?");
if (!strReq.ToString().EndsWith("&") && !strReq.ToString().EndsWith("?"))
strReq.Append("&");
strReq.AppendFormat(Map.NumberFormatEnUs, "REQUEST=GetMap&BBOX={0},{1},{2},{3}",
box.MinX, box.MinY, box.MaxX, box.MaxY);
strReq.AppendFormat("&WIDTH={0}&HEIGHT={1}", size.Width, size.Height);
strReq.Append("&LAYERS=");
if (_layerList != null && _layerList.Count > 0)
{
foreach (string layer in _layerList)
strReq.AppendFormat("{0},", layer);
strReq.Remove(strReq.Length - 1, 1);
}
strReq.AppendFormat("&FORMAT={0}", _mimeType);
if (SRID < 0)
throw new ApplicationException("Spatial reference system not set");
if (Version == "1.3.0")
strReq.AppendFormat("&CRS={0}:{1}", Authority, SRID);
else
strReq.AppendFormat("&SRS={0}:{1}", Authority, SRID);
strReq.AppendFormat("&VERSION={0}", Version);
strReq.Append("&Styles=");
if (_stylesList != null && _stylesList.Count > 0)
{
foreach (string style in _stylesList)
strReq.AppendFormat("{0},", style);
strReq.Remove(strReq.Length - 1, 1);
}
strReq.AppendFormat("&TRANSPARENT={0}", Transparent);
if (!Transparent)
{
//var background = Uri.EscapeDataString(ColorTranslator.ToHtml(_bgColor));
strReq.AppendFormat("&BGCOLOR={0}", ToHexValue(_bgColor));
}
return strReq.ToString();
}
/// <summary>
/// Gets or sets a value indicating the authority of the spatial reference system.
/// </summary>
/// <remarks>Must not be <value>null</value></remarks>
public string Authority { get; set; } = "EPSG";
private static string ToHexValue(Color color)
{
return color.R.ToString("X2") +
color.G.ToString("X2") +
color.B.ToString("X2");
}
/// <summary>
/// Returns the preferred URL to use when communicating with the wms-server
/// Favors GET-requests over POST-requests
/// </summary>
/// <returns>Instance of Client.WmsOnlineResource</returns>
protected Client.WmsOnlineResource GetPreferredMethod()
{
//We prefer get. Seek for supported 'get' method
for (int i = 0; i < _wmsClient.GetMapRequests.Length; i++)
if (_wmsClient.GetMapRequests[i].Type.ToLower() == "get")
return _wmsClient.GetMapRequests[i];
//Next we prefer the 'post' method
for (int i = 0; i < _wmsClient.GetMapRequests.Length; i++)
if (_wmsClient.GetMapRequests[i].Type.ToLower() == "post")
return _wmsClient.GetMapRequests[i];
return _wmsClient.GetMapRequests[0];
}
private Envelope GetEnvelope()
{
var boxes = new Collection<Envelope>();
var sridBoxes = getBoundingBoxes(RootLayer);
foreach (var sridBox in sridBoxes)
{
if (SRID == sridBox.SRID)
boxes.Add(sridBox);
}
if (boxes.Count > 0)
{
var res = new Envelope();
foreach (var envelope in boxes)
res.ExpandToInclude(envelope);
return res;
}
if (SRID == 4326)
return RootLayer.LatLonBoundingBox;
try
{
var projection = this.GetCoordinateSystem();
if (projection == null)
{
Logger.Warn("WmsLayer envelope is null because there is no Coordinate System found for SRID " + SRID);
return null;
}
var wgs84 = Session.Instance.CoordinateSystemServices.GetCoordinateSystem(4326);
var transformation = Session.Instance.CoordinateSystemServices.CreateTransformation(wgs84, projection);
return ToTarget(RootLayer.LatLonBoundingBox, transformation);
}
catch (Exception e)
{
Logger.Warn("Error calculating Envelope Transformation from WGS84 to SRID " + SRID, e);
return null;
}
}
/// <summary>
/// Gets all the boundingboxes from the Client.WmsServerLayer
/// </summary>
/// <returns>List of all spatial referenced boundingboxes</returns>
private List<SpatialReferencedBoundingBox> getBoundingBoxes(Client.WmsServerLayer layer)
{
var box = new List<SpatialReferencedBoundingBox>();
box.AddRange(layer.SRIDBoundingBoxes);
if (layer.ChildLayers.Length > 0)
{
for (int i = 0; i < layer.ChildLayers.Length; i++)
{
box.AddRange(getBoundingBoxes(layer.ChildLayers[i]));
}
}
return box;
}
/// <summary>
/// Recursive method for adding all WMS layers to layer list
/// Skips "top level" layer if addFirstLayer is false
/// </summary>
/// <param name="wmsServerLayer"></param>
/// <param name="addFirstLayer"></param>
/// <returns></returns>
public void AddChildLayers(Client.WmsServerLayer wmsServerLayer, bool addFirstLayer)
{
if (addFirstLayer)
{
AddLayer(wmsServerLayer.Name);
}
foreach (Client.WmsServerLayer childlayer in wmsServerLayer.ChildLayers)
{
AddChildLayers(childlayer, true);
}
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>CustomConversionGoal</c> resource.</summary>
public sealed partial class CustomConversionGoalName : gax::IResourceName, sys::IEquatable<CustomConversionGoalName>
{
/// <summary>The possible contents of <see cref="CustomConversionGoalName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </summary>
CustomerGoal = 1,
}
private static gax::PathTemplate s_customerGoal = new gax::PathTemplate("customers/{customer_id}/customConversionGoals/{goal_id}");
/// <summary>Creates a <see cref="CustomConversionGoalName"/> 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="CustomConversionGoalName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomConversionGoalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomConversionGoalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomConversionGoalName"/> with the pattern
/// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CustomConversionGoalName"/> constructed from the provided ids.
/// </returns>
public static CustomConversionGoalName FromCustomerGoal(string customerId, string goalId) =>
new CustomConversionGoalName(ResourceNameType.CustomerGoal, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), goalId: gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </returns>
public static string Format(string customerId, string goalId) => FormatCustomerGoal(customerId, goalId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>.
/// </returns>
public static string FormatCustomerGoal(string customerId, string goalId) =>
s_customerGoal.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomConversionGoalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomConversionGoalName"/> if successful.</returns>
public static CustomConversionGoalName Parse(string customConversionGoalName) =>
Parse(customConversionGoalName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomConversionGoalName"/> 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>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customConversionGoalName">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="CustomConversionGoalName"/> if successful.</returns>
public static CustomConversionGoalName Parse(string customConversionGoalName, bool allowUnparsed) =>
TryParse(customConversionGoalName, allowUnparsed, out CustomConversionGoalName 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="CustomConversionGoalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomConversionGoalName"/>, 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 customConversionGoalName, out CustomConversionGoalName result) =>
TryParse(customConversionGoalName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomConversionGoalName"/> 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>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customConversionGoalName">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="CustomConversionGoalName"/>, 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 customConversionGoalName, bool allowUnparsed, out CustomConversionGoalName result)
{
gax::GaxPreconditions.CheckNotNull(customConversionGoalName, nameof(customConversionGoalName));
gax::TemplatedResourceName resourceName;
if (s_customerGoal.TryParseName(customConversionGoalName, out resourceName))
{
result = FromCustomerGoal(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customConversionGoalName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomConversionGoalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string goalId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
GoalId = goalId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomConversionGoalName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param>
public CustomConversionGoalName(string customerId, string goalId) : this(ResourceNameType.CustomerGoal, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), goalId: gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId)))
{
}
/// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Goal</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string GoalId { 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.CustomerGoal: return s_customerGoal.Expand(CustomerId, GoalId);
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 CustomConversionGoalName);
/// <inheritdoc/>
public bool Equals(CustomConversionGoalName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomConversionGoalName a, CustomConversionGoalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomConversionGoalName a, CustomConversionGoalName b) => !(a == b);
}
public partial class CustomConversionGoal
{
/// <summary>
/// <see cref="gagvr::CustomConversionGoalName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomConversionGoalName ResourceNameAsCustomConversionGoalName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomConversionGoalName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CustomConversionGoalName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CustomConversionGoalName CustomConversionGoalName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomConversionGoalName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="ConversionActionName"/>-typed view over the <see cref="ConversionActions"/> resource name
/// property.
/// </summary>
internal gax::ResourceNameList<ConversionActionName> ConversionActionsAsConversionActionNames
{
get => new gax::ResourceNameList<ConversionActionName>(ConversionActions, s => string.IsNullOrEmpty(s) ? null : ConversionActionName.Parse(s, allowUnparsed: true));
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/Battle/BattleAction.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data.Battle {
/// <summary>Holder for reflection information generated from POGOProtos/Data/Battle/BattleAction.proto</summary>
public static partial class BattleActionReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/Battle/BattleAction.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static BattleActionReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CilQT0dPUHJvdG9zL0RhdGEvQmF0dGxlL0JhdHRsZUFjdGlvbi5wcm90bxIW",
"UE9HT1Byb3Rvcy5EYXRhLkJhdHRsZRoqUE9HT1Byb3Rvcy9EYXRhL0JhdHRs",
"ZS9CYXR0bGVSZXN1bHRzLnByb3RvGi1QT0dPUHJvdG9zL0RhdGEvQmF0dGxl",
"L0JhdHRsZUFjdGlvblR5cGUucHJvdG8aLlBPR09Qcm90b3MvRGF0YS9CYXR0",
"bGUvQmF0dGxlUGFydGljaXBhbnQucHJvdG8ihQQKDEJhdHRsZUFjdGlvbhI2",
"CgRUeXBlGAEgASgOMiguUE9HT1Byb3Rvcy5EYXRhLkJhdHRsZS5CYXR0bGVB",
"Y3Rpb25UeXBlEhcKD2FjdGlvbl9zdGFydF9tcxgCIAEoAxITCgtkdXJhdGlv",
"bl9tcxgDIAEoBRIUCgxlbmVyZ3lfZGVsdGEYBSABKAUSFgoOYXR0YWNrZXJf",
"aW5kZXgYBiABKAUSFAoMdGFyZ2V0X2luZGV4GAcgASgFEhkKEWFjdGl2ZV9w",
"b2tlbW9uX2lkGAggASgGEkAKDXBsYXllcl9qb2luZWQYCSABKAsyKS5QT0dP",
"UHJvdG9zLkRhdGEuQmF0dGxlLkJhdHRsZVBhcnRpY2lwYW50Ej0KDmJhdHRs",
"ZV9yZXN1bHRzGAogASgLMiUuUE9HT1Byb3Rvcy5EYXRhLkJhdHRsZS5CYXR0",
"bGVSZXN1bHRzEioKImRhbWFnZV93aW5kb3dzX3N0YXJ0X3RpbWVzdGFtcF9t",
"c3MYCyABKAMSKAogZGFtYWdlX3dpbmRvd3NfZW5kX3RpbWVzdGFtcF9tc3MY",
"DCABKAMSPgoLcGxheWVyX2xlZnQYDSABKAsyKS5QT0dPUHJvdG9zLkRhdGEu",
"QmF0dGxlLkJhdHRsZVBhcnRpY2lwYW50EhkKEXRhcmdldF9wb2tlbW9uX2lk",
"GA4gASgGYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Data.Battle.BattleResultsReflection.Descriptor, global::POGOProtos.Data.Battle.BattleActionTypeReflection.Descriptor, global::POGOProtos.Data.Battle.BattleParticipantReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Battle.BattleAction), global::POGOProtos.Data.Battle.BattleAction.Parser, new[]{ "Type", "ActionStartMs", "DurationMs", "EnergyDelta", "AttackerIndex", "TargetIndex", "ActivePokemonId", "PlayerJoined", "BattleResults", "DamageWindowsStartTimestampMss", "DamageWindowsEndTimestampMss", "PlayerLeft", "TargetPokemonId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class BattleAction : pb::IMessage<BattleAction> {
private static readonly pb::MessageParser<BattleAction> _parser = new pb::MessageParser<BattleAction>(() => new BattleAction());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BattleAction> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.Battle.BattleActionReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BattleAction() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BattleAction(BattleAction other) : this() {
type_ = other.type_;
actionStartMs_ = other.actionStartMs_;
durationMs_ = other.durationMs_;
energyDelta_ = other.energyDelta_;
attackerIndex_ = other.attackerIndex_;
targetIndex_ = other.targetIndex_;
activePokemonId_ = other.activePokemonId_;
PlayerJoined = other.playerJoined_ != null ? other.PlayerJoined.Clone() : null;
BattleResults = other.battleResults_ != null ? other.BattleResults.Clone() : null;
damageWindowsStartTimestampMss_ = other.damageWindowsStartTimestampMss_;
damageWindowsEndTimestampMss_ = other.damageWindowsEndTimestampMss_;
PlayerLeft = other.playerLeft_ != null ? other.PlayerLeft.Clone() : null;
targetPokemonId_ = other.targetPokemonId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BattleAction Clone() {
return new BattleAction(this);
}
/// <summary>Field number for the "Type" field.</summary>
public const int TypeFieldNumber = 1;
private global::POGOProtos.Data.Battle.BattleActionType type_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Data.Battle.BattleActionType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "action_start_ms" field.</summary>
public const int ActionStartMsFieldNumber = 2;
private long actionStartMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long ActionStartMs {
get { return actionStartMs_; }
set {
actionStartMs_ = value;
}
}
/// <summary>Field number for the "duration_ms" field.</summary>
public const int DurationMsFieldNumber = 3;
private int durationMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int DurationMs {
get { return durationMs_; }
set {
durationMs_ = value;
}
}
/// <summary>Field number for the "energy_delta" field.</summary>
public const int EnergyDeltaFieldNumber = 5;
private int energyDelta_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int EnergyDelta {
get { return energyDelta_; }
set {
energyDelta_ = value;
}
}
/// <summary>Field number for the "attacker_index" field.</summary>
public const int AttackerIndexFieldNumber = 6;
private int attackerIndex_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int AttackerIndex {
get { return attackerIndex_; }
set {
attackerIndex_ = value;
}
}
/// <summary>Field number for the "target_index" field.</summary>
public const int TargetIndexFieldNumber = 7;
private int targetIndex_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int TargetIndex {
get { return targetIndex_; }
set {
targetIndex_ = value;
}
}
/// <summary>Field number for the "active_pokemon_id" field.</summary>
public const int ActivePokemonIdFieldNumber = 8;
private ulong activePokemonId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong ActivePokemonId {
get { return activePokemonId_; }
set {
activePokemonId_ = value;
}
}
/// <summary>Field number for the "player_joined" field.</summary>
public const int PlayerJoinedFieldNumber = 9;
private global::POGOProtos.Data.Battle.BattleParticipant playerJoined_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Data.Battle.BattleParticipant PlayerJoined {
get { return playerJoined_; }
set {
playerJoined_ = value;
}
}
/// <summary>Field number for the "battle_results" field.</summary>
public const int BattleResultsFieldNumber = 10;
private global::POGOProtos.Data.Battle.BattleResults battleResults_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Data.Battle.BattleResults BattleResults {
get { return battleResults_; }
set {
battleResults_ = value;
}
}
/// <summary>Field number for the "damage_windows_start_timestamp_mss" field.</summary>
public const int DamageWindowsStartTimestampMssFieldNumber = 11;
private long damageWindowsStartTimestampMss_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long DamageWindowsStartTimestampMss {
get { return damageWindowsStartTimestampMss_; }
set {
damageWindowsStartTimestampMss_ = value;
}
}
/// <summary>Field number for the "damage_windows_end_timestamp_mss" field.</summary>
public const int DamageWindowsEndTimestampMssFieldNumber = 12;
private long damageWindowsEndTimestampMss_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long DamageWindowsEndTimestampMss {
get { return damageWindowsEndTimestampMss_; }
set {
damageWindowsEndTimestampMss_ = value;
}
}
/// <summary>Field number for the "player_left" field.</summary>
public const int PlayerLeftFieldNumber = 13;
private global::POGOProtos.Data.Battle.BattleParticipant playerLeft_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Data.Battle.BattleParticipant PlayerLeft {
get { return playerLeft_; }
set {
playerLeft_ = value;
}
}
/// <summary>Field number for the "target_pokemon_id" field.</summary>
public const int TargetPokemonIdFieldNumber = 14;
private ulong targetPokemonId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong TargetPokemonId {
get { return targetPokemonId_; }
set {
targetPokemonId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BattleAction);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BattleAction other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Type != other.Type) return false;
if (ActionStartMs != other.ActionStartMs) return false;
if (DurationMs != other.DurationMs) return false;
if (EnergyDelta != other.EnergyDelta) return false;
if (AttackerIndex != other.AttackerIndex) return false;
if (TargetIndex != other.TargetIndex) return false;
if (ActivePokemonId != other.ActivePokemonId) return false;
if (!object.Equals(PlayerJoined, other.PlayerJoined)) return false;
if (!object.Equals(BattleResults, other.BattleResults)) return false;
if (DamageWindowsStartTimestampMss != other.DamageWindowsStartTimestampMss) return false;
if (DamageWindowsEndTimestampMss != other.DamageWindowsEndTimestampMss) return false;
if (!object.Equals(PlayerLeft, other.PlayerLeft)) return false;
if (TargetPokemonId != other.TargetPokemonId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Type != 0) hash ^= Type.GetHashCode();
if (ActionStartMs != 0L) hash ^= ActionStartMs.GetHashCode();
if (DurationMs != 0) hash ^= DurationMs.GetHashCode();
if (EnergyDelta != 0) hash ^= EnergyDelta.GetHashCode();
if (AttackerIndex != 0) hash ^= AttackerIndex.GetHashCode();
if (TargetIndex != 0) hash ^= TargetIndex.GetHashCode();
if (ActivePokemonId != 0UL) hash ^= ActivePokemonId.GetHashCode();
if (playerJoined_ != null) hash ^= PlayerJoined.GetHashCode();
if (battleResults_ != null) hash ^= BattleResults.GetHashCode();
if (DamageWindowsStartTimestampMss != 0L) hash ^= DamageWindowsStartTimestampMss.GetHashCode();
if (DamageWindowsEndTimestampMss != 0L) hash ^= DamageWindowsEndTimestampMss.GetHashCode();
if (playerLeft_ != null) hash ^= PlayerLeft.GetHashCode();
if (TargetPokemonId != 0UL) hash ^= TargetPokemonId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Type != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Type);
}
if (ActionStartMs != 0L) {
output.WriteRawTag(16);
output.WriteInt64(ActionStartMs);
}
if (DurationMs != 0) {
output.WriteRawTag(24);
output.WriteInt32(DurationMs);
}
if (EnergyDelta != 0) {
output.WriteRawTag(40);
output.WriteInt32(EnergyDelta);
}
if (AttackerIndex != 0) {
output.WriteRawTag(48);
output.WriteInt32(AttackerIndex);
}
if (TargetIndex != 0) {
output.WriteRawTag(56);
output.WriteInt32(TargetIndex);
}
if (ActivePokemonId != 0UL) {
output.WriteRawTag(65);
output.WriteFixed64(ActivePokemonId);
}
if (playerJoined_ != null) {
output.WriteRawTag(74);
output.WriteMessage(PlayerJoined);
}
if (battleResults_ != null) {
output.WriteRawTag(82);
output.WriteMessage(BattleResults);
}
if (DamageWindowsStartTimestampMss != 0L) {
output.WriteRawTag(88);
output.WriteInt64(DamageWindowsStartTimestampMss);
}
if (DamageWindowsEndTimestampMss != 0L) {
output.WriteRawTag(96);
output.WriteInt64(DamageWindowsEndTimestampMss);
}
if (playerLeft_ != null) {
output.WriteRawTag(106);
output.WriteMessage(PlayerLeft);
}
if (TargetPokemonId != 0UL) {
output.WriteRawTag(113);
output.WriteFixed64(TargetPokemonId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (ActionStartMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(ActionStartMs);
}
if (DurationMs != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(DurationMs);
}
if (EnergyDelta != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(EnergyDelta);
}
if (AttackerIndex != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(AttackerIndex);
}
if (TargetIndex != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(TargetIndex);
}
if (ActivePokemonId != 0UL) {
size += 1 + 8;
}
if (playerJoined_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PlayerJoined);
}
if (battleResults_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BattleResults);
}
if (DamageWindowsStartTimestampMss != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(DamageWindowsStartTimestampMss);
}
if (DamageWindowsEndTimestampMss != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(DamageWindowsEndTimestampMss);
}
if (playerLeft_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PlayerLeft);
}
if (TargetPokemonId != 0UL) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BattleAction other) {
if (other == null) {
return;
}
if (other.Type != 0) {
Type = other.Type;
}
if (other.ActionStartMs != 0L) {
ActionStartMs = other.ActionStartMs;
}
if (other.DurationMs != 0) {
DurationMs = other.DurationMs;
}
if (other.EnergyDelta != 0) {
EnergyDelta = other.EnergyDelta;
}
if (other.AttackerIndex != 0) {
AttackerIndex = other.AttackerIndex;
}
if (other.TargetIndex != 0) {
TargetIndex = other.TargetIndex;
}
if (other.ActivePokemonId != 0UL) {
ActivePokemonId = other.ActivePokemonId;
}
if (other.playerJoined_ != null) {
if (playerJoined_ == null) {
playerJoined_ = new global::POGOProtos.Data.Battle.BattleParticipant();
}
PlayerJoined.MergeFrom(other.PlayerJoined);
}
if (other.battleResults_ != null) {
if (battleResults_ == null) {
battleResults_ = new global::POGOProtos.Data.Battle.BattleResults();
}
BattleResults.MergeFrom(other.BattleResults);
}
if (other.DamageWindowsStartTimestampMss != 0L) {
DamageWindowsStartTimestampMss = other.DamageWindowsStartTimestampMss;
}
if (other.DamageWindowsEndTimestampMss != 0L) {
DamageWindowsEndTimestampMss = other.DamageWindowsEndTimestampMss;
}
if (other.playerLeft_ != null) {
if (playerLeft_ == null) {
playerLeft_ = new global::POGOProtos.Data.Battle.BattleParticipant();
}
PlayerLeft.MergeFrom(other.PlayerLeft);
}
if (other.TargetPokemonId != 0UL) {
TargetPokemonId = other.TargetPokemonId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
type_ = (global::POGOProtos.Data.Battle.BattleActionType) input.ReadEnum();
break;
}
case 16: {
ActionStartMs = input.ReadInt64();
break;
}
case 24: {
DurationMs = input.ReadInt32();
break;
}
case 40: {
EnergyDelta = input.ReadInt32();
break;
}
case 48: {
AttackerIndex = input.ReadInt32();
break;
}
case 56: {
TargetIndex = input.ReadInt32();
break;
}
case 65: {
ActivePokemonId = input.ReadFixed64();
break;
}
case 74: {
if (playerJoined_ == null) {
playerJoined_ = new global::POGOProtos.Data.Battle.BattleParticipant();
}
input.ReadMessage(playerJoined_);
break;
}
case 82: {
if (battleResults_ == null) {
battleResults_ = new global::POGOProtos.Data.Battle.BattleResults();
}
input.ReadMessage(battleResults_);
break;
}
case 88: {
DamageWindowsStartTimestampMss = input.ReadInt64();
break;
}
case 96: {
DamageWindowsEndTimestampMss = input.ReadInt64();
break;
}
case 106: {
if (playerLeft_ == null) {
playerLeft_ = new global::POGOProtos.Data.Battle.BattleParticipant();
}
input.ReadMessage(playerLeft_);
break;
}
case 113: {
TargetPokemonId = input.ReadFixed64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Methods for manipulating arrays.
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class ArrayUtil
{
/// <summary>
/// Maximum length for an array; we set this to "a
/// bit" below <see cref="int.MaxValue"/> because the exact max
/// allowed byte[] is JVM dependent, so we want to avoid
/// a case where a large value worked during indexing on
/// one JVM but failed later at search time with a
/// different JVM.
/// </summary>
public static readonly int MAX_ARRAY_LENGTH = int.MaxValue - 256;
private ArrayUtil() // no instance
{
}
/*
Begin Apache Harmony code
Revision taken on Friday, June 12. https://svn.apache.org/repos/asf/harmony/enhanced/classlib/archive/java6/modules/luni/src/main/java/java/lang/Integer.java
*/
/// <summary>
/// Parses the string argument as if it was an <see cref="int"/> value and returns the
/// result. Throws <see cref="FormatException"/> if the string does not represent an
/// int quantity.
/// <para/>
/// NOTE: This was parseInt() in Lucene
/// </summary>
/// <param name="chars"> A string representation of an int quantity. </param>
/// <returns> The value represented by the argument </returns>
/// <exception cref="FormatException"> If the argument could not be parsed as an int quantity. </exception>
public static int ParseInt32(char[] chars)
{
return ParseInt32(chars, 0, chars.Length, 10);
}
/// <summary>
/// Parses a char array into an <see cref="int"/>.
/// <para/>
/// NOTE: This was parseInt() in Lucene
/// </summary>
/// <param name="chars"> The character array </param>
/// <param name="offset"> The offset into the array </param>
/// <param name="len"> The length </param>
/// <returns> the <see cref="int"/> </returns>
/// <exception cref="FormatException"> If it can't parse </exception>
public static int ParseInt32(char[] chars, int offset, int len)
{
return ParseInt32(chars, offset, len, 10);
}
/// <summary>
/// Parses the string argument as if it was an <see cref="int"/> value and returns the
/// result. Throws <see cref="FormatException"/> if the string does not represent an
/// <see cref="int"/> quantity. The second argument specifies the radix to use when parsing
/// the value.
/// <para/>
/// NOTE: This was parseInt() in Lucene
/// </summary>
/// <param name="chars"> A string representation of an int quantity. </param>
/// <param name="radix"> The base to use for conversion. </param>
/// <returns> The value represented by the argument </returns>
/// <exception cref="FormatException"> If the argument could not be parsed as an int quantity. </exception>
public static int ParseInt32(char[] chars, int offset, int len, int radix)
{
int minRadix = 2, maxRadix = 36;
if (chars == null || radix < minRadix || radix > maxRadix)
{
throw new FormatException();
}
int i = 0;
if (len == 0)
{
throw new FormatException("chars length is 0");
}
bool negative = chars[offset + i] == '-';
if (negative && ++i == len)
{
throw new FormatException("can't convert to an int");
}
if (negative == true)
{
offset++;
len--;
}
return Parse(chars, offset, len, radix, negative);
}
private static int Parse(char[] chars, int offset, int len, int radix, bool negative)
{
int max = int.MinValue / radix;
int result = 0;
for (int i = 0; i < len; i++)
{
int digit = (int)char.GetNumericValue(chars[i + offset]);
if (digit == -1)
{
throw new FormatException("Unable to parse");
}
if (max > result)
{
throw new FormatException("Unable to parse");
}
int next = result * radix - digit;
if (next > result)
{
throw new FormatException("Unable to parse");
}
result = next;
}
/*while (offset < len) {
}*/
if (!negative)
{
result = -result;
if (result < 0)
{
throw new FormatException("Unable to parse");
}
}
return result;
}
/*
END APACHE HARMONY CODE
*/
/// <summary>
/// Returns an array size >= <paramref name="minTargetSize"/>, generally
/// over-allocating exponentially to achieve amortized
/// linear-time cost as the array grows.
/// <para/>
/// NOTE: this was originally borrowed from Python 2.4.2
/// listobject.c sources (attribution in LICENSE.txt), but
/// has now been substantially changed based on
/// discussions from java-dev thread with subject "Dynamic
/// array reallocation algorithms", started on Jan 12
/// 2010.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="minTargetSize"> Minimum required value to be returned. </param>
/// <param name="bytesPerElement"> Bytes used by each element of
/// the array. See constants in <see cref="RamUsageEstimator"/>. </param>
public static int Oversize(int minTargetSize, int bytesPerElement)
{
if (minTargetSize < 0)
{
// catch usage that accidentally overflows int
throw new ArgumentException("invalid array size " + minTargetSize);
}
if (minTargetSize == 0)
{
// wait until at least one element is requested
return 0;
}
// asymptotic exponential growth by 1/8th, favors
// spending a bit more CPU to not tie up too much wasted
// RAM:
int extra = minTargetSize >> 3;
if (extra < 3)
{
// for very small arrays, where constant overhead of
// realloc is presumably relatively high, we grow
// faster
extra = 3;
}
int newSize = minTargetSize + extra;
// add 7 to allow for worst case byte alignment addition below:
if (newSize + 7 < 0)
{
// int overflowed -- return max allowed array size
return int.MaxValue;
}
if (Constants.RUNTIME_IS_64BIT)
{
// round up to 8 byte alignment in 64bit env
switch (bytesPerElement)
{
case 4:
// round up to multiple of 2
return (newSize + 1) & 0x7ffffffe;
case 2:
// round up to multiple of 4
return (newSize + 3) & 0x7ffffffc;
case 1:
// round up to multiple of 8
return (newSize + 7) & 0x7ffffff8;
case 8:
// no rounding
default:
// odd (invalid?) size
return newSize;
}
}
else
{
// round up to 4 byte alignment in 64bit env
switch (bytesPerElement)
{
case 2:
// round up to multiple of 2
return (newSize + 1) & 0x7ffffffe;
case 1:
// round up to multiple of 4
return (newSize + 3) & 0x7ffffffc;
case 4:
case 8:
// no rounding
default:
// odd (invalid?) size
return newSize;
}
}
}
public static int GetShrinkSize(int currentSize, int targetSize, int bytesPerElement)
{
int newSize = Oversize(targetSize, bytesPerElement);
// Only reallocate if we are "substantially" smaller.
// this saves us from "running hot" (constantly making a
// bit bigger then a bit smaller, over and over):
if (newSize < currentSize / 2)
{
return newSize;
}
else
{
return currentSize;
}
}
public static short[] Grow(short[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
short[] newArray = new short[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT16)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static short[] Grow(short[] array)
{
return Grow(array, 1 + array.Length);
}
public static float[] Grow(float[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
float[] newArray = new float[Oversize(minSize, RamUsageEstimator.NUM_BYTES_SINGLE)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static float[] Grow(float[] array)
{
return Grow(array, 1 + array.Length);
}
public static double[] Grow(double[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
double[] newArray = new double[Oversize(minSize, RamUsageEstimator.NUM_BYTES_DOUBLE)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static double[] Grow(double[] array)
{
return Grow(array, 1 + array.Length);
}
public static short[] Shrink(short[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT16);
if (newSize != array.Length)
{
short[] newArray = new short[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
public static int[] Grow(int[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
int[] newArray = new int[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT32)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static int[] Grow(int[] array)
{
return Grow(array, 1 + array.Length);
}
public static int[] Shrink(int[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT32);
if (newSize != array.Length)
{
int[] newArray = new int[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
public static long[] Grow(long[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
long[] newArray = new long[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT64)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static long[] Grow(long[] array)
{
return Grow(array, 1 + array.Length);
}
public static long[] Shrink(long[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT64);
if (newSize != array.Length)
{
long[] newArray = new long[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
[CLSCompliant(false)]
public static sbyte[] Grow(sbyte[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
var newArray = new sbyte[Oversize(minSize, 1)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static byte[] Grow(byte[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
byte[] newArray = new byte[Oversize(minSize, 1)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static byte[] Grow(byte[] array)
{
return Grow(array, 1 + array.Length);
}
public static byte[] Shrink(byte[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, 1);
if (newSize != array.Length)
{
var newArray = new byte[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
public static bool[] Grow(bool[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
bool[] newArray = new bool[Oversize(minSize, 1)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static bool[] Grow(bool[] array)
{
return Grow(array, 1 + array.Length);
}
public static bool[] Shrink(bool[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, 1);
if (newSize != array.Length)
{
bool[] newArray = new bool[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
public static char[] Grow(char[] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
char[] newArray = new char[Oversize(minSize, RamUsageEstimator.NUM_BYTES_CHAR)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
public static char[] Grow(char[] array)
{
return Grow(array, 1 + array.Length);
}
public static char[] Shrink(char[] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_CHAR);
if (newSize != array.Length)
{
char[] newArray = new char[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
[CLSCompliant(false)]
public static int[][] Grow(int[][] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
var newArray = new int[Oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
[CLSCompliant(false)]
public static int[][] Grow(int[][] array)
{
return Grow(array, 1 + array.Length);
}
[CLSCompliant(false)]
public static int[][] Shrink(int[][] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
if (newSize != array.Length)
{
int[][] newArray = new int[newSize][];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
[CLSCompliant(false)]
public static float[][] Grow(float[][] array, int minSize)
{
Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?");
if (array.Length < minSize)
{
float[][] newArray = new float[Oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
else
{
return array;
}
}
[CLSCompliant(false)]
public static float[][] Grow(float[][] array)
{
return Grow(array, 1 + array.Length);
}
[CLSCompliant(false)]
public static float[][] Shrink(float[][] array, int targetSize)
{
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
if (newSize != array.Length)
{
float[][] newArray = new float[newSize][];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
}
else
{
return array;
}
}
/// <summary>
/// Returns hash of chars in range start (inclusive) to
/// end (inclusive)
/// </summary>
public static int GetHashCode(char[] array, int start, int end)
{
int code = 0;
for (int i = end - 1; i >= start; i--)
{
code = code * 31 + array[i];
}
return code;
}
/// <summary>
/// Returns hash of bytes in range start (inclusive) to
/// end (inclusive)
/// </summary>
public static int GetHashCode(byte[] array, int start, int end)
{
int code = 0;
for (int i = end - 1; i >= start; i--)
{
code = code * 31 + array[i];
}
return code;
}
// Since Arrays.equals doesn't implement offsets for equals
/// <summary>
/// See if two array slices are the same.
/// </summary>
/// <param name="left"> The left array to compare </param>
/// <param name="offsetLeft"> The offset into the array. Must be positive </param>
/// <param name="right"> The right array to compare </param>
/// <param name="offsetRight"> the offset into the right array. Must be positive </param>
/// <param name="length"> The length of the section of the array to compare </param>
/// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal
/// </returns>
/// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/>
public static bool Equals(char[] left, int offsetLeft, char[] right, int offsetRight, int length)
{
if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length))
{
for (int i = 0; i < length; i++)
{
if (left[offsetLeft + i] != right[offsetRight + i])
{
return false;
}
}
return true;
}
return false;
}
// Since Arrays.equals doesn't implement offsets for equals
/// <summary>
/// See if two array slices are the same.
/// </summary>
/// <param name="left"> The left array to compare </param>
/// <param name="offsetLeft"> The offset into the array. Must be positive </param>
/// <param name="right"> The right array to compare </param>
/// <param name="offsetRight"> the offset into the right array. Must be positive </param>
/// <param name="length"> The length of the section of the array to compare </param>
/// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal
/// </returns>
/// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/>
public static bool Equals(byte[] left, int offsetLeft, byte[] right, int offsetRight, int length)
{
if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length))
{
for (int i = 0; i < length; i++)
{
if (left[offsetLeft + i] != right[offsetRight + i])
{
return false;
}
}
return true;
}
return false;
}
/* DISABLE this FOR NOW: this has performance problems until Java creates intrinsics for Class#getComponentType() and Array.newInstance()
public static <T> T[] grow(T[] array, int minSize) {
assert minSize >= 0: "size must be positive (got " + minSize + "): likely integer overflow?";
if (array.length < minSize) {
@SuppressWarnings("unchecked") final T[] newArray =
(T[]) Array.newInstance(array.getClass().getComponentType(), oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
} else
return array;
}
public static <T> T[] grow(T[] array) {
return grow(array, 1 + array.length);
}
public static <T> T[] shrink(T[] array, int targetSize) {
assert targetSize >= 0: "size must be positive (got " + targetSize + "): likely integer overflow?";
final int newSize = getShrinkSize(array.length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
if (newSize != array.length) {
@SuppressWarnings("unchecked") final T[] newArray =
(T[]) Array.newInstance(array.getClass().getComponentType(), newSize);
System.arraycopy(array, 0, newArray, 0, newSize);
return newArray;
} else
return array;
}
*/
// Since Arrays.equals doesn't implement offsets for equals
/// <summary>
/// See if two array slices are the same.
/// </summary>
/// <param name="left"> The left array to compare </param>
/// <param name="offsetLeft"> The offset into the array. Must be positive </param>
/// <param name="right"> The right array to compare </param>
/// <param name="offsetRight"> the offset into the right array. Must be positive </param>
/// <param name="length"> The length of the section of the array to compare </param>
/// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal
/// </returns>
/// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/>
public static bool Equals(int[] left, int offsetLeft, int[] right, int offsetRight, int length)
{
if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length))
{
for (int i = 0; i < length; i++)
{
if (left[offsetLeft + i] != right[offsetRight + i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// NOTE: This was toIntArray() in Lucene
/// </summary>
public static int[] ToInt32Array(ICollection<int?> ints)
{
int[] result = new int[ints.Count];
int upto = 0;
foreach (int? v in ints)
{
if (v.HasValue)
{
result[upto++] = v.Value;
}
else
{
throw new NullReferenceException(); // LUCENENET NOTE: This is the same behavior you get in Java when setting int = Integer and the integer is null.
}
}
// paranoia:
Debug.Assert(upto == result.Length);
return result;
}
// LUCENENET specific - we don't have an IComparable<T> constraint -
// the logic of GetNaturalComparer<T> handles that so we just
// do a cast here.
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
private class NaturalComparer<T> : IComparer<T> //where T : IComparable<T>
{
private NaturalComparer()
{
}
public static NaturalComparer<T> Default { get; } = new NaturalComparer<T>();
public virtual int Compare(T o1, T o2)
{
return ((IComparable<T>)o1).CompareTo(o2);
}
}
/// <summary>
/// Get the natural <see cref="IComparer{T}"/> for the provided object class.
/// <para/>
/// The comparer returned depends on the <typeparam name="T"/> argument:
/// <list type="number">
/// <item><description>If the type is <see cref="string"/>, the comparer returned uses
/// the <see cref="string.CompareOrdinal(string, string)"/> to make the comparison
/// to ensure that the current culture doesn't affect the results. This is the
/// default string comparison used in Java, and what Lucene's design depends on.</description></item>
/// <item><description>If the type implements <see cref="IComparable{T}"/>, the comparer uses
/// <see cref="IComparable{T}.CompareTo(T)"/> for the comparison. This allows
/// the use of types with custom comparison schemes.</description></item>
/// <item><description>If neither of the above conditions are true, will default to <see cref="Comparer{T}.Default"/>.</description></item>
/// </list>
/// <para/>
/// NOTE: This was naturalComparer() in Lucene
/// </summary>
public static IComparer<T> GetNaturalComparer<T>()
//where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
Type genericClosingType = typeof(T);
// LUCENENET specific - we need to ensure that strings are compared
// in a culture-insenitive manner.
if (genericClosingType.Equals(typeof(string)))
{
return (IComparer<T>)StringComparer.Ordinal;
}
// LUCENENET specific - Only return the NaturalComparer if the type
// implements IComparable<T>, otherwise use Comparer<T>.Default.
// This allows the comparison to be customized, but it is not mandatory
// to implement IComparable<T>.
else if (typeof(IComparable<T>).IsAssignableFrom(genericClosingType))
{
return NaturalComparer<T>.Default;
}
return Comparer<T>.Default;
}
/// <summary>
/// Swap values stored in slots <paramref name="i"/> and <paramref name="j"/> </summary>
public static void Swap<T>(T[] arr, int i, int j)
{
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// intro-sorts
/// <summary>
/// Sorts the given array slice using the <see cref="IComparer{T}"/>. This method uses the intro sort
/// algorithm, but falls back to insertion sort for small arrays. </summary>
/// <param name="fromIndex"> Start index (inclusive) </param>
/// <param name="toIndex"> End index (exclusive) </param>
public static void IntroSort<T>(T[] a, int fromIndex, int toIndex, IComparer<T> comp)
{
if (toIndex - fromIndex <= 1)
{
return;
}
(new ArrayIntroSorter<T>(a, comp)).Sort(fromIndex, toIndex);
}
/// <summary>
/// Sorts the given array using the <see cref="IComparer{T}"/>. This method uses the intro sort
/// algorithm, but falls back to insertion sort for small arrays.
/// </summary>
public static void IntroSort<T>(T[] a, IComparer<T> comp)
{
IntroSort(a, 0, a.Length, comp);
}
/// <summary>
/// Sorts the given array slice in natural order. This method uses the intro sort
/// algorithm, but falls back to insertion sort for small arrays. </summary>
/// <param name="fromIndex"> Start index (inclusive) </param>
/// <param name="toIndex"> End index (exclusive) </param>
public static void IntroSort<T>(T[] a, int fromIndex, int toIndex) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
if (toIndex - fromIndex <= 1)
{
return;
}
IntroSort(a, fromIndex, toIndex, ArrayUtil.GetNaturalComparer<T>());
}
/// <summary>
/// Sorts the given array in natural order. This method uses the intro sort
/// algorithm, but falls back to insertion sort for small arrays.
/// </summary>
public static void IntroSort<T>(T[] a) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
IntroSort(a, 0, a.Length);
}
// tim sorts:
/// <summary>
/// Sorts the given array slice using the <see cref="IComparer{T}"/>. This method uses the Tim sort
/// algorithm, but falls back to binary sort for small arrays. </summary>
/// <param name="fromIndex"> Start index (inclusive) </param>
/// <param name="toIndex"> End index (exclusive) </param>
public static void TimSort<T>(T[] a, int fromIndex, int toIndex, IComparer<T> comp)
{
if (toIndex - fromIndex <= 1)
{
return;
}
(new ArrayTimSorter<T>(a, comp, a.Length / 64)).Sort(fromIndex, toIndex);
}
/// <summary>
/// Sorts the given array using the <see cref="IComparer{T}"/>. this method uses the Tim sort
/// algorithm, but falls back to binary sort for small arrays.
/// </summary>
public static void TimSort<T>(T[] a, IComparer<T> comp)
{
TimSort(a, 0, a.Length, comp);
}
/// <summary>
/// Sorts the given array slice in natural order. this method uses the Tim sort
/// algorithm, but falls back to binary sort for small arrays. </summary>
/// <param name="fromIndex"> Start index (inclusive) </param>
/// <param name="toIndex"> End index (exclusive) </param>
public static void TimSort<T>(T[] a, int fromIndex, int toIndex) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
if (toIndex - fromIndex <= 1)
{
return;
}
TimSort(a, fromIndex, toIndex, ArrayUtil.GetNaturalComparer<T>());
}
/// <summary>
/// Sorts the given array in natural order. this method uses the Tim sort
/// algorithm, but falls back to binary sort for small arrays.
/// </summary>
public static void TimSort<T>(T[] a) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
TimSort(a, 0, a.Length);
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.TinyCPUSimulator;
using System;
using System.Windows.Forms;
namespace Mosa.Tool.TinySimulator
{
public partial class ScriptView : SimulatorDockContent
{
private int lineNbr = 0;
private bool wait = false;
public ScriptView(MainForm mainForm)
: base(mainForm)
{
InitializeComponent();
}
public override void UpdateDock(BaseSimState simState)
{
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
lineNbr = 0;
wait = false;
Execute();
}
public void ExecutingCompleted()
{
AddOutput(lineNbr, "STATUS: Execution completed");
wait = false;
Execute();
}
private void Execute()
{
while (!wait && richTextBox1.Lines.Length > lineNbr)
{
var l = richTextBox1.Lines[lineNbr];
lineNbr++;
string line = l.Trim();
if (string.IsNullOrEmpty(line))
return;
string cmd = string.Empty;
string data = string.Empty;
Split(line, out cmd, out data);
Execute(lineNbr, cmd, data);
}
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
if (string.IsNullOrEmpty(openFileDialog1.FileName))
return;
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
protected void Split(string line, out string first, out string rest)
{
int spacepos = line.IndexOf(' ');
int tabpos = line.IndexOf('\t');
int pos = (tabpos >= 0) ? tabpos : spacepos;
first = string.Empty;
rest = string.Empty;
if (pos < 0)
{
first = line.Trim();
}
else
{
first = line.Substring(0, pos).Trim();
rest = line.Substring(pos).Trim();
}
}
private void toolStripLabel3_Click(object sender, EventArgs e)
{
int lineNbr = 0;
foreach (var l in richTextBox1.Lines)
{
lineNbr++;
string line = l.Trim();
if (string.IsNullOrEmpty(line))
continue;
string cmd = string.Empty;
string data = string.Empty;
Split(line, out cmd, out data);
Execute(lineNbr, cmd, data);
}
}
protected void Execute(int lineNbr, string cmd, string data)
{
switch (cmd.ToLower())
{
case "load": LoadAssembly(lineNbr, data); return;
case "compile": Compile(lineNbr, data); return;
case "add-breakpoint-label": AddBreakpointByLabel(lineNbr, data); return;
case "add-watch-label": AddWatchByLabel(lineNbr, data); return;
case "execute": Execute(lineNbr, data); return;
case "step": Step(lineNbr, data); return;
case "restart": Restart(lineNbr, data); return;
case "record": Record(lineNbr, data); return;
default: return;
}
}
protected void AddOutput(int lineNbr, string data)
{
MainForm.AddOutput(lineNbr.ToString() + ": " + data);
}
protected void LoadAssembly(int lineNbr, string data)
{
AddOutput(lineNbr, "STATUS: Load assembly " + data);
MainForm.Stop();
MainForm.LoadAssembly(data);
}
protected void Compile(int lineNbr, string data)
{
AddOutput(lineNbr, "STATUS: Compiling");
MainForm.StartSimulator();
}
protected void AddBreakpointByLabel(int lineNbr, string data)
{
var symbol = SimCPU.GetSymbol(data);
AddOutput(lineNbr, "STATUS: Add breakpoint " + symbol.Name + " at " + MainForm.Format(symbol.Address, MainForm.Display32));
MainForm.AddBreakpoint(symbol.Name, symbol.Address);
}
protected void Execute(int lineNbr, string data)
{
AddOutput(lineNbr, "STATUS: Executing!");
wait = true;
MainForm.Start();
}
protected void Restart(int lineNbr, string data)
{
AddOutput(lineNbr, "STATUS: Restart");
wait = true;
MainForm.Restart();
}
protected void Record(int lineNbr, string data)
{
if (data.Length == 0)
Record(lineNbr, true);
else
{
bool record = false;
data = data.ToUpper();
if (data[0] == 'Y' || data[0] == 'T' || data == "ON")
record = true;
Record(lineNbr, record);
}
}
protected void Record(int lineNbr, bool record)
{
AddOutput(lineNbr, "STATUS: Record " + (record ? "On" : "Off"));
MainForm.Record = record;
}
protected void Step(int lineNbr, string data)
{
uint step = Convert.ToUInt32(data);
AddOutput(lineNbr, "STATUS: Executing " + step.ToString() + " steps!");
wait = true;
MainForm.ExecuteSteps(step);
}
protected void AddWatchByLabel(int lineNbr, string data)
{
var symbol = SimCPU.GetSymbol(data);
AddOutput(lineNbr, "STATUS: Add watach " + symbol.Name + " at " + MainForm.Format(symbol.Address, MainForm.Display32));
MainForm.AddWatch(symbol.Name, symbol.Address, (int)symbol.Size);
}
}
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX
{
public delegate bool ContactDestroyedCallback(object userPersistentData);
public class PersistentManifold
{
private static ContactDestroyedCallback _contactDestroyedCallback = null;
private static float _contactBreakingThreshold = 0.02f;
private ManifoldPoint[] _pointCache = new ManifoldPoint[4];
// this two body pointers can point to the physics rigidbody class.
// object will allow any rigidbody class
private object _bodyA;
private object _bodyB;
private int _cachedPoints;
public PersistentManifold(object bodyA, object bodyB)
{
_bodyA = bodyA;
_bodyB = bodyB;
_cachedPoints = 0;
}
public object BodyA { get { return _bodyA; } }
public object BodyB { get { return _bodyB; } }
public int ContactsCount { get { return _cachedPoints; } }
public static ContactDestroyedCallback ContactDestroyedCallback { get { return _contactDestroyedCallback; } set { _contactDestroyedCallback = value; } }
public static float ContactBreakingThreshold { get { return _contactBreakingThreshold; } }
public void SetBodies(object bodyA, object bodyB)
{
_bodyA = bodyA;
_bodyB = bodyB;
}
public ManifoldPoint GetContactPoint(int index)
{
if (index >= _cachedPoints)
throw new ArgumentOutOfRangeException("index", "index must be smaller than cachedPoints");
return _pointCache[index];
}
public int GetCacheEntry(ManifoldPoint newPoint)
{
float shortestDist = ContactBreakingThreshold * ContactBreakingThreshold;
int size = ContactsCount;
int nearestPoint = -1;
for (int i = 0; i < size; i++)
{
ManifoldPoint mp = _pointCache[i];
Vector3 diffA = mp.LocalPointA - newPoint.LocalPointA;
float distToManiPoint = Vector3.Dot(diffA, diffA);
if (distToManiPoint < shortestDist)
{
shortestDist = distToManiPoint;
nearestPoint = i;
}
}
return nearestPoint;
}
public void AddManifoldPoint(ManifoldPoint newPoint)
{
if (!ValidContactDistance(newPoint))
throw new BulletException();
int insertIndex = ContactsCount;
if (insertIndex == 4)
{
//sort cache so best points come first, based on area
insertIndex = SortCachedPoints(newPoint);
}
else
{
_cachedPoints++;
}
ReplaceContactPoint(newPoint, insertIndex);
}
public void RemoveContactPoint(int index)
{
ClearUserCache(_pointCache[index]);
int lastUsedIndex = ContactsCount - 1;
_pointCache[index] = _pointCache[lastUsedIndex];
//get rid of duplicated userPersistentData pointer
_pointCache[lastUsedIndex].UserPersistentData = null;
_cachedPoints--;
}
public void ReplaceContactPoint(ManifoldPoint newPoint, int insertIndex)
{
BulletDebug.Assert(ValidContactDistance(newPoint));
if (_pointCache[insertIndex] != null)
{
int lifeTime = _pointCache[insertIndex].LifeTime;
BulletDebug.Assert(lifeTime >= 0);
object cache = _pointCache[insertIndex].UserPersistentData;
_pointCache[insertIndex] = newPoint;
_pointCache[insertIndex].UserPersistentData = cache;
_pointCache[insertIndex].LifeTime = lifeTime;
}
else
{
_pointCache[insertIndex] = newPoint;
}
//ClearUserCache(_pointCache[insertIndex]);
//_pointCache[insertIndex] = newPoint;
}
public bool ValidContactDistance(ManifoldPoint pt)
{
return pt.Distance <= ContactBreakingThreshold;
}
// calculated new worldspace coordinates and depth, and reject points that exceed the collision margin
public void RefreshContactPoints(Matrix trA, Matrix trB)
{
// first refresh worldspace positions and distance
for (int i = ContactsCount - 1; i >= 0; i--)
{
ManifoldPoint manifoldPoint = _pointCache[i];
manifoldPoint.PositionWorldOnA = MathHelper.MatrixToVector(trA,manifoldPoint.LocalPointA);
manifoldPoint.PositionWorldOnB = MathHelper.MatrixToVector(trB, manifoldPoint.LocalPointB);
manifoldPoint.Distance = Vector3.Dot(manifoldPoint.PositionWorldOnA - manifoldPoint.PositionWorldOnB, manifoldPoint.NormalWorldOnB);
manifoldPoint.LifeTime++;
}
// then
float distance2d;
Vector3 projectedDifference, projectedPoint;
for (int i = ContactsCount - 1; i >= 0; i--)
{
ManifoldPoint manifoldPoint = _pointCache[i];
//contact becomes invalid when signed distance exceeds margin (projected on contactnormal direction)
if (!ValidContactDistance(manifoldPoint))
{
RemoveContactPoint(i);
}
else
{
//contact also becomes invalid when relative movement orthogonal to normal exceeds margin
projectedPoint = manifoldPoint.PositionWorldOnA - manifoldPoint.NormalWorldOnB * manifoldPoint.Distance;
projectedDifference = manifoldPoint.PositionWorldOnB - projectedPoint;
distance2d = Vector3.Dot(projectedDifference, projectedDifference);
if (distance2d > ContactBreakingThreshold * ContactBreakingThreshold)
{
RemoveContactPoint(i);
}
}
}
}
public void ClearManifold()
{
for (int i = 0; i < _cachedPoints; i++)
{
ClearUserCache(_pointCache[i]);
}
_cachedPoints = 0;
}
private void ClearUserCache(ManifoldPoint pt)
{
if (pt != null)
{
object oldPtr = pt.UserPersistentData;
if (oldPtr != null)
{
if (pt.UserPersistentData != null && _contactDestroyedCallback != null)
{
_contactDestroyedCallback(pt.UserPersistentData);
pt.UserPersistentData = null;
}
}
}
}
// sort cached points so most isolated points come first
private int SortCachedPoints(ManifoldPoint pt)
{
//calculate 4 possible cases areas, and take biggest area
//also need to keep 'deepest'
int maxPenetrationIndex = -1;
float maxPenetration = pt.Distance;
for (int i = 0; i < 4; i++)
{
if (_pointCache[i].Distance < maxPenetration)
{
maxPenetrationIndex = i;
maxPenetration = _pointCache[i].Distance;
}
}
float res0 = 0, res1 = 0, res2 = 0, res3 = 0;
if (maxPenetrationIndex != 0)
{
Vector3 a0 = pt.LocalPointA - _pointCache[1].LocalPointA;
Vector3 b0 = _pointCache[3].LocalPointA - _pointCache[2].LocalPointA;
Vector3 cross = Vector3.Cross(a0, b0);
res0 = cross.LengthSquared();
}
if (maxPenetrationIndex != 1)
{
Vector3 a1 = pt.LocalPointA - _pointCache[0].LocalPointA;
Vector3 b1 = _pointCache[3].LocalPointA - _pointCache[2].LocalPointA;
Vector3 cross = Vector3.Cross(a1, b1);
res1 = cross.LengthSquared();
}
if (maxPenetrationIndex != 2)
{
Vector3 a2 = pt.LocalPointA - _pointCache[0].LocalPointA;
Vector3 b2 = _pointCache[3].LocalPointA - _pointCache[1].LocalPointA;
Vector3 cross = Vector3.Cross(a2, b2);
res2 = cross.LengthSquared();
}
if (maxPenetrationIndex != 3)
{
Vector3 a3 = pt.LocalPointA - _pointCache[0].LocalPointA;
Vector3 b3 = _pointCache[2].LocalPointA - _pointCache[1].LocalPointA;
Vector3 cross = Vector3.Cross(a3, b3);
res3 = cross.LengthSquared();
}
Vector4 maxvec = new Vector4(res0, res1, res2, res3);
int biggestarea = MathHelper.ClosestAxis(maxvec);
return biggestarea;
}
private int FindContactPoint(ManifoldPoint unUsed, int numUnused, ManifoldPoint pt) { return 0; }
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprActualPatologiaEmbarazo class.
/// </summary>
[Serializable]
public partial class AprActualPatologiaEmbarazoCollection : ActiveList<AprActualPatologiaEmbarazo, AprActualPatologiaEmbarazoCollection>
{
public AprActualPatologiaEmbarazoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprActualPatologiaEmbarazoCollection</returns>
public AprActualPatologiaEmbarazoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprActualPatologiaEmbarazo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_ActualPatologiaEmbarazo table.
/// </summary>
[Serializable]
public partial class AprActualPatologiaEmbarazo : ActiveRecord<AprActualPatologiaEmbarazo>, IActiveRecord
{
#region .ctors and Default Settings
public AprActualPatologiaEmbarazo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprActualPatologiaEmbarazo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprActualPatologiaEmbarazo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprActualPatologiaEmbarazo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_ActualPatologiaEmbarazo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdActualPatologiaEmbarazo = new TableSchema.TableColumn(schema);
colvarIdActualPatologiaEmbarazo.ColumnName = "idActualPatologiaEmbarazo";
colvarIdActualPatologiaEmbarazo.DataType = DbType.Int32;
colvarIdActualPatologiaEmbarazo.MaxLength = 0;
colvarIdActualPatologiaEmbarazo.AutoIncrement = true;
colvarIdActualPatologiaEmbarazo.IsNullable = false;
colvarIdActualPatologiaEmbarazo.IsPrimaryKey = true;
colvarIdActualPatologiaEmbarazo.IsForeignKey = false;
colvarIdActualPatologiaEmbarazo.IsReadOnly = false;
colvarIdActualPatologiaEmbarazo.DefaultSetting = @"";
colvarIdActualPatologiaEmbarazo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdActualPatologiaEmbarazo);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdEmbarazo = new TableSchema.TableColumn(schema);
colvarIdEmbarazo.ColumnName = "idEmbarazo";
colvarIdEmbarazo.DataType = DbType.Int32;
colvarIdEmbarazo.MaxLength = 0;
colvarIdEmbarazo.AutoIncrement = false;
colvarIdEmbarazo.IsNullable = false;
colvarIdEmbarazo.IsPrimaryKey = false;
colvarIdEmbarazo.IsForeignKey = true;
colvarIdEmbarazo.IsReadOnly = false;
colvarIdEmbarazo.DefaultSetting = @"";
colvarIdEmbarazo.ForeignKeyTableName = "APR_Embarazo";
schema.Columns.Add(colvarIdEmbarazo);
TableSchema.TableColumn colvarIdPatologiaEmbarazo = new TableSchema.TableColumn(schema);
colvarIdPatologiaEmbarazo.ColumnName = "idPatologiaEmbarazo";
colvarIdPatologiaEmbarazo.DataType = DbType.Int32;
colvarIdPatologiaEmbarazo.MaxLength = 0;
colvarIdPatologiaEmbarazo.AutoIncrement = false;
colvarIdPatologiaEmbarazo.IsNullable = false;
colvarIdPatologiaEmbarazo.IsPrimaryKey = false;
colvarIdPatologiaEmbarazo.IsForeignKey = true;
colvarIdPatologiaEmbarazo.IsReadOnly = false;
colvarIdPatologiaEmbarazo.DefaultSetting = @"";
colvarIdPatologiaEmbarazo.ForeignKeyTableName = "Sys_CIE10";
schema.Columns.Add(colvarIdPatologiaEmbarazo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_ActualPatologiaEmbarazo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdActualPatologiaEmbarazo")]
[Bindable(true)]
public int IdActualPatologiaEmbarazo
{
get { return GetColumnValue<int>(Columns.IdActualPatologiaEmbarazo); }
set { SetColumnValue(Columns.IdActualPatologiaEmbarazo, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdEmbarazo")]
[Bindable(true)]
public int IdEmbarazo
{
get { return GetColumnValue<int>(Columns.IdEmbarazo); }
set { SetColumnValue(Columns.IdEmbarazo, value); }
}
[XmlAttribute("IdPatologiaEmbarazo")]
[Bindable(true)]
public int IdPatologiaEmbarazo
{
get { return GetColumnValue<int>(Columns.IdPatologiaEmbarazo); }
set { SetColumnValue(Columns.IdPatologiaEmbarazo, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysCIE10 ActiveRecord object related to this AprActualPatologiaEmbarazo
///
/// </summary>
public DalSic.SysCIE10 SysCIE10
{
get { return DalSic.SysCIE10.FetchByID(this.IdPatologiaEmbarazo); }
set { SetColumnValue("idPatologiaEmbarazo", value.Id); }
}
/// <summary>
/// Returns a AprEmbarazo ActiveRecord object related to this AprActualPatologiaEmbarazo
///
/// </summary>
public DalSic.AprEmbarazo AprEmbarazo
{
get { return DalSic.AprEmbarazo.FetchByID(this.IdEmbarazo); }
set { SetColumnValue("idEmbarazo", value.IdEmbarazo); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdEfector,int varIdEmbarazo,int varIdPatologiaEmbarazo)
{
AprActualPatologiaEmbarazo item = new AprActualPatologiaEmbarazo();
item.IdEfector = varIdEfector;
item.IdEmbarazo = varIdEmbarazo;
item.IdPatologiaEmbarazo = varIdPatologiaEmbarazo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdActualPatologiaEmbarazo,int varIdEfector,int varIdEmbarazo,int varIdPatologiaEmbarazo)
{
AprActualPatologiaEmbarazo item = new AprActualPatologiaEmbarazo();
item.IdActualPatologiaEmbarazo = varIdActualPatologiaEmbarazo;
item.IdEfector = varIdEfector;
item.IdEmbarazo = varIdEmbarazo;
item.IdPatologiaEmbarazo = varIdPatologiaEmbarazo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdActualPatologiaEmbarazoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdEmbarazoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdPatologiaEmbarazoColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdActualPatologiaEmbarazo = @"idActualPatologiaEmbarazo";
public static string IdEfector = @"idEfector";
public static string IdEmbarazo = @"idEmbarazo";
public static string IdPatologiaEmbarazo = @"idPatologiaEmbarazo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ERY.EMath
{
[Serializable]
public struct Complex
{
public const double TOLERANCE = 1e-10;
public double x, y;
public double RealPart { get { return x; } set { x = value; } }
public double ImagPart { get { return y; } set { y = value; } }
public Complex(double real)
{
x = real;
y = 0;
}
public Complex(double real, double imag)
{
x = real;
y = imag;
}
public static implicit operator Complex(double x)
{
return new Complex(x);
}
public void Set(double real, double imag)
{
x = real;
y = imag;
}
public void SetPolar(double mag, double arg)
{
x = mag * Math.Cos(arg);
y = mag * Math.Sin(arg);
}
public override string ToString()
{
return ToString("");
}
public string ToString(string formatString)
{
string buffer;
double rx = x, ry = y;
if (formatString != "")
formatString = ":" + formatString;
string real = string.Format("{0" + formatString + "}", x);
string imag = string.Format("{0" + formatString + "}", Math.Abs(y));
if (double.Parse(imag) == 0)
ry = 0;
if ((ry > 0 && imag != "") && (rx != 0 && real != ""))
buffer = "(" + real + " + " + imag + "i)";
else if ((ry < 0 && imag != "") && (rx != 0 && real != ""))
buffer = "(" + real + " - " + imag + "i)";
else if (ry > 0 && imag != "")
buffer = imag + "i";
else if (ry < 0 && imag != "")
buffer = "-" + imag + "i";
else
buffer = real;
return buffer;
}
public double Magnitude
{
get
{
return Math.Sqrt(MagnitudeSquared);
}
}
public double MagnitudeSquared
{
get
{
return x * x + y * y;
}
}
/// <summary>
/// Returns the argument of the complex number: Atan y/x)
/// </summary>
public double Argument
{
get
{
return Math.Atan2(y, x);
}
}
/// <summary>
/// Returns the phase of the complex number: this / Magnitude.
/// </summary>
public Complex Phase
{
get
{
return this / Magnitude;
}
}
public Complex Conjugate()
{
return new Complex(x, -y);
}
public Complex Invert()
{
double denom = x * x + y * y;
Complex retval = new Complex(x / denom, -y / denom);
return retval;
}
public static Complex operator -(Complex t)
{
return new Complex(-t.x, -t.y);
}
public static Complex operator +(Complex a, Complex b)
{
return new Complex(a.x + b.x, a.y + b.y);
}
public static Complex operator -(Complex a, Complex b)
{
return new Complex(a.x - b.x, a.y - b.y);
}
public static Complex operator *(Complex a, Complex b)
{
double new_x = a.x * b.x - a.y * b.y;
double new_y = a.x * b.y + a.y * b.x;
return new Complex(new_x, new_y);
}
public static Complex operator /(Complex a, Complex b)
{
return a * b.Invert();
}
// Possibly optimized version?
//public static Complex operator /(Complex lhs, Complex rhs)
//{
// Complex result = new Complex();
// double e;
// double f;
// if (System.Math.Abs(rhs.ImagPart) < System.Math.Abs(rhs.RealPart))
// {
// e = rhs.ImagPart / rhs.RealPart;
// f = rhs.RealPart + rhs.ImagPart * e;
// result.RealPart = (lhs.RealPart + lhs.ImagPart * e) / f;
// result.ImagPart = (lhs.ImagPart - lhs.RealPart * e) / f;
// }
// else
// {
// e = rhs.RealPart / rhs.ImagPart;
// f = rhs.ImagPart + rhs.RealPart * e;
// result.RealPart = (lhs.ImagPart + lhs.RealPart * e) / f;
// result.ImagPart = (-lhs.RealPart + lhs.ImagPart * e) / f;
// }
// return result;
//}
public static Complex operator /(Complex a, double b)
{
return new Complex(a.RealPart / b, a.ImagPart / b);
}
public static Complex operator +(double r, Complex t)
{
return new Complex(t.RealPart + r, t.ImagPart);
}
public static Complex operator +(Complex t, double r)
{
return new Complex(t.RealPart + r, t.ImagPart);
}
public static Complex operator -(double r, Complex t)
{
return new Complex(r - t.RealPart, -t.ImagPart);
}
public static Complex operator -(Complex t, double r)
{
return new Complex(t.RealPart - r, t.ImagPart);
}
public static Complex operator *(double r, Complex t)
{
return new Complex(t.x * r, t.y * r);
}
public static Complex operator /(double r, Complex t)
{
return new Complex(r) / t;
}
public static Complex operator *(Complex t, double r)
{
return new Complex(t.x * r, t.y * r);
}
public static Complex Hypot(Complex a, Complex b)
{
Complex r;
if (a.Magnitude > b.Magnitude)
{
r = b / a;
r = a.Magnitude * Complex.Sqrt(1 + r * r);
}
else if (b != 0)
{
r = a / b;
r = b.Magnitude * Complex.Sqrt(1 + r * r);
}
else
{
r = 0.0;
}
return r;
}
public static Complex Exp(Complex t)
{
Complex retval = new Complex();
retval.SetPolar(Math.Exp(t.x), t.y);
return retval;
}
public static Complex Log(Complex t)
{
Complex retval = new Complex();
retval.Set(Math.Log(t.Magnitude), t.Argument);
return retval;
}
public static Complex Pow(Complex t, Complex u)
{
if (t == 0 && u != 0)
return 0;
Complex retval = new Complex();
retval.SetPolar(
Math.Pow(t.Magnitude, u.x) * Math.Exp(-t.Argument * u.y),
t.Argument * u.x + u.y * Math.Log(t.Magnitude));
return retval;
}
public static Complex Sqrt(Complex t)
{
Complex retval = new Complex();
retval.SetPolar(Math.Sqrt(t.Magnitude), t.Argument / 2);
return retval;
}
public static Complex Sin(Complex t)
{
return new Complex(Math.Sin(t.x) * Math.Cosh(t.y), Math.Cos(t.x) * Math.Sinh(t.y));
}
public static Complex Cos(Complex t)
{
return new Complex(Math.Cos(t.x) * Math.Cosh(t.y), -Math.Sin(t.x) * Math.Sinh(t.y));
}
public static Complex Tan(Complex t)
{
return new Complex(Math.Tan(t.x), Math.Tanh(t.y)) /
new Complex(1, -Math.Tan(t.x) * Math.Tanh(t.y));
}
public static bool operator ==(Complex a, Complex b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
if (dx > TOLERANCE)
return false;
if (dy > TOLERANCE)
return false;
else
return true;
}
public static bool operator !=(Complex a, Complex b)
{
return !(a == b);
}
public Complex Round()
{
return Round(TOLERANCE);
}
public Complex Round(double tolerance)
{
Complex retval = new Complex(x, y);
if (Math.Abs(x) < tolerance) retval.x = 0;
if (Math.Abs(y) < tolerance) retval.y = 0;
return retval;
}
public override bool Equals(object obj)
{
if (obj is Complex)
return this == (Complex)obj;
else if (obj is double)
{
return this == new Complex((double)obj);
}
else
return false;
}
public override int GetHashCode()
{
return x.GetHashCode() - y.GetHashCode();
}
public static Complex Parse(string val)
{
val = val.Trim();
if (val.StartsWith("(") && val.EndsWith(")") && val.Length > 2)
{
val = val.Substring(1, val.Length - 2).Trim();
if (val.Length == 0)
throw new FormatException("Could not understand value.");
}
Regex number = new Regex(@"[+-]? *[0-9]+(\.[0-9]+)?([dDeE][+-][0-9]+)?[^i]");
Regex cplxr = new Regex(@"[+-]?[0-9]+(\.[0-9]+)?([dDeE][+-][0-9]+)? *[+-] *[0-9]+(\.[0-9]+)?([dDeE][+-][0-9]+)?i");
Regex imaginary = new Regex(@"[+-]? *[0-9]+(\.[0-9]+)?([dDeE][+-][0-9]+)?i");
var m = cplxr.Matches(val, 0);
var n = number.Matches(val, 0);
var im = imaginary.Matches(val, 0);
if (m.Count == 0 && im.Count == 0)
return new Complex(double.Parse(val));
else if (m.Count == 0)
{
string imag = val.Remove(val.IndexOf('i'));
Complex retval = new Complex(0, double.Parse(imag));
return retval;
}
else if (m.Count == 1 && n.Count > 0 && im.Count == 1)
{
m = number.Matches(val, 0);
string real = n[0].ToString().Trim();
string imag_text = im[0].ToString();
string imag =imag_text.Remove(imag_text.IndexOf('i')).Replace(" ", "");
Complex retval = new Complex(double.Parse(real), double.Parse(imag));
return retval;
}
else
throw new FormatException("Could not understand value.");
}
public static Complex Parse(string real, string imag)
{
return new Complex(double.Parse(real), double.Parse(imag));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Models;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Tests the methods on IPublishedContent using the DefaultPublishedContentStore
/// </summary>
[TestFixture]
public class PublishedContentTests : PublishedContentTestBase
{
private PluginManager _pluginManager;
public override void Initialize()
{
// required so we can access property.Value
//PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();
base.Initialize();
// this is so the model factory looks into the test assembly
_pluginManager = PluginManager.Current;
PluginManager.Current = new PluginManager(new ActivatorServiceProvider(), CacheHelper.RuntimeCache, ProfilingLogger, false)
{
AssembliesToScan = _pluginManager.AssembliesToScan
.Union(new[] { typeof(PublishedContentTests).Assembly })
};
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
// when they are requested, but we must declare those that we
// explicitely want to be here...
var propertyTypes = new[]
{
// AutoPublishedContentType will auto-generate other properties
new PublishedPropertyType("umbracoNaviHide", 0, Constants.PropertyEditors.TrueFalseAlias),
new PublishedPropertyType("selectedNodes", 0, "?"),
new PublishedPropertyType("umbracoUrlAlias", 0, "?"),
new PublishedPropertyType("content", 0, Constants.PropertyEditors.TinyMCEAlias),
new PublishedPropertyType("testRecursive", 0, "?"),
};
var type = new AutoPublishedContentType(0, "anything", propertyTypes);
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
}
public override void TearDown()
{
PluginManager.Current = _pluginManager;
ApplicationContext.Current.DisposeIfDisposable();
ApplicationContext.Current = null;
}
protected override void FreezeResolution()
{
var types = PluginManager.Current.ResolveTypes<PublishedContentModel>();
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver(
new PublishedContentModelFactory(types));
base.FreezeResolution();
}
protected override string GetXmlContent(int templateId)
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
<!ELEMENT CustomDocument ANY>
<!ATTLIST CustomDocument id ID #REQUIRED>
]>
<root id=""-1"">
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[this/is/my/alias, anotheralias]]></umbracoUrlAlias>
<umbracoNaviHide>1</umbracoNaviHide>
<testRecursive><![CDATA[This is the recursive val]]></testRecursive>
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc="""">
<content><![CDATA[<div>This is some content</div>]]></content>
<umbracoUrlAlias><![CDATA[page2/alias, 2ndpagealias]]></umbracoUrlAlias>
<testRecursive><![CDATA[]]></testRecursive>
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[only/one/alias]]></umbracoUrlAlias>
<creatorName><![CDATA[Custom data with same property name as the member name]]></creatorName>
<testRecursive><![CDATA[]]></testRecursive>
</Home>
<CustomDocument id=""1177"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1177"" isDoc="""" />
<CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""" />
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoNaviHide>1</umbracoNaviHide>
</Home>
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<CustomDocument id=""4444"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,4444"" isDoc="""">
<selectedNodes><![CDATA[1172,1176,1173]]></selectedNodes>
</CustomDocument>
</Home>
<CustomDocument id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
</root>";
}
internal IPublishedContent GetNode(int id)
{
var ctx = GetUmbracoContext("/test", 1234);
var doc = ctx.ContentCache.GetById(id);
Assert.IsNotNull(doc);
return doc;
}
[Test]
[Ignore("IPublishedContent currently (6.1 as of april 25, 2013) has bugs")]
public void Fails()
{
var content = GetNode(1173);
var c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst());
var c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument").First(x => x.Id == 1177);
Assert.IsTrue(c2.IsFirst());
// First is not implemented
var c2a = content.Children.First(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177);
Assert.IsTrue(c2a.IsFirst()); // so here it's luck
c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst()); // and here it fails
// but even using supported (where) method...
// do not replace by First(x => ...) here since it's not supported at the moment
c1 = content.Children.Where(x => x.Id == 1177).First();
c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177).First();
Assert.IsFalse(c1.IsFirst()); // here it fails because c2 has corrupted it
// so there's only 1 IPublishedContent instance
// which keeps changing collection, ie being modified
// which is *bad* from a cache point of vue
// and from a consistency point of vue...
// => we want clones!
}
[Test]
public void Is_Last_From_Where_Filter_Dynamic_Linq()
{
var doc = GetNode(1173);
var items = doc.Children.Where("Visible").ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Where_Filter()
{
var doc = GetNode(1173);
var items = doc
.Children
.Where(x => x.IsVisible())
.ToContentSet();
Assert.AreEqual(3, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1177:
Assert.IsFalse(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1178:
Assert.IsFalse(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[PublishedContentModel("Home")]
internal class Home : PublishedContentModel
{
public Home(IPublishedContent content)
: base(content)
{}
}
[Test]
[Ignore("Fails as long as PublishedContentModel is internal.")] // fixme
public void Is_Last_From_Where_Filter2()
{
var doc = GetNode(1173);
var items = doc.Children
.Select(x => x.CreateModel()) // linq, returns IEnumerable<IPublishedContent>
// only way around this is to make sure every IEnumerable<T> extension
// explicitely returns a PublishedContentSet, not an IEnumerable<T>
.OfType<Home>() // ours, return IEnumerable<Home> (actually a PublishedContentSet<Home>)
.Where(x => x.IsVisible()) // so, here it's linq again :-(
.ToContentSet() // so, we need that one for the test to pass
.ToArray();
Assert.AreEqual(1, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[Test]
public void Is_Last_From_Take()
{
var doc = GetNode(1173);
var items = doc.Children.Take(3).ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Skip()
{
var doc = GetNode(1173);
foreach (var d in doc.Children.Skip(1))
{
if (d.Id != 1176)
{
Assert.IsFalse(d.IsLast());
}
else
{
Assert.IsTrue(d.IsLast());
}
}
}
[Test]
public void Is_Last_From_Concat()
{
var doc = GetNode(1173);
var items = doc.Children
.Concat(new[] { GetNode(1175), GetNode(4444) })
.ToContentSet();
foreach (var item in items)
{
if (item.Id != 4444)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Descendants_Ordered_Properly()
{
var doc = GetNode(1046);
var expected = new[] {1046, 1173, 1174, 1177, 1178, 1176, 1175, 4444, 1172};
var exindex = 0;
// must respect the XPath descendants-or-self axis!
foreach (var d in doc.DescendantsOrSelf())
Assert.AreEqual(expected[exindex++], d.Id);
}
[Test]
public void Test_Get_Recursive_Val()
{
var doc = GetNode(1174);
var rVal = doc.GetRecursiveValue("testRecursive");
var nullVal = doc.GetRecursiveValue("DoNotFindThis");
Assert.AreEqual("This is the recursive val", rVal);
Assert.AreEqual("", nullVal);
}
[Test]
public void Get_Property_Value_Uses_Converter()
{
var doc = GetNode(1173);
var propVal = doc.GetPropertyValue("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal);
Assert.AreEqual("<div>This is some content</div>", propVal.ToString());
var propVal2 = doc.GetPropertyValue<IHtmlString>("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal2);
Assert.AreEqual("<div>This is some content</div>", propVal2.ToString());
var propVal3 = doc.GetPropertyValue("Content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal3);
Assert.AreEqual("<div>This is some content</div>", propVal3.ToString());
}
[Test]
public void Complex_Linq()
{
var doc = GetNode(1173);
var result = doc.Ancestors().OrderBy(x => x.Level)
.Single()
.Descendants()
.FirstOrDefault(x => x.GetPropertyValue<string>("selectedNodes", "").Split(',').Contains("1173"));
Assert.IsNotNull(result);
}
[Test]
public void Index()
{
var doc = GetNode(1173);
Assert.AreEqual(0, doc.Index());
doc = GetNode(1176);
Assert.AreEqual(3, doc.Index());
doc = GetNode(1177);
Assert.AreEqual(1, doc.Index());
doc = GetNode(1178);
Assert.AreEqual(2, doc.Index());
}
[Test]
public void Is_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1172);
Assert.IsFalse(doc.IsFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1175);
Assert.IsFalse(doc.IsFirst());
}
[Test]
public void Is_Not_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1172);
Assert.IsTrue(doc.IsNotFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1175);
Assert.IsTrue(doc.IsNotFirst());
}
[Test]
public void Is_Position()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1172);
Assert.IsTrue(doc.IsPosition(1));
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1175);
Assert.IsTrue(doc.IsPosition(1));
}
[Test]
public void Children_GroupBy_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.GroupBy("DocumentTypeAlias");
Assert.AreEqual(2, found1.Count());
Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count());
Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count());
}
[Test]
public void Children_Where_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.Where("DocumentTypeAlias == \"CustomDocument\"");
var found2 = doc.Children.Where("DocumentTypeAlias == \"Home\"");
Assert.AreEqual(1, found1.Count());
Assert.AreEqual(2, found2.Count());
}
[Test]
public void Children_Order_By_Update_Date()
{
var doc = GetNode(1173);
var ordered = doc.Children.OrderBy("UpdateDate");
var correctOrder = new[] { 1178, 1177, 1174, 1176 };
for (var i = 0; i < correctOrder.Length; i++)
{
Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id);
}
}
[Test]
public void FirstChild()
{
var doc = GetNode(1173); // has child nodes
Assert.IsNotNull(doc.FirstChild());
Assert.IsNotNull(doc.FirstChild(x => true));
Assert.IsNotNull(doc.FirstChild<IPublishedContent>());
doc = GetNode(1175); // does not have child nodes
Assert.IsNull(doc.FirstChild());
Assert.IsNull(doc.FirstChild(x => true));
Assert.IsNull(doc.FirstChild<IPublishedContent>());
}
[Test]
public void HasProperty()
{
var doc = GetNode(1173);
var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias);
Assert.AreEqual(true, (bool)hasProp);
}
[Test]
public void HasValue()
{
var doc = GetNode(1173);
var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias);
var noValue = doc.HasValue("blahblahblah");
Assert.IsTrue(hasValue);
Assert.IsFalse(noValue);
}
[Test]
public void Ancestors_Where_Visible()
{
var doc = GetNode(1174);
var whereVisible = doc.Ancestors().Where("Visible");
Assert.AreEqual(1, whereVisible.Count());
}
[Test]
public void Visible()
{
var hidden = GetNode(1046);
var visible = GetNode(1173);
Assert.IsFalse(hidden.IsVisible());
Assert.IsTrue(visible.IsVisible());
}
[Test]
public void Ancestor_Or_Self()
{
var doc = GetNode(1173);
var result = doc.AncestorOrSelf();
Assert.IsNotNull(result);
// ancestor-or-self has to be self!
Assert.AreEqual(1173, result.Id);
}
[Test]
public void U4_4559()
{
var doc = GetNode(1174);
var result = doc.AncestorOrSelf(1);
Assert.IsNotNull(result);
Assert.AreEqual(1046, result.Id);
}
[Test]
public void Ancestors_Or_Self()
{
var doc = GetNode(1174);
var result = doc.AncestorsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 }));
}
[Test]
public void Ancestors()
{
var doc = GetNode(1174);
var result = doc.Ancestors();
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 }));
}
[Test]
public void Descendants_Or_Self()
{
var doc = GetNode(1046);
var result = doc.DescendantsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(8, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 }));
}
[Test]
public void Descendants()
{
var doc = GetNode(1046);
var result = doc.Descendants();
Assert.IsNotNull(result);
Assert.AreEqual(7, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 }));
}
[Test]
public void Up()
{
var doc = GetNode(1173);
var result = doc.Up();
Assert.IsNotNull(result);
Assert.AreEqual((int)1046, (int)result.Id);
}
[Test]
public void Down()
{
var doc = GetNode(1173);
var result = doc.Down();
Assert.IsNotNull(result);
Assert.AreEqual((int)1174, (int)result.Id);
}
[Test]
public void Next()
{
var doc = GetNode(1173);
var result = doc.Next();
Assert.IsNotNull(result);
Assert.AreEqual((int)1175, (int)result.Id);
}
[Test]
public void Next_Without_Sibling()
{
var doc = GetNode(1176);
Assert.IsNull(doc.Next());
}
[Test]
public void Previous_Without_Sibling()
{
var doc = GetNode(1173);
Assert.IsNull(doc.Previous());
}
[Test]
public void Previous()
{
var doc = GetNode(1176);
var result = doc.Previous();
Assert.IsNotNull(result);
Assert.AreEqual((int)1178, (int)result.Id);
}
[Test]
public void DetachedProperty1()
{
var type = new PublishedPropertyType("detached", Constants.PropertyEditors.IntegerAlias);
var prop = PublishedProperty.GetDetached(type.Detached(), "5548");
Assert.IsInstanceOf<int>(prop.Value);
Assert.AreEqual(5548, prop.Value);
}
public void CreateDetachedContentSample()
{
bool previewing = false;
var t = PublishedContentType.Get(PublishedItemType.Content, "detachedSomething");
var values = new Dictionary<string, object>();
var properties = t.PropertyTypes.Select(x =>
{
object value;
if (values.TryGetValue(x.PropertyTypeAlias, out value) == false) value = null;
return PublishedProperty.GetDetached(x.Detached(), value, previewing);
});
// and if you want some sort of "model" it's up to you really...
var c = new DetachedContent(properties);
}
public void CreatedDetachedContentInConverterSample()
{
// the converter args
PublishedPropertyType argPropertyType = null;
object argSource = null;
bool argPreview = false;
var pt1 = new PublishedPropertyType("legend", 0, Constants.PropertyEditors.TextboxAlias);
var pt2 = new PublishedPropertyType("image", 0, Constants.PropertyEditors.MediaPickerAlias);
string val1 = "";
int val2 = 0;
var c = new ImageWithLegendModel(
PublishedProperty.GetDetached(pt1.Nested(argPropertyType), val1, argPreview),
PublishedProperty.GetDetached(pt2.Nested(argPropertyType), val2, argPreview));
}
class ImageWithLegendModel
{
private IPublishedProperty _legendProperty;
private IPublishedProperty _imageProperty;
public ImageWithLegendModel(IPublishedProperty legendProperty, IPublishedProperty imageProperty)
{
_legendProperty = legendProperty;
_imageProperty = imageProperty;
}
public string Legend { get { return _legendProperty.GetValue<string>(); } }
public IPublishedContent Image { get { return _imageProperty.GetValue<IPublishedContent>(); } }
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Context;
using Internals.Extensions;
using Logging;
using Pipeline;
using Transports;
using Util;
public class MassTransitBus :
IBusControl,
IDisposable
{
static readonly ILog _log = Logger.Get<MassTransitBus>();
readonly IBusObserver _busObservable;
readonly IConsumePipe _consumePipe;
readonly IBusHostControl[] _hosts;
readonly Lazy<IPublishEndpoint> _publishEndpoint;
readonly IPublishEndpointProvider _publishEndpointProvider;
readonly IReceiveEndpoint[] _receiveEndpoints;
readonly ReceiveObservable _receiveObservers;
readonly ISendEndpointProvider _sendEndpointProvider;
BusHandle _busHandle;
public MassTransitBus(Uri address, IConsumePipe consumePipe, ISendEndpointProvider sendEndpointProvider,
IPublishEndpointProvider publishEndpointProvider, IEnumerable<IReceiveEndpoint> receiveEndpoints, IEnumerable<IBusHostControl> hosts,
IBusObserver busObservable)
{
Address = address;
_consumePipe = consumePipe;
_sendEndpointProvider = sendEndpointProvider;
_publishEndpointProvider = publishEndpointProvider;
_busObservable = busObservable;
_receiveEndpoints = receiveEndpoints.ToArray();
_hosts = hosts.ToArray();
_receiveObservers = new ReceiveObservable();
_publishEndpoint = new Lazy<IPublishEndpoint>(() => publishEndpointProvider.CreatePublishEndpoint(address));
}
ConnectHandle IConsumePipeConnector.ConnectConsumePipe<T>(IPipe<ConsumeContext<T>> pipe)
{
return _consumePipe.ConnectConsumePipe(pipe);
}
ConnectHandle IRequestPipeConnector.ConnectRequestPipe<T>(Guid requestId, IPipe<ConsumeContext<T>> pipe)
{
return _consumePipe.ConnectRequestPipe(requestId, pipe);
}
ConnectHandle IConsumeMessageObserverConnector.ConnectConsumeMessageObserver<T>(IConsumeMessageObserver<T> observer)
{
return new MultipleConnectHandle(_receiveEndpoints.Select(x => x.ConnectConsumeMessageObserver(observer)));
}
ConnectHandle IConsumeObserverConnector.ConnectConsumeObserver(IConsumeObserver observer)
{
return new MultipleConnectHandle(_receiveEndpoints.Select(x => x.ConnectConsumeObserver(observer)));
}
Task IPublishEndpoint.Publish<T>(T message, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(message, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(message, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, Type messageType, CancellationToken cancellationToken)
{
return PublishEndpointConverterCache.Publish(this, message, messageType, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, Type messageType, IPipe<PublishContext> publishPipe,
CancellationToken cancellationToken)
{
return PublishEndpointConverterCache.Publish(this, message, messageType, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish<T>(values, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish(values, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
return _publishEndpoint.Value.Publish<T>(values, publishPipe, cancellationToken);
}
public Uri Address { get; }
Task<ISendEndpoint> ISendEndpointProvider.GetSendEndpoint(Uri address)
{
return _sendEndpointProvider.GetSendEndpoint(address);
}
BusHandle IBusControl.Start()
{
return TaskUtil.Await(() => StartAsync(CancellationToken.None));
}
public async Task<BusHandle> StartAsync(CancellationToken cancellationToken)
{
if (_busHandle != null)
{
_log.Warn($"The bus was already started, additional Start attempts are ignored: {Address}");
return _busHandle;
}
await _busObservable.PreStart(this).ConfigureAwait(false);
Handle busHandle = null;
var endpoints = new List<ReceiveEndpointHandle>();
var hosts = new List<HostHandle>();
var observers = new List<ConnectHandle>();
var busReady = new BusReady(_receiveEndpoints);
try
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Starting bus hosts...");
foreach (var host in _hosts)
{
var hostHandle = host.Start();
hosts.Add(hostHandle);
}
if (_log.IsDebugEnabled)
_log.DebugFormat("Starting receive endpoints...");
foreach (var endpoint in _receiveEndpoints)
{
var observerHandle = endpoint.ConnectReceiveObserver(_receiveObservers);
observers.Add(observerHandle);
var handle = endpoint.Start();
endpoints.Add(handle);
}
busHandle = new Handle(hosts, endpoints, observers, this, _busObservable, busReady);
await busHandle.Ready.WithCancellation(cancellationToken).ConfigureAwait(false);
await _busObservable.PostStart(this, busReady.Ready).ConfigureAwait(false);
_busHandle = busHandle;
return _busHandle;
}
catch (Exception ex)
{
try
{
if (busHandle != null)
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Stopping bus hosts...");
await busHandle.StopAsync(cancellationToken).ConfigureAwait(false);
}
else
{
var handle = new Handle(hosts, endpoints, observers, this, _busObservable, busReady);
await handle.StopAsync(cancellationToken).ConfigureAwait(false);
}
}
catch (Exception stopException)
{
_log.Error("Failed to stop partially created bus", stopException);
}
await _busObservable.StartFaulted(this, ex).ConfigureAwait(false);
throw;
}
}
void IBusControl.Stop(CancellationToken cancellationToken)
{
if (_busHandle == null)
{
_log.Warn($"The bus could not be stopped as it was never started: {Address}");
return;
}
_busHandle.Stop(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken = new CancellationToken())
{
if (_busHandle == null)
{
_log.Warn($"The bus could not be stopped as it was never started: {Address}");
return TaskUtil.Completed;
}
return _busHandle.StopAsync(cancellationToken);
}
public ConnectHandle ConnectReceiveObserver(IReceiveObserver observer)
{
return _receiveObservers.Connect(observer);
}
public ConnectHandle ConnectPublishObserver(IPublishObserver observer)
{
return _publishEndpointProvider.ConnectPublishObserver(observer);
}
void IProbeSite.Probe(ProbeContext context)
{
var scope = context.CreateScope("bus");
scope.Set(new
{
Address
});
foreach (var host in _hosts)
host.Probe(scope);
foreach (var receiveEndpoint in _receiveEndpoints)
receiveEndpoint.Probe(scope);
}
public ConnectHandle ConnectSendObserver(ISendObserver observer)
{
return _sendEndpointProvider.ConnectSendObserver(observer);
}
ConnectHandle IReceiveEndpointObserverConnector.ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return new MultipleConnectHandle(_receiveEndpoints.Select(x => x.ConnectReceiveEndpointObserver(observer)));
}
void IDisposable.Dispose()
{
_busHandle?.Stop(CancellationToken.None);
(_sendEndpointProvider as IDisposable)?.Dispose();
(_publishEndpointProvider as IDisposable)?.Dispose();
}
class BusReady
{
readonly ReadyObserver[] _observers;
public BusReady(IEnumerable<IReceiveEndpoint> receiveEndpoints)
{
_observers = receiveEndpoints.Select(x => new ReadyObserver(x)).ToArray();
}
public Task<ReceiveEndpointReady[]> Ready
{
get { return ReadyOrNot(_observers.Select(x => x.Ready)); }
}
async Task<ReceiveEndpointReady[]> ReadyOrNot(IEnumerable<Task<ReceiveEndpointReady>> observers)
{
var tasks = observers as Task<ReceiveEndpointReady>[] ?? observers.ToArray();
foreach (Task<ReceiveEndpointReady> observer in tasks)
{
await observer.ConfigureAwait(false);
}
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
class ReadyObserver :
IReceiveEndpointObserver
{
readonly ConnectHandle _handle;
readonly TaskCompletionSource<ReceiveEndpointReady> _ready;
public ReadyObserver(IReceiveEndpoint endpoint)
{
_ready = new TaskCompletionSource<ReceiveEndpointReady>();
_handle = endpoint.ConnectReceiveEndpointObserver(this);
}
public Task<ReceiveEndpointReady> Ready => _ready.Task;
Task IReceiveEndpointObserver.Ready(ReceiveEndpointReady ready)
{
_ready.TrySetResult(ready);
_handle.Disconnect();
return TaskUtil.Completed;
}
Task IReceiveEndpointObserver.Completed(ReceiveEndpointCompleted completed)
{
return TaskUtil.Completed;
}
public Task Faulted(ReceiveEndpointFaulted faulted)
{
_ready.TrySetException(faulted.Exception);
_handle.Disconnect();
return TaskUtil.Completed;
}
}
}
class Handle :
BusHandle
{
readonly IBus _bus;
readonly IBusObserver _busObserver;
readonly ReceiveEndpointHandle[] _endpointHandles;
readonly HostHandle[] _hostHandles;
readonly ConnectHandle[] _observerHandles;
bool _stopped;
public Handle(IEnumerable<HostHandle> hostHandles, IEnumerable<ReceiveEndpointHandle> endpointHandles, IEnumerable<ConnectHandle> observerHandles,
IBus bus, IBusObserver busObserver, BusReady ready)
{
_bus = bus;
_busObserver = busObserver;
_endpointHandles = endpointHandles.ToArray();
_hostHandles = hostHandles.ToArray();
_observerHandles = observerHandles.ToArray();
Ready = ready.Ready;
}
public Task<ReceiveEndpointReady[]> Ready { get; }
public void Stop(CancellationToken cancellationToken)
{
if (_stopped)
return;
TaskUtil.Await(() => StopAsync(cancellationToken), cancellationToken);
_stopped = true;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_stopped)
return;
await _busObserver.PreStop(_bus).ConfigureAwait(false);
try
{
foreach (var observerHandle in _observerHandles)
observerHandle.Disconnect();
if (_log.IsDebugEnabled)
_log.DebugFormat("Stopping endpoints...");
await Task.WhenAll(_endpointHandles.Select(x => x.Stop(cancellationToken))).ConfigureAwait(false);
if (_log.IsDebugEnabled)
_log.DebugFormat("Stopping hosts...");
await Task.WhenAll(_hostHandles.Select(x => x.Stop(cancellationToken))).ConfigureAwait(false);
await _busObserver.PostStop(_bus).ConfigureAwait(false);
}
catch (Exception exception)
{
await _busObserver.StopFaulted(_bus, exception).ConfigureAwait(false);
throw;
}
_stopped = true;
}
void IDisposable.Dispose()
{
Stop(CancellationToken.None);
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace Microsoft.PowerShell.Commands
{
#region BaseCsvWritingCommand
/// <summary>
/// This class implements the base for exportcsv and converttocsv commands
/// </summary>
public abstract class BaseCsvWritingCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Property that sets delimiter
/// </summary>
[Parameter(Position = 1, ParameterSetName = "Delimiter")]
[ValidateNotNull]
public char Delimiter
{
get
{
return _delimiter;
}
set
{
_delimiter = value;
}
}
/// <summary>
/// Delimiter to be used.
/// </summary>
private char _delimiter;
///<summary>
///Culture switch for csv conversion
///</summary>
[Parameter(ParameterSetName = "UseCulture")]
public SwitchParameter UseCulture { get; set; }
/// <summary>
/// Abstract Property - Input Object which is written in Csv format
/// Derived as Different Attributes.In ConvertTo-CSV, This is a positional parameter. Export-CSV not a Positional behaviour.
/// </summary>
public abstract PSObject InputObject
{
get;
set;
}
/// <summary>
/// NoTypeInformation : should the #TYPE line be generated
/// </summary>
[Parameter]
[Alias("NTI")]
public SwitchParameter NoTypeInformation
{
get
{
return _noTypeInformation;
}
set
{
_noTypeInformation = value;
}
}
private bool _noTypeInformation;
#endregion Command Line Parameters
/// <summary>
/// Write the string to a file or pipeline
/// </summary>
public virtual void WriteCsvLine(string line)
{
}
/// <summary>
/// BeginProcessing override
/// </summary>
protected override void BeginProcessing()
{
_delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, _delimiter, UseCulture);
}
}
#endregion
#region Export-CSV Command
/// <summary>
/// implementation for the export-csv command
/// </summary>
[Cmdlet(VerbsData.Export, "Csv", SupportsShouldProcess = true, DefaultParameterSetName = "Delimiter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113299")]
public sealed class ExportCsvCommand : BaseCsvWritingCommand, IDisposable
{
#region Command Line Parameters
// If a Passthru parameter is added, the ShouldProcess
// implementation will need to be changed.
/// <summary>
/// Input Object for CSV Writing.
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true)]
public override PSObject InputObject { get; set; }
/// <summary>
/// mandatory file name to write to
/// </summary>
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string Path
{
get
{
return _path;
}
set
{
_path = value;
_specifiedPath = true;
}
}
private string _path;
private bool _specifiedPath = false;
/// <summary>
/// The literal path of the mandatory file name to write to
/// </summary>
[Parameter()]
[ValidateNotNullOrEmpty]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Property that prevents file overwrite.
/// </summary>
[Parameter()]
[Alias("NoOverwrite")]
public SwitchParameter NoClobber
{
get
{
return _noclobber;
}
set
{
_noclobber = value;
}
}
private bool _noclobber;
/// <summary>
/// Encoding optional flag
/// </summary>
[Parameter()]
[ValidateSetAttribute(new string[] { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" })]
public string Encoding { get; set; }
/// <summary>
/// Property that sets append parameter.
/// </summary>
[Parameter]
public SwitchParameter Append { get; set; }
private bool _isActuallyAppending; // true if Append=true AND the file written was not empty (or nonexistent) when the cmdlet was invoked
#endregion
#region Overrides
private bool _shouldProcess;
private IList<string> _propertyNames;
private IList<string> _preexistingPropertyNames;
private ExportCsvHelper _helper;
/// <summary>
/// BeginProcessing override
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
_shouldProcess = ShouldProcess(Path);
if (!_shouldProcess) return;
CreateFileStream();
_helper = new ExportCsvHelper(this, base.Delimiter);
}
/// <summary>
/// Convert the current input object to Csv and write to file/WriteObject
/// </summary>
protected override
void
ProcessRecord()
{
if (InputObject == null || _sw == null)
{
return;
}
if (!_shouldProcess) return;
//Process first object
if (_propertyNames == null)
{
// figure out the column names (and lock-in their order)
_propertyNames = _helper.BuildPropertyNames(InputObject, _propertyNames);
if (_isActuallyAppending && _preexistingPropertyNames != null)
{
this.ReconcilePreexistingPropertyNames();
}
// write headers (row1: typename + row2: column names)
if (!_isActuallyAppending)
{
if (NoTypeInformation == false)
{
WriteCsvLine(_helper.GetTypeString(InputObject));
}
WriteCsvLine(_helper.ConvertPropertyNamesCSV(_propertyNames));
}
}
string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames);
WriteCsvLine(csv);
_sw.Flush();
}
/// <summary>
/// EndProcessing
/// </summary>
protected override void EndProcessing()
{
CleanUp();
}
#endregion Overrides
#region file
/// <summary>
/// handle to file stream
/// </summary>
private FileStream _fs;
/// <summary>
/// stream writer used to write to file
/// </summary>
private StreamWriter _sw = null;
/// <summary>
/// handle to file whose read-only attribute should be reset when we are done
/// </summary>
private FileInfo _readOnlyFileInfo = null;
private void CreateFileStream()
{
Dbg.Assert(_path != null, "FileName is mandatory parameter");
string resolvedFilePath = PathUtils.ResolveFilePath(this.Path, this, _isLiteralPath);
bool isCsvFileEmpty = true;
if (this.Append && File.Exists(resolvedFilePath))
{
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath))
{
isCsvFileEmpty = streamReader.Peek() == -1 ? true : false;
}
}
// If the csv file is empty then even append is treated as regular export (i.e., both header & values are added to the CSV file).
_isActuallyAppending = this.Append && File.Exists(resolvedFilePath) && !isCsvFileEmpty;
if (_isActuallyAppending)
{
Encoding encodingObject;
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath))
{
ImportCsvHelper readingHelper = new ImportCsvHelper(
this, this.Delimiter, null /* header */, null /* typeName */, streamReader);
readingHelper.ReadHeader();
_preexistingPropertyNames = readingHelper.Header;
encodingObject = streamReader.CurrentEncoding;
}
PathUtils.MasterStreamOpen(
this,
this.Path,
encodingObject,
false, // defaultEncoding
Append,
Force,
NoClobber,
out _fs,
out _sw,
out _readOnlyFileInfo,
_isLiteralPath);
}
else
{
PathUtils.MasterStreamOpen(
this,
this.Path,
Encoding ?? "ASCII",
false, // defaultEncoding
Append,
Force,
NoClobber,
out _fs,
out _sw,
out _readOnlyFileInfo,
_isLiteralPath);
}
}
private
void
CleanUp()
{
if (_fs != null)
{
if (_sw != null)
{
_sw.Flush();
_sw.Dispose();
_sw = null;
}
_fs.Dispose();
_fs = null;
// reset the read-only attribute
if (null != _readOnlyFileInfo)
_readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
}
if (_helper != null)
{
_helper.Dispose();
}
}
private void ReconcilePreexistingPropertyNames()
{
Dbg.Assert(_isActuallyAppending, "This method should only get called when appending");
Dbg.Assert(_preexistingPropertyNames != null, "This method should only get called when we have successfully read preexisting property names");
HashSet<string> appendedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string appendedPropertyName in _propertyNames)
{
appendedPropertyNames.Add(appendedPropertyName);
}
foreach (string preexistingPropertyName in _preexistingPropertyNames)
{
if (!appendedPropertyNames.Contains(preexistingPropertyName))
{
if (!Force)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture, // property names and file names are culture invariant
CsvCommandStrings.CannotAppendCsvWithMismatchedPropertyNames,
preexistingPropertyName,
this.Path);
InvalidOperationException exception = new InvalidOperationException(errorMessage);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName);
this.ThrowTerminatingError(errorRecord);
}
}
}
_propertyNames = _preexistingPropertyNames;
_preexistingPropertyNames = null;
}
/// <summary>
/// Write the csv line to file
/// </summary>
/// <param name="line"></param>
public override void
WriteCsvLine(string line)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("ExportCsvCommand");
}
_sw.WriteLine(line);
}
#endregion file
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
private bool _disposed;
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
if (_disposed == false)
{
CleanUp();
}
_disposed = true;
}
#endregion IDisposable Members
}
#endregion Export-CSV Command
#region Import-CSV Command
/// <summary>
/// Implements Import-Csv command
/// </summary>
[Cmdlet(VerbsData.Import, "Csv", DefaultParameterSetName = "Delimiter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113341")]
public sealed
class
ImportCsvCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Property that sets delimiter
/// </summary>
[Parameter(Position = 1, ParameterSetName = "Delimiter")]
[ValidateNotNull]
public char Delimiter { get; set; }
/// <summary>
/// mandatory file name to read from
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
public String[] Path
{
get
{
return _paths;
}
set
{
_paths = value;
_specifiedPath = true;
}
}
private string[] _paths;
private bool _specifiedPath = false;
/// <summary>
/// The literal path of the mandatory file name to read from
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _paths;
}
set
{
_paths = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Property that sets UseCulture parameter
/// </summary>
[Parameter(ParameterSetName = "UseCulture", Mandatory = true)]
[ValidateNotNull]
public SwitchParameter UseCulture
{
get
{
return _useculture;
}
set
{
_useculture = value;
}
}
private bool _useculture;
///<summary>
/// Header property to customize the names
///</summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Header { get; set; }
/// <summary>
/// Encoding optional flag
/// </summary>
[Parameter()]
[ValidateSetAttribute(new[] { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" })]
public string Encoding { get; set; }
/// <summary>
/// Avoid writing out duplicate warning messages when there are
/// one or more unspecified names
/// </summary>
private bool _alreadyWarnedUnspecifiedNames = false;
#endregion Command Line Parameters
#region Override Methods
/// <summary>
///
/// </summary>
protected override void BeginProcessing()
{
Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, _useculture);
}
/// <summary>
/// ProcessRecord overload
/// </summary>
protected override void ProcessRecord()
{
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
if (_paths != null)
{
foreach (string path in _paths)
{
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, null /* typeName */, streamReader);
try
{
helper.Import(ref _alreadyWarnedUnspecifiedNames);
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
}
}
}//if
}////ProcessRecord
}
#endregion Override Methods
#endregion Import-CSV Command
#region ConvertTo-CSV Command
/// <summary>
/// Implements ConvertTo-Csv command
/// </summary>
[Cmdlet(VerbsData.ConvertTo, "Csv", DefaultParameterSetName = "Delimiter",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135203", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(String))]
public sealed class ConvertToCsvCommand : BaseCsvWritingCommand
{
#region Parameter
/// <summary>
/// Overrides Base InputObject
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
public override PSObject InputObject { get; set; }
#endregion Parameter
#region Overrides
/// <summary>
/// Stores Property Names
/// </summary>
private IList<string> _propertyNames;
/// <summary>
///
/// </summary>
private ExportCsvHelper _helper;
/// <summary>
/// BeginProcessing override
/// </summary>
protected override
void
BeginProcessing()
{
base.BeginProcessing();
_helper = new ExportCsvHelper(this, base.Delimiter);
}
/// <summary>
/// Convert the current input object to Csv and write to stream/WriteObject
/// </summary>
protected override
void
ProcessRecord()
{
if (InputObject == null)
{
return;
}
//Process first object
if (_propertyNames == null)
{
_propertyNames = _helper.BuildPropertyNames(InputObject, _propertyNames);
if (NoTypeInformation == false)
{
WriteCsvLine(_helper.GetTypeString(InputObject));
}
//Write property information
string properties = _helper.ConvertPropertyNamesCSV(_propertyNames);
if (!properties.Equals(""))
WriteCsvLine(properties);
}
string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames);
//write to the console
if (csv != "")
WriteCsvLine(csv);
}
#endregion Overrides
#region CSV conversion
/// <summary>
///
/// </summary>
/// <param name="line"></param>
public override void
WriteCsvLine(string line)
{
WriteObject(line);
}
#endregion CSV conversion
}
#endregion ConvertTo-CSV Command
#region ConvertFrom-CSV Command
/// <summary>
/// Implements ConvertFrom-Csv command
/// </summary>
[Cmdlet(VerbsData.ConvertFrom, "Csv", DefaultParameterSetName = "Delimiter",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135201", RemotingCapability = RemotingCapability.None)]
public sealed
class
ConvertFromCsvCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Property that sets delimiter
/// </summary>
[Parameter(Position = 1, ParameterSetName = "Delimiter")]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
public char Delimiter { get; set; }
///<summary>
///Culture switch for csv conversion
///</summary>
[Parameter(ParameterSetName = "UseCulture", Mandatory = true)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
public SwitchParameter UseCulture { get; set; }
/// <summary>
/// Input Object which is written in Csv format
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public PSObject[] InputObject { get; set; }
///<summary>
/// Header property to customize the names
///</summary>
[Parameter(Mandatory = false)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Header { get; set; }
/// <summary>
/// Avoid writing out duplicate warning messages when there are
/// one or more unspecified names
/// </summary>
private bool _alreadyWarnedUnspecifiedNames = false;
#endregion Command Line Parameters
#region Overrides
/// <summary>
/// BeginProcessing override
/// </summary>
protected override
void
BeginProcessing()
{
Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture);
}
/// <summary>
/// Convert the current input object to Csv and write to stream/WriteObject
/// </summary>
protected override
void
ProcessRecord()
{
foreach (PSObject pObject in InputObject)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(pObject.ToString())))
using (StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.Unicode))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, _typeName, streamReader);
try
{
helper.Import(ref _alreadyWarnedUnspecifiedNames);
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
if ((Header == null) && (helper.Header != null))
{
Header = helper.Header.ToArray();
}
if ((_typeName == null) && (helper.TypeName != null))
{
_typeName = helper.TypeName;
}
}
}
}
#endregion Overrides
private string _typeName;
}
#endregion ConvertFrom-CSV Command
#region CSV conversion
#region ExportHelperConversion
/// <summary>
///
/// </summary>
internal class ExportCsvHelper : IDisposable
{
/// <summary>
///
/// </summary>
private PSCmdlet _cmdlet;
private char _delimiter;
/// <summary>
///
/// </summary>
/// <param name="cmdlet"></param>
/// <param name="delimiter"></param>
internal
ExportCsvHelper(PSCmdlet cmdlet, char delimiter)
{
if (cmdlet == null)
{
}
_cmdlet = cmdlet;
_delimiter = delimiter;
}
//Name of properties to be written in CSV format
/// <summary>
/// Get the name of properties from source PSObject and
/// add them to _propertyNames.
/// </summary>
internal
IList<string>
BuildPropertyNames(PSObject source, IList<string> propertyNames)
{
Dbg.Assert(propertyNames == null, "This method should be called only once per cmdlet instance");
// serialize only Extended and Adapted properties..
PSMemberInfoCollection<PSPropertyInfo> srcPropertiesToSearch =
new PSMemberInfoIntegratingCollection<PSPropertyInfo>(source,
PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted));
propertyNames = new Collection<string>();
foreach (PSPropertyInfo prop in srcPropertiesToSearch)
{
propertyNames.Add(prop.Name);
}
return propertyNames;
}
/// <summary>
/// Converts PropertyNames in to a CSV string
/// </summary>
/// <returns></returns>
internal
string
ConvertPropertyNamesCSV(IList<string> propertyNames)
{
Dbg.Assert(propertyNames != null, "BuildPropertyNames should be called before this method");
StringBuilder dest = new StringBuilder();
bool first = true;
foreach (string propertyName in propertyNames)
{
if (first)
{
first = false;
}
else
{
//changed to delimiter
dest.Append(_delimiter);
}
EscapeAndAppendString(dest, propertyName);
}
return dest.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="mshObject"></param>
/// <param name="propertyNames"></param>
/// <returns></returns>
internal
string
ConvertPSObjectToCSV(PSObject mshObject, IList<string> propertyNames)
{
Dbg.Assert(propertyNames != null, "PropertyName collection can be empty here, but it should not be null");
StringBuilder dest = new StringBuilder();
bool first = true;
foreach (string propertyName in propertyNames)
{
if (first)
{
first = false;
}
else
{
dest.Append(_delimiter);
}
PSPropertyInfo property = mshObject.Properties[propertyName] as PSPropertyInfo;
string value = null;
//If property is not present, assume value is null
if (property != null)
{
value = GetToStringValueForProperty(property);
}
EscapeAndAppendString(dest, value);
}
return dest.ToString();
}
/// <summary>
/// Get value from property object
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
internal
string
GetToStringValueForProperty(PSPropertyInfo property)
{
Dbg.Assert(property != null, "Caller should validate the parameter");
string value = null;
try
{
object temp = property.Value;
if (temp != null)
{
value = temp.ToString();
}
}
//If we cannot read some value, treat it as null.
catch (Exception ex)
{
UtilityCommon.CheckForSevereException(_cmdlet, ex);
}
return value;
}
/// <summary>
/// Prepares string for writing type information
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
internal
string
GetTypeString(PSObject source)
{
string type = null;
//get type of source
Collection<string> tnh = source.TypeNames;
if (tnh == null || tnh.Count == 0)
{
type = "#TYPE";
}
else
{
Dbg.Assert(tnh[0] != null, "type hierarchy should not have null values");
string temp = tnh[0];
//If type starts with CSV: remove it. This would happen when you export
//an imported object. import-csv adds CSV. prefix to the type.
if (temp.StartsWith(ImportExportCSVHelper.CSVTypePrefix, StringComparison.OrdinalIgnoreCase))
{
temp = temp.Substring(4);
}
type = string.Format(System.Globalization.CultureInfo.InvariantCulture, "#TYPE {0}", temp);
}
return type;
}
/// <summary>
/// Escapes the " in string if necessary.
/// Encloses the string in double quotes if necessary.
/// </summary>
/// <returns></returns>
internal static
void
EscapeAndAppendString(StringBuilder dest, string source)
{
if (source == null)
{
return;
}
//Adding Double quote to all strings
dest.Append('"');
for (int i = 0; i < source.Length; i++)
{
char c = source[i];
//Double quote in the string is escaped with double quote
if ((c == '"'))
{
dest.Append('"');
}
dest.Append(c);
}
dest.Append('"');
}
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
private bool _disposed;
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
if (_disposed == false)
{
GC.SuppressFinalize(this);
}
_disposed = true;
}
#endregion IDisposable Members
}
#endregion ExportHelperConversion
#region ImportHelperConversion
/// <summary>
/// Helper class to import single CSV file
/// </summary>
internal class ImportCsvHelper
{
#region constructor
/// <summary>
/// Reference to cmdlet which is using this helper class
/// </summary>
private readonly PSCmdlet _cmdlet;
/// <summary>
/// CSV delimiter (default is the "comma" / "," character)
/// </summary>
private readonly char _delimiter;
/// <summary>
/// Use "UnspecifiedName" when the name is null or empty
/// </summary>
private const string UnspecifiedName = "H";
/// <summary>
/// Avoid writing out duplicate warning messages when there are
/// one or more unspecified names
/// </summary>
private bool _alreadyWarnedUnspecifiedName = false;
/// <summary>
/// Reference to header values
/// </summary>
internal IList<string> Header { get; private set; }
/// <summary>
/// ETS type name from the first line / comment in the CSV
/// </summary>
internal string TypeName { get; private set; }
/// <summary>
/// Reader of the csv content
/// </summary>
private readonly StreamReader _sr;
internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList<string> header, string typeName, StreamReader streamReader)
{
Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
Dbg.Assert(streamReader != null, "Caller should verify textReader != null");
_cmdlet = cmdlet;
_delimiter = delimiter;
Header = header;
TypeName = typeName;
_sr = streamReader;
}
#endregion constructor
#region reading helpers
/// <summary>
/// This is set to true when end of file is reached
/// </summary>
private
bool EOF
{
get
{
return _sr.EndOfStream;
}
}
private
char
ReadChar()
{
Dbg.Assert(!EOF, "This should not be called if EOF is reached");
int i = _sr.Read();
return (char)i;
}
/// <summary>
/// Peeks the next character in the stream and returns true if it is
/// same as passed in character.
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private
bool
PeekNextChar(char c)
{
int i = _sr.Peek();
if (i == -1)
{
return false;
}
return (c == (char)i);
}
/// <summary>
/// Reads a line from file. This consumes the end of line.
/// Only use it when end of line chars are not important.
/// </summary>
/// <returns></returns>
private string
ReadLine()
{
return _sr.ReadLine();
}
#endregion reading helpers
internal void ReadHeader()
{
//Read #Type record if available
if ((TypeName == null) && (!this.EOF))
{
TypeName = ReadTypeInformation();
}
if ((Header == null) && (!this.EOF))
{
Collection<string> values = ParseNextRecord(true);
if (values.Count != 0)
{
Header = values;
}
}
if (Header != null && Header.Count > 0)
{
ValidatePropertyNames(Header);
}
}
internal
void
Import(ref bool alreadyWriteOutWarning)
{
_alreadyWarnedUnspecifiedName = alreadyWriteOutWarning;
ReadHeader();
while (true)
{
Collection<string> values = ParseNextRecord(false);
if (values.Count == 0)
break;
if (values.Count == 1 && String.IsNullOrEmpty(values[0]))
{
// skip the blank lines
continue;
}
PSObject result = BuildMshobject(TypeName, Header, values, _delimiter);
_cmdlet.WriteObject(result);
}
alreadyWriteOutWarning = _alreadyWarnedUnspecifiedName;
}
/// <summary>
/// Validate the names of properties
/// </summary>
/// <param name="names"></param>
private static void ValidatePropertyNames(IList<string> names)
{
if (names != null)
{
if (names.Count == 0)
{
//If there are no names, it is an error
}
else
{
HashSet<string> headers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string currentHeader in names)
{
if (!String.IsNullOrEmpty(currentHeader))
{
if (!headers.Contains(currentHeader))
{
headers.Add(currentHeader);
}
else
{
// throw a terminating error as there are duplicate headers in the input.
string memberAlreadyPresentMsg =
String.Format(CultureInfo.InvariantCulture,
ExtendedTypeSystem.MemberAlreadyPresent,
currentHeader);
ExtendedTypeSystemException exception = new ExtendedTypeSystemException(memberAlreadyPresentMsg);
throw exception;
}
}
}
}
}
}
/// <summary>
/// Read the type information, if present
/// </summary>
/// <returns>Type string if present else null</returns>
private string
ReadTypeInformation()
{
string type = null;
if (PeekNextChar('#'))
{
string temp = ReadLine();
if (temp.StartsWith("#Type", StringComparison.OrdinalIgnoreCase))
{
type = temp.Substring(5);
type = type.Trim();
if (type.Length == 0)
{
type = null;
}
else
{
type = ImportExportCSVHelper.CSVTypePrefix + type;
}
}
}
return type;
}
/// <summary>
/// Reads the next record from the file and returns parsed collection
/// of string.
/// </summary>
/// <param name="isHeaderRow">
/// Indicates if the parsed row is a header row or a values row.
/// </param>
/// <returns>
/// Parsed collection of strings.
/// </returns>
private Collection<string>
ParseNextRecord(bool isHeaderRow)
{
//Collection of strings to return
Collection<string> result = new Collection<string>();
//current string
StringBuilder current = new StringBuilder();
bool seenBeginQuote = false;
// int i = 0;
while (!EOF)
{
//Read the next character
char ch = ReadChar();
if ((ch == _delimiter))
{
if (seenBeginQuote)
{
//Delimiter inside double quotes is part of string.
//Ex:
//"foo, bar"
//is parsed as
//->foo, bar<-
current.Append(ch);
}
else
{
//Delimiter outside quotes is end of current word.
result.Add(current.ToString());
current.Remove(0, current.Length);
}
}
else if (ch == '"')
{
if (seenBeginQuote)
{
if (PeekNextChar('"'))
{
//"" inside double quote are single quote
//ex: "foo""bar"
//is read as
//->foo"bar<-
//PeekNextChar only peeks. Read the next char.
ReadChar();
current.Append('"');
}
else
{
//We have seen a matching end quote.
seenBeginQuote = false;
//Read
//everything till we hit next delimiter.
//In correct CSV,1) end quote is followed by delimiter
//2)end quote is followed some whitespaces and
//then delimiter.
//We eat the whitespaces seen after the ending quote.
//However if there are other characters, we add all of them
//to string.
//Ex: ->"foo bar"<- is read as ->foo bar<-
//->"foo bar" <- is read as ->foo bar<-
//->"foo bar" ab <- is read as ->"foo bar" ab <-
bool endofRecord = false;
ReadTillNextDelimiter(current, ref endofRecord, true);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endofRecord)
break;
}
}
else if (current.Length == 0)
{
//We are at the beginning of a new word.
//This quote is the first quote.
seenBeginQuote = true;
}
else
{
//We are seeing a quote after the start of
//the word. This is error, however we will be
//lenient here and do what excel does:
//Ex: foo "ba,r"
//In above example word read is ->foo "ba<-
//Basically we read till next delimiter
bool endOfRecord = false;
current.Append(ch);
ReadTillNextDelimiter(current, ref endOfRecord, false);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endOfRecord)
break;
}
}
else if (ch == ' ' || ch == '\t')
{
if (seenBeginQuote)
{
//Spaces in side quote are valid
current.Append(ch);
}
else if (current.Length == 0)
{
//ignore leading spaces
continue;
}
else
{
//We are not in quote and we are not at the
//beginning of a word. We should not be seeing
//spaces here. This is an error condition, however
//we will be lenient here and do what excel does,
//that is read till next delimiter.
//Ex: ->foo <- is read as ->foo<-
//Ex: ->foo bar<- is read as ->foo bar<-
//Ex: ->foo bar <- is read as ->foo bar <-
//Ex: ->foo bar "er,ror"<- is read as ->foo bar "er<-
bool endOfRecord = false;
current.Append(ch);
ReadTillNextDelimiter(current, ref endOfRecord, true);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endOfRecord)
break;
}
}
else if (IsNewLine(ch))
{
if (ch == '\r')
{
ReadChar();
}
if (seenBeginQuote)
{
//newline inside quote are valid
current.Append(ch);
if (ch == '\r')
{
current.Append('\n');
}
}
else
{
result.Add(current.ToString());
current.Remove(0, current.Length);
//New line outside quote is end of word and end of record
break;
}
}
else
{
current.Append(ch);
}
}
if (current.Length != 0)
{
result.Add(current.ToString());
}
//Trim all trailing blankspaces and delimiters ( single/multiple ).
// If there is only one element in the row and if its a blankspace we dont trim it.
// A trailing delimiter is represented as a blankspace while being added to result collection
// which is getting trimmed along with blankspaces supplied through the CSV in the below loop.
if (isHeaderRow)
{
while (result.Count > 1 && result[result.Count - 1].Equals(string.Empty))
{
result.RemoveAt(result.Count - 1);
}
}
return result;
}
private
bool
IsNewLine(char ch)
{
bool newLine = false;
if (ch == '\n')
{
newLine = true;
}
else if (ch == '\r')
{
if (PeekNextChar('\n'))
{
newLine = true;
}
}
return newLine;
}
/// <summary>
/// This function reads the characters till next delimiter and adds them
/// to current
/// </summary>
/// <param name="current"></param>
/// <param name="endOfRecord">
/// this is true if end of record is reached
/// when delimiter is hit. This would be true if delimiter is NewLine
/// </param>
/// <param name="eatTrailingBlanks">
/// If this is true, eat the trailing blanks. Note:if there are non
/// whitespace characters present, then trailing blanks are not consumed
/// </param>
private
void
ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks)
{
StringBuilder temp = new StringBuilder();
//Did we see any non-whitespace character
bool nonWhiteSpace = false;
while (true)
{
if (EOF)
{
endOfRecord = true;
break;
}
char ch = ReadChar();
if (ch == _delimiter)
{
break;
}
else if (IsNewLine(ch))
{
endOfRecord = true;
if (ch == '\r')
{
ReadChar();
}
break;
}
else
{
temp.Append(ch);
if (ch != ' ' && ch != '\t')
{
nonWhiteSpace = true;
}
}
}
if (eatTrailingBlanks && !nonWhiteSpace)
{
string s = temp.ToString();
s = s.Trim();
current.Append(s);
}
else
{
current.Append(temp);
}
}
private
PSObject
BuildMshobject(string type, IList<string> names, Collection<string> values, char delimiter)
{
//string[] namesarray = null;
PSObject result = new PSObject();
char delimiterlocal = delimiter;
int unspecifiedNameIndex = 1;
if (type != null && type.Length > 0)
{
result.TypeNames.Clear();
result.TypeNames.Add(type);
}
for (int i = 0; i <= names.Count - 1; i++)
{
string name = names[i];
string value = null;
////if name is null and delimiter is '"', continue
if (name.Length == 0 && delimiterlocal == '"')
continue;
////if name is null and delimiter is not '"', use a default property name 'UnspecifiedName'
if (string.IsNullOrEmpty(name))
{
name = UnspecifiedName + unspecifiedNameIndex;
unspecifiedNameIndex++;
}
//If no value was present in CSV file, we write null.
if (i < values.Count)
{
value = values[i];
}
result.Properties.Add(new PSNoteProperty(name, value));
}
if (!_alreadyWarnedUnspecifiedName && unspecifiedNameIndex != 1)
{
_cmdlet.WriteWarning(CsvCommandStrings.UseDefaultNameForUnspecifiedHeader);
_alreadyWarnedUnspecifiedName = true;
}
return result;
}
}
#endregion ImportHelperConversion
#region ExportImport Helper
/// <summary>
/// Helper class for CSV conversion
/// </summary>
internal static class ImportExportCSVHelper
{
internal const char CSVDelimiter = ',';
internal const string CSVTypePrefix = "CSV:";
internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName, char Delimiter, bool UseCulture)
{
switch (ParameterSetName)
{
case "Delimiter":
//if delimiter is not given, it should take , as value
if (Delimiter == '\0')
{
Delimiter = ImportExportCSVHelper.CSVDelimiter;
}
break;
case "UseCulture":
if (UseCulture == true)
{
// ListSeparator is apparently always a character even though the property returns a string, checked via:
// [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1
Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0];
}
break;
default:
{
Delimiter = ImportExportCSVHelper.CSVDelimiter;
}
break;
}
return Delimiter;
}
}
#endregion ExportImport Helper
#endregion CSV conversion
}
| |
// ***********************************************************************
// Copyright (c) 2009-2014 Charlie Poole
//
// 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.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
#if SILVERLIGHT
using System.Web.UI;
#endif // SILVERLIGHT
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Api
{
/// <summary>
/// FrameworkController provides a facade for use in loading, browsing
/// and running tests without requiring a reference to the NUnit
/// framework. All calls are encapsulated in constructors for
/// this class and its nested classes, which only require the
/// types of the Common Type System as arguments.
///
/// The controller supports four actions: Load, Explore, Count and Run.
/// They are intended to be called by a driver, which should allow for
/// proper sequencing of calls. Load must be called before any of the
/// other actions. The driver may support other actions, such as
/// reload on run, by combining these calls.
/// </summary>
public class FrameworkController : LongLivedMarshalByRefObject
{
#if !PORTABLE && !SILVERLIGHT
private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log";
#endif
// Pre-loaded test assembly, if passed in constructor
private Assembly _testAssembly;
#region Constructors
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings)
{
Initialize(assemblyNameOrPath, settings);
this.Builder = new DefaultTestAssemblyBuilder();
this.Runner = new NUnitTestAssemblyRunner(this.Builder);
Test.IdPrefix = idPrefix;
}
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings)
: this(assembly.FullName, idPrefix, settings)
{
_testAssembly = assembly;
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType)
{
Initialize(assemblyNameOrPath, settings);
Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType));
Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder });
Test.IdPrefix = idPrefix ?? "";
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType)
: this(assembly.FullName, idPrefix, settings, runnerType, builderType)
{
_testAssembly = assembly;
}
#if !SILVERLIGHT && !NETCF && !PORTABLE
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
#endif
private void Initialize(string assemblyPath, IDictionary settings)
{
AssemblyNameOrPath = assemblyPath;
var newSettings = settings as IDictionary<string, object>;
Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel))
{
var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter))
InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel);
#if !PORTABLE && !SILVERLIGHT
else
{
var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory) ? (string)Settings[FrameworkPackageSettings.WorkDirectory] : Env.DefaultWorkDirectory;
var logName = string.Format(LOG_FILE_FORMAT, Process.GetCurrentProcess().Id, Path.GetFileName(assemblyPath));
InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
}
#endif
}
}
#endregion
#region Properties
/// <summary>
/// Gets the ITestAssemblyBuilder used by this controller instance.
/// </summary>
/// <value>The builder.</value>
public ITestAssemblyBuilder Builder { get; private set; }
/// <summary>
/// Gets the ITestAssemblyRunner used by this controller instance.
/// </summary>
/// <value>The runner.</value>
public ITestAssemblyRunner Runner { get; private set; }
/// <summary>
/// Gets the AssemblyName or the path for which this FrameworkController was created
/// </summary>
public string AssemblyNameOrPath { get; private set; }
/// <summary>
/// Gets the Assembly for which this
/// </summary>
public Assembly Assembly { get; private set; }
/// <summary>
/// Gets a dictionary of settings for the FrameworkController
/// </summary>
internal IDictionary<string, object> Settings { get; private set; }
#endregion
#region Public Action methods Used by nunit.driver for running portable tests
/// <summary>
/// Loads the tests in the assembly
/// </summary>
/// <returns></returns>
public string LoadTests()
{
if (_testAssembly != null)
Runner.Load(_testAssembly, Settings);
else
Runner.Load(AssemblyNameOrPath, Settings);
return Runner.LoadedTest.ToXml(false).OuterXml;
}
/// <summary>
/// Returns info about the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of exploring the tests</returns>
public string ExploreTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
if (Runner.LoadedTest == null)
throw new InvalidOperationException("The Explore method was called but no test has been loaded");
// TODO: Make use of the filter
return Runner.LoadedTest.ToXml(true).OuterXml;
}
/// <summary>
/// Runs the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE && !SILVERLIGHT
InsertEnvironmentElement(result);
#endif
// Ensure that the CallContext of the thread is not polluted
// by our TestExecutionContext, which is not serializable.
TestExecutionContext.ClearCurrentContext();
return result.OuterXml;
}
#if !NET_2_0
class ActionCallback : ICallbackEventHandler
{
Action<string> _callback;
public ActionCallback(Action<string> callback)
{
_callback = callback;
}
public string GetCallbackResult()
{
throw new NotImplementedException();
}
public void RaiseCallbackEvent(string report)
{
if(_callback != null)
_callback.Invoke(report);
}
}
/// <summary>
/// Runs the tests in an assembly syncronously reporting back the test results through the callback
/// or through the return value
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(Action<string> callback, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
var handler = new ActionCallback(callback);
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE && !SILVERLIGHT
InsertEnvironmentElement(result);
#endif
// Ensure that the CallContext of the thread is not polluted
// by our TestExecutionContext, which is not serializable.
TestExecutionContext.ClearCurrentContext();
return result.OuterXml;
}
/// <summary>
/// Runs the tests in an assembly asyncronously reporting back the test results through the callback
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
private void RunAsync(Action<string> callback, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
var handler = new ActionCallback(callback);
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
#endif
/// <summary>
/// Stops the test run
/// </summary>
/// <param name="force">True to force the stop, false for a cooperative stop</param>
public void StopRun(bool force)
{
Runner.StopRun(force);
}
/// <summary>
/// Counts the number of test cases in the loaded TestSuite
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The number of tests</returns>
public int CountTests(string filter)
{
Guard.ArgumentNotNull(filter, "filter");
return Runner.CountTestCases(TestFilter.FromXml(filter));
}
#endregion
#region Private Action Methods Used by Nested Classes
private void LoadTests(ICallbackEventHandler handler)
{
handler.RaiseCallbackEvent(LoadTests());
}
private void ExploreTests(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
if (Runner.LoadedTest == null)
throw new InvalidOperationException("The Explore method was called but no test has been loaded");
// TODO: Make use of the filter
handler.RaiseCallbackEvent(Runner.LoadedTest.ToXml(true).OuterXml);
}
private void RunTests(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
#if !PORTABLE && !SILVERLIGHT
InsertEnvironmentElement(result);
#endif
// Ensure that the CallContext of the thread is not polluted
// by our TestExecutionContext, which is not serializable.
TestExecutionContext.ClearCurrentContext();
handler.RaiseCallbackEvent(result.OuterXml);
}
private void RunAsync(ICallbackEventHandler handler, string filter)
{
Guard.ArgumentNotNull(filter, "filter");
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
private void StopRun(ICallbackEventHandler handler, bool force)
{
StopRun(force);
}
private void CountTests(ICallbackEventHandler handler, string filter)
{
handler.RaiseCallbackEvent(CountTests(filter).ToString());
}
#if !PORTABLE && !SILVERLIGHT
/// <summary>
/// Inserts environment element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <returns>The new node</returns>
public static TNode InsertEnvironmentElement(TNode targetNode)
{
TNode env = new TNode("environment");
targetNode.ChildNodes.Insert(0, env);
env.AddAttribute("framework-version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
env.AddAttribute("clr-version", Environment.Version.ToString());
env.AddAttribute("os-version", Environment.OSVersion.ToString());
env.AddAttribute("platform", Environment.OSVersion.Platform.ToString());
#if !NETCF
env.AddAttribute("cwd", Environment.CurrentDirectory);
env.AddAttribute("machine-name", Environment.MachineName);
env.AddAttribute("user", Environment.UserName);
env.AddAttribute("user-domain", Environment.UserDomainName);
#endif
env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString());
env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString());
env.AddAttribute("os-architecture", GetProcessorArchitecture());
return env;
}
private static string GetProcessorArchitecture()
{
return IntPtr.Size == 8 ? "x64" : "x86";
}
#endif
/// <summary>
/// Inserts settings element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <param name="settings">Settings dictionary</param>
/// <returns>The new node</returns>
public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings)
{
TNode settingsNode = new TNode("settings");
targetNode.ChildNodes.Insert(0, settingsNode);
foreach (string key in settings.Keys)
AddSetting(settingsNode, key, settings[key]);
#if PARALLEL
// Add default values for display
if (!settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers))
AddSetting(settingsNode, FrameworkPackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
#endif
return settingsNode;
}
private static void AddSetting(TNode settingsNode, string name, object value)
{
TNode setting = new TNode("setting");
setting.AddAttribute("name", name);
setting.AddAttribute("value", value.ToString());
settingsNode.ChildNodes.Add(setting);
}
#endregion
#region Nested Action Classes
#region TestContollerAction
/// <summary>
/// FrameworkControllerAction is the base class for all actions
/// performed against a FrameworkController.
/// </summary>
public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject
{
}
#endregion
#region LoadTestsAction
/// <summary>
/// LoadTestsAction loads a test into the FrameworkController
/// </summary>
public class LoadTestsAction : FrameworkControllerAction
{
/// <summary>
/// LoadTestsAction loads the tests in an assembly.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="handler">The callback handler.</param>
public LoadTestsAction(FrameworkController controller, object handler)
{
controller.LoadTests((ICallbackEventHandler)handler);
}
}
#endregion
#region ExploreTestsAction
/// <summary>
/// ExploreTestsAction returns info about the tests in an assembly
/// </summary>
public class ExploreTestsAction : FrameworkControllerAction
{
/// <summary>
/// Initializes a new instance of the <see cref="ExploreTestsAction"/> class.
/// </summary>
/// <param name="controller">The controller for which this action is being performed.</param>
/// <param name="filter">Filter used to control which tests are included (NYI)</param>
/// <param name="handler">The callback handler.</param>
public ExploreTestsAction(FrameworkController controller, string filter, object handler)
{
controller.ExploreTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region CountTestsAction
/// <summary>
/// CountTestsAction counts the number of test cases in the loaded TestSuite
/// held by the FrameworkController.
/// </summary>
public class CountTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a CountsTestAction and perform the count of test cases.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public CountTestsAction(FrameworkController controller, string filter, object handler)
{
controller.CountTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunTestsAction
/// <summary>
/// RunTestsAction runs the loaded TestSuite held by the FrameworkController.
/// </summary>
public class RunTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunTestsAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunTestsAction(FrameworkController controller, string filter, object handler)
{
controller.RunTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunAsyncAction
/// <summary>
/// RunAsyncAction initiates an asynchronous test run, returning immediately
/// </summary>
public class RunAsyncAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunAsyncAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunAsyncAction(FrameworkController controller, string filter, object handler)
{
controller.RunAsync((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region StopRunAction
/// <summary>
/// StopRunAction stops an ongoing run.
/// </summary>
public class StopRunAction : FrameworkControllerAction
{
/// <summary>
/// Construct a StopRunAction and stop any ongoing run. If no
/// run is in process, no error is raised.
/// </summary>
/// <param name="controller">The FrameworkController for which a run is to be stopped.</param>
/// <param name="force">True the stop should be forced, false for a cooperative stop.</param>
/// <param name="handler">>A callback handler used to report results</param>
/// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks>
public StopRunAction(FrameworkController controller, bool force, object handler)
{
controller.StopRun((ICallbackEventHandler)handler, force);
}
}
#endregion
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Tracing;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.Azure.Mobile.Server.Config;
using Microsoft.Azure.Mobile.Server.Notifications;
using Microsoft.Azure.NotificationHubs;
using Microsoft.Azure.NotificationHubs.Messaging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ZumoE2EServerApp.Controllers
{
[MobileAppController]
public class PushApiController : ApiController
{
private ITraceWriter traceWriter;
private PushClient pushClient;
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
this.traceWriter = this.Configuration.Services.GetTraceWriter();
this.pushClient = new PushClient(this.Configuration);
}
[Route("api/push")]
public async Task<HttpResponseMessage> Post()
{
var data = await this.Request.Content.ReadAsAsync<JObject>();
var method = (string)data["method"];
if (method == null)
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
if (method == "send")
{
var serialize = new JsonSerializer();
var token = (string)data["token"];
if (data["payload"] == null || token == null)
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
// Payload could be a string or a dictionary
var payloadString = data["payload"].ToString();
var type = (string)data["type"];
var tag = (string)data["tag"];
if (type == "template")
{
TemplatePushMessage message = new TemplatePushMessage();
var payload = JObject.Parse(payloadString);
var keys = payload.Properties();
foreach (JProperty key in keys)
{
this.traceWriter.Info("Key: " + key.Name);
message.Add(key.Name, (string)key.Value);
}
var result = await this.pushClient.SendAsync(message);
}
else if (type == "gcm")
{
GooglePushMessage message = new GooglePushMessage();
message.JsonPayload = payloadString;
var result = await this.pushClient.SendAsync(message);
}
else if (type == "apns")
{
ApplePushMessage message = new ApplePushMessage();
this.traceWriter.Info(payloadString.ToString());
message.JsonPayload = payloadString.ToString();
var result = await this.pushClient.SendAsync(message);
}
else if (type == "wns")
{
var wnsType = (string)data["wnsType"];
WindowsPushMessage message = new WindowsPushMessage();
message.XmlPayload = payloadString;
message.Headers.Add("X-WNS-Type", type + '/' + wnsType);
if (tag != null)
{
await this.pushClient.SendAsync(message, tag);
}
else
{
await this.pushClient.SendAsync(message);
}
}
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
[Route("api/verifyRegisterInstallationResult")]
public async Task<bool> GetVerifyRegisterInstallationResult(string channelUri, string templates = null, string secondaryTiles = null)
{
var nhClient = this.GetNhClient();
HttpResponseMessage msg = new HttpResponseMessage();
msg.StatusCode = HttpStatusCode.InternalServerError;
IEnumerable<string> installationIds;
if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds))
{
return await Retry(async () =>
{
var installationId = installationIds.FirstOrDefault();
Installation nhInstallation = await nhClient.GetInstallationAsync(installationId);
string nhTemplates = null;
string nhSecondaryTiles = null;
if (nhInstallation.Templates != null)
{
nhTemplates = JsonConvert.SerializeObject(nhInstallation.Templates);
nhTemplates = Regex.Replace(nhTemplates, @"\s+", String.Empty);
templates = Regex.Replace(templates, @"\s+", String.Empty);
}
if (nhInstallation.SecondaryTiles != null)
{
nhSecondaryTiles = JsonConvert.SerializeObject(nhInstallation.SecondaryTiles);
nhSecondaryTiles = Regex.Replace(nhSecondaryTiles, @"\s+", String.Empty);
secondaryTiles = Regex.Replace(secondaryTiles, @"\s+", String.Empty);
}
if (nhInstallation.PushChannel.ToLower() != channelUri.ToLower())
{
msg.Content = new StringContent(string.Format("ChannelUri did not match. Expected {0} Found {1}", channelUri, nhInstallation.PushChannel));
throw new HttpResponseException(msg);
}
if (templates != nhTemplates)
{
msg.Content = new StringContent(string.Format("Templates did not match. Expected {0} Found {1}", templates, nhTemplates));
throw new HttpResponseException(msg);
}
if (secondaryTiles != nhSecondaryTiles)
{
msg.Content = new StringContent(string.Format("SecondaryTiles did not match. Expected {0} Found {1}", secondaryTiles, nhSecondaryTiles));
throw new HttpResponseException(msg);
}
bool tagsVerified = await VerifyTags(channelUri, installationId, nhClient);
if (!tagsVerified)
{
msg.Content = new StringContent("Did not find installationId tag");
throw new HttpResponseException(msg);
}
return true;
});
}
msg.Content = new StringContent("Did not find X-ZUMO-INSTALLATION-ID header in the incoming request");
throw new HttpResponseException(msg);
}
[Route("api/verifyUnregisterInstallationResult")]
public async Task<bool> GetVerifyUnregisterInstallationResult()
{
IEnumerable<string> installationIds;
string responseErrorMessage = null;
if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds))
{
return await Retry(async () =>
{
var installationId = installationIds.FirstOrDefault();
try
{
Installation nhInstallation = await this.GetNhClient().GetInstallationAsync(installationId);
}
catch (MessagingEntityNotFoundException)
{
return true;
}
responseErrorMessage = string.Format("Found deleted Installation with id {0}", installationId);
return false;
});
}
HttpResponseMessage msg = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent(responseErrorMessage)
};
throw new HttpResponseException(msg);
}
[Route("api/deleteRegistrationsForChannel")]
public async Task DeleteRegistrationsForChannel(string channelUri)
{
await Retry(async () =>
{
await this.GetNhClient().DeleteRegistrationsByChannelAsync(channelUri);
return true;
});
}
[Route("api/register")]
public void Register(string data)
{
var installation = JsonConvert.DeserializeObject<Installation>(data);
new PushClient(this.Configuration).HubClient.CreateOrUpdateInstallation(installation);
}
private NotificationHubClient GetNhClient()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
return NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
}
private async Task<bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient)
{
IPrincipal user = this.User;
int expectedTagsCount = 1;
if (user.Identity != null && user.Identity.IsAuthenticated)
{
expectedTagsCount = 2;
}
string continuationToken = null;
do
{
CollectionQueryResult<RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100);
continuationToken = regsForChannel.ContinuationToken;
foreach (RegistrationDescription reg in regsForChannel)
{
RegistrationDescription registration = await nhClient.GetRegistrationAsync<RegistrationDescription>(reg.RegistrationId);
if (registration.Tags == null || registration.Tags.Count() != expectedTagsCount)
{
return false;
}
if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}"))
{
return false;
}
ClaimsIdentity identity = user.Identity as ClaimsIdentity;
Claim userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
string userId = (userIdClaim != null) ? userIdClaim.Value : string.Empty;
if (expectedTagsCount > 1 && !registration.Tags.Contains("_UserId:" + userId))
{
return false;
}
}
} while (continuationToken != null);
return true;
}
private async Task<bool> Retry(Func<Task<bool>> target)
{
var sleepTimes = new int[3] { 1000, 3000, 5000 };
for (var i = 0; i < sleepTimes.Length; i++)
{
System.Threading.Thread.Sleep(sleepTimes[i]);
try
{
// if the call succeeds, return the result
return await target();
}
catch (Exception)
{
// if an exception was thrown and we've already retried three times, rethrow
if (i == 2)
throw;
}
}
return false;
}
}
}
| |
//
// The MIT License (MIT)
//
// 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.
namespace Sidekick.SpacedRepetition.Extensions
{
using System;
using System.Threading.Tasks;
using AgnosticDatabase.Interfaces;
using Sidekick.Shared.Extensions;
using Sidekick.SpacedRepetition.Models;
/// <summary>Card review-actions-related extension methods.</summary>
public static class CardActionExtensions
{
#region Methods
/// <summary>Dismisses card and postpone review to next day.</summary>
/// <param name="card">Card instance.</param>
public static CardAction Dismiss(this Card card)
{
card.MiscState = card.MiscState | CardMiscStateFlag.Dismissed;
// TODO: If card is overdue, interval bonus is lost
card.Due = Math.Max(card.Due, DateTimeExtensions.Tomorrow.ToUnixTimestamp());
return CardAction.Dismiss;
}
/// <summary>
/// Answers current card with specified grade and calculate outcomes. No modification
/// saved.
/// </summary>
/// <param name="card">Card instance.</param>
/// <param name="grade">The grade.</param>
public static CardAction Answer(this Card card, Grade grade)
{
CardAction cardAction = CardAction.Invalid;
card.CurrentReviewTime = DateTime.Now.UnixTimestamp();
// New card
if (card.IsNew())
card.UpdateLearningStep(true);
// Handle card learning
if (card.IsLearning())
switch (grade)
{
case Grade.FailSevere:
case Grade.FailMedium:
case Grade.Fail:
// TODO: If relearning, further decrease ease and interval ?
cardAction = card.UpdateLearningStep(true);
break;
case Grade.Hard:
case Grade.Good:
cardAction = card.UpdateLearningStep();
break;
case Grade.Easy:
cardAction = card.Graduate(true);
break;
}
// Handle card review (graduated card)
else
switch (grade)
{
case Grade.FailSevere:
case Grade.FailMedium:
case Grade.Fail:
cardAction = card.Lapse(grade);
break;
case Grade.Hard:
case Grade.Good:
case Grade.Easy:
cardAction = card.Review(grade);
break;
}
// Update card properties
card.MiscState = CardMiscStateFlag.None;
card.Reviews++;
card.LastModified = card.CurrentReviewTime;
if (cardAction == CardAction.Delete)
card.PracticeState = PracticeState.Deleted;
return cardAction;
}
/// <summary>Dismisses the asynchronous.</summary>
/// <param name="card">The card.</param>
/// <param name="db">Database instance.</param>
/// <returns></returns>
public static async Task DismissAsync(this Card card, IDatabaseAsync db)
{
card.Dismiss();
await db.UpdateAsync(card).ConfigureAwait(false);
}
/// <summary>
/// Answers current card with specified grade and calculate outcomes. Modifications are
/// saved to database.
/// </summary>
/// <param name="card">Card instance</param>
/// <param name="grade">The grade.</param>
/// <param name="db">Database instance</param>
public static async Task AnswerAsync(this Card card, Grade grade, IDatabaseAsync db)
{
CardAction cardAction = card.Answer(grade);
if (db != null)
switch (cardAction)
{
case CardAction.Delete:
await db.DeleteAsync<Card>(card.Id).ConfigureAwait(false);
break;
case CardAction.Update:
await db.UpdateAsync(card).ConfigureAwait(false);
break;
default:
throw new InvalidOperationException(
"Card.Answer ended up in an invalid Card Action state.");
}
}
/// <summary>Save card modifications to database according to CardAction.</summary>
/// <param name="card">Card instance</param>
/// <param name="cardAction">The resulting card action.</param>
/// <param name="db">Database instance</param>
public static async Task AnswerAsync(
this Card card, CardAction cardAction, IDatabaseAsync db)
{
if (db != null)
switch (cardAction)
{
case CardAction.Delete:
await db.DeleteAsync<Card>(card.Id).ConfigureAwait(false);
break;
case CardAction.Update:
await db.UpdateAsync(card).ConfigureAwait(false);
break;
default:
throw new InvalidOperationException(
"Card.Answer ended up in an invalid Card Action state.");
}
}
/// <summary>
/// Computes all grading options for given card, according to its State. Card values are
/// unaffected.
/// </summary>
/// <param name="card">Card instance.</param>
/// <returns>Description of all grading options outcomes</returns>
public static ReviewAnswerInfo[] ComputeGrades(this Card card)
{
int currentReviewTime = DateTime.Now.UnixTimestamp();
ReviewAnswerInfo[] reviewAnswerInfos;
// Learning grades
if (card.IsNew() || card.IsLearning())
reviewAnswerInfos = new[] { ReviewAnswerInfo.Fail, ReviewAnswerInfo.Good, ReviewAnswerInfo.Easy };
// Due grades
else
reviewAnswerInfos = new[]
{
ReviewAnswerInfo.Fail, ReviewAnswerInfo.Hard, ReviewAnswerInfo.Good, ReviewAnswerInfo.Easy
};
// Compute outcomes of each grade option
for (int i = 0; i < reviewAnswerInfos.Length; i++)
{
ReviewAnswerInfo reviewAnswerInfo = reviewAnswerInfos[i];
Card cardClone = card.Clone();
cardClone.CurrentReviewTime = currentReviewTime;
cardClone.Answer(reviewAnswerInfo.Grade);
reviewAnswerInfo.NextReview = cardClone.DueDateTime;
//// TODO: Set ReviewAnswerInfo.CardValueAftermath
}
return reviewAnswerInfos;
}
#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.Security;
using Microsoft.Win32;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
namespace System.IO
{
[Serializable]
public abstract partial class FileSystemInfo : MarshalByRefObject, ISerializable
{
protected String FullPath; // fully qualified path of the file or directory
protected String OriginalPath; // path passed in by the user
private String _displayPath = ""; // path that can be displayed to the user
[System.Security.SecurityCritical]
protected FileSystemInfo()
{
}
protected FileSystemInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
FullPath = Path.GetFullPath(info.GetString(nameof(FullPath)));
OriginalPath = info.GetString(nameof(OriginalPath));
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(OriginalPath), OriginalPath, typeof(String));
info.AddValue(nameof(FullPath), FullPath, typeof(String));
}
// Full path of the directory/file
public virtual String FullName
{
[System.Security.SecuritySafeCritical]
get
{
return FullPath;
}
}
public String Extension
{
get
{
// GetFullPathInternal would have already stripped out the terminating "." if present.
int length = FullPath.Length;
for (int i = length; --i >= 0;)
{
char ch = FullPath[i];
if (ch == '.')
return FullPath.Substring(i, length - i);
if (PathInternal.IsDirectorySeparator(ch) || ch == Path.VolumeSeparatorChar)
break;
}
return String.Empty;
}
}
// For files name of the file is returned, for directories the last directory in hierarchy is returned if possible,
// otherwise the fully qualified name s returned
public abstract String Name
{
get;
}
// Whether a file/directory exists
public abstract bool Exists
{
get;
}
// Delete a file/directory
public abstract void Delete();
public DateTime CreationTime
{
get
{
// depends on the security check in get_CreationTimeUtc
return CreationTimeUtc.ToLocalTime();
}
set
{
CreationTimeUtc = value.ToUniversalTime();
}
}
public DateTime CreationTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.CreationTime.UtcDateTime;
}
set
{
FileSystemObject.CreationTime = File.GetUtcDateTimeOffset(value);
}
}
public DateTime LastAccessTime
{
get
{
// depends on the security check in get_LastAccessTimeUtc
return LastAccessTimeUtc.ToLocalTime();
}
set
{
LastAccessTimeUtc = value.ToUniversalTime();
}
}
public DateTime LastAccessTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.LastAccessTime.UtcDateTime;
}
set
{
FileSystemObject.LastAccessTime = File.GetUtcDateTimeOffset(value);
}
}
public DateTime LastWriteTime
{
get
{
// depends on the security check in get_LastWriteTimeUtc
return LastWriteTimeUtc.ToLocalTime();
}
set
{
LastWriteTimeUtc = value.ToUniversalTime();
}
}
public DateTime LastWriteTimeUtc
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.LastWriteTime.UtcDateTime;
}
set
{
FileSystemObject.LastWriteTime = File.GetUtcDateTimeOffset(value);
}
}
public void Refresh()
{
FileSystemObject.Refresh();
}
public FileAttributes Attributes
{
[System.Security.SecuritySafeCritical]
get
{
return FileSystemObject.Attributes;
}
[System.Security.SecurityCritical] // auto-generated
set
{
FileSystemObject.Attributes = value;
}
}
internal String DisplayPath
{
get
{
return _displayPath;
}
set
{
_displayPath = value;
}
}
}
}
| |
/*****************************************************************************
The MIT License (MIT)
Copyright (c) 2016 APIMATIC Limited ( https://apimatic.io )
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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace APIMATIC.SDK.Common
{
public static class APIHelper
{
//DateTime format to use for parsing and converting dates
public static string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
/// <summary>
/// JSON Serialization of a given object.
/// </summary>
/// <param name="obj">The object to serialize into JSON</param>
/// <param name="converter">The converter to use for date time conversion</param>
/// <returns>The serialized Json string representation of the given object</returns>
public static string JsonSerialize(object obj, JsonConverter converter = null)
{
if (null == obj)
return null;
var settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
};
if (converter == null)
settings.Converters.Add(new IsoDateTimeConverter());
else
settings.Converters.Add(converter);
return JsonConvert.SerializeObject(obj, Formatting.None, settings);
}
/// <summary>
/// JSON Deserialization of the given json string.
/// </summary>
/// <param name="json">The json string to deserialize</param>
/// <param name="converter">The converter to use for date time conversion</param>
/// <typeparam name="T">The type of the object to desialize into</typeparam>
/// <returns>The deserialized object</returns>
public static T JsonDeserialize<T>(string json, JsonConverter converter = null)
{
if (string.IsNullOrWhiteSpace(json))
return default(T);
if (converter == null)
return JsonConvert.DeserializeObject<T>(json, new IsoDateTimeConverter());
else
return JsonConvert.DeserializeObject<T>(json, converter);
}
/// <summary>
/// Replaces template parameters in the given url
/// </summary>
/// <param name="queryUrl">The query url string to replace the template parameters</param>
/// <param name="parameters">The parameters to replace in the url</param>
public static void AppendUrlWithTemplateParameters
(StringBuilder queryBuilder, IEnumerable<KeyValuePair<string, object>> parameters)
{
//perform parameter validation
if (null == queryBuilder)
throw new ArgumentNullException("queryBuilder");
if (null == parameters)
return;
//iterate and replace parameters
foreach (KeyValuePair<string, object> pair in parameters)
{
string replaceValue = string.Empty;
//load element value as string
if (null == pair.Value)
replaceValue = "";
else if (pair.Value is ICollection)
replaceValue = flattenCollection(pair.Value as ICollection, ArrayDeserialization.None, '/', false);
else if (pair.Value is DateTime)
replaceValue = ((DateTime)pair.Value).ToString(DateTimeFormat);
else
replaceValue = pair.Value.ToString();
replaceValue = Uri.EscapeUriString(replaceValue);
//find the template parameter and replace it with its value
queryBuilder.Replace($"{{{pair.Key}}}", replaceValue);
}
}
/// <summary>
/// Appends the given set of parameters to the given query string
/// </summary>
/// <param name="queryUrl">The query url string to append the parameters</param>
/// <param name="parameters">The parameters to append</param>
public static void AppendUrlWithQueryParameters
(StringBuilder queryBuilder, IEnumerable<KeyValuePair<string, object>> parameters)
{
AppendUrlWithQueryParameters(queryBuilder,parameters,ArrayDeserialization.UnIndexed);
}
/// <summary>
/// Appends the given set of parameters to the given query string
/// </summary>
/// <param name="queryUrl">The query url string to append the parameters</param>
/// <param name="parameters">The parameters to append</param>
public static void AppendUrlWithQueryParameters
(StringBuilder queryBuilder, IEnumerable<KeyValuePair<string, object>> parameters, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed, char separator = '&')
{
//perform parameter validation
if (null == queryBuilder)
throw new ArgumentNullException("queryBuilder");
if (null == parameters)
return;
//does the query string already has parameters
bool hasParams = (indexOf(queryBuilder, "?") > 0);
//iterate and append parameters
foreach (KeyValuePair<string, object> pair in parameters)
{
//ignore null values
if (pair.Value == null)
continue;
//if already has parameters, use the & to append new parameters
queryBuilder.Append((hasParams) ? '&' : '?');
//indicate that now the query has some params
hasParams = true;
string paramKeyValPair;
//load element value as string
if (pair.Value is ICollection)
paramKeyValPair = flattenCollection(pair.Value as ICollection, arrayDeserializationFormat, separator,
true, pair.Key);
else if (pair.Value is DateTime)
paramKeyValPair =
$"{Uri.EscapeDataString(pair.Key)}={((DateTime) pair.Value).ToString(DateTimeFormat)}";
else if (pair.Value is Boolean)
paramKeyValPair = $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value.ToString().ToLowerInvariant())}";
else
paramKeyValPair = $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value.ToString())}";
//append keyval pair for current parameter
queryBuilder.Append(paramKeyValPair);
}
}
/// <summary>
/// StringBuilder extension method to implement IndexOf functionality.
/// This does a StringComparison.Ordinal kind of comparison.
/// </summary>
/// <param name="stringBuilder">The string builder to find the index in</param>
/// <param name="strCheck">The string to locate in the string builder</param>
/// <returns>The index of string inside the string builder</returns>
private static int indexOf(StringBuilder stringBuilder, string strCheck)
{
if (stringBuilder == null)
throw new ArgumentNullException("stringBuilder");
if (strCheck == null)
return 0;
//iterate over the input
for (int inputCounter = 0; inputCounter < stringBuilder.Length; inputCounter++)
{
int matchCounter;
//attempt to locate a potential match
for (matchCounter = 0;
(matchCounter < strCheck.Length)
&& (inputCounter + matchCounter < stringBuilder.Length)
&& (stringBuilder[inputCounter + matchCounter] == strCheck[matchCounter]);
matchCounter++) ;
//verify the match
if (matchCounter == strCheck.Length)
return inputCounter;
}
return -1;
}
/// <summary>
/// Validates and processes the given query Url to clean empty slashes
/// </summary>
/// <param name="queryBuilder">The given query Url to process</param>
/// <returns>Clean Url as string</returns>
public static string CleanUrl(StringBuilder queryBuilder)
{
//convert to immutable string
string url = queryBuilder.ToString();
//ensure that the urls are absolute
Match match = Regex.Match(url, "^https?://[^/]+");
if (!match.Success)
throw new ArgumentException("Invalid Url format.");
//remove redundant forward slashes
int index = url.IndexOf('?');
string protocol = match.Value;
string query = url.Substring(protocol.Length, (index == -1 ? url.Length : index) - protocol.Length);
query = Regex.Replace(query, "//+", "/");
string parameters = index == -1 ? "" : url.Substring(index);
//return process url
return string.Concat(protocol, query, parameters); ;
}
/// <summary>
/// Used for flattening a collection of objects into a string
/// </summary>
/// <param name="array">Array of elements to flatten</param>
/// <param name="fmt">Format string to use for array flattening</param>
/// <param name="separator">Separator to use for string concat</param>
/// <returns>Representative string made up of array elements</returns>
private static string flattenCollection(ICollection array, ArrayDeserialization fmt, char separator,
bool urlEncode, string key = "")
{
StringBuilder builder = new StringBuilder();
string format = string.Empty;
if (fmt == ArrayDeserialization.UnIndexed)
format = String.Format("{0}[]={{0}}{{1}}", key);
else if (fmt == ArrayDeserialization.Indexed)
format = String.Format("{0}[{{2}}]={{0}}{{1}}", key);
else if (fmt == ArrayDeserialization.Plain)
format = String.Format("{0}={{0}}{{1}}", key);
else if (fmt == ArrayDeserialization.Csv || fmt == ArrayDeserialization.Psv ||
fmt == ArrayDeserialization.Tsv)
{
builder.Append(String.Format("{0}=", key));
format = "{0}{1}";
}
else
format = "{0}{1}";
//append all elements in the array into a string
int index = 0;
foreach (object element in array)
builder.AppendFormat(format, getElementValue(element, urlEncode), separator, index++);
//remove the last separator, if appended
if ((builder.Length > 1) && (builder[builder.Length - 1] == separator))
builder.Length -= 1;
return builder.ToString();
}
private static string getElementValue(object element, bool urlEncode)
{
string elemValue = null;
//replace null values with empty string to maintain index order
if (null == element)
elemValue = string.Empty;
else if (element is DateTime)
elemValue = ((DateTime)element).ToString(DateTimeFormat);
else if (element is DateTimeOffset)
elemValue = ((DateTimeOffset)element).ToString(DateTimeFormat);
else
elemValue = element.ToString();
if (urlEncode)
elemValue = Uri.EscapeDataString(elemValue);
return elemValue;
}
/// <summary>
/// Prepares the object as form fields using the provided name.
/// </summary>
/// <param name="name">root name for the variable</param>
/// <param name="value">form field value</param>
/// <param name="keys">Contains a flattend and form friendly values</param>
/// <param name="arrayDeserializationFormat">Format for deserializing array</param>
/// <returns>Contains a flattend and form friendly values</returns>
public static List<KeyValuePair<string, object>> PrepareFormFieldsFromObject(
string name, object value, List<KeyValuePair<string, object>> keys = null, PropertyInfo propInfo = null, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed)
{
keys = keys ?? new List<KeyValuePair<string, object>>();
if (value == null)
{
return keys;
}
else if (value is Stream)
{
keys.Add(new KeyValuePair<string, object>(name, value));
return keys;
}
else if (value is JObject)
{
var valueAccept = (value as JObject);
foreach (var property in valueAccept.Properties())
{
string pKey = property.Name;
object pValue = property.Value;
var fullSubName = name + '[' + pKey + ']';
PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo, arrayDeserializationFormat);
}
}
else if (value is IList)
{
var enumerator = ((IEnumerable)value).GetEnumerator();
var hasNested = false;
while (enumerator.MoveNext())
{
var subValue = enumerator.Current;
if (subValue != null && (subValue is JObject || subValue is IList || subValue is IDictionary || !(subValue.GetType().Namespace.StartsWith("System"))))
{
hasNested = true;
break;
}
}
int i = 0;
enumerator.Reset();
while (enumerator.MoveNext())
{
var fullSubName = name + '[' + i + ']';
if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.UnIndexed)
fullSubName = name + "[]";
else if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.Plain)
fullSubName = name;
var subValue = enumerator.Current;
if (subValue == null) continue;
PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat);
i++;
}
}
else if (value is JToken)
{
keys.Add(new KeyValuePair<string, object>(name, value.ToString()));
}
else if (value is Enum)
{
#if WINDOWS_UWP || DNXCORE50 || NETSTANDARD1_3
Assembly thisAssembly = value.GetType().GetTypeInfo().Assembly;
#else
Assembly thisAssembly = value.GetType().Assembly;
#endif
string enumTypeName = value.GetType().FullName;
Type enumHelperType = thisAssembly.GetType($"{enumTypeName}Helper");
object enumValue = (int)value;
if (enumHelperType != null)
{
#if NETSTANDARD1_3
//this enum has an associated helper, use that to load the value
MethodInfo enumHelperMethod = enumHelperType.GetRuntimeMethod("ToValue", new[] { value.GetType() });
#else
MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() });
#endif
if (enumHelperMethod != null)
enumValue = enumHelperMethod.Invoke(null, new object[] { value });
}
keys.Add(new KeyValuePair<string, object>(name, enumValue));
}
else if (value is IDictionary)
{
var obj = (IDictionary)value;
foreach (var sName in obj.Keys)
{
var subName = sName.ToString();
var subValue = obj[subName];
string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat);
}
}
else if (!(value.GetType().Namespace.StartsWith("System")))
{
//Custom object Iterate through its properties
#if NETSTANDARD1_3
var enumerator = value.GetType().GetRuntimeProperties().GetEnumerator();
#else
var enumerator = value.GetType().GetProperties().GetEnumerator();;
#endif
PropertyInfo pInfo = null;
var t = new JsonPropertyAttribute().GetType();
while (enumerator.MoveNext())
{
pInfo = enumerator.Current as PropertyInfo;
var jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault();
var subName = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name;
string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
var subValue = pInfo.GetValue(value, null);
PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo, arrayDeserializationFormat);
}
}
else if (value is DateTime)
{
string convertedValue = null;
var pInfo = propInfo?.GetCustomAttributes(true);
if (pInfo != null)
{
foreach (object attr in pInfo)
{
JsonConverterAttribute converterAttr = attr as JsonConverterAttribute;
if (converterAttr != null)
convertedValue = JsonSerialize(value, (JsonConverter)Activator.CreateInstance(converterAttr.ConverterType, converterAttr.ConverterParameters)).Replace("\"", "");
}
}
keys.Add(new KeyValuePair<string, object>(name, (convertedValue) ?? ((DateTime)value).ToString(DateTimeFormat)));
}
else
{
keys.Add(new KeyValuePair<string, object>(name, value));
}
return keys;
}
/// <summary>
/// Add/update entries with the new dictionary.
/// </summary>
/// <param name="dictionary"></param>
/// <param name="dictionary2"></param>
public static void Add(this Dictionary<string, object> dictionary, Dictionary<string, object> dictionary2)
{
foreach (var kvp in dictionary2)
{
dictionary[kvp.Key] = kvp.Value;
}
}
/// <summary>
/// Runs asynchronous tasks synchronously and throws the first caught exception
/// </summary>
/// <param name="t">The task to be run synchronously</param>
public static void RunTaskSynchronously(Task t)
{
try
{
Task.WaitAll(t);
}
catch (AggregateException e)
{
if (e.InnerExceptions.Count > 0)
throw e.InnerExceptions[0];
throw;
}
}
}
}
| |
// 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 MultiplySubtractScalarDouble()
{
var test = new SimpleTernaryOpTest__MultiplySubtractScalarDouble();
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();
if (Sse2.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 (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 class works
test.RunClassLclFldScenario();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 SimpleTernaryOpTest__MultiplySubtractScalarDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = 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.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.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<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractScalarDouble testClass)
{
var result = Fma.MultiplySubtractScalar(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__MultiplySubtractScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtractScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtractScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtractScalar(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2)),
Sse2.LoadVector128((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtractScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractScalarDouble();
var result = Fma.MultiplySubtractScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtractScalar(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2)),
Sse2.LoadVector128((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _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<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractScalar)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class ValueSimpleTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//ValueSimple Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\ValueSimple
//01,02,03,04,05,06,07,09,11,12,13,14,15
//12 Failed
//Test Case Calls
[TestMethod]
public MFTestResults ValueSimple01_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" byte is an alias for System.Byte");
if (ValueSimpleTestClass01.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple02_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" char is an alias for System.Char");
if (ValueSimpleTestClass02.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple03_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" short is an alias for System.Int16");
if (ValueSimpleTestClass03.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple04_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" int is an alias for System.Int32");
if (ValueSimpleTestClass04.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple05_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" long is an alias for System.Int64");
if (ValueSimpleTestClass05.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple06_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" float is an alias for System.Single");
if (ValueSimpleTestClass06.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple07_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" double is an alias for System.Double");
if (ValueSimpleTestClass07.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple09_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" bool is an alias for System.Boolean");
if (ValueSimpleTestClass09.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple11_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" A simple type and the structure type it aliases are completely indistinguishable.");
Log.Comment(" In other words, writing the reserved work byte is exactly the same as writing ");
Log.Comment(" System.Byte, and writing System.Int32 is exactly the same as writing the reserved");
Log.Comment(" word int.");
if (ValueSimpleTestClass11.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple12_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" Because a simple type aliases a struct type, every simple type has members.");
if (ValueSimpleTestClass12.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple13_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" sbyte is an alias for System.SByte");
if (ValueSimpleTestClass13.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple14_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" ushort is an alias for System.UInt16");
if (ValueSimpleTestClass14.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueSimple15_Test()
{
Log.Comment(" Section 4.1");
Log.Comment(" uint is an alias for System.UInt32");
if (ValueSimpleTestClass15.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
//Compiled Test Cases
public class ValueSimpleTestClass01
{
public static bool testMethod()
{
byte b = 0;
if (b.GetType() == Type.GetType("System.Byte"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass02
{
public static bool testMethod()
{
char c = 'a';
if (c.GetType() == Type.GetType("System.Char"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass03
{
public static bool testMethod()
{
short s = 0;
if (s.GetType() == Type.GetType("System.Int16"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass04
{
public static bool testMethod()
{
int i = 0;
if (i.GetType() == Type.GetType("System.Int32"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass05
{
public static bool testMethod()
{
long l = 0L;
if (l.GetType() == Type.GetType("System.Int64"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass06
{
public static bool testMethod()
{
float f = 0.0f;
if (f.GetType() == Type.GetType("System.Single"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass07
{
public static bool testMethod()
{
double d = 0.0d;
if (d.GetType() == Type.GetType("System.Double"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass09
{
public static bool testMethod()
{
bool b = true;
if (b.GetType() == Type.GetType("System.Boolean"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass11
{
public static bool testMethod()
{
System.Byte b = 2;
System.Int32 i = 2;
if ((b == 2) && (i == 2))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass12
{
public static bool testMethod()
{
bool RetVal = true;
int i = int.MaxValue;
if (i != Int32.MaxValue)
{
RetVal = false;
}
string s = i.ToString();
if (!s.Equals(Int32.MaxValue.ToString()))
{
RetVal = false;
}
i = 123;
string t = 123.ToString();
if (!t.Equals(i.ToString()))
{
RetVal = false;
}
return RetVal;
}
}
public class ValueSimpleTestClass13
{
public static bool testMethod()
{
sbyte b = 0;
if (b.GetType() == Type.GetType("System.SByte"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass14
{
public static bool testMethod()
{
ushort s = 0;
if (s.GetType() == Type.GetType("System.UInt16"))
{
return true;
}
else
{
return false;
}
}
}
public class ValueSimpleTestClass15
{
public static bool testMethod()
{
uint i = 0;
if (i.GetType() == Type.GetType("System.UInt32"))
{
return true;
}
else
{
return false;
}
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/1/2008 11:23:05 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.IO;
namespace DotSpatial.Data
{
public class RasterBounds : IRasterBounds
{
#region Private Variables
private double[] _affine;
private readonly int _numColumns;
private readonly int _numRows;
private string _worldFile;
#endregion
#region Constructors
/// <summary>
/// Creates a new RasterBounds
/// </summary>
public RasterBounds()
{
_affine = new double[6];
}
/// <summary>
/// Attempts to read the very simple 6 number world file associated with an image
/// </summary>
/// <param name="numRows">The number of rows in this raster</param>
/// <param name="numColumns">The number of columns in this raster</param>
/// <param name="worldFileName">A world file to attempt to read</param>
public RasterBounds(int numRows, int numColumns, string worldFileName)
{
_numRows = numRows;
_numColumns = numColumns;
_affine = new double[6];
this.OpenWorldFile(worldFileName);
}
/// <summary>
/// Creates a new instance of the RasterBounds class
/// </summary>
/// <param name="numRows">The number of rows for this raster</param>
/// <param name="numColumns">The number of columns for this raster</param>
/// <param name="affineCoefficients">The affine coefficients describing the location of this raster.</param>
public RasterBounds(int numRows, int numColumns, double[] affineCoefficients)
{
_affine = affineCoefficients;
_numRows = numRows;
_numColumns = numColumns;
}
/// <summary>
/// Creates a new raster bounds that is georeferenced to the specified envelope.
/// </summary>
/// <param name="numRows">The number of rows</param>
/// <param name="numColumns">The number of columns</param>
/// <param name="bounds">The bounding envelope</param>
public RasterBounds(int numRows, int numColumns, Extent bounds)
{
_affine = new double[6];
_numRows = numRows;
_numColumns = numColumns;
Extent = bounds;
}
#endregion
#region Methods
IRasterBounds IRasterBounds.Copy()
{
return Copy();
}
/// <summary>
/// Attempts to load the data from the file listed in WorldFile
/// </summary>
public virtual void Open(string fileName)
{
this.OpenWorldFile(fileName);
}
/// <summary>
/// Attempts to save the data to the file listed in WorldFile
/// </summary>
public virtual void Save()
{
this.SaveWorldFile();
}
/// <summary>
/// Returns a duplicate of this object as an object.
/// </summary>
/// <returns>A duplicate of this object as an object.</returns>
public object Clone()
{
return MemberwiseClone();
}
/// <summary>
/// Creates a duplicate of this RasterBounds class.
/// </summary>
/// <returns>A RasterBounds that has the same properties but does not point to the same internal array.</returns>
public RasterBounds Copy()
{
var result = (RasterBounds)MemberwiseClone();
result.AffineCoefficients = new double[6];
for (int i = 0; i < 6; i++)
{
result.AffineCoefficients[i] = _affine[i];
}
return result;
}
#endregion
#region IRasterBounds Members
/// <summary>
/// Gets or sets the double affine coefficients that control the world-file
/// positioning of this image. X' and Y' are real world coords.
/// X' = [0] + [1] * Column + [2] * Row
/// Y' = [3] + [4] * Column + [5] * Row
/// </summary>
[Category("GeoReference"), Description("X' = [0] + [1] * Column + [2] * Row, Y' = [3] + [4] * Column + [5] * Row")]
public virtual double[] AffineCoefficients
{
get { return _affine; }
set
{
_affine = value;
}
}
/// <summary>
/// Gets or sets the desired width per cell. This will keep the skew the same, but
/// will adjust both the column based and row based width coefficients in order
/// to match the specified cell width. This can be thought of as the width
/// of a bounding box that contains an entire grid cell, no matter if it is skewed.
/// </summary>
public double CellWidth
{
get
{
double[] affine = AffineCoefficients;
// whatever sign the coefficients are, they only increase the cell width
return Math.Abs(affine[1]) + Math.Abs(affine[2]);
}
set
{
double[] affine = AffineCoefficients;
double columnFactor = affine[1] / CellWidth;
double rowFactor = affine[2] / CellWidth;
affine[1] = Math.Sign(affine[1]) * value * columnFactor;
affine[2] = Math.Sign(affine[2]) * value * rowFactor;
AffineCoefficients = affine; // use the setter for overriding classes
}
}
/// <summary>
/// Gets or sets the desired height per cell. This will keep the skew the same, but
/// will adjust both the column based and row based height coefficients in order
/// to match the specified cell height. This can be thought of as the height
/// of a bounding box that contains an entire grid cell, no matter if it is skewed.
/// </summary>
public double CellHeight
{
get
{
double[] affine = AffineCoefficients;
// whatever sign the coefficients are, they only increase the cell hight
return Math.Abs(affine[4]) + Math.Abs(affine[5]);
}
set
{
double[] affine = AffineCoefficients;
double columnFactor = affine[4] / CellWidth;
double rowFactor = affine[5] / CellWidth;
affine[4] = Math.Sign(affine[4]) * value * columnFactor;
affine[5] = Math.Sign(affine[5]) * value * rowFactor;
AffineCoefficients = affine; // use the setter for overriding classes
}
}
/// <summary>
/// Gets or sets the rectangular bounding box for this raster.
/// </summary>
public Extent Extent
{
get
{
double[] affine = AffineCoefficients;
if (affine[1] == 0 || affine[5] == 0) return null;
return new Extent(this.Left(), this.Bottom(), this.Right(), this.Top());
}
set
{
// Preserve the skew, but translate and scale to fit the envelope.
if (value != null)
{
X = value.X;
Y = value.Y;
Width = value.Width;
Height = value.Height;
}
}
}
/// <summary>
/// Gets or sets the height of the entire bounds. This is derived by considering both the
/// column and row based contributions to the overall height. Changing this will keep
/// the skew ratio the same, but adjust both portions so that the overall height
/// will match the specified height.
/// </summary>
public double Height
{
get { return Math.Abs(_affine[4]) * NumColumns + Math.Abs(_affine[5]) * NumRows; }
set
{
if (Height == 0 && _numRows > 0)
{
_affine[5] = -(value / _numRows);
_affine[4] = 0;
return;
}
double columnFactor = NumColumns * Math.Abs(_affine[4]) / Height;
double rowFactor = NumRows * Math.Abs(_affine[5]) / Height;
double newColumnHeight = value * columnFactor;
double newRowHeight = value * rowFactor;
_affine[4] = Math.Sign(_affine[4]) * newColumnHeight / NumColumns;
_affine[5] = Math.Sign(_affine[5]) * newRowHeight / NumRows;
}
}
/// <summary>
/// Gets the number of rows in the raster.
/// </summary>
[Category("General"), Description("Gets the number of rows in the underlying raster.")]
public virtual int NumRows
{
get { return _numRows; }
}
/// <summary>
/// Gets the number of columns in the raster.
/// </summary>
[Category("General"), Description("Gets the number of columns in the raster.")]
public virtual int NumColumns
{
get { return _numColumns; }
}
/// <summary>
/// Gets or sets the geographic width of this raster. This will include the skew term
/// in the width estimate, so it will adjust both the width and the skew coefficient,
/// but preserve the ratio of skew to cell width.
/// </summary>
public double Width
{
get
{
return NumColumns * Math.Abs(_affine[1]) + NumRows * Math.Abs(_affine[2]);
}
set
{
if (Width == 0 && _numColumns > 0)
{
_affine[1] = value / _numColumns;
_affine[2] = 0;
return;
}
double columnFactor = NumColumns * Math.Abs(_affine[1]) / Width;
double rowFactor = NumRows * Math.Abs(_affine[2]) / Width;
double newColumnWidth = value * columnFactor;
double newRowWidth = value * rowFactor;
_affine[1] = Math.Sign(_affine[1]) * newColumnWidth / NumColumns;
_affine[2] = Math.Sign(_affine[2]) * newRowWidth / NumRows;
}
}
/// <summary>
/// Gets or sets the fileName of the wordfile that describes the geographic coordinates of this raster. If a relative path gets assigned it is changed to the absolute path including the file extension.
/// </summary>
[Category("GeoReference"), Description("Returns the Geographic width of the envelope that completely contains this raster.")]
public string WorldFile
{
get { return _worldFile; }
set { _worldFile = Path.GetFullPath(value); }
}
/// <summary>
/// Gets or sets the horizontal placement of the upper left corner of this bounds. Because
/// of the skew, this upper left position may not actually be the same as the upper left
/// corner of the image itself (_affine[0]). Instead, this is the top left corner of
/// the rectangular extent for this raster.
/// </summary>
public double X
{
get
{
double xMin = double.MaxValue;
double[] affine = AffineCoefficients; // in case this is an overridden property
double nr = NumRows;
double nc = NumColumns;
// Because these coefficients can be negative, we can't make assumptions about what corner is furthest left.
if (affine[0] < xMin) xMin = affine[0]; // TopLeft;
if (affine[0] + nc * affine[1] < xMin) xMin = affine[0] + nc * affine[1]; // TopRight;
if (affine[0] + nr * affine[2] < xMin) xMin = affine[0] + nr * affine[2]; // BottomLeft;
if (affine[0] + nc * affine[1] + nr * affine[2] < xMin) xMin = affine[0] + nc * affine[1] + nr * affine[2]; // BottomRight
// the coordinate thus far is the center of the cell. The actual left is half a cell further left.
return xMin - Math.Abs(affine[1]) / 2 - Math.Abs(affine[2]) / 2;
}
set
{
double dx = value - X;
_affine[0] = _affine[0] + dx; // resetting affine[0] will shift everything else
}
}
/// <summary>
/// Gets or sets the vertical placement of the upper left corner of this bounds, which is the
/// same as the top. The top left corner of the actual image may not be in this position
/// because of skew, but this represents the maximum Y value of the rectangular extents
/// that contains the image.
/// </summary>
public double Y
{
get
{
double yMax = double.MinValue;
double[] affine = AffineCoefficients; // in case this is an overridden property
double nr = NumRows;
double nc = NumColumns;
// Because these coefficients can be negative, we can't make assumptions about what corner is furthest left.
if (affine[3] > yMax) yMax = affine[3]; // TopLeft;
if (affine[3] + nc * affine[4] > yMax) yMax = affine[3] + nc * affine[4]; // TopRight;
if (affine[3] + nr * affine[5] > yMax) yMax = affine[3] + nr * affine[5]; // BottomLeft;
if (affine[3] + nc * affine[4] + nr * affine[5] > yMax) yMax = affine[3] + nc * affine[4] + nr * affine[5]; // BottomRight
// the value thus far is at the center of the cell. Return a value half a cell further
return yMax + Math.Abs(affine[4]) / 2 + Math.Abs(affine[5]) / 2;
}
set
{
double dy = value - Y;
_affine[3] += dy; // resets the dY
}
}
#endregion
}
}
| |
/*
* 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 System;
using System.IO;
using System.Collections;
using Apache.NMS;
using Apache.NMS.Util;
namespace Apache.NMS.Commands
{
public class StreamMessage : Message, IStreamMessage
{
private EndianBinaryReader dataIn = null;
private EndianBinaryWriter dataOut = null;
private MemoryStream byteBuffer = null;
private int bytesRemaining = -1;
public bool ReadBoolean()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.BOOLEAN_TYPE)
{
return this.dataIn.ReadBoolean();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Boolean.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a bool");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Boolean type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public byte ReadByte()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Byte.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a byte");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Byte type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public char ReadChar()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.CHAR_TYPE)
{
return this.dataIn.ReadChar();
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a char");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Char type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public short ReadInt16()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.SHORT_TYPE)
{
return this.dataIn.ReadInt16();
}
else if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Int16.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a short");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Int16 type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public int ReadInt32()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.INTEGER_TYPE)
{
return this.dataIn.ReadInt32();
}
else if(type == PrimitiveMap.SHORT_TYPE)
{
return this.dataIn.ReadInt16();
}
else if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Int32.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a int");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Int32 type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public long ReadInt64()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.LONG_TYPE)
{
return this.dataIn.ReadInt64();
}
else if(type == PrimitiveMap.INTEGER_TYPE)
{
return this.dataIn.ReadInt32();
}
else if(type == PrimitiveMap.SHORT_TYPE)
{
return this.dataIn.ReadInt16();
}
else if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Int64.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a long");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Int64 type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public float ReadSingle()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.FLOAT_TYPE)
{
return this.dataIn.ReadSingle();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Single.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a float");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Single type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public double ReadDouble()
{
InitializeReading();
try
{
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.DOUBLE_TYPE)
{
return this.dataIn.ReadDouble();
}
else if(type == PrimitiveMap.FLOAT_TYPE)
{
return this.dataIn.ReadSingle();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return Single.Parse(this.dataIn.ReadString16());
}
else if(type == PrimitiveMap.NULL)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new NMSException("Cannot convert Null type to a double");
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a Double type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public string ReadString()
{
InitializeReading();
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.BIG_STRING_TYPE)
{
return this.dataIn.ReadString32();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return this.dataIn.ReadString16();
}
else if(type == PrimitiveMap.LONG_TYPE)
{
return this.dataIn.ReadInt64().ToString();
}
else if(type == PrimitiveMap.INTEGER_TYPE)
{
return this.dataIn.ReadInt32().ToString();
}
else if(type == PrimitiveMap.SHORT_TYPE)
{
return this.dataIn.ReadInt16().ToString();
}
else if(type == PrimitiveMap.FLOAT_TYPE)
{
return this.dataIn.ReadSingle().ToString();
}
else if(type == PrimitiveMap.DOUBLE_TYPE)
{
return this.dataIn.ReadDouble().ToString();
}
else if(type == PrimitiveMap.CHAR_TYPE)
{
return this.dataIn.ReadChar().ToString();
}
else if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte().ToString();
}
else if(type == PrimitiveMap.BOOLEAN_TYPE)
{
return this.dataIn.ReadBoolean().ToString();
}
else if(type == PrimitiveMap.NULL)
{
return null;
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a known type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public int ReadBytes(byte[] value)
{
InitializeReading();
if(value == null)
{
throw new NullReferenceException("Passed Byte Array is null");
}
try
{
if(this.bytesRemaining == -1)
{
long startingPos = this.byteBuffer.Position;
byte type = this.dataIn.ReadByte();
if(type != PrimitiveMap.BYTE_ARRAY_TYPE)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Not a byte array");
}
this.bytesRemaining = this.dataIn.ReadInt32();
}
else if(this.bytesRemaining == 0)
{
this.bytesRemaining = -1;
return -1;
}
if(value.Length <= this.bytesRemaining)
{
// small buffer
this.bytesRemaining -= value.Length;
this.dataIn.Read(value, 0, value.Length);
return value.Length;
}
else
{
// big buffer
int rc = this.dataIn.Read(value, 0, this.bytesRemaining);
this.bytesRemaining = 0;
return rc;
}
}
catch(EndOfStreamException ex)
{
throw NMSExceptionSupport.CreateMessageEOFException(ex);
}
catch(IOException ex)
{
throw NMSExceptionSupport.CreateMessageFormatException(ex);
}
}
public Object ReadObject()
{
InitializeReading();
long startingPos = this.byteBuffer.Position;
try
{
int type = this.dataIn.ReadByte();
if(type == PrimitiveMap.BIG_STRING_TYPE)
{
return this.dataIn.ReadString32();
}
else if(type == PrimitiveMap.STRING_TYPE)
{
return this.dataIn.ReadString16();
}
else if(type == PrimitiveMap.LONG_TYPE)
{
return this.dataIn.ReadInt64();
}
else if(type == PrimitiveMap.INTEGER_TYPE)
{
return this.dataIn.ReadInt32();
}
else if(type == PrimitiveMap.SHORT_TYPE)
{
return this.dataIn.ReadInt16();
}
else if(type == PrimitiveMap.FLOAT_TYPE)
{
return this.dataIn.ReadSingle();
}
else if(type == PrimitiveMap.DOUBLE_TYPE)
{
return this.dataIn.ReadDouble();
}
else if(type == PrimitiveMap.CHAR_TYPE)
{
return this.dataIn.ReadChar();
}
else if(type == PrimitiveMap.BYTE_TYPE)
{
return this.dataIn.ReadByte();
}
else if(type == PrimitiveMap.BOOLEAN_TYPE)
{
return this.dataIn.ReadBoolean();
}
else if(type == PrimitiveMap.BYTE_ARRAY_TYPE)
{
int length = this.dataIn.ReadInt32();
byte[] data = new byte[length];
this.dataIn.Read(data, 0, length);
return data;
}
else if(type == PrimitiveMap.NULL)
{
return null;
}
else
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw new MessageFormatException("Value is not a known type.");
}
}
catch(FormatException e)
{
this.byteBuffer.Seek(startingPos, SeekOrigin.Begin);
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteBoolean(bool value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.BOOLEAN_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteByte(byte value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.BYTE_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteBytes(byte[] value)
{
InitializeWriting();
this.WriteBytes(value, 0, value.Length);
}
public void WriteBytes(byte[] value, int offset, int length)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.BYTE_ARRAY_TYPE);
this.dataOut.Write((int) length);
this.dataOut.Write(value, offset, length);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteChar(char value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.CHAR_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteInt16(short value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.SHORT_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteInt32(int value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.INTEGER_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteInt64(long value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.LONG_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteSingle(float value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.FLOAT_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteDouble(double value)
{
InitializeWriting();
try
{
this.dataOut.Write(PrimitiveMap.DOUBLE_TYPE);
this.dataOut.Write(value);
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteString(string value)
{
InitializeWriting();
try
{
if( value.Length > 8192 )
{
this.dataOut.Write(PrimitiveMap.BIG_STRING_TYPE);
this.dataOut.WriteString32(value);
}
else
{
this.dataOut.Write(PrimitiveMap.STRING_TYPE);
this.dataOut.WriteString16(value);
}
}
catch(IOException e)
{
NMSExceptionSupport.Create(e);
}
}
public void WriteObject(Object value)
{
InitializeWriting();
if( value is System.Byte )
{
this.WriteByte( (byte) value );
}
else if( value is Char )
{
this.WriteChar( (char) value );
}
else if( value is Boolean )
{
this.WriteBoolean( (bool) value );
}
else if( value is Int16 )
{
this.WriteInt16( (short) value );
}
else if( value is Int32 )
{
this.WriteInt32( (int) value );
}
else if( value is Int64 )
{
this.WriteInt64( (long) value );
}
else if( value is Single )
{
this.WriteSingle( (float) value );
}
else if( value is Double )
{
this.WriteDouble( (double) value );
}
else if( value is byte[] )
{
this.WriteBytes( (byte[]) value );
}
else if( value is String )
{
this.WriteString( (string) value );
}
else
{
throw new MessageFormatException("Cannot write non-primitive type:" + value.GetType());
}
}
public override Object Clone()
{
StoreContent();
return base.Clone();
}
public override void ClearBody()
{
base.ClearBody();
this.byteBuffer = null;
this.dataIn = null;
this.dataOut = null;
this.bytesRemaining = -1;
}
public void Reset()
{
StoreContent();
this.dataIn = null;
this.dataOut = null;
this.byteBuffer = null;
this.bytesRemaining = -1;
this.ReadOnlyBody = true;
}
private void InitializeReading()
{
FailIfWriteOnlyBody();
if(this.dataIn == null)
{
this.byteBuffer = new MemoryStream(this.Content, false);
this.dataIn = new EndianBinaryReader(this.byteBuffer);
}
}
private void InitializeWriting()
{
FailIfReadOnlyBody();
if(this.dataOut == null)
{
this.byteBuffer = new MemoryStream();
this.dataOut = new EndianBinaryWriter(this.byteBuffer);
}
}
private void StoreContent()
{
if( dataOut != null)
{
dataOut.Close();
this.Content = byteBuffer.ToArray();
this.dataOut = null;
this.byteBuffer = null;
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.CompilerServices;
using BTDB.Buffer;
using BTDB.StreamLayer;
namespace BTDB.EventStoreLayer
{
public class ReadOnlyEventStore : IReadEventStore
{
protected IEventFileStorage File;
protected readonly ITypeSerializersMapping Mapping;
protected readonly ICompressionStrategy CompressionStrategy;
protected ulong NextReadPosition;
const int FirstReadAhead = 4096;
protected const int HeaderSize = 8;
protected const uint SectorSize = 512;
protected const ulong SectorMask = ~(ulong)(SectorSize - 1);
protected const uint SectorMaskUInt = (uint)(SectorMask & uint.MaxValue);
protected ulong EndBufferPosition;
protected readonly byte[] EndBuffer = new byte[SectorSize];
protected uint EndBufferLen;
protected readonly uint MaxBlockSize;
bool _knownAsCorrupted;
internal bool KnownAsFinished;
protected WeakReference<byte[]> ReadBufferWeakReference = new WeakReference<byte[]>(null);
public ReadOnlyEventStore(IEventFileStorage file, ITypeSerializersMapping mapping, ICompressionStrategy compressionStrategy)
{
File = file;
Mapping = mapping;
CompressionStrategy = compressionStrategy;
EndBufferPosition = ulong.MaxValue;
MaxBlockSize = Math.Min(File.MaxBlockSize, 0x1000000); // For Length there is only 3 bytes so maximum could be less
if (MaxBlockSize < FirstReadAhead) throw new ArgumentException("file.MaxBlockSize is less than FirstReadAhead");
}
public void ReadFromStartToEnd(IEventStoreObserver observer)
{
NextReadPosition = 0;
ReadToEnd(observer);
}
internal byte[] GetReadBuffer()
{
byte[] res;
if (ReadBufferWeakReference.TryGetTarget(out res))
return res;
res = new byte[FirstReadAhead + MaxBlockSize];
ReadBufferWeakReference.SetTarget(res);
return res;
}
public void ReadToEnd(IEventStoreObserver observer)
{
var overflowWriter = default(ByteBufferWriter);
var bufferBlock = GetReadBuffer();
var bufferStartPosition = NextReadPosition & SectorMask;
var bufferFullLength = 0;
var bufferReadOffset = (int)(NextReadPosition - bufferStartPosition);
var currentReadAhead = FirstReadAhead;
var buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, currentReadAhead);
var bufReadLength = (int)File.Read(buf, bufferStartPosition);
bufferFullLength += bufReadLength;
while (true)
{
if (bufferStartPosition + (ulong)bufferReadOffset + HeaderSize > File.MaxFileSize)
{
KnownAsFinished = true;
return;
}
if (bufferReadOffset == bufferFullLength)
{
break;
}
if (bufferReadOffset + HeaderSize > bufferFullLength)
{
for (var i = bufferReadOffset; i < bufferFullLength; i++)
{
if (bufferBlock[i] != 0)
{
SetCorrupted();
return;
}
}
break;
}
var blockCheckSum = PackUnpack.UnpackUInt32LE(bufferBlock, bufferReadOffset);
bufferReadOffset += 4;
var blockLen = PackUnpack.UnpackUInt32LE(bufferBlock, bufferReadOffset);
if (blockCheckSum == 0 && blockLen == 0)
{
bufferReadOffset -= 4;
break;
}
var blockType = (BlockType)(blockLen & 0xff);
blockLen >>= 8;
if (blockType == BlockType.LastBlock && blockLen == 0)
{
if (Checksum.CalcFletcher32(bufferBlock, (uint)bufferReadOffset, 4) != blockCheckSum)
{
SetCorrupted();
return;
}
KnownAsFinished = true;
return;
}
if (blockLen == 0 && blockType != (BlockType.FirstBlock | BlockType.LastBlock))
{
SetCorrupted();
return;
}
if (blockLen + HeaderSize > MaxBlockSize)
{
SetCorrupted();
return;
}
bufferReadOffset += 4;
var bufferLenToFill = (uint)(bufferReadOffset + (int)blockLen + FirstReadAhead) & SectorMaskUInt;
if (bufferLenToFill > bufferBlock.Length) bufferLenToFill = (uint)bufferBlock.Length;
buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, (int)(bufferLenToFill - bufferFullLength));
if (buf.Length > 0)
{
bufferLenToFill = (uint)(bufferReadOffset + (int)blockLen + currentReadAhead) & SectorMaskUInt;
if (bufferLenToFill > bufferBlock.Length) bufferLenToFill = (uint)bufferBlock.Length;
if (bufferStartPosition + bufferLenToFill > File.MaxFileSize)
{
bufferLenToFill = (uint)(File.MaxFileSize - bufferStartPosition);
}
buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, (int)(bufferLenToFill - bufferFullLength));
if (buf.Length > 0) {
if (currentReadAhead * 4 < MaxBlockSize)
{
currentReadAhead = currentReadAhead * 2;
}
bufReadLength = (int)File.Read(buf, bufferStartPosition + (ulong)bufferFullLength);
bufferFullLength += bufReadLength;
}
}
if (bufferReadOffset + (int)blockLen > bufferFullLength)
{
SetCorrupted();
return;
}
if (Checksum.CalcFletcher32(bufferBlock, (uint)bufferReadOffset - 4, blockLen + 4) != blockCheckSum)
{
SetCorrupted();
return;
}
var blockTypeBlock = blockType & (BlockType.FirstBlock | BlockType.MiddleBlock | BlockType.LastBlock);
var stopReadingRequested = false;
if (blockTypeBlock == (BlockType.FirstBlock | BlockType.LastBlock))
{
stopReadingRequested = Process(blockType, ByteBuffer.NewSync(bufferBlock, bufferReadOffset, (int)blockLen), observer);
}
else
{
if (blockTypeBlock == BlockType.FirstBlock)
{
overflowWriter = new ByteBufferWriter();
}
else if (blockTypeBlock == BlockType.MiddleBlock || blockTypeBlock == BlockType.LastBlock)
{
if (overflowWriter == null)
{
SetCorrupted();
return;
}
}
else
{
SetCorrupted();
return;
}
overflowWriter.WriteBlock(ByteBuffer.NewSync(bufferBlock, bufferReadOffset, (int)blockLen));
if (blockTypeBlock == BlockType.LastBlock)
{
stopReadingRequested = Process(blockType, overflowWriter.Data, observer);
overflowWriter = null;
}
}
bufferReadOffset += (int)blockLen;
if (overflowWriter == null)
NextReadPosition = bufferStartPosition + (ulong)bufferReadOffset;
if (stopReadingRequested)
{
return;
}
var nextBufferStartPosition = (bufferStartPosition + (ulong)bufferReadOffset) & SectorMask;
var bufferMoveDistance = (int)(nextBufferStartPosition - bufferStartPosition);
if (bufferMoveDistance <= 0) continue;
Array.Copy(bufferBlock, bufferMoveDistance, bufferBlock, 0, bufferFullLength - bufferMoveDistance);
bufferStartPosition = nextBufferStartPosition;
bufferFullLength -= bufferMoveDistance;
bufferReadOffset -= bufferMoveDistance;
}
if (overflowWriter != null)
{
// It is not corrupted here just unfinished, but definitely not appendable
EndBufferPosition = ulong.MaxValue;
return;
}
EndBufferLen = (uint)(bufferReadOffset - (bufferReadOffset & SectorMaskUInt));
EndBufferPosition = bufferStartPosition + (ulong)bufferReadOffset - EndBufferLen;
Array.Copy(bufferBlock, bufferReadOffset - EndBufferLen, EndBuffer, 0, EndBufferLen);
}
public bool IsKnownAsCorrupted()
{
return _knownAsCorrupted;
}
public bool IsKnownAsFinished()
{
return KnownAsFinished;
}
public bool IsKnownAsAppendable()
{
return EndBufferPosition != ulong.MaxValue;
}
bool Process(BlockType blockType, ByteBuffer block, IEventStoreObserver observer)
{
if ((blockType & BlockType.Compressed) != 0)
{
CompressionStrategy.Decompress(ref block);
}
var reader = new ByteBufferReader(block);
if ((blockType & BlockType.HasTypeDeclaration) != 0)
{
Mapping.LoadTypeDescriptors(reader);
}
var metadata = (blockType & BlockType.HasMetadata) != 0 ? Mapping.LoadObject(reader) : null;
uint eventCount;
if ((blockType & BlockType.HasOneEvent) != 0)
{
eventCount = 1;
}
else if ((blockType & BlockType.HasMoreEvents) != 0)
{
eventCount = reader.ReadVUInt32();
}
else
{
eventCount = 0;
}
var readEvents = observer.ObservedMetadata(metadata, eventCount);
if (!readEvents) return observer.ShouldStopReadingNextEvents();
var events = new object[eventCount];
var successfulEventCount = 0;
for (var i = 0; i < eventCount; i++)
{
var ev = Mapping.LoadObject(reader);
if (ev == null) continue;
events[successfulEventCount] = ev;
successfulEventCount++;
}
if (eventCount != successfulEventCount)
{
Array.Resize(ref events, successfulEventCount);
}
observer.ObservedEvents(events);
return observer.ShouldStopReadingNextEvents();
}
void SetCorrupted([CallerLineNumber] int sourceLineNumber = 0)
{
_knownAsCorrupted = true;
EndBufferPosition = ulong.MaxValue;
throw new InvalidDataException($"EventStore is corrupted (detailed line number {sourceLineNumber})");
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Network Client
/// </summary>
public partial interface INetworkManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The subscription credentials which uniquely identify the Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
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>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationGatewaysOperations.
/// </summary>
IApplicationGatewaysOperations ApplicationGateways { get; }
/// <summary>
/// Gets the IExpressRouteCircuitAuthorizationsOperations.
/// </summary>
IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; }
/// <summary>
/// Gets the IExpressRouteCircuitPeeringsOperations.
/// </summary>
IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; }
/// <summary>
/// Gets the IExpressRouteCircuitsOperations.
/// </summary>
IExpressRouteCircuitsOperations ExpressRouteCircuits { get; }
/// <summary>
/// Gets the IExpressRouteServiceProvidersOperations.
/// </summary>
IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; }
/// <summary>
/// Gets the ILoadBalancersOperations.
/// </summary>
ILoadBalancersOperations LoadBalancers { get; }
/// <summary>
/// Gets the ILoadBalancerBackendAddressPoolsOperations.
/// </summary>
ILoadBalancerBackendAddressPoolsOperations LoadBalancerBackendAddressPools { get; }
/// <summary>
/// Gets the ILoadBalancerFrontendIPConfigurationsOperations.
/// </summary>
ILoadBalancerFrontendIPConfigurationsOperations LoadBalancerFrontendIPConfigurations { get; }
/// <summary>
/// Gets the IInboundNatRulesOperations.
/// </summary>
IInboundNatRulesOperations InboundNatRules { get; }
/// <summary>
/// Gets the ILoadBalancerLoadBalancingRulesOperations.
/// </summary>
ILoadBalancerLoadBalancingRulesOperations LoadBalancerLoadBalancingRules { get; }
/// <summary>
/// Gets the ILoadBalancerNetworkInterfacesOperations.
/// </summary>
ILoadBalancerNetworkInterfacesOperations LoadBalancerNetworkInterfaces { get; }
/// <summary>
/// Gets the ILoadBalancerProbesOperations.
/// </summary>
ILoadBalancerProbesOperations LoadBalancerProbes { get; }
/// <summary>
/// Gets the INetworkInterfacesOperations.
/// </summary>
INetworkInterfacesOperations NetworkInterfaces { get; }
/// <summary>
/// Gets the INetworkInterfaceIPConfigurationsOperations.
/// </summary>
INetworkInterfaceIPConfigurationsOperations NetworkInterfaceIPConfigurations { get; }
/// <summary>
/// Gets the INetworkInterfaceLoadBalancersOperations.
/// </summary>
INetworkInterfaceLoadBalancersOperations NetworkInterfaceLoadBalancers { get; }
/// <summary>
/// Gets the INetworkSecurityGroupsOperations.
/// </summary>
INetworkSecurityGroupsOperations NetworkSecurityGroups { get; }
/// <summary>
/// Gets the ISecurityRulesOperations.
/// </summary>
ISecurityRulesOperations SecurityRules { get; }
/// <summary>
/// Gets the IDefaultSecurityRulesOperations.
/// </summary>
IDefaultSecurityRulesOperations DefaultSecurityRules { get; }
/// <summary>
/// Gets the INetworkWatchersOperations.
/// </summary>
INetworkWatchersOperations NetworkWatchers { get; }
/// <summary>
/// Gets the IPacketCapturesOperations.
/// </summary>
IPacketCapturesOperations PacketCaptures { get; }
/// <summary>
/// Gets the IPublicIPAddressesOperations.
/// </summary>
IPublicIPAddressesOperations PublicIPAddresses { get; }
/// <summary>
/// Gets the IRouteFiltersOperations.
/// </summary>
IRouteFiltersOperations RouteFilters { get; }
/// <summary>
/// Gets the IRouteFilterRulesOperations.
/// </summary>
IRouteFilterRulesOperations RouteFilterRules { get; }
/// <summary>
/// Gets the IRouteTablesOperations.
/// </summary>
IRouteTablesOperations RouteTables { get; }
/// <summary>
/// Gets the IRoutesOperations.
/// </summary>
IRoutesOperations Routes { get; }
/// <summary>
/// Gets the IBgpServiceCommunitiesOperations.
/// </summary>
IBgpServiceCommunitiesOperations BgpServiceCommunities { get; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
IUsagesOperations Usages { get; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
IVirtualNetworksOperations VirtualNetworks { get; }
/// <summary>
/// Gets the ISubnetsOperations.
/// </summary>
ISubnetsOperations Subnets { get; }
/// <summary>
/// Gets the IVirtualNetworkPeeringsOperations.
/// </summary>
IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; }
/// <summary>
/// Gets the IVirtualNetworkGatewaysOperations.
/// </summary>
IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; }
/// <summary>
/// Gets the IVirtualNetworkGatewayConnectionsOperations.
/// </summary>
IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; }
/// <summary>
/// Gets the ILocalNetworkGatewaysOperations.
/// </summary>
ILocalNetworkGatewaysOperations LocalNetworkGateways { get; }
/// <summary>
/// Checks whether a domain name in the cloudapp.net zone is available
/// for use.
/// </summary>
/// <param name='location'>
/// The location of the domain name.
/// </param>
/// <param name='domainNameLabel'>
/// The domain name to be verified. It must conform to the following
/// regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class CatalogHeaderDecoder
{
public const ushort BLOCK_LENGTH = 32;
public const ushort TEMPLATE_ID = 20;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private CatalogHeaderDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public CatalogHeaderDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public CatalogHeaderDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int VersionId()
{
return 1;
}
public static int VersionSinceVersion()
{
return 0;
}
public static int VersionEncodingOffset()
{
return 0;
}
public static int VersionEncodingLength()
{
return 4;
}
public static string VersionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int VersionNullValue()
{
return -2147483648;
}
public static int VersionMinValue()
{
return -2147483647;
}
public static int VersionMaxValue()
{
return 2147483647;
}
public int Version()
{
return _buffer.GetInt(_offset + 0, ByteOrder.LittleEndian);
}
public static int LengthId()
{
return 2;
}
public static int LengthSinceVersion()
{
return 0;
}
public static int LengthEncodingOffset()
{
return 4;
}
public static int LengthEncodingLength()
{
return 4;
}
public static string LengthMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LengthNullValue()
{
return -2147483648;
}
public static int LengthMinValue()
{
return -2147483647;
}
public static int LengthMaxValue()
{
return 2147483647;
}
public int Length()
{
return _buffer.GetInt(_offset + 4, ByteOrder.LittleEndian);
}
public static int NextRecordingIdId()
{
return 3;
}
public static int NextRecordingIdSinceVersion()
{
return 0;
}
public static int NextRecordingIdEncodingOffset()
{
return 8;
}
public static int NextRecordingIdEncodingLength()
{
return 8;
}
public static string NextRecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long NextRecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long NextRecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long NextRecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long NextRecordingId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int AlignmentId()
{
return 4;
}
public static int AlignmentSinceVersion()
{
return 0;
}
public static int AlignmentEncodingOffset()
{
return 16;
}
public static int AlignmentEncodingLength()
{
return 4;
}
public static string AlignmentMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int AlignmentNullValue()
{
return -2147483648;
}
public static int AlignmentMinValue()
{
return -2147483647;
}
public static int AlignmentMaxValue()
{
return 2147483647;
}
public int Alignment()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public static int ReservedId()
{
return 5;
}
public static int ReservedSinceVersion()
{
return 0;
}
public static int ReservedEncodingOffset()
{
return 31;
}
public static int ReservedEncodingLength()
{
return 1;
}
public static string ReservedMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static sbyte ReservedNullValue()
{
return (sbyte)-128;
}
public static sbyte ReservedMinValue()
{
return (sbyte)-127;
}
public static sbyte ReservedMaxValue()
{
return (sbyte)127;
}
public sbyte Reserved()
{
return unchecked((sbyte)_buffer.GetByte(_offset + 31));
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[CatalogHeader](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='version', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Version=");
builder.Append(Version());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='length', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=4, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=4, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Length=");
builder.Append(Length());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='nextRecordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("NextRecordingId=");
builder.Append(NextRecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='alignment', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Alignment=");
builder.Append(Alignment());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='reserved', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=31, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int8', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=1, offset=31, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT8, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Reserved=");
builder.Append(Reserved());
Limit(originalLimit);
return builder;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace SharedHeaders
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
public partial class BatchManagementDummyClient : ServiceClient<BatchManagementDummyClient>, IBatchManagementDummyClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription ID. This is a GUID-formatted string (e.g.
/// 00000000-0000-0000-0000-000000000000)
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The API version to be used with the HTTP request.
/// </summary>
public string ApiVersion { get; private 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 IBatchAccountOperations.
/// </summary>
public virtual IBatchAccountOperations BatchAccount { get; private set; }
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BatchManagementDummyClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BatchManagementDummyClient 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 BatchManagementDummyClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BatchAccount = new BatchAccountOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2017-05-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new 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 ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
namespace Gu.Wpf.UiAutomation
{
using System.Globalization;
using System.Windows.Automation;
public static partial class AutomationElementExt
{
public static string AcceleratorKey(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.AcceleratorKeyProperty);
}
public static string AccessKey(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.AccessKeyProperty);
}
public static string AutomationId(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.AutomationIdProperty);
}
public static System.Windows.Rect BoundingRectangle(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (System.Windows.Rect)element.GetCurrentPropertyValue(AutomationElementIdentifiers.BoundingRectangleProperty);
}
public static string ClassName(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ClassNameProperty);
}
public static System.Windows.Point ClickablePoint(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (System.Windows.Point)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ClickablePointProperty);
}
public static ControlType ControlType(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (ControlType)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ControlTypeProperty);
}
public static CultureInfo Culture(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (CultureInfo)element.GetCurrentPropertyValue(AutomationElementIdentifiers.CultureProperty);
}
public static string FrameworkId(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.FrameworkIdProperty);
}
public static bool HasKeyboardFocus(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.HasKeyboardFocusProperty);
}
public static string HelpText(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.HelpTextProperty);
}
public static bool IsContentElement(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsContentElementProperty);
}
public static bool IsControlElement(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsControlElementProperty);
}
public static bool IsDockPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsDockPatternAvailableProperty);
}
public static bool IsEnabled(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsEnabledProperty);
}
public static bool IsExpandCollapsePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsExpandCollapsePatternAvailableProperty);
}
public static bool IsGridItemPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsGridItemPatternAvailableProperty);
}
public static bool IsGridPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsGridPatternAvailableProperty);
}
public static bool IsInvokePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsInvokePatternAvailableProperty);
}
public static bool IsItemContainerPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsItemContainerPatternAvailableProperty);
}
public static bool IsKeyboardFocusable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsKeyboardFocusableProperty);
}
public static bool IsMultipleViewPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsMultipleViewPatternAvailableProperty);
}
public static bool IsOffscreen(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsOffscreenProperty);
}
public static bool IsPassword(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsPasswordProperty);
}
public static bool IsRangeValuePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsRangeValuePatternAvailableProperty);
}
public static bool IsRequiredForForm(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsRequiredForFormProperty);
}
public static bool IsScrollItemPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsScrollItemPatternAvailableProperty);
}
public static bool IsScrollPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsScrollPatternAvailableProperty);
}
public static bool IsSelectionItemPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsSelectionItemPatternAvailableProperty);
}
public static bool IsSelectionPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsSelectionPatternAvailableProperty);
}
public static bool IsSynchronizedInputPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsSynchronizedInputPatternAvailableProperty);
}
public static bool IsTableItemPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsTableItemPatternAvailableProperty);
}
public static bool IsTablePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsTablePatternAvailableProperty);
}
public static bool IsTextPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsTextPatternAvailableProperty);
}
public static bool IsTogglePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsTogglePatternAvailableProperty);
}
public static bool IsTransformPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsTransformPatternAvailableProperty);
}
public static bool IsValuePatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsValuePatternAvailableProperty);
}
public static bool IsWindowPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsWindowPatternAvailableProperty);
}
public static bool IsVirtualizedItemPatternAvailable(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (bool)element.GetCurrentPropertyValue(AutomationElementIdentifiers.IsVirtualizedItemPatternAvailableProperty);
}
public static string ItemStatus(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ItemStatusProperty);
}
public static string ItemType(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ItemTypeProperty);
}
public static object LabeledBy(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return element.GetCurrentPropertyValue(AutomationElementIdentifiers.LabeledByProperty);
}
public static string LocalizedControlType(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.LocalizedControlTypeProperty);
}
public static string Name(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (string)element.GetCurrentPropertyValue(AutomationElementIdentifiers.NameProperty);
}
public static int NativeWindowHandle(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (int)element.GetCurrentPropertyValue(AutomationElementIdentifiers.NativeWindowHandleProperty);
}
public static OrientationType Orientation(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (OrientationType)element.GetCurrentPropertyValue(AutomationElementIdentifiers.OrientationProperty);
}
public static int ProcessId(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (int)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ProcessIdProperty);
}
public static int[] RuntimeId(this AutomationElement element)
{
if (element is null)
{
throw new System.ArgumentNullException(nameof(element));
}
return (int[])element.GetCurrentPropertyValue(AutomationElementIdentifiers.RuntimeIdProperty);
}
}
}
| |
//
// 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 System.Text;
namespace Encog.Neural.HyperNEAT.Substrate
{
/// <summary>
/// The substrate defines the structure of the produced HyperNEAT network.
///
/// A substrate is made up of nodes and links. A node has a location that is an
/// n-dimensional coordinate. Nodes are grouped into input and output clusters.
/// There can also be hidden neurons between these two.
///
/// A HyperNEAT network works by training a CPPN that produces the actual
/// resulting NEAT network. The size of the substrate can then be adjusted to
/// create larger networks than what the HyperNEAT network was originally trained
/// with.
///
/// NeuroEvolution of Augmenting Topologies (NEAT) is a genetic algorithm for the
/// generation of evolving artificial neural networks. It was developed by Ken
/// Stanley while at The University of Texas at Austin.
///
/// -----------------------------------------------------------------------------
/// http://www.cs.ucf.edu/~kstanley/
/// Encog's NEAT implementation was drawn from the following three Journal
/// Articles. For more complete BibTeX sources, see NEATNetwork.java.
///
/// Evolving Neural Networks Through Augmenting Topologies
///
/// Generating Large-Scale Neural Networks Through Discovering Geometric
/// Regularities
///
/// Automatic feature selection in neuroevolution
[Serializable]
public class Substrate
{
/// <summary>
/// The dimensions of the network.
/// </summary>
private int dimensions;
/// <summary>
/// The input nodes.
/// </summary>
private IList<SubstrateNode> inputNodes = new List<SubstrateNode>();
/// <summary>
/// The output nodes.
/// </summary>
private IList<SubstrateNode> outputNodes = new List<SubstrateNode>();
/// <summary>
/// The hidden nodes.
/// </summary>
private IList<SubstrateNode> hiddenNodes = new List<SubstrateNode>();
/// <summary>
/// The links between nodes.
/// </summary>
private IList<SubstrateLink> links = new List<SubstrateLink>();
/// <summary>
/// The current neuron id.
/// </summary>
private int currentNeuronNumber;
/// <summary>
/// The number of activation cycles.
/// </summary>
public int ActivationCycles { get; set; }
/// <summary>
/// Construct a substrate with the specified number of dimensions in the
/// input/output layers.
/// </summary>
/// <param name="theDimensions">The dimensions</param>
public Substrate(int theDimensions)
{
this.dimensions = theDimensions;
this.currentNeuronNumber = 1;
this.ActivationCycles = 1;
}
/// <summary>
/// The hidden nodes.
/// </summary>
public IList<SubstrateNode> HiddenNodes
{
get
{
return hiddenNodes;
}
}
/// <summary>
/// The dimensions.
/// </summary>
public int Dimensions
{
get
{
return this.dimensions;
}
}
/// <summary>
/// The input nodes.
/// </summary>
public IList<SubstrateNode> InputNodes
{
get
{
return inputNodes;
}
}
/// <summary>
/// The output nodes.
/// </summary>
public IList<SubstrateNode> OutputNodes
{
get
{
return outputNodes;
}
}
/// <summary>
/// The input count.
/// </summary>
public int InputCount
{
get
{
return this.inputNodes.Count;
}
}
/// <summary>
/// The output count.
/// </summary>
public int OutputCount
{
get
{
return this.outputNodes.Count;
}
}
/// <summary>
/// Create a node.
/// </summary>
/// <returns>The node.</returns>
public SubstrateNode CreateNode()
{
SubstrateNode result = new SubstrateNode(this.currentNeuronNumber++,
this.dimensions);
return result;
}
/// <summary>
/// Create input node.
/// </summary>
/// <returns>An input node.</returns>
public SubstrateNode CreateInputNode()
{
SubstrateNode result = CreateNode();
this.inputNodes.Add(result);
return result;
}
/// <summary>
/// Create output node.
/// </summary>
/// <returns>An output node.</returns>
public SubstrateNode CreateOutputNode()
{
SubstrateNode result = CreateNode();
this.outputNodes.Add(result);
return result;
}
/// <summary>
/// Create hidden node.
/// </summary>
/// <returns>A hidden node.</returns>
public SubstrateNode CreateHiddenNode()
{
SubstrateNode result = CreateNode();
this.hiddenNodes.Add(result);
return result;
}
/// <summary>
/// Create a link.
/// </summary>
/// <param name="inputNode">The from node.</param>
/// <param name="outputNode">The to node.</param>
public void CreateLink(SubstrateNode inputNode, SubstrateNode outputNode)
{
SubstrateLink link = new SubstrateLink(inputNode, outputNode);
this.links.Add(link);
}
/// <summary>
/// The links.
/// </summary>
public IList<SubstrateLink> Links
{
get
{
return links;
}
}
/// <summary>
/// The link count.
/// </summary>
public int LinkCount
{
get
{
return links.Count;
}
}
/// <summary>
/// The total count of nodes.
/// </summary>
public int NodeCount
{
get
{
return 1 + this.inputNodes.Count + this.outputNodes.Count
+ this.hiddenNodes.Count;
}
}
/// <summary>
/// Get the biased nodes.
/// </summary>
/// <returns>A list of all nodes that are connected to the bias neuron. This
/// is typically all non-input neurons.</returns>
public IList<SubstrateNode> GetBiasedNodes()
{
return this.hiddenNodes.Union(this.outputNodes).ToList();
}
}
}
| |
// InflaterDynHeader.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using GitHub.ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace GitHub.ICSharpCode.SharpZipLib.Zip.Compression
{
class InflaterDynHeader
{
#region Constants
const int LNUM = 0;
const int DNUM = 1;
const int BLNUM = 2;
const int BLLENS = 3;
const int LENS = 4;
const int REPS = 5;
static readonly int[] repMin = { 3, 3, 11 };
static readonly int[] repBits = { 2, 3, 7 };
static readonly int[] BL_ORDER =
{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
#endregion
#region Constructors
public InflaterDynHeader()
{
}
#endregion
public bool Decode(StreamManipulator input)
{
decode_loop:
for (;;) {
switch (mode) {
case LNUM:
lnum = input.PeekBits(5);
if (lnum < 0) {
return false;
}
lnum += 257;
input.DropBits(5);
// System.err.println("LNUM: "+lnum);
mode = DNUM;
goto case DNUM; // fall through
case DNUM:
dnum = input.PeekBits(5);
if (dnum < 0) {
return false;
}
dnum++;
input.DropBits(5);
// System.err.println("DNUM: "+dnum);
num = lnum+dnum;
litdistLens = new byte[num];
mode = BLNUM;
goto case BLNUM; // fall through
case BLNUM:
blnum = input.PeekBits(4);
if (blnum < 0) {
return false;
}
blnum += 4;
input.DropBits(4);
blLens = new byte[19];
ptr = 0;
// System.err.println("BLNUM: "+blnum);
mode = BLLENS;
goto case BLLENS; // fall through
case BLLENS:
while (ptr < blnum) {
int len = input.PeekBits(3);
if (len < 0) {
return false;
}
input.DropBits(3);
// System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len);
blLens[BL_ORDER[ptr]] = (byte) len;
ptr++;
}
blTree = new InflaterHuffmanTree(blLens);
blLens = null;
ptr = 0;
mode = LENS;
goto case LENS; // fall through
case LENS:
{
int symbol;
while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) {
/* Normal case: symbol in [0..15] */
// System.err.println("litdistLens["+ptr+"]: "+symbol);
litdistLens[ptr++] = lastLen = (byte)symbol;
if (ptr == num) {
/* Finished */
return true;
}
}
/* need more input ? */
if (symbol < 0) {
return false;
}
/* otherwise repeat code */
if (symbol >= 17) {
/* repeat zero */
// System.err.println("repeating zero");
lastLen = 0;
} else {
if (ptr == 0) {
throw new SharpZipBaseException();
}
}
repSymbol = symbol-16;
}
mode = REPS;
goto case REPS; // fall through
case REPS:
{
int bits = repBits[repSymbol];
int count = input.PeekBits(bits);
if (count < 0) {
return false;
}
input.DropBits(bits);
count += repMin[repSymbol];
// System.err.println("litdistLens repeated: "+count);
if (ptr + count > num) {
throw new SharpZipBaseException();
}
while (count-- > 0) {
litdistLens[ptr++] = lastLen;
}
if (ptr == num) {
/* Finished */
return true;
}
}
mode = LENS;
goto decode_loop;
}
}
}
public InflaterHuffmanTree BuildLitLenTree()
{
byte[] litlenLens = new byte[lnum];
Array.Copy(litdistLens, 0, litlenLens, 0, lnum);
return new InflaterHuffmanTree(litlenLens);
}
public InflaterHuffmanTree BuildDistTree()
{
byte[] distLens = new byte[dnum];
Array.Copy(litdistLens, lnum, distLens, 0, dnum);
return new InflaterHuffmanTree(distLens);
}
#region Instance Fields
byte[] blLens;
byte[] litdistLens;
InflaterHuffmanTree blTree;
/// <summary>
/// The current decode mode
/// </summary>
int mode;
int lnum, dnum, blnum, num;
int repSymbol;
byte lastLen;
int ptr;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MachiningCloudManager.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System.Security.Claims;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Areas.Admin.Features.Goals;
using AllReady.Areas.Admin.ViewModels.Campaign;
using AllReady.Areas.Admin.ViewModels.Goal;
using AllReady.Constants;
using AllReady.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
using ClaimTypes = AllReady.Security.ClaimTypes;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class GoalAdminControllerTests
{
private const int OrgAdminOrgId = 123;
#region Create
[Fact]
public async void TestGoalCreateForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel())
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Create(123);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async void TestGoalCreateForOrgAdmin()
{
const int campaignId = 123;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel {Id = campaignId, OrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Create(campaignId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
var vm = result.ViewData.Model as GoalEditViewModel;
Assert.NotNull(vm);
Assert.Equal(campaignId, vm.CampaignId);
Assert.Equal(OrgAdminOrgId, vm.OrganizationId);
}
[Fact]
public async void TestGoalCreateForSiteAdmin()
{
const int campaignId = 123;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel {Id = campaignId, OrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Create(campaignId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Edit", result.ViewName);
var vm = result.ViewData.Model as GoalEditViewModel;
Assert.NotNull(vm);
Assert.Equal(campaignId, vm.CampaignId);
Assert.Equal(OrgAdminOrgId, vm.OrganizationId);
}
#endregion
#region CreatePost
[Fact]
public async void TestGoalCreatePostForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel())
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Create(123, new GoalEditViewModel());
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async void TestGoalCreatePostForSiteAdminWithValidModelStateReturnsRedirectToAction()
{
const int campaignId = 123;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel {Id = campaignId, OrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
var vm = new GoalEditViewModel {GoalType = GoalType.Text, TextualGoal = "Aim to please"};
// Act
var result = await goalController.Create(campaignId, vm) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalEditCommand>()), Times.Once);
}
[Fact]
public async void GoalCreatePostForOrgAdminWithValidModelStateReturnsRedirectToAction()
{
const int campaignId = 123;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel {Id = campaignId, OrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
var vm = new GoalEditViewModel {GoalType = GoalType.Text, TextualGoal = "Aim to please"};
// Act
var result = await goalController.Create(campaignId, vm) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalEditCommand>()), Times.Once);
}
#endregion
#region Delete
[Fact]
public async void TestGoalDeleteForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel {OwningOrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Delete(567);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async void TestGoalDeleteForOrgAdminForNonexistantGoalReturn404()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync((GoalDeleteViewModel)null)
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, true, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Delete(987);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async void TestGoalDeleteOrgAdminDisplaysConfirmationPage()
{
const int goalId = 567;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel
{
Id = goalId,
OwningOrganizationId = OrgAdminOrgId,
TextualGoal = "This goal should be deleted",
GoalType = GoalType.Numeric,
NumericGoal = 100
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, true, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Delete(goalId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Delete", result.ViewName);
var goalDeleteViewModel = (GoalDeleteViewModel) result.ViewData.Model;
Assert.Equal("This goal should be deleted", goalDeleteViewModel.TextualGoal);
Assert.Equal(GoalType.Numeric, goalDeleteViewModel.GoalType);
Assert.Equal(100, goalDeleteViewModel.NumericGoal);
}
[Fact]
public async void TestGoalDeleteSiteAdminDisplaysConfirmationPage()
{
const int goalId = 567;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel
{
Id = goalId,
OwningOrganizationId = OrgAdminOrgId,
TextualGoal = "This goal should be deleted",
GoalType = GoalType.Numeric,
NumericGoal = 100
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, true, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Delete(goalId) as ViewResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Delete", result.ViewName);
var goalDeleteViewModel = (GoalDeleteViewModel)result.ViewData.Model;
Assert.Equal("This goal should be deleted", goalDeleteViewModel.TextualGoal);
Assert.Equal(GoalType.Numeric, goalDeleteViewModel.GoalType);
Assert.Equal(100, goalDeleteViewModel.NumericGoal);
}
#endregion
#region DeleteConfirmed
[Fact]
public async void TestGoalDeleteConfirmedForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel { OwningOrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.DeleteConfirmed(567);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async void TestGoalDeleteConfirmedForOrgAdminForNonexistantGoalReturn404()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync((GoalDeleteViewModel)null)
.Verifiable();
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.DeleteConfirmed(987);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async void TestGoalDeleteConfirmedOrgAdminRedirectToAction()
{
const int campaignId = 123;
const int goalId = 567;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel
{
Id = goalId,
OwningOrganizationId = OrgAdminOrgId,
CampaignId = campaignId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, true, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.DeleteConfirmed(goalId) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalDeleteCommand>()), Times.Once);
}
[Fact]
public async void TestGoalDeleteConfirmedSiteAdminRedirectToAction()
{
const int campaignId = 123;
const int goalId = 567;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalDeleteQuery>()))
.ReturnsAsync(new GoalDeleteViewModel
{
Id = goalId,
OwningOrganizationId = OrgAdminOrgId,
CampaignId = campaignId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, true, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.DeleteConfirmed(goalId) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalDeleteCommand>()), Times.Once);
}
#endregion
#region Edit
[Fact]
public async void TestGoalEditForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel(){OrganizationId = OrgAdminOrgId})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Edit(456);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async void TestGoalEditForOrgAdminForNonexistantGoalReturn404()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync((GoalEditViewModel)null)
.Verifiable();
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Edit(987);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async void TestGoalEditForOrgAdmin()
{
const int campaignId = 123;
const int goalId = 456;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel
{
Id = goalId,
CampaignId = campaignId,
OrganizationId = OrgAdminOrgId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
// Act
var actionResult = await goalController.Edit(goalId);
// Assert
Assert.IsType<ViewResult>(actionResult);
var viewResult = (ViewResult) actionResult;
Assert.Equal("Edit", viewResult.ViewName);
var vm = viewResult.ViewData.Model as GoalEditViewModel;
Assert.NotNull(vm);
Assert.Equal(campaignId, vm.CampaignId);
Assert.Equal(OrgAdminOrgId, vm.OrganizationId);
}
[Fact]
public async void TestGoalEditForSiteAdmin()
{
const int campaignId = 123;
const int goalId = 456;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel
{
Id = goalId,
CampaignId = campaignId,
OrganizationId = OrgAdminOrgId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
// Act
var actionResult = await goalController.Edit(goalId);
// Assert
Assert.IsType<ViewResult>(actionResult);
var viewResult = (ViewResult) actionResult;
Assert.Equal("Edit", viewResult.ViewName);
var vm = viewResult.ViewData.Model as GoalEditViewModel;
Assert.NotNull(vm);
Assert.Equal(campaignId, vm.CampaignId);
Assert.Equal(OrgAdminOrgId, vm.OrganizationId);
}
#endregion
#region EditPost
[Fact]
public async void GoalEditPostForOrgAdminWithIncorrectIdInModelStateReturnsBadRequest()
{
const int campaignId = 123;
const int goalId = 456;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel
{
Id = goalId,
CampaignId = campaignId,
OrganizationId = OrgAdminOrgId
})
.Verifiable();
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
var vm = new GoalEditViewModel {Id = goalId, GoalType = GoalType.Text, TextualGoal = "Aim to please"};
// Act
var result = await goalController.Edit(987, vm);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async void GoalEditPostForOrgAdminWithValidModelStateReturnsRedirectToAction()
{
const int campaignId = 123;
const int goalId = 456;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel
{
Id = goalId,
CampaignId = campaignId,
OrganizationId = OrgAdminOrgId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(OrgAdminOrgId));
goalController.ControllerContext = mockContext.Object;
var vm = new GoalEditViewModel {Id = goalId, GoalType = GoalType.Text, TextualGoal = "Aim to please"};
// Act
var result = await goalController.Edit(goalId, vm) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalEditCommand>()), Times.Once);
}
[Fact]
public async void TestGoalEditPostForSiteAdminWithValidModelStateReturnsRedirectToAction()
{
const int campaignId = 123;
const int goalId = 456;
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel
{
Id = goalId,
CampaignId = campaignId,
OrganizationId = OrgAdminOrgId
})
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, true, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(SiteAdmin());
goalController.ControllerContext = mockContext.Object;
var vm = new GoalEditViewModel {Id = goalId, GoalType = GoalType.Text, TextualGoal = "Aim to please"};
// Act
var result = await goalController.Edit(goalId, vm) as RedirectToActionResult;
// Assert
Assert.NotNull(result);
Assert.Equal("Details", result.ActionName);
Assert.Equal("Campaign", result.ControllerName);
Assert.Equal(AreaNames.Admin, result.RouteValues["area"]);
Assert.Equal(campaignId, result.RouteValues["id"]);
mockMediator.Verify(mock => mock.SendAsync(It.IsAny<GoalEditCommand>()), Times.Once);
}
[Fact]
public async void TestGoalEditPostForWrongOrgAdminReturns401()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<GoalEditQuery>()))
.ReturnsAsync(new GoalEditViewModel())
.Verifiable();
mockMediator.Setup(x => x.SendAsync(It.IsAny<AuthorizableCampaignQuery>())).ReturnsAsync(new FakeAuthorizableCampaign(false, false, false, false));
var goalController = new GoalController(mockMediator.Object);
var mockContext = MockControllerContextWithUser(OrgAdmin(654));
goalController.ControllerContext = mockContext.Object;
// Act
var result = await goalController.Edit(456, new GoalEditViewModel(){Id = 456});
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
#endregion
private static ClaimsPrincipal OrgAdmin(int orgAdminOrgId)
{
return new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(ClaimTypes.Organization, orgAdminOrgId.ToString())
}));
}
private static ClaimsPrincipal SiteAdmin()
{
return new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.UserType, nameof(UserType.SiteAdmin))
}));
}
private static Mock<ControllerContext> MockControllerContextWithUser(ClaimsPrincipal principle)
{
var mockHttpContext = new Mock<HttpContext>();
mockHttpContext.Setup(mock => mock.User).Returns(() => principle);
var mockContext = new Mock<ControllerContext>();
mockContext.Object.HttpContext = mockHttpContext.Object;
return mockContext;
}
}
}
| |
// <copyright file="FisherSnedecorTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous
{
/// <summary>
/// Fisher-Snedecor distribution tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class FisherSnedecorTests
{
/// <summary>
/// Can create fisher snedecor.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(Double.PositiveInfinity, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(Double.PositiveInfinity, 1.0)]
[TestCase(0.1, Double.PositiveInfinity)]
[TestCase(1.0, Double.PositiveInfinity)]
[TestCase(10.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, Double.PositiveInfinity)]
public void CanCreateFisherSnedecor(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
Assert.AreEqual(d1, n.DegreesOfFreedom1);
Assert.AreEqual(d2, n.DegreesOfFreedom2);
}
/// <summary>
/// <c>FisherSnedecor</c> create fails with bad parameters.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(Double.NaN, Double.NaN)]
[TestCase(0.0, Double.NaN)]
[TestCase(-1.0, Double.NaN)]
[TestCase(-10.0, Double.NaN)]
[TestCase(Double.NaN, 0.0)]
[TestCase(0.0, 0.0)]
[TestCase(-1.0, 0.0)]
[TestCase(-10.0, 0.0)]
[TestCase(Double.NaN, -1.0)]
[TestCase(0.0, -1.0)]
[TestCase(-1.0, -1.0)]
[TestCase(-10.0, -1.0)]
[TestCase(Double.NaN, -10.0)]
[TestCase(0.0, -10.0)]
[TestCase(-1.0, -10.0)]
[TestCase(-10.0, -10.0)]
public void FisherSnedecorCreateFailsWithBadParameters(double d1, double d2)
{
Assert.That(() => new FisherSnedecor(d1, d2), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var n = new FisherSnedecor(2d, 1d);
Assert.AreEqual("FisherSnedecor(d1 = 2, d2 = 1)", n.ToString());
}
/// <summary>
/// Validate mean.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(Double.PositiveInfinity, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(Double.PositiveInfinity, 1.0)]
[TestCase(0.1, Double.PositiveInfinity)]
[TestCase(1.0, Double.PositiveInfinity)]
[TestCase(10.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, Double.PositiveInfinity)]
public void ValidateMean(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
if (d2 > 2)
{
Assert.AreEqual(d2 / (d2 - 2.0), n.Mean);
}
}
/// <summary>
/// Validate variance.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(Double.PositiveInfinity, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(Double.PositiveInfinity, 1.0)]
[TestCase(0.1, Double.PositiveInfinity)]
[TestCase(1.0, Double.PositiveInfinity)]
[TestCase(10.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, Double.PositiveInfinity)]
public void ValidateVariance(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
if (d2 > 4)
{
Assert.AreEqual((2.0 * d2 * d2 * (d1 + d2 - 2.0)) / (d1 * (d2 - 2.0) * (d2 - 2.0) * (d2 - 4.0)), n.Variance);
}
}
/// <summary>
/// Validate standard deviation.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(Double.PositiveInfinity, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(Double.PositiveInfinity, 1.0)]
[TestCase(0.1, Double.PositiveInfinity)]
[TestCase(1.0, Double.PositiveInfinity)]
[TestCase(10.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, Double.PositiveInfinity)]
public void ValidateStdDev(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
if (d2 > 4)
{
Assert.AreEqual(Math.Sqrt(n.Variance), n.StdDev);
}
}
/// <summary>
/// Validate entropy throws <c>NotSupportedException</c>.
/// </summary>
[Test]
public void ValidateEntropyThrowsNotSupportedException()
{
var n = new FisherSnedecor(1.0, 2.0);
Assert.Throws<NotSupportedException>(() => { var ent = n.Entropy; });
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(Double.PositiveInfinity, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(Double.PositiveInfinity, 1.0)]
[TestCase(0.1, Double.PositiveInfinity)]
[TestCase(1.0, Double.PositiveInfinity)]
[TestCase(10.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, Double.PositiveInfinity)]
public void ValidateSkewness(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
if (d2 > 6)
{
Assert.AreEqual((((2.0 * d1) + d2 - 2.0) * Math.Sqrt(8.0 * (d2 - 4.0))) / ((d2 - 6.0) * Math.Sqrt(d1 * (d1 + d2 - 2.0))), n.Skewness);
}
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
[TestCase(0.1, 0.1)]
[TestCase(1.0, 0.1)]
[TestCase(10.0, 0.1)]
[TestCase(100.0, 0.1)]
[TestCase(0.1, 1.0)]
[TestCase(1.0, 1.0)]
[TestCase(10.0, 1.0)]
[TestCase(100.0, 1.0)]
[TestCase(0.1, 100.0)]
[TestCase(1.0, 100.0)]
[TestCase(10.0, 100.0)]
[TestCase(100.0, 100.0)]
public void ValidateMode(double d1, double d2)
{
var n = new FisherSnedecor(d1, d2);
if (d1 > 2)
{
Assert.AreEqual((d2 * (d1 - 2.0)) / (d1 * (d2 + 2.0)), n.Mode);
}
}
/// <summary>
/// Validate median throws <c>NotSupportedException</c>.
/// </summary>
[Test]
public void ValidateMedianThrowsNotSupportedException()
{
var n = new FisherSnedecor(1.0, 2.0);
Assert.Throws<NotSupportedException>(() => { var m = n.Median; });
}
/// <summary>
/// Validate minimum.
/// </summary>
[Test]
public void ValidateMinimum()
{
var n = new FisherSnedecor(1.0, 2.0);
Assert.AreEqual(0.0, n.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
[Test]
public void ValidateMaximum()
{
var n = new FisherSnedecor(1.0, 2.0);
Assert.AreEqual(Double.PositiveInfinity, n.Maximum);
}
/// <summary>
/// Validate density.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
/// <param name="x">Input X value</param>
[TestCase(0.1, 0.1, 1.0)]
[TestCase(1.0, 0.1, 1.0)]
[TestCase(10.0, 0.1, 1.0)]
[TestCase(100.0, 0.1, 1.0)]
[TestCase(0.1, 1.0, 1.0)]
[TestCase(1.0, 1.0, 1.0)]
[TestCase(10.0, 1.0, 1.0)]
[TestCase(100.0, 1.0, 1.0)]
[TestCase(0.1, 100.0, 1.0)]
[TestCase(1.0, 100.0, 1.0)]
[TestCase(10.0, 100.0, 1.0)]
[TestCase(100.0, 100.0, 1.0)]
[TestCase(0.1, 0.1, 10.0)]
[TestCase(1.0, 0.1, 10.0)]
[TestCase(10.0, 0.1, 10.0)]
[TestCase(100.0, 0.1, 10.0)]
[TestCase(0.1, 1.0, 10.0)]
[TestCase(1.0, 1.0, 10.0)]
[TestCase(10.0, 1.0, 10.0)]
[TestCase(100.0, 1.0, 10.0)]
[TestCase(0.1, 100.0, 10.0)]
[TestCase(1.0, 100.0, 10.0)]
[TestCase(10.0, 100.0, 10.0)]
[TestCase(100.0, 100.0, 10.0)]
public void ValidateDensity(double d1, double d2, double x)
{
var n = new FisherSnedecor(d1, d2);
double expected = Math.Sqrt(Math.Pow(d1*x, d1)*Math.Pow(d2, d2)/Math.Pow((d1*x) + d2, d1 + d2))/(x*SpecialFunctions.Beta(d1/2.0, d2/2.0));
Assert.AreEqual(expected, n.Density(x));
Assert.AreEqual(expected, FisherSnedecor.PDF(d1, d2, x));
}
/// <summary>
/// Validate density log.
/// </summary>
/// <param name="d1">Degrees of freedom 1</param>
/// <param name="d2">Degrees of freedom 2</param>
/// <param name="x">Input X value</param>
[TestCase(0.1, 0.1, 1.0)]
[TestCase(1.0, 0.1, 1.0)]
[TestCase(10.0, 0.1, 1.0)]
[TestCase(100.0, 0.1, 1.0)]
[TestCase(0.1, 1.0, 1.0)]
[TestCase(1.0, 1.0, 1.0)]
[TestCase(10.0, 1.0, 1.0)]
[TestCase(100.0, 1.0, 1.0)]
[TestCase(0.1, 100.0, 1.0)]
[TestCase(1.0, 100.0, 1.0)]
[TestCase(10.0, 100.0, 1.0)]
[TestCase(100.0, 100.0, 1.0)]
[TestCase(0.1, 0.1, 10.0)]
[TestCase(1.0, 0.1, 10.0)]
[TestCase(10.0, 0.1, 10.0)]
[TestCase(100.0, 0.1, 10.0)]
[TestCase(0.1, 1.0, 10.0)]
[TestCase(1.0, 1.0, 10.0)]
[TestCase(10.0, 1.0, 10.0)]
[TestCase(100.0, 1.0, 10.0)]
[TestCase(0.1, 100.0, 10.0)]
[TestCase(1.0, 100.0, 10.0)]
[TestCase(10.0, 100.0, 10.0)]
[TestCase(100.0, 100.0, 10.0)]
public void ValidateDensityLn(double d1, double d2, double x)
{
var n = new FisherSnedecor(d1, d2);
double expected = Math.Log(Math.Sqrt(Math.Pow(d1*x, d1)*Math.Pow(d2, d2)/Math.Pow((d1*x) + d2, d1 + d2))/(x*SpecialFunctions.Beta(d1/2.0, d2/2.0)));
Assert.AreEqual(expected, n.DensityLn(x));
Assert.AreEqual(expected, FisherSnedecor.PDFLn(d1, d2, x));
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var n = new FisherSnedecor(1.0, 2.0);
n.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var n = new FisherSnedecor(1.0, 2.0);
var ied = n.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
[TestCase(0.1, 0.1, 1.0)]
[TestCase(1.0, 0.1, 1.0)]
[TestCase(10.0, 0.1, 1.0)]
[TestCase(0.1, 1.0, 1.0)]
[TestCase(1.0, 1.0, 1.0)]
[TestCase(10.0, 1.0, 1.0)]
[TestCase(0.1, 0.1, 10.0)]
[TestCase(1.0, 0.1, 10.0)]
[TestCase(10.0, 0.1, 10.0)]
[TestCase(0.1, 1.0, 10.0)]
[TestCase(1.0, 1.0, 10.0)]
[TestCase(10.0, 1.0, 10.0)]
public void ValidateCumulativeDistribution(double d1, double d2, double x)
{
var n = new FisherSnedecor(d1, d2);
double expected = SpecialFunctions.BetaRegularized(d1/2.0, d2/2.0, d1*x/(d2 + (x*d1)));
Assert.That(n.CumulativeDistribution(x), Is.EqualTo(expected));
Assert.That(FisherSnedecor.CDF(d1, d2, x), Is.EqualTo(expected));
}
[TestCase(0.1, 0.1, 1.0)]
[TestCase(1.0, 0.1, 1.0)]
[TestCase(10.0, 0.1, 1.0)]
[TestCase(0.1, 1.0, 1.0)]
[TestCase(1.0, 1.0, 1.0)]
[TestCase(10.0, 1.0, 1.0)]
[TestCase(0.1, 0.1, 10.0)]
[TestCase(1.0, 0.1, 10.0)]
[TestCase(10.0, 0.1, 10.0)]
[TestCase(0.1, 1.0, 10.0)]
[TestCase(1.0, 1.0, 10.0)]
[TestCase(10.0, 1.0, 10.0)]
public void ValidateInverseCumulativeDistribution(double d1, double d2, double x)
{
var n = new FisherSnedecor(d1, d2);
double p = SpecialFunctions.BetaRegularized(d1/2.0, d2/2.0, d1*x/(d2 + (x*d1)));
Assert.That(n.InverseCumulativeDistribution(p), Is.EqualTo(x).Within(1e-8));
Assert.That(FisherSnedecor.InvCDF(d1, d2, p), Is.EqualTo(x).Within(1e-8));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Core.TestFramework
{
/// <summary>
/// Represents the ambient environment in which the test suite is
/// being run.
/// </summary>
public abstract class TestEnvironment
{
private static readonly string RepositoryRoot;
private readonly string _prefix;
private TokenCredential _credential;
private TestRecording _recording;
private readonly Dictionary<string, string> _environmentFile = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected TestEnvironment(string serviceName)
{
_prefix = serviceName.ToUpperInvariant() + "_";
if (RepositoryRoot == null)
{
throw new InvalidOperationException("Unexpected error, repository root not found");
}
var sdkDirectory = Path.Combine(RepositoryRoot, "sdk", serviceName);
if (!Directory.Exists(sdkDirectory))
{
throw new InvalidOperationException($"SDK directory {sdkDirectory} not found");
}
var testEnvironmentFile = Path.Combine(RepositoryRoot, "sdk", serviceName, "test-resources.json.env");
if (File.Exists(testEnvironmentFile))
{
var json = JsonDocument.Parse(
ProtectedData.Unprotect(File.ReadAllBytes(testEnvironmentFile), null, DataProtectionScope.CurrentUser)
);
foreach (var property in json.RootElement.EnumerateObject())
{
_environmentFile[property.Name] = property.Value.GetString();
}
}
}
static TestEnvironment()
{
// Traverse parent directories until we find an "artifacts" directory
// parent of that would become a repo root for test environment resolution purposes
var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
while (directoryInfo.Name != "artifacts")
{
if (directoryInfo.Parent == null)
{
return;
}
directoryInfo = directoryInfo.Parent;
}
RepositoryRoot = directoryInfo?.Parent?.FullName;
}
internal RecordedTestMode? Mode { get; set; }
/// <summary>
/// The name of the Azure subscription containing the resource group to be used for Live tests. Recorded.
/// </summary>
public string SubscriptionId => GetRecordedVariable("SUBSCRIPTION_ID");
/// <summary>
/// The name of the Azure resource group to be used for Live tests. Recorded.
/// </summary>
public string ResourceGroup => GetRecordedVariable("RESOURCE_GROUP");
/// <summary>
/// The location of the Azure resource group to be used for Live tests (e.g. westus2). Recorded.
/// </summary>
public string Location => GetRecordedVariable("LOCATION");
/// <summary>
/// The environment of the Azure resource group to be used for Live tests (e.g. AzureCloud). Recorded.
/// </summary>
public string AzureEnvironment => GetRecordedVariable("ENVIRONMENT");
/// <summary>
/// The name of the Azure Active Directory tenant that holds the service principal to use during Live tests. Recorded.
/// </summary>
public string TenantId => GetRecordedVariable("TENANT_ID");
/// <summary>
/// The client id of the Azure Active Directory service principal to use during Live tests. Recorded.
/// </summary>
public string ClientId => GetRecordedVariable("CLIENT_ID");
/// <summary>
/// The client secret of the Azure Active Directory service principal to use during Live tests. Not recorded.
/// </summary>
public string ClientSecret => GetVariable("CLIENT_SECRET");
public TokenCredential Credential
{
get
{
if (_credential != null)
{
return _credential;
}
if (Mode == RecordedTestMode.Playback)
{
_credential = new TestCredential();
}
else
{
// Don't take a hard dependency on Azure.Identity
var type = Type.GetType("Azure.Identity.ClientSecretCredential, Azure.Identity");
if (type == null)
{
throw new InvalidOperationException("Azure.Identity must be referenced to use Credential in Live environment.");
}
_credential = (TokenCredential) Activator.CreateInstance(
type,
GetVariable("TENANT_ID"),
GetVariable("CLIENT_ID"),
GetVariable("CLIENT_SECRET")
);
}
return _credential;
}
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name)
{
if (Mode == RecordedTestMode.Playback)
{
return GetRecordedValue(name);
}
string value = GetOptionalVariable(name);
SetRecordedValue(name, value);
return value;
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name)
{
var value = GetRecordedOptionalVariable(name);
EnsureValue(name, value);
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetOptionalVariable(string name)
{
var prefixedName = _prefix + name;
// Environment variables override the environment file
var value = Environment.GetEnvironmentVariable(prefixedName) ??
Environment.GetEnvironmentVariable(name);
if (value == null)
{
_environmentFile.TryGetValue(prefixedName, out value);
}
if (value == null)
{
_environmentFile.TryGetValue(name, out value);
}
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetVariable(string name)
{
var value = GetOptionalVariable(name);
EnsureValue(name, value);
return value;
}
private void EnsureValue(string name, string value)
{
if (value == null)
{
var prefixedName = _prefix + name;
throw new InvalidOperationException(
$"Unable to find environment variable {prefixedName} or {name} required by test." + Environment.NewLine +
"Make sure the test environment was initialized using eng/common/TestResources/New-TestResources.ps1 script.");
}
}
public void SetRecording(TestRecording recording)
{
_credential = null;
_recording = recording;
}
private string GetRecordedValue(string name)
{
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be retrieved outside the test method invocation");
}
return _recording.GetVariable(name, null);
}
private void SetRecordedValue(string name, string value)
{
if (!Mode.HasValue)
{
return;
}
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be set outside the test method invocation");
}
_recording?.SetVariable(name, value);
}
private class TestCredential : TokenCredential
{
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new ValueTask<AccessToken>(GetToken(requestContext, cancellationToken));
}
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new AccessToken("TEST TOKEN " + string.Join(" ", requestContext.Scopes), DateTimeOffset.MaxValue);
}
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace System
{
/// <summary>Methods for parsing numbers and strings.</summary>
internal static class ParseNumbers
{
internal const int LeftAlign = 0x0001;
internal const int RightAlign = 0x0004;
internal const int PrefixSpace = 0x0008;
internal const int PrintSign = 0x0010;
internal const int PrintBase = 0x0020;
internal const int PrintAsI1 = 0x0040;
internal const int PrintAsI2 = 0x0080;
internal const int PrintAsI4 = 0x0100;
internal const int TreatAsUnsigned = 0x0200;
internal const int TreatAsI1 = 0x0400;
internal const int TreatAsI2 = 0x0800;
internal const int IsTight = 0x1000;
internal const int NoSpace = 0x2000;
internal const int PrintRadixBase = 0x4000;
private const int MinRadix = 2;
private const int MaxRadix = 36;
public static unsafe long StringToLong(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToLong(s, radix, flags, ref pos);
}
public static long StringToLong(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
long result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
Number.ThrowOverflowException(TypeCode.Int64);
if (r == 10)
{
result *= sign;
}
return result;
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToInt(s, radix, flags, ref pos);
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
// They're requied to tell me where to start parsing.
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
// Consume the 0x if we're in an unknown base or in base-16.
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
int result = GrabInts(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((flags & TreatAsI1) != 0)
{
if ((uint)result > 0xFF)
Number.ThrowOverflowException(TypeCode.SByte);
}
else if ((flags & TreatAsI2) != 0)
{
if ((uint)result > 0xFFFF)
Number.ThrowOverflowException(TypeCode.Int16);
}
else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
{
Number.ThrowOverflowException(TypeCode.Int32);
}
if (r == 10)
{
result *= sign;
}
return result;
}
public static string IntToString(int n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer = stackalloc char[66]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
// If the number is negative, make it positive and remember the sign.
// If the number is MIN_VALUE, this will still be negative, so we'll have to
// special case this later.
bool isNegative = false;
uint l;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
l = (10 == radix) ? (uint)-n : (uint)n;
}
else
{
l = (uint)n;
}
// The conversion to a uint will sign extend the number. In order to ensure
// that we only get as many bits as we expect, we chop the number.
if ((flags & PrintAsI1) != 0)
{
l &= 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
l &= 0xFFFF;
}
// Special case the 0.
int index;
if (0 == l)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for (...;i<buffer.Length;...) loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
uint div = l / (uint)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
uint charVal = l - (div * (uint)radix);
l = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (l == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(l == 0, $"Expected {l} == 0");
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
}
if (10 == radix)
{
// If it was negative, append the sign, else if they requested, add the '+'.
// If they requested a leading space, put it on.
if (isNegative)
{
buffer[index++] = '-';
}
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
public static string LongToString(long n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer = stackalloc char[67]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
// If the number is negative, make it positive and remember the sign.
ulong ul;
bool isNegative = false;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
ul = (10 == radix) ? (ulong)(-n) : (ulong)n;
}
else
{
ul = (ulong)n;
}
if ((flags & PrintAsI1) != 0)
{
ul &= 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
ul &= 0xFFFF;
}
else if ((flags & PrintAsI4) != 0)
{
ul &= 0xFFFFFFFF;
}
// Special case the 0.
int index;
if (0 == ul)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
ulong div = ul / (ulong)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
int charVal = (int)(ul - (div * (ulong)radix));
ul = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (ul == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(ul == 0, $"Expected {ul} == 0");
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
else if ((flags & PrintRadixBase) != 0)
{
buffer[index++] = '#';
buffer[index++] = (char)((radix % 10) + '0');
buffer[index++] = (char)((radix / 10) + '0');
}
}
if (10 == radix)
{
// If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
// else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
// If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
private static void EatWhiteSpace(ReadOnlySpan<char> s, ref int i)
{
int localIndex = i;
for (; localIndex < s.Length && char.IsWhiteSpace(s[localIndex]); localIndex++) ;
i = localIndex;
}
private static long GrabLongs(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
ulong result = 0;
ulong maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = 0x7FFFFFFFFFFFFFFF / 10;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || ((long)result) < 0)
{
Number.ThrowOverflowException(TypeCode.Int64);
}
result = result * (ulong)radix + (ulong)value;
i++;
}
if ((long)result < 0 && result != 0x8000000000000000)
{
Number.ThrowOverflowException(TypeCode.Int64);
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffffffffffff / 10 :
radix == 16 ? 0xffffffffffffffff / 16 :
radix == 8 ? 0xffffffffffffffff / 8 :
0xffffffffffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
Number.ThrowOverflowException(TypeCode.UInt64);
}
ulong temp = result * (ulong)radix + (ulong)value;
if (temp < result) // this means overflow as well
{
Number.ThrowOverflowException(TypeCode.UInt64);
}
result = temp;
i++;
}
}
return (long)result;
}
private static int GrabInts(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
uint result = 0;
uint maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = (0x7FFFFFFF / 10);
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || (int)result < 0)
{
Number.ThrowOverflowException(TypeCode.Int32);
}
result = result * (uint)radix + (uint)value;
i++;
}
if ((int)result < 0 && result != 0x80000000)
{
Number.ThrowOverflowException(TypeCode.Int32);
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffff / 10 :
radix == 16 ? 0xffffffff / 16 :
radix == 8 ? 0xffffffff / 8 :
0xffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
Number.ThrowOverflowException(TypeCode.UInt32);
}
uint temp = result * (uint)radix + (uint)value;
if (temp < result) // this means overflow as well
{
Number.ThrowOverflowException(TypeCode.UInt32);
}
result = temp;
i++;
}
}
return (int)result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsDigit(char c, int radix, out int result)
{
int tmp;
if ((uint)(c - '0') <= 9)
{
result = tmp = c - '0';
}
else if ((uint)(c - 'A') <= 'Z' - 'A')
{
result = tmp = c - 'A' + 10;
}
else if ((uint)(c - 'a') <= 'z' - 'a')
{
result = tmp = c - 'a' + 10;
}
else
{
result = -1;
return false;
}
return tmp < radix;
}
}
}
| |
using System;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.MembershipService;
namespace Orleans.Hosting
{
/// <summary>
/// Extensions for <see cref="ISiloHostBuilder"/> instances.
/// </summary>
public static class CoreHostingExtensions
{
/// <summary>
/// Configure the container to use Orleans.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The host builder.</returns>
public static ISiloHostBuilder ConfigureDefaults(this ISiloHostBuilder builder)
{
return builder.ConfigureServices((context, services) =>
{
if (!context.Properties.ContainsKey("OrleansServicesAdded"))
{
services.PostConfigure<SiloOptions>(
options => options.SiloName =
options.SiloName
?? context.HostingEnvironment.ApplicationName
?? $"Silo_{Guid.NewGuid().ToString("N").Substring(0, 5)}");
services.TryAddSingleton<Silo>();
DefaultSiloServices.AddDefaultServices(context.GetApplicationPartManager(), services);
context.Properties.Add("OrleansServicesAdded", true);
}
});
}
/// <summary>
/// Configures the silo to use development-only clustering and listen on localhost.
/// </summary>
/// <param name="builder">The silo builder.</param>
/// <param name="siloPort">The silo port.</param>
/// <param name="gatewayPort">The gateway port.</param>
/// <param name="primarySiloEndpoint">
/// The endpoint of the primary silo, or <see langword="null"/> to use this silo as the primary.
/// </param>
/// <param name="serviceId">The service id.</param>
/// <param name="clusterId">The cluster id.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder UseLocalhostClustering(
this ISiloHostBuilder builder,
int siloPort = EndpointOptions.DEFAULT_SILO_PORT,
int gatewayPort = EndpointOptions.DEFAULT_GATEWAY_PORT,
IPEndPoint primarySiloEndpoint = null,
string serviceId = ClusterOptions.DevelopmentServiceId,
string clusterId = ClusterOptions.DevelopmentClusterId)
{
builder.Configure<EndpointOptions>(options =>
{
options.AdvertisedIPAddress = IPAddress.Loopback;
options.SiloPort = siloPort;
options.GatewayPort = gatewayPort;
});
builder.UseDevelopmentClustering(optionsBuilder => ConfigurePrimarySiloEndpoint(optionsBuilder, primarySiloEndpoint));
builder.Configure<ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
builder.ConfigureServices(services =>
{
// If the caller did not override service id or cluster id, configure default values as a fallback.
if (string.Equals(serviceId, ClusterOptions.DevelopmentServiceId) && string.Equals(clusterId, ClusterOptions.DevelopmentClusterId))
{
services.PostConfigure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId)) options.ClusterId = ClusterOptions.DevelopmentClusterId;
if (string.IsNullOrWhiteSpace(options.ServiceId)) options.ServiceId = ClusterOptions.DevelopmentServiceId;
});
}
else
{
services.Configure<ClusterOptions>(options =>
{
options.ServiceId = serviceId;
options.ClusterId = clusterId;
});
}
});
return builder;
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
/// <param name="builder"></param>
/// <param name="primarySiloEndpoint">
/// The endpoint of the primary silo, or <see langword="null"/> to use this silo as the primary.
/// </param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder UseDevelopmentClustering(this ISiloHostBuilder builder, IPEndPoint primarySiloEndpoint)
{
return builder.UseDevelopmentClustering(optionsBuilder => ConfigurePrimarySiloEndpoint(optionsBuilder, primarySiloEndpoint));
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
public static ISiloHostBuilder UseDevelopmentClustering(
this ISiloHostBuilder builder,
Action<DevelopmentClusterMembershipOptions> configureOptions)
{
return builder.UseDevelopmentClustering(options => options.Configure(configureOptions));
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
public static ISiloHostBuilder UseDevelopmentClustering(
this ISiloHostBuilder builder,
Action<OptionsBuilder<DevelopmentClusterMembershipOptions>> configureOptions)
{
return builder.ConfigureServices(
services =>
{
configureOptions?.Invoke(services.AddOptions<DevelopmentClusterMembershipOptions>());
services.ConfigureFormatter<DevelopmentClusterMembershipOptions>();
services
.AddSingleton<SystemTargetBasedMembershipTable>()
.AddFromExisting<IMembershipTable, SystemTargetBasedMembershipTable>();
});
}
/// <summary>
/// Enables support for interacting with the runtime from an external context. For example, outside the context of a grain.
/// </summary>
[Obsolete("This method is no longer necessary and will be removed in a future release.")]
public static ISiloHostBuilder EnableDirectClient(this ISiloHostBuilder builder)
{
return builder;
}
/// <summary>
/// Configure the container to use Orleans.
/// </summary>
/// <param name="builder">The silo builder.</param>
/// <returns>The silo builder.</returns>
public static ISiloBuilder ConfigureDefaults(this ISiloBuilder builder)
{
return builder.ConfigureServices((context, services) =>
{
if (!context.Properties.ContainsKey("OrleansServicesAdded"))
{
services.PostConfigure<SiloOptions>(
options => options.SiloName =
options.SiloName
?? context.HostingEnvironment.ApplicationName
?? $"Silo_{Guid.NewGuid().ToString("N").Substring(0, 5)}");
services.TryAddSingleton<Silo>();
DefaultSiloServices.AddDefaultServices(context.GetApplicationPartManager(), services);
context.Properties.Add("OrleansServicesAdded", true);
}
});
}
/// <summary>
/// Configures the silo to use development-only clustering and listen on localhost.
/// </summary>
/// <param name="builder">The silo builder.</param>
/// <param name="siloPort">The silo port.</param>
/// <param name="gatewayPort">The gateway port.</param>
/// <param name="primarySiloEndpoint">
/// The endpoint of the primary silo, or <see langword="null"/> to use this silo as the primary.
/// </param>
/// <param name="serviceId">The service id.</param>
/// <param name="clusterId">The cluster id.</param>
/// <returns>The silo builder.</returns>
public static ISiloBuilder UseLocalhostClustering(
this ISiloBuilder builder,
int siloPort = EndpointOptions.DEFAULT_SILO_PORT,
int gatewayPort = EndpointOptions.DEFAULT_GATEWAY_PORT,
IPEndPoint primarySiloEndpoint = null,
string serviceId = ClusterOptions.DevelopmentServiceId,
string clusterId = ClusterOptions.DevelopmentClusterId)
{
builder.Configure<EndpointOptions>(options =>
{
options.AdvertisedIPAddress = IPAddress.Loopback;
options.SiloPort = siloPort;
options.GatewayPort = gatewayPort;
});
builder.UseDevelopmentClustering(optionsBuilder => ConfigurePrimarySiloEndpoint(optionsBuilder, primarySiloEndpoint));
builder.Configure<ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
builder.ConfigureServices(services =>
{
// If the caller did not override service id or cluster id, configure default values as a fallback.
if (string.Equals(serviceId, ClusterOptions.DevelopmentServiceId) && string.Equals(clusterId, ClusterOptions.DevelopmentClusterId))
{
services.PostConfigure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId)) options.ClusterId = ClusterOptions.DevelopmentClusterId;
if (string.IsNullOrWhiteSpace(options.ServiceId)) options.ServiceId = ClusterOptions.DevelopmentServiceId;
});
}
else
{
services.Configure<ClusterOptions>(options =>
{
options.ServiceId = serviceId;
options.ClusterId = clusterId;
});
}
});
return builder;
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
/// <param name="builder"></param>
/// <param name="primarySiloEndpoint">
/// The endpoint of the primary silo, or <see langword="null"/> to use this silo as the primary.
/// </param>
/// <returns>The silo builder.</returns>
public static ISiloBuilder UseDevelopmentClustering(this ISiloBuilder builder, IPEndPoint primarySiloEndpoint)
{
return builder.UseDevelopmentClustering(optionsBuilder => ConfigurePrimarySiloEndpoint(optionsBuilder, primarySiloEndpoint));
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
public static ISiloBuilder UseDevelopmentClustering(
this ISiloBuilder builder,
Action<DevelopmentClusterMembershipOptions> configureOptions)
{
return builder.UseDevelopmentClustering(options => options.Configure(configureOptions));
}
/// <summary>
/// Configures the silo to use development-only clustering.
/// </summary>
public static ISiloBuilder UseDevelopmentClustering(
this ISiloBuilder builder,
Action<OptionsBuilder<DevelopmentClusterMembershipOptions>> configureOptions)
{
return builder.ConfigureServices(
services =>
{
configureOptions?.Invoke(services.AddOptions<DevelopmentClusterMembershipOptions>());
services.ConfigureFormatter<DevelopmentClusterMembershipOptions>();
services
.AddSingleton<SystemTargetBasedMembershipTable>()
.AddFromExisting<IMembershipTable, SystemTargetBasedMembershipTable>();
});
}
/// <summary>
/// Enables support for interacting with the runtime from an external context. For example, outside the context of a grain.
/// </summary>
[Obsolete("This method is no longer necessary and will be removed in a future release.")]
public static ISiloBuilder EnableDirectClient(this ISiloBuilder builder)
{
// Note that this method was added with [Obsolete] to ease migration from ISiloHostBuilder to ISiloBuilder.
return builder;
}
private static void ConfigurePrimarySiloEndpoint(OptionsBuilder<DevelopmentClusterMembershipOptions> optionsBuilder, IPEndPoint primarySiloEndpoint)
{
optionsBuilder.Configure((DevelopmentClusterMembershipOptions options, IOptions<EndpointOptions> endpointOptions) =>
{
if (primarySiloEndpoint is null)
{
primarySiloEndpoint = endpointOptions.Value.GetPublicSiloEndpoint();
}
options.PrimarySiloEndpoint = primarySiloEndpoint;
});
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PolymorphismOperations.
/// </summary>
public static partial class PolymorphismOperationsExtensions
{
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Fish GetValid(this IPolymorphismOperations operations)
{
return Task.Factory.StartNew(s => ((IPolymorphismOperations)s).GetValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Fish> GetValidAsync(this IPolymorphismOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
public static void PutValid(this IPolymorphismOperations operations, Fish complexBody)
{
Task.Factory.StartNew(s => ((IPolymorphismOperations)s).PutValidAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutValidAsync(this IPolymorphismOperations operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
public static void PutValidMissingRequired(this IPolymorphismOperations operations, Fish complexBody)
{
Task.Factory.StartNew(s => ((IPolymorphismOperations)s).PutValidMissingRequiredAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutValidMissingRequiredAsync(this IPolymorphismOperations operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using Nethereum.Signer;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Eth.Transactions;
using Nethereum.Hex.HexTypes;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Nethereum.Contracts;
using Nethereum.Contracts.CQS;
using Nethereum.Contracts.Extensions;
using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.Blocks;
using Nethereum.Util;
using Nethereum.Hex.HexConvertors.Extensions;
namespace Nethereum.JsonRpc.UnityClient
{
public class TransactionSignedUnityRequest : UnityRequest<string>
{
private string _url;
private readonly string _privateKey;
private readonly string _account;
private readonly BigInteger? _chainId;
private readonly LegacyTransactionSigner _transactionSigner;
private readonly EthGetTransactionCountUnityRequest _transactionCountRequest;
private readonly EthSendRawTransactionUnityRequest _ethSendTransactionRequest;
private readonly EthEstimateGasUnityRequest _ethEstimateGasUnityRequest;
private readonly EthGasPriceUnityRequest _ethGasPriceUnityRequest;
public IFee1559SuggestionUnityRequestStrategy Fee1559SuggestionStrategy { get; set; }
public bool EstimateGas { get; set; } = true;
public bool UseLegacyAsDefault { get; set; } = false;
public TransactionSignedUnityRequest(string url, string privateKey, BigInteger? chainId = null, Dictionary<string, string> requestHeaders = null)
{
_chainId = chainId;
_url = url;
_account = EthECKey.GetPublicAddress(privateKey);
_privateKey = privateKey;
_transactionSigner = new LegacyTransactionSigner();
_ethSendTransactionRequest = new EthSendRawTransactionUnityRequest(_url);
_ethSendTransactionRequest.RequestHeaders = requestHeaders;
_transactionCountRequest = new EthGetTransactionCountUnityRequest(_url);
_transactionCountRequest.RequestHeaders = requestHeaders;
_ethEstimateGasUnityRequest = new EthEstimateGasUnityRequest(_url);
_ethEstimateGasUnityRequest.RequestHeaders = requestHeaders;
_ethGasPriceUnityRequest = new EthGasPriceUnityRequest(_url);
_ethGasPriceUnityRequest.RequestHeaders = requestHeaders;
Fee1559SuggestionStrategy = new SimpleFeeSuggestionUnityRequestStrategy(url, requestHeaders);
}
public IEnumerator SignAndSendTransaction<TContractFunction>(TContractFunction function, string contractAdress) where TContractFunction : FunctionMessage
{
var transactionInput = function.CreateTransactionInput(contractAdress);
yield return SignAndSendTransaction(transactionInput);
}
public IEnumerator SignAndSendDeploymentContractTransaction<TDeploymentMessage>(TDeploymentMessage deploymentMessage)
where TDeploymentMessage : ContractDeploymentMessage
{
var transactionInput = deploymentMessage.CreateTransactionInput();
yield return SignAndSendTransaction(transactionInput);
}
public IEnumerator SignAndSendDeploymentContractTransaction<TDeploymentMessage>()
where TDeploymentMessage : ContractDeploymentMessage, new()
{
var deploymentMessage = new TDeploymentMessage();
yield return SignAndSendDeploymentContractTransaction(deploymentMessage);
}
public IEnumerator SignAndSendTransaction(TransactionInput transactionInput)
{
if (transactionInput == null) throw new ArgumentNullException("transactionInput");
if (string.IsNullOrEmpty(transactionInput.From)) transactionInput.From = _account;
if (!transactionInput.From.IsTheSameAddress(_account))
{
throw new Exception("Transaction Input From address does not match private keys address");
}
if (transactionInput.Gas == null)
{
if (EstimateGas)
{
yield return _ethEstimateGasUnityRequest.SendRequest(transactionInput);
if (_ethEstimateGasUnityRequest.Exception == null)
{
var gas = _ethEstimateGasUnityRequest.Result;
transactionInput.Gas = gas;
}
else
{
this.Exception = _ethEstimateGasUnityRequest.Exception;
yield break;
}
}
else
{
transactionInput.Gas = new HexBigInteger(LegacyTransaction.DEFAULT_GAS_LIMIT);
}
}
if (IsTransactionToBeSendAsEIP1559(transactionInput))
{
transactionInput.Type = new HexBigInteger(TransactionType.EIP1559.AsByte());
if (transactionInput.MaxPriorityFeePerGas != null)
{
if (transactionInput.MaxFeePerGas == null)
{
yield return Fee1559SuggestionStrategy.SuggestFee(transactionInput.MaxPriorityFeePerGas.Value);
if (Fee1559SuggestionStrategy.Exception != null)
{
transactionInput.MaxFeePerGas = new HexBigInteger(Fee1559SuggestionStrategy.Result.MaxFeePerGas.Value);
}
else
{
this.Exception = Fee1559SuggestionStrategy.Exception;
yield break;
}
}
}
else
{
yield return Fee1559SuggestionStrategy.SuggestFee();
if (Fee1559SuggestionStrategy.Exception != null)
{
if (transactionInput.MaxFeePerGas == null)
{
transactionInput.MaxFeePerGas =
new HexBigInteger(Fee1559SuggestionStrategy.Result.MaxFeePerGas.Value);
transactionInput.MaxPriorityFeePerGas =
new HexBigInteger(Fee1559SuggestionStrategy.Result.MaxPriorityFeePerGas.Value);
}
else
{
if (transactionInput.MaxFeePerGas < Fee1559SuggestionStrategy.Result.MaxPriorityFeePerGas)
{
transactionInput.MaxPriorityFeePerGas = transactionInput.MaxFeePerGas;
}
else
{
transactionInput.MaxPriorityFeePerGas = new HexBigInteger(Fee1559SuggestionStrategy.Result.MaxPriorityFeePerGas.Value);
}
}
}
else
{
this.Exception = Fee1559SuggestionStrategy.Exception;
yield break;
}
}
}
else
{
if (transactionInput.GasPrice == null)
{
yield return _ethGasPriceUnityRequest.SendRequest();
if (_ethGasPriceUnityRequest.Exception == null)
{
var gasPrice = _ethGasPriceUnityRequest.Result;
transactionInput.GasPrice = gasPrice;
}
else
{
this.Exception = _ethGasPriceUnityRequest.Exception;
yield break;
}
}
}
var nonce = transactionInput.Nonce;
if (nonce == null)
{
yield return _transactionCountRequest.SendRequest(_account, Nethereum.RPC.Eth.DTOs.BlockParameter.CreateLatest());
if (_transactionCountRequest.Exception == null)
{
nonce = _transactionCountRequest.Result;
}
else
{
this.Exception = _transactionCountRequest.Exception;
yield break;
}
}
var value = transactionInput.Value;
if (value == null)
value = new HexBigInteger(0);
string signedTransaction;
if (IsTransactionToBeSendAsEIP1559(transactionInput))
{
var transaction1559 = new Transaction1559(_chainId.Value, nonce, transactionInput.MaxPriorityFeePerGas.Value, transactionInput.MaxFeePerGas.Value,
transactionInput.Gas.Value, transactionInput.To, value.Value, transactionInput.Data,
null);
transaction1559.Sign(new EthECKey(_privateKey));
signedTransaction = transaction1559.GetRLPEncoded().ToHex();
}
else
{
if (_chainId == null)
{
signedTransaction = _transactionSigner.SignTransaction(_privateKey, transactionInput.To, value.Value, nonce,
transactionInput.GasPrice.Value, transactionInput.Gas.Value, transactionInput.Data);
}
else
{
signedTransaction = _transactionSigner.SignTransaction(_privateKey, _chainId.Value, transactionInput.To, value.Value, nonce,
transactionInput.GasPrice.Value, transactionInput.Gas.Value, transactionInput.Data);
}
}
yield return _ethSendTransactionRequest.SendRequest(signedTransaction);
if (_ethSendTransactionRequest.Exception == null)
{
this.Result = _ethSendTransactionRequest.Result;
}
else
{
this.Exception = _ethSendTransactionRequest.Exception;
yield break;
}
}
public bool IsTransactionToBeSendAsEIP1559(TransactionInput transaction)
{
return (!UseLegacyAsDefault && transaction.GasPrice == null) || (transaction.MaxPriorityFeePerGas != null) || (transaction.Type != null && transaction.Type.Value == TransactionType.EIP1559.AsByte());
}
}
}
| |
// 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 global::System;
using global::System.Diagnostics;
using global::System.Collections;
using global::System.Reflection;
using global::System.Collections.Generic;
using global::System.Reflection.Runtime.General;
using global::System.Reflection.Runtime.TypeInfos;
using global::System.Reflection.Runtime.Assemblies;
using global::Internal.Metadata.NativeFormat;
using global::Internal.Reflection.Core;
using global::Internal.Reflection.Core.NonPortable;
namespace System.Reflection.Runtime.TypeParsing
{
//
// The TypeName class is the base class for a family of types that represent the nodes in a parse tree for
// assembly-qualified type names.
//
internal abstract class TypeName
{
public abstract Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result);
public abstract override String ToString();
}
//
// Represents a parse of a type name OPTIONALLY qualified by an assembly name. If present, the assembly name follows
// a comma following the type name.
//
// Note that unlike the reflection model, the assembly qualification is a property of a typename string as a whole
// rather than the property of the single namespace type that "represents" the type. This model is simply a better match to
// how type names passed to GetType() are constructed and parsed.
//
internal sealed class AssemblyQualifiedTypeName : TypeName
{
public AssemblyQualifiedTypeName(NonQualifiedTypeName typeName, RuntimeAssemblyName assemblyName)
{
Debug.Assert(typeName != null);
TypeName = typeName;
AssemblyName = assemblyName;
}
public NonQualifiedTypeName TypeName { get; private set; }
public RuntimeAssemblyName AssemblyName { get; private set; } // This can return null if the type name was not actually qualified.
public sealed override String ToString()
{
return TypeName.ToString() + ((AssemblyName == null) ? "" : ", " + AssemblyName.FullName);
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
if (AssemblyName == null)
{
return TypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out result);
}
else
{
RuntimeAssembly newAssembly;
Exception assemblyLoadException = RuntimeAssembly.TryGetRuntimeAssembly(reflectionDomain, AssemblyName, out newAssembly);
if (assemblyLoadException != null)
return assemblyLoadException;
return TypeName.TryResolve(reflectionDomain, newAssembly, ignoreCase, out result);
}
}
}
//
// Base class for all non-assembly-qualified type names.
//
internal abstract class NonQualifiedTypeName : TypeName
{
}
//
// Base class for namespace or nested type.
//
internal abstract class NamedTypeName : NonQualifiedTypeName
{
}
//
// Non-nested named type. The full name is the namespace-qualified name. For example, the FullName for
// System.Collections.Generic.IList<> is "System.Collections.Generic.IList`1".
//
internal sealed partial class NamespaceTypeName : NamedTypeName
{
public NamespaceTypeName(String[] namespaceParts, String name)
{
Debug.Assert(namespaceParts != null);
Debug.Assert(name != null);
_name = name;
_namespaceParts = namespaceParts;
}
public sealed override String ToString()
{
String fullName = "";
for (int i = 0; i < _namespaceParts.Length; i++)
{
fullName += _namespaceParts[_namespaceParts.Length - i - 1];
fullName += ".";
}
fullName += _name;
return fullName;
}
private bool TryResolveNamespaceDefinitionCaseSensitive(MetadataReader reader, ScopeDefinitionHandle scopeDefinitionHandle, out NamespaceDefinition namespaceDefinition)
{
namespaceDefinition = scopeDefinitionHandle.GetScopeDefinition(reader).RootNamespaceDefinition.GetNamespaceDefinition(reader);
IEnumerable<NamespaceDefinitionHandle> candidates = namespaceDefinition.NamespaceDefinitions;
int idx = _namespaceParts.Length;
while (idx-- != 0)
{
// Each iteration finds a match for one segment of the namespace chain.
String expected = _namespaceParts[idx];
bool foundMatch = false;
foreach (NamespaceDefinitionHandle candidate in candidates)
{
namespaceDefinition = candidate.GetNamespaceDefinition(reader);
if (namespaceDefinition.Name.StringOrNullEquals(expected, reader))
{
// Found a match for this segment of the namespace chain. Move on to the next level.
foundMatch = true;
candidates = namespaceDefinition.NamespaceDefinitions;
break;
}
}
if (!foundMatch)
{
return false;
}
}
return true;
}
private Exception UncachedTryResolveCaseSensitive(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, out RuntimeType result)
{
result = null;
foreach (QScopeDefinition scopeDefinition in currentAssembly.AllScopes)
{
MetadataReader reader = scopeDefinition.Reader;
ScopeDefinitionHandle scopeDefinitionHandle = scopeDefinition.Handle;
NamespaceDefinition namespaceDefinition;
if (!TryResolveNamespaceDefinitionCaseSensitive(reader, scopeDefinitionHandle, out namespaceDefinition))
{
continue;
}
// We've successfully drilled down the namespace chain. Now look for a top-level type matching the type name.
IEnumerable<TypeDefinitionHandle> candidateTypes = namespaceDefinition.TypeDefinitions;
foreach (TypeDefinitionHandle candidateType in candidateTypes)
{
TypeDefinition typeDefinition = candidateType.GetTypeDefinition(reader);
if (typeDefinition.Name.StringEquals(_name, reader))
{
result = reflectionDomain.ResolveTypeDefinition(reader, candidateType);
return null;
}
}
// No match found in this assembly - see if there's a matching type forwarder.
IEnumerable<TypeForwarderHandle> candidateTypeForwarders = namespaceDefinition.TypeForwarders;
foreach (TypeForwarderHandle typeForwarderHandle in candidateTypeForwarders)
{
TypeForwarder typeForwarder = typeForwarderHandle.GetTypeForwarder(reader);
if (typeForwarder.Name.StringEquals(_name, reader))
{
RuntimeAssemblyName redirectedAssemblyName = typeForwarder.Scope.ToRuntimeAssemblyName(reader);
AssemblyQualifiedTypeName redirectedTypeName = new AssemblyQualifiedTypeName(this, redirectedAssemblyName);
return redirectedTypeName.TryResolve(reflectionDomain, null, /*ignoreCase: */false, out result);
}
}
}
{
String typeName = this.ToString();
String message = SR.Format(SR.TypeLoad_TypeNotFound, typeName, currentAssembly.FullName);
return ReflectionCoreNonPortable.CreateTypeLoadException(message, typeName);
}
}
private Exception TryResolveCaseInsensitive(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, out RuntimeType result)
{
String fullName = this.ToString().ToLower();
LowLevelDictionary<String, QHandle> dict = GetCaseInsensitiveTypeDictionary(currentAssembly);
QHandle qualifiedHandle;
if (!dict.TryGetValue(fullName, out qualifiedHandle))
{
result = null;
return new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, this.ToString(), currentAssembly.FullName));
}
MetadataReader reader = qualifiedHandle.Reader;
Handle typeDefOrForwarderHandle = qualifiedHandle.Handle;
HandleType handleType = typeDefOrForwarderHandle.HandleType;
switch (handleType)
{
case HandleType.TypeDefinition:
{
TypeDefinitionHandle typeDefinitionHandle = typeDefOrForwarderHandle.ToTypeDefinitionHandle(reader);
result = reflectionDomain.ResolveTypeDefinition(reader, typeDefinitionHandle);
return null;
}
case HandleType.TypeForwarder:
{
TypeForwarder typeForwarder = typeDefOrForwarderHandle.ToTypeForwarderHandle(reader).GetTypeForwarder(reader);
ScopeReferenceHandle destinationScope = typeForwarder.Scope;
RuntimeAssemblyName destinationAssemblyName = destinationScope.ToRuntimeAssemblyName(reader);
RuntimeAssembly destinationAssembly;
Exception exception = RuntimeAssembly.TryGetRuntimeAssembly(reflectionDomain, destinationAssemblyName, out destinationAssembly);
if (exception != null)
{
result = null;
return exception;
}
return TryResolveCaseInsensitive(reflectionDomain, destinationAssembly, out result);
}
default:
throw new InvalidOperationException();
}
}
private static LowLevelDictionary<String, QHandle> CreateCaseInsensitiveTypeDictionary(RuntimeAssembly assembly)
{
//
// Collect all of the *non-nested* types and type-forwards.
//
// The keys are full typenames in lower-cased form.
// The value is a tuple containing either a TypeDefinitionHandle or TypeForwarderHandle and the associated Reader
// for that handle.
//
// We do not store nested types here. The container type is resolved and chosen first, then the nested type chosen from
// that. If we chose the wrong container type and fail the match as a result, that's too bad. (The desktop CLR has the
// same issue.)
//
ReflectionDomain reflectionDomain = assembly.ReflectionDomain;
LowLevelDictionary<String, QHandle> dict = new LowLevelDictionary<string, QHandle>();
foreach (QScopeDefinition scope in assembly.AllScopes)
{
MetadataReader reader = scope.Reader;
ScopeDefinition scopeDefinition = scope.ScopeDefinition;
IEnumerable<NamespaceDefinitionHandle> topLevelNamespaceHandles = new NamespaceDefinitionHandle[] { scopeDefinition.RootNamespaceDefinition };
IEnumerable<NamespaceDefinitionHandle> allNamespaceHandles = reader.GetTransitiveNamespaces(topLevelNamespaceHandles);
foreach (NamespaceDefinitionHandle namespaceHandle in allNamespaceHandles)
{
String ns = namespaceHandle.ToNamespaceName(reader);
if (ns.Length != 0)
ns = ns + ".";
ns = ns.ToLower();
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions)
{
String fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLower();
QHandle existingValue;
if (!dict.TryGetValue(fullName, out existingValue))
{
dict.Add(fullName, new QHandle(reader, typeDefinitionHandle));
}
}
foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders)
{
String fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLower();
QHandle existingValue;
if (!dict.TryGetValue(fullName, out existingValue))
{
dict.Add(fullName, new QHandle(reader, typeForwarderHandle));
}
}
}
}
return dict;
}
private String _name;
private String[] _namespaceParts;
}
//
// A nested type. The Name is the simple name of the type (not including any portion of its declaring type name.
//
internal sealed class NestedTypeName : NamedTypeName
{
public NestedTypeName(String name, NamedTypeName declaringType)
{
Name = name;
DeclaringType = declaringType;
}
public String Name { get; private set; }
public NamedTypeName DeclaringType { get; private set; }
public sealed override String ToString()
{
return DeclaringType + "+" + Name;
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType declaringType;
Exception typeLoadException = DeclaringType.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out declaringType);
if (typeLoadException != null)
return typeLoadException;
TypeInfo nestedTypeInfo = FindDeclaredNestedType(declaringType.GetTypeInfo(), Name, ignoreCase);
if (nestedTypeInfo == null)
return new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, declaringType.FullName + "+" + Name, currentAssembly.FullName));
result = (RuntimeType)(nestedTypeInfo.AsType());
return null;
}
private TypeInfo FindDeclaredNestedType(TypeInfo declaringTypeInfo, String name, bool ignoreCase)
{
TypeInfo nestedType = declaringTypeInfo.GetDeclaredNestedType(name);
if (nestedType != null)
return nestedType;
if (!ignoreCase)
return null;
//
// Desktop compat note: If there is more than one nested type that matches the name in a case-blind match,
// we might not return the same one that the desktop returns. The actual selection method is influenced both by the type's
// placement in the IL and the implementation details of the CLR's internal hashtables so it would be very
// hard to replicate here.
//
// Desktop compat note #2: Case-insensitive lookups: If we don't find a match, we do *not* go back and search
// other declaring types that might match the case-insensitive search and contain the nested type being sought.
// Though this is somewhat unsatisfactory, the desktop CLR has the same limitation.
//
foreach (TypeInfo candidate in declaringTypeInfo.DeclaredNestedTypes)
{
String candidateName = candidate.Name;
if (name.Equals(candidateName, StringComparison.OrdinalIgnoreCase))
return candidate;
}
return null;
}
}
//
// Abstract base for array, byref and pointer type names.
//
internal abstract class HasElementTypeName : NonQualifiedTypeName
{
public HasElementTypeName(TypeName elementTypeName)
{
ElementTypeName = elementTypeName;
}
public TypeName ElementTypeName { get; private set; }
}
//
// A single-dimensional zero-lower-bound array type name.
//
internal sealed class ArrayTypeName : HasElementTypeName
{
public ArrayTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override String ToString()
{
return ElementTypeName + "[]";
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType elementType;
Exception typeLoadException = ElementTypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out elementType);
if (typeLoadException != null)
return typeLoadException;
result = ReflectionCoreNonPortable.GetArrayType(elementType);
return null;
}
}
//
// A multidim array type name.
//
internal sealed class MultiDimArrayTypeName : HasElementTypeName
{
public MultiDimArrayTypeName(TypeName elementTypeName, int rank)
: base(elementTypeName)
{
_rank = rank;
}
public sealed override String ToString()
{
return ElementTypeName + "[" + (_rank == 1 ? "*" : new String(',', _rank - 1)) + "]";
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType elementType;
Exception typeLoadException = ElementTypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out elementType);
if (typeLoadException != null)
return typeLoadException;
result = ReflectionCoreNonPortable.GetMultiDimArrayType(elementType, _rank);
return null;
}
private int _rank;
}
//
// A byref type.
//
internal sealed class ByRefTypeName : HasElementTypeName
{
public ByRefTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override String ToString()
{
return ElementTypeName + "&";
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType elementType;
Exception typeLoadException = ElementTypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out elementType);
if (typeLoadException != null)
return typeLoadException;
result = ReflectionCoreNonPortable.GetByRefType(elementType);
return null;
}
}
//
// A pointer type.
//
internal sealed class PointerTypeName : HasElementTypeName
{
public PointerTypeName(TypeName elementTypeName)
: base(elementTypeName)
{
}
public sealed override String ToString()
{
return ElementTypeName + "*";
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType elementType;
Exception typeLoadException = ElementTypeName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out elementType);
if (typeLoadException != null)
return typeLoadException;
result = ReflectionCoreNonPortable.GetPointerType(elementType);
return null;
}
}
//
// A constructed generic type.
//
internal sealed class ConstructedGenericTypeName : NonQualifiedTypeName
{
public ConstructedGenericTypeName(NamedTypeName genericType, IEnumerable<TypeName> genericArguments)
{
GenericType = genericType;
GenericArguments = genericArguments;
}
public NamedTypeName GenericType { get; private set; }
public IEnumerable<TypeName> GenericArguments { get; private set; }
public sealed override String ToString()
{
String s = GenericType.ToString();
s += "[";
String sep = "";
foreach (TypeName genericTypeArgument in GenericArguments)
{
s += sep;
sep = ",";
AssemblyQualifiedTypeName assemblyQualifiedTypeArgument = genericTypeArgument as AssemblyQualifiedTypeName;
if (assemblyQualifiedTypeArgument == null || assemblyQualifiedTypeArgument.AssemblyName == null)
s += genericTypeArgument.ToString();
else
s += "[" + genericTypeArgument.ToString() + "]";
}
s += "]";
return s;
}
public sealed override Exception TryResolve(ReflectionDomain reflectionDomain, RuntimeAssembly currentAssembly, bool ignoreCase, out RuntimeType result)
{
result = null;
RuntimeType genericType;
Exception typeLoadException = GenericType.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out genericType);
if (typeLoadException != null)
return typeLoadException;
LowLevelList<RuntimeType> genericTypeArguments = new LowLevelList<RuntimeType>();
foreach (TypeName genericTypeArgumentName in GenericArguments)
{
RuntimeType genericTypeArgument;
typeLoadException = genericTypeArgumentName.TryResolve(reflectionDomain, currentAssembly, ignoreCase, out genericTypeArgument);
if (typeLoadException != null)
return typeLoadException;
genericTypeArguments.Add(genericTypeArgument);
}
result = ReflectionCoreNonPortable.GetConstructedGenericType(genericType, genericTypeArguments.ToArray());
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an array with all values
/// </summary>
public static double[] Values(dquat q) => q.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<double> GetEnumerator(dquat q) => q.GetEnumerator();
/// <summary>
/// Returns a string representation of this quaternion using ', ' as a seperator.
/// </summary>
public static string ToString(dquat q) => q.ToString();
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator.
/// </summary>
public static string ToString(dquat q, string sep) => q.ToString(sep);
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(dquat q, string sep, IFormatProvider provider) => q.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format for each component.
/// </summary>
public static string ToString(dquat q, string sep, string format) => q.ToString(sep, format);
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(dquat q, string sep, string format, IFormatProvider provider) => q.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (4).
/// </summary>
public static int Count(dquat q) => q.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(dquat q, dquat rhs) => q.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(dquat q, object obj) => q.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(dquat q) => q.GetHashCode();
/// <summary>
/// Returns a bvec4 from component-wise application of IsInfinity (double.IsInfinity(v)).
/// </summary>
public static bvec4 IsInfinity(dquat v) => dquat.IsInfinity(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsFinite (!double.IsNaN(v) && !double.IsInfinity(v)).
/// </summary>
public static bvec4 IsFinite(dquat v) => dquat.IsFinite(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsNaN (double.IsNaN(v)).
/// </summary>
public static bvec4 IsNaN(dquat v) => dquat.IsNaN(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)).
/// </summary>
public static bvec4 IsNegativeInfinity(dquat v) => dquat.IsNegativeInfinity(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)).
/// </summary>
public static bvec4 IsPositiveInfinity(dquat v) => dquat.IsPositiveInfinity(v);
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(dquat lhs, dquat rhs) => dquat.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(dquat lhs, dquat rhs) => dquat.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(dquat lhs, dquat rhs) => dquat.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(dquat lhs, dquat rhs) => dquat.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(dquat lhs, dquat rhs) => dquat.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(dquat lhs, dquat rhs) => dquat.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two quaternions.
/// </summary>
public static double Dot(dquat lhs, dquat rhs) => dquat.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean length of this quaternion.
/// </summary>
public static double Length(dquat q) => q.Length;
/// <summary>
/// Returns the squared euclidean length of this quaternion.
/// </summary>
public static double LengthSqr(dquat q) => q.LengthSqr;
/// <summary>
/// Returns a copy of this quaternion with length one (undefined if this has zero length).
/// </summary>
public static dquat Normalized(dquat q) => q.Normalized;
/// <summary>
/// Returns a copy of this quaternion with length one (returns zero if length is zero).
/// </summary>
public static dquat NormalizedSafe(dquat q) => q.NormalizedSafe;
/// <summary>
/// Returns the represented angle of this quaternion.
/// </summary>
public static double Angle(dquat q) => q.Angle;
/// <summary>
/// Returns the represented axis of this quaternion.
/// </summary>
public static dvec3 Axis(dquat q) => q.Axis;
/// <summary>
/// Returns the represented yaw angle of this quaternion.
/// </summary>
public static double Yaw(dquat q) => q.Yaw;
/// <summary>
/// Returns the represented pitch angle of this quaternion.
/// </summary>
public static double Pitch(dquat q) => q.Pitch;
/// <summary>
/// Returns the represented roll angle of this quaternion.
/// </summary>
public static double Roll(dquat q) => q.Roll;
/// <summary>
/// Returns the represented euler angles (pitch, yaw, roll) of this quaternion.
/// </summary>
public static dvec3 EulerAngles(dquat q) => q.EulerAngles;
/// <summary>
/// Rotates this quaternion from an axis and an angle (in radians).
/// </summary>
public static dquat Rotated(dquat q, double angle, dvec3 v) => q.Rotated(angle, v);
/// <summary>
/// Creates a dmat3 that realizes the rotation of this quaternion
/// </summary>
public static dmat3 ToMat3(dquat q) => q.ToMat3;
/// <summary>
/// Creates a dmat4 that realizes the rotation of this quaternion
/// </summary>
public static dmat4 ToMat4(dquat q) => q.ToMat4;
/// <summary>
/// Returns the conjugated quaternion
/// </summary>
public static dquat Conjugate(dquat q) => q.Conjugate;
/// <summary>
/// Returns the inverse quaternion
/// </summary>
public static dquat Inverse(dquat q) => q.Inverse;
/// <summary>
/// Returns the cross product between two quaternions.
/// </summary>
public static dquat Cross(dquat q1, dquat q2) => dquat.Cross(q1, q2);
/// <summary>
/// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions).
/// </summary>
public static dquat Mix(dquat x, dquat y, double a) => dquat.Mix(x, y, a);
/// <summary>
/// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions).
/// </summary>
public static dquat SLerp(dquat x, dquat y, double a) => dquat.SLerp(x, y, a);
/// <summary>
/// Applies squad interpolation of these quaternions
/// </summary>
public static dquat Squad(dquat q1, dquat q2, dquat s1, dquat s2, double h) => dquat.Squad(q1, q2, s1, s2, h);
/// <summary>
/// Returns a dquat from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static dquat Lerp(dquat min, dquat max, dquat a) => dquat.Lerp(min, max, a);
}
}
| |
// 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.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Data.SqlClient
{
internal sealed partial class SNILoadHandle : SafeHandle
{
internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher);
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher);
private readonly uint _sniStatus = TdsEnums.SNI_UNINITIALIZED;
private readonly EncryptionOptions _encryptionOption;
private SNILoadHandle() : base(IntPtr.Zero, true)
{
// From security review - SafeHandle guarantees this is only called once.
// The reason for the safehandle is guaranteed initialization and termination of SNI to
// ensure SNI terminates and cleans up properly.
try { }
finally
{
_sniStatus = SNINativeMethodWrapper.SNIInitialize();
uint value = 0;
// VSDevDiv 479597: If initialize fails, don't call QueryInfo.
if (TdsEnums.SNI_SUCCESS == _sniStatus)
{
// Query OS to find out whether encryption is supported.
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value);
}
_encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF;
base.handle = (IntPtr)1; // Initialize to non-zero dummy variable.
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
if (base.handle != IntPtr.Zero)
{
if (TdsEnums.SNI_SUCCESS == _sniStatus)
{
LocalDBAPI.ReleaseDLLHandles();
SNINativeMethodWrapper.SNITerminate();
}
base.handle = IntPtr.Zero;
}
return true;
}
public uint Status
{
get
{
return _sniStatus;
}
}
public EncryptionOptions Options
{
get
{
return _encryptionOption;
}
}
private static void ReadDispatcher(IntPtr key, IntPtr packet, uint error)
{
// This is the app-domain dispatcher for all async read callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's read callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?");
if (IntPtr.Zero != key)
{
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj)
{
stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
private static void WriteDispatcher(IntPtr key, IntPtr packet, uint error)
{
// This is the app-domain dispatcher for all async write callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's write callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?");
if (IntPtr.Zero != key)
{
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj)
{
stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
}
internal sealed class SNIHandle : SafeHandle
{
private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
private readonly bool _fSync = false;
// creates a physical connection
internal SNIHandle(
SNINativeMethodWrapper.ConsumerInfo myInfo,
string serverName,
byte[] spnBuffer,
bool ignoreSniOpenTimeout,
int timeout,
out byte[] instanceName,
bool flushCache,
bool fSync,
bool fParallel)
: base(IntPtr.Zero, true)
{
try { }
finally
{
_fSync = fSync;
instanceName = new byte[256]; // Size as specified by netlibs.
if (ignoreSniOpenTimeout)
{
timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
}
_status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
spnBuffer, instanceName, flushCache, fSync, timeout, fParallel);
}
}
// constructs SNI Handle for MARS session
internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true)
{
try { }
finally
{
_status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr)
{
if (0 != SNINativeMethodWrapper.SNIClose(ptr))
{
return false; // SNIClose should never fail.
}
}
return true;
}
internal uint Status
{
get
{
return _status;
}
}
}
internal sealed class SNIPacket : SafeHandle
{
internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true)
{
SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
if (IntPtr.Zero == base.handle)
{
throw SQL.SNIPacketAllocationFailure();
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr)
{
SNINativeMethodWrapper.SNIPacketRelease(ptr);
}
return true;
}
}
internal sealed class WritePacketCache : IDisposable
{
private bool _disposed;
private Stack<SNIPacket> _packets;
public WritePacketCache()
{
_disposed = false;
_packets = new Stack<SNIPacket>();
}
public SNIPacket Take(SNIHandle sniHandle)
{
SNIPacket packet;
if (_packets.Count > 0)
{
// Success - reset the packet
packet = _packets.Pop();
SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
}
else
{
// Failed to take a packet - create a new one
packet = new SNIPacket(sniHandle);
}
return packet;
}
public void Add(SNIPacket packet)
{
if (!_disposed)
{
_packets.Push(packet);
}
else
{
// If we're disposed, then get rid of any packets added to us
packet.Dispose();
}
}
public void Clear()
{
while (_packets.Count > 0)
{
_packets.Pop().Dispose();
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Clear();
}
}
}
}
| |
// 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.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.XPath;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.Xslt
{
using TypeFactory = XmlQueryTypeFactory;
#if DEBUG
using XmlILTrace = System.Xml.Xsl.IlGen.XmlILTrace;
#endif
internal enum XslVersion
{
Version10 = 0,
ForwardsCompatible = 1,
Current = Version10,
}
// RootLevel is underdeveloped consept currently. I plane to move here more collections from Compiler.
// Compiler is like a stylesheet in some sense. it has a lot of properties of stylesheet. Instead of
// inhereting from Styleseet (or StylesheetLevel) I desided to agregate special subclass of StylesheetLevel.
// One more reason to for this design is to normolize apply-templates and apply-imports to one concept:
// apply-templates is apply-imports(compiler.Root).
// For now I don't create new files for these new classes to simplify integrations WebData <-> WebData_xsl
internal class RootLevel : StylesheetLevel
{
public RootLevel(Stylesheet principal)
{
base.Imports = new Stylesheet[] { principal };
}
}
internal class Compiler
{
public XsltSettings Settings;
public bool IsDebug;
public string ScriptAssemblyPath;
public int Version; // 0 - Auto; 1 - XSLT 1.0; 2 - XSLT 2.0
public string inputTypeAnnotations; // null - "unspecified"; "preserve"; "strip"
public CompilerResults CompilerResults; // Results of the compilation
public int CurrentPrecedence = 0; // Decreases by 1 with each import
public XslNode StartApplyTemplates;
public RootLevel Root;
public Scripts Scripts;
public Output Output = new Output();
public List<VarPar> ExternalPars = new List<VarPar>();
public List<VarPar> GlobalVars = new List<VarPar>();
public List<WhitespaceRule> WhitespaceRules = new List<WhitespaceRule>();
public DecimalFormats DecimalFormats = new DecimalFormats();
public Keys Keys = new Keys();
public List<ProtoTemplate> AllTemplates = new List<ProtoTemplate>();
public Dictionary<QilName, VarPar> AllGlobalVarPars = new Dictionary<QilName, VarPar>();
public Dictionary<QilName, Template> NamedTemplates = new Dictionary<QilName, Template>();
public Dictionary<QilName, AttributeSet> AttributeSets = new Dictionary<QilName, AttributeSet>();
public Dictionary<string, NsAlias> NsAliases = new Dictionary<string, NsAlias>();
private Dictionary<string, int> _moduleOrder = new Dictionary<string, int>();
public Compiler(XsltSettings settings, bool debug, string scriptAssemblyPath)
{
Debug.Assert(CompilerResults == null, "Compiler cannot be reused");
// Keep all intermediate files if tracing is enabled
TempFileCollection tempFiles = settings.TempFiles ?? new TempFileCollection();
#if DEBUG
if (XmlILTrace.IsEnabled) {
tempFiles.KeepFiles = true;
}
#endif
Settings = settings;
IsDebug = settings.IncludeDebugInformation | debug;
ScriptAssemblyPath = scriptAssemblyPath;
CompilerResults = new CompilerResults(tempFiles);
Scripts = new Scripts(this);
}
public CompilerResults Compile(object stylesheet, XmlResolver xmlResolver, out QilExpression qil)
{
Debug.Assert(stylesheet != null);
Debug.Assert(Root == null, "Compiler cannot be reused");
new XsltLoader().Load(this, stylesheet, xmlResolver);
qil = QilGenerator.CompileStylesheet(this);
SortErrors();
return CompilerResults;
}
public Stylesheet CreateStylesheet()
{
Stylesheet sheet = new Stylesheet(this, CurrentPrecedence);
if (CurrentPrecedence-- == 0)
{
Root = new RootLevel(sheet);
}
return sheet;
}
public void AddModule(string baseUri)
{
if (!_moduleOrder.ContainsKey(baseUri))
{
_moduleOrder[baseUri] = _moduleOrder.Count;
}
}
public void ApplyNsAliases(ref string prefix, ref string nsUri)
{
NsAlias alias;
if (NsAliases.TryGetValue(nsUri, out alias))
{
nsUri = alias.ResultNsUri;
prefix = alias.ResultPrefix;
}
}
// Returns true in case of redefinition
public bool SetNsAlias(string ssheetNsUri, string resultNsUri, string resultPrefix, int importPrecedence)
{
NsAlias oldNsAlias;
if (NsAliases.TryGetValue(ssheetNsUri, out oldNsAlias))
{
// Namespace alias for this stylesheet namespace URI has already been defined
Debug.Assert(importPrecedence <= oldNsAlias.ImportPrecedence, "Stylesheets must be processed in the order of decreasing import precedence");
if (importPrecedence < oldNsAlias.ImportPrecedence || resultNsUri == oldNsAlias.ResultNsUri)
{
// Either the identical definition or lower precedence - ignore it
return false;
}
// Recover by choosing the declaration that occurs later in the stylesheet
}
NsAliases[ssheetNsUri] = new NsAlias(resultNsUri, resultPrefix, importPrecedence);
return oldNsAlias != null;
}
private void MergeWhitespaceRules(Stylesheet sheet)
{
for (int idx = 0; idx <= 2; idx++)
{
sheet.WhitespaceRules[idx].Reverse();
this.WhitespaceRules.AddRange(sheet.WhitespaceRules[idx]);
}
sheet.WhitespaceRules = null;
}
private void MergeAttributeSets(Stylesheet sheet)
{
foreach (QilName attSetName in sheet.AttributeSets.Keys)
{
AttributeSet attSet;
if (!this.AttributeSets.TryGetValue(attSetName, out attSet))
{
this.AttributeSets[attSetName] = sheet.AttributeSets[attSetName];
}
else
{
// Lower import precedence - insert before all previous definitions
attSet.MergeContent(sheet.AttributeSets[attSetName]);
}
}
sheet.AttributeSets = null;
}
private void MergeGlobalVarPars(Stylesheet sheet)
{
foreach (VarPar var in sheet.GlobalVarPars)
{
Debug.Assert(var.NodeType == XslNodeType.Variable || var.NodeType == XslNodeType.Param);
if (!AllGlobalVarPars.ContainsKey(var.Name))
{
if (var.NodeType == XslNodeType.Variable)
{
GlobalVars.Add(var);
}
else
{
ExternalPars.Add(var);
}
AllGlobalVarPars[var.Name] = var;
}
}
sheet.GlobalVarPars = null;
}
public void MergeWithStylesheet(Stylesheet sheet)
{
MergeWhitespaceRules(sheet);
MergeAttributeSets(sheet);
MergeGlobalVarPars(sheet);
}
public static string ConstructQName(string prefix, string localName)
{
if (prefix.Length == 0)
{
return localName;
}
else
{
return prefix + ':' + localName;
}
}
public bool ParseQName(string qname, out string prefix, out string localName, IErrorHelper errorHelper)
{
Debug.Assert(qname != null);
try
{
ValidateNames.ParseQNameThrow(qname, out prefix, out localName);
return true;
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_042]*/e.Message, null);
prefix = PhantomNCName;
localName = PhantomNCName;
return false;
}
}
public bool ParseNameTest(string nameTest, out string prefix, out string localName, IErrorHelper errorHelper)
{
Debug.Assert(nameTest != null);
try
{
ValidateNames.ParseNameTestThrow(nameTest, out prefix, out localName);
return true;
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_043]*/e.Message, null);
prefix = PhantomNCName;
localName = PhantomNCName;
return false;
}
}
public void ValidatePiName(string name, IErrorHelper errorHelper)
{
Debug.Assert(name != null);
try
{
ValidateNames.ValidateNameThrow(
/*prefix:*/string.Empty, /*localName:*/name, /*ns:*/string.Empty,
XPathNodeType.ProcessingInstruction, ValidateNames.Flags.AllExceptPrefixMapping
);
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_044]*/e.Message, null);
}
}
public readonly string PhantomNCName = "error";
private int _phantomNsCounter = 0;
public string CreatePhantomNamespace()
{
// Prepend invalid XmlChar to ensure this name would not clash with any namespace name in the stylesheet
return "\0namespace" + _phantomNsCounter++;
}
public bool IsPhantomNamespace(string namespaceName)
{
return namespaceName.Length > 0 && namespaceName[0] == '\0';
}
public bool IsPhantomName(QilName qname)
{
string nsUri = qname.NamespaceUri;
return nsUri.Length > 0 && nsUri[0] == '\0';
}
// -------------------------------- Error Handling --------------------------------
private int ErrorCount
{
get
{
return CompilerResults.Errors.Count;
}
set
{
Debug.Assert(value <= ErrorCount);
for (int idx = ErrorCount - 1; idx >= value; idx--)
{
CompilerResults.Errors.RemoveAt(idx);
}
}
}
private int _savedErrorCount = -1;
public void EnterForwardsCompatible()
{
Debug.Assert(_savedErrorCount == -1, "Nested EnterForwardsCompatible calls");
_savedErrorCount = ErrorCount;
}
// Returns true if no errors were suppressed
public bool ExitForwardsCompatible(bool fwdCompat)
{
Debug.Assert(_savedErrorCount != -1, "ExitForwardsCompatible without EnterForwardsCompatible");
if (fwdCompat && ErrorCount > _savedErrorCount)
{
ErrorCount = _savedErrorCount;
Debug.Assert((_savedErrorCount = -1) < 0);
return false;
}
Debug.Assert((_savedErrorCount = -1) < 0);
return true;
}
public CompilerError CreateError(ISourceLineInfo lineInfo, string res, params string[] args)
{
AddModule(lineInfo.Uri);
return new CompilerError(
lineInfo.Uri, lineInfo.Start.Line, lineInfo.Start.Pos, /*errorNumber:*/string.Empty,
/*errorText:*/XslTransformException.CreateMessage(res, args)
);
}
public void ReportError(ISourceLineInfo lineInfo, string res, params string[] args)
{
CompilerError error = CreateError(lineInfo, res, args);
CompilerResults.Errors.Add(error);
}
public void ReportWarning(ISourceLineInfo lineInfo, string res, params string[] args)
{
int warningLevel = 1;
if (0 <= Settings.WarningLevel && Settings.WarningLevel < warningLevel)
{
// Ignore warning
return;
}
CompilerError error = CreateError(lineInfo, res, args);
if (Settings.TreatWarningsAsErrors)
{
error.ErrorText = XslTransformException.CreateMessage(SR.Xslt_WarningAsError, error.ErrorText);
CompilerResults.Errors.Add(error);
}
else
{
error.IsWarning = true;
CompilerResults.Errors.Add(error);
}
}
private void SortErrors()
{
CompilerErrorCollection errorColl = this.CompilerResults.Errors;
if (errorColl.Count > 1)
{
CompilerError[] errors = new CompilerError[errorColl.Count];
errorColl.CopyTo(errors, 0);
Array.Sort<CompilerError>(errors, new CompilerErrorComparer(_moduleOrder));
errorColl.Clear();
errorColl.AddRange(errors);
}
}
private class CompilerErrorComparer : IComparer<CompilerError>
{
private Dictionary<string, int> _moduleOrder;
public CompilerErrorComparer(Dictionary<string, int> moduleOrder)
{
_moduleOrder = moduleOrder;
}
public int Compare(CompilerError x, CompilerError y)
{
if ((object)x == (object)y)
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
int result = _moduleOrder[x.FileName].CompareTo(_moduleOrder[y.FileName]);
if (result != 0)
return result;
result = x.Line.CompareTo(y.Line);
if (result != 0)
return result;
result = x.Column.CompareTo(y.Column);
if (result != 0)
return result;
result = x.IsWarning.CompareTo(y.IsWarning);
if (result != 0)
return result;
result = string.CompareOrdinal(x.ErrorNumber, y.ErrorNumber);
if (result != 0)
return result;
return string.CompareOrdinal(x.ErrorText, y.ErrorText);
}
}
}
internal class Output
{
public XmlWriterSettings Settings;
public string Version;
public string Encoding;
public XmlQualifiedName Method;
// All the xsl:output elements occurring in a stylesheet are merged into a single effective xsl:output element.
// We store the import precedence of each attribute value to catch redefinitions with the same import precedence.
public const int NeverDeclaredPrec = int.MinValue;
public int MethodPrec = NeverDeclaredPrec;
public int VersionPrec = NeverDeclaredPrec;
public int EncodingPrec = NeverDeclaredPrec;
public int OmitXmlDeclarationPrec = NeverDeclaredPrec;
public int StandalonePrec = NeverDeclaredPrec;
public int DocTypePublicPrec = NeverDeclaredPrec;
public int DocTypeSystemPrec = NeverDeclaredPrec;
public int IndentPrec = NeverDeclaredPrec;
public int MediaTypePrec = NeverDeclaredPrec;
public Output()
{
Settings = new XmlWriterSettings();
Settings.OutputMethod = XmlOutputMethod.AutoDetect;
Settings.AutoXmlDeclaration = true;
Settings.ConformanceLevel = ConformanceLevel.Auto;
Settings.MergeCDataSections = true;
}
}
internal class DecimalFormats : KeyedCollection<XmlQualifiedName, DecimalFormatDecl>
{
protected override XmlQualifiedName GetKeyForItem(DecimalFormatDecl format)
{
return format.Name;
}
}
internal class DecimalFormatDecl
{
public readonly XmlQualifiedName Name;
public readonly string InfinitySymbol;
public readonly string NanSymbol;
public readonly char[] Characters;
public static DecimalFormatDecl Default = new DecimalFormatDecl(new XmlQualifiedName(), "Infinity", "NaN", ".,%\u20300#;-");
public DecimalFormatDecl(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters)
{
Debug.Assert(characters.Length == 8);
this.Name = name;
this.InfinitySymbol = infinitySymbol;
this.NanSymbol = nanSymbol;
this.Characters = characters.ToCharArray();
}
}
internal class NsAlias
{
public readonly string ResultNsUri;
public readonly string ResultPrefix;
public readonly int ImportPrecedence;
public NsAlias(string resultNsUri, string resultPrefix, int importPrecedence)
{
this.ResultNsUri = resultNsUri;
this.ResultPrefix = resultPrefix;
this.ImportPrecedence = importPrecedence;
}
}
}
| |
// 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 gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>DomainCategory</c> resource.</summary>
public sealed partial class DomainCategoryName : gax::IResourceName, sys::IEquatable<DomainCategoryName>
{
/// <summary>The possible contents of <see cref="DomainCategoryName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </summary>
CustomerCampaignBase64CategoryLanguageCode = 1,
}
private static gax::PathTemplate s_customerCampaignBase64CategoryLanguageCode = new gax::PathTemplate("customers/{customer_id}/domainCategories/{campaign_id_base64_category_language_code}");
/// <summary>Creates a <see cref="DomainCategoryName"/> 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="DomainCategoryName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DomainCategoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DomainCategoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DomainCategoryName"/> with the pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="DomainCategoryName"/> constructed from the provided ids.</returns>
public static DomainCategoryName FromCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) =>
new DomainCategoryName(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DomainCategoryName"/> with pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string base64CategoryId, string languageCodeId) =>
FormatCustomerCampaignBase64CategoryLanguageCode(customerId, campaignId, base64CategoryId, languageCodeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DomainCategoryName"/> with pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>.
/// </returns>
public static string FormatCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) =>
s_customerCampaignBase64CategoryLanguageCode.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="DomainCategoryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DomainCategoryName"/> if successful.</returns>
public static DomainCategoryName Parse(string domainCategoryName) => Parse(domainCategoryName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DomainCategoryName"/> 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>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="domainCategoryName">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="DomainCategoryName"/> if successful.</returns>
public static DomainCategoryName Parse(string domainCategoryName, bool allowUnparsed) =>
TryParse(domainCategoryName, allowUnparsed, out DomainCategoryName 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="DomainCategoryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DomainCategoryName"/>, 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 domainCategoryName, out DomainCategoryName result) =>
TryParse(domainCategoryName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DomainCategoryName"/> 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>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="domainCategoryName">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="DomainCategoryName"/>, 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 domainCategoryName, bool allowUnparsed, out DomainCategoryName result)
{
gax::GaxPreconditions.CheckNotNull(domainCategoryName, nameof(domainCategoryName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignBase64CategoryLanguageCode.TryParseName(domainCategoryName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignBase64CategoryLanguageCode(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(domainCategoryName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private DomainCategoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string base64CategoryId = null, string campaignId = null, string customerId = null, string languageCodeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
Base64CategoryId = base64CategoryId;
CampaignId = campaignId;
CustomerId = customerId;
LanguageCodeId = languageCodeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DomainCategoryName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param>
public DomainCategoryName(string customerId, string campaignId, string base64CategoryId, string languageCodeId) : this(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId)))
{
}
/// <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>Base64Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string Base64CategoryId { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>LanguageCode</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string LanguageCodeId { 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.CustomerCampaignBase64CategoryLanguageCode: return s_customerCampaignBase64CategoryLanguageCode.Expand(CustomerId, $"{CampaignId}~{Base64CategoryId}~{LanguageCodeId}");
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 DomainCategoryName);
/// <inheritdoc/>
public bool Equals(DomainCategoryName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DomainCategoryName a, DomainCategoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DomainCategoryName a, DomainCategoryName b) => !(a == b);
}
public partial class DomainCategory
{
/// <summary>
/// <see cref="DomainCategoryName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal DomainCategoryName ResourceNameAsDomainCategoryName
{
get => string.IsNullOrEmpty(ResourceName) ? null : DomainCategoryName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/// <remarks> MAC tester - vectors from
/// <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIP 81</a> and
/// <a href="http://www.itl.nist.gov/fipspubs/fip113.htm">FIP 113</a>.
/// </remarks>
[TestFixture]
public class MacTest
: ITest
{
public string Name
{
get { return "IMac"; }
}
internal static byte[] keyBytes;
internal static byte[] ivBytes;
internal static byte[] input1;
internal static byte[] output1;
internal static byte[] output2;
internal static byte[] output3;
//
// these aren't NIST vectors, just for regression testing.
//
internal static byte[] input2;
internal static byte[] output4;
internal static byte[] output5;
internal static byte[] output6;
public MacTest()
{
}
public virtual ITestResult Perform()
{
KeyParameter key = new KeyParameter(keyBytes);
IBlockCipher cipher = new DesEngine();
IMac mac = new CbcBlockCipherMac(cipher);
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input1, 0, input1.Length);
byte[] outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output1))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output1) + " got " + Hex.ToHexString(outBytes));
}
//
// mac with IV.
//
ParametersWithIV param = new ParametersWithIV(key, ivBytes);
mac.Init(param);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output2))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output2) + " got " + Hex.ToHexString(outBytes));
}
//
// CFB mac with IV - 8 bit CFB mode
//
param = new ParametersWithIV(key, ivBytes);
mac = new CfbBlockCipherMac(cipher);
mac.Init(param);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output3))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output3) + " got " + Hex.ToHexString(outBytes));
}
//
// word aligned data - zero IV
//
mac.Init(key);
mac.BlockUpdate(input2, 0, input2.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output4))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output4) + " got " + Hex.ToHexString(outBytes));
}
//
// word aligned data - zero IV - CBC padding
//
mac = new CbcBlockCipherMac(cipher, new Pkcs7Padding());
mac.Init(key);
mac.BlockUpdate(input2, 0, input2.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output5))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output5) + " got " + Hex.ToHexString(outBytes));
}
//
// non-word aligned data - zero IV - CBC padding
//
mac.Reset();
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output6))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes));
}
//
// non-word aligned data - zero IV - CBC padding
//
mac.Init(key);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output6))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes));
}
return new SimpleTestResult(true, Name + ": Okay");
}
public static void Main(
string[] args)
{
MacTest test = new MacTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
static MacTest()
{
keyBytes = Hex.Decode("0123456789abcdef");
ivBytes = Hex.Decode("1234567890abcdef");
input1 = Hex.Decode("37363534333231204e6f77206973207468652074696d6520666f7220");
output1 = Hex.Decode("f1d30f68");
output2 = Hex.Decode("58d2e77e");
output3 = Hex.Decode("cd647403");
input2 = Hex.Decode("3736353433323120");
output4 = Hex.Decode("3af549c9");
output5 = Hex.Decode("188fbdd5");
output6 = Hex.Decode("7045eecd");
}
}
}
| |
// 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Reflection.Emit
{
public sealed class GenericTypeParameterBuilder : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Private Data Members
internal TypeBuilder m_type;
#endregion
#region Constructor
internal GenericTypeParameterBuilder(TypeBuilder type)
{
m_type = type;
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_type.Name;
}
public override bool Equals(object o)
{
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
return object.ReferenceEquals(g.m_type, m_type);
}
public override int GetHashCode() { return m_type.GetHashCode(); }
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for (int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
return st;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName { get { return null; } }
public override String Namespace { get { return null; } }
public override String AssemblyQualifiedName { get { return null; } }
public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
public override bool IsTypeDefinition => false;
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { throw new InvalidOperationException(); }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return false; } }
public override bool IsGenericParameter { get { return true; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } }
public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
protected override bool IsValueTypeImpl() { return false; }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
#region Public Members
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_type.SetGenParamCustomAttribute(customBuilder);
}
public void SetBaseTypeConstraint(Type baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
}
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_type.SetGenParamAttributes(genericParameterAttributes);
}
#endregion
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using no.teilin.turlogg.Data;
namespace no.teilin.turlogg.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("no.teilin.turlogg.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("no.teilin.turlogg.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("no.teilin.turlogg.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("no.teilin.turlogg.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Administration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Activation;
using System.Security;
using System.Security.Permissions;
class AppDomainInstanceProvider : ProviderBase, IWmiProvider
{
void IWmiProvider.EnumInstances(IWmiInstances instances)
{
Fx.Assert(null != instances, "");
IWmiInstance instance = instances.NewInstance(null);
FillAppDomainInfo(instance);
instances.AddInstance(instance);
}
bool IWmiProvider.GetInstance(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
bool bFound = false;
if ((int)instance.GetProperty(AdministrationStrings.ProcessId) == AppDomainInfo.Current.ProcessId
&& String.Equals((string)instance.GetProperty(AdministrationStrings.Name), AppDomainInfo.Current.Name, StringComparison.Ordinal))
{
FillAppDomainInfo(instance);
bFound = true;
}
return bFound;
}
internal static string GetReference()
{
return String.Format(CultureInfo.InvariantCulture, AdministrationStrings.AppDomainInfo +
"." +
AdministrationStrings.AppDomainId +
"={0}," +
AdministrationStrings.Name +
"='{1}'," +
AdministrationStrings.ProcessId +
"={2}",
AppDomainInfo.Current.Id,
AppDomainInfo.Current.Name,
AppDomainInfo.Current.ProcessId);
}
internal static void FillAppDomainInfo(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
AppDomainInfo domainInfo = AppDomainInfo.Current;
instance.SetProperty(AdministrationStrings.Name, domainInfo.Name);
instance.SetProperty(AdministrationStrings.AppDomainId, domainInfo.Id);
instance.SetProperty(AdministrationStrings.PerformanceCounters, PerformanceCounters.Scope.ToString());
instance.SetProperty(AdministrationStrings.IsDefault, domainInfo.IsDefaultAppDomain);
instance.SetProperty(AdministrationStrings.ProcessId, domainInfo.ProcessId);
instance.SetProperty(AdministrationStrings.TraceLevel, DiagnosticUtility.Level.ToString());
instance.SetProperty(AdministrationStrings.LogMalformedMessages, MessageLogger.LogMalformedMessages);
instance.SetProperty(AdministrationStrings.LogMessagesAtServiceLevel, MessageLogger.LogMessagesAtServiceLevel);
instance.SetProperty(AdministrationStrings.LogMessagesAtTransportLevel, MessageLogger.LogMessagesAtTransportLevel);
instance.SetProperty(AdministrationStrings.ServiceConfigPath, AspNetEnvironment.Current.ConfigurationPath);
FillListenersInfo(instance);
}
static IWmiInstance[] CreateListenersInfo(TraceSource traceSource, IWmiInstance instance)
{
Fx.Assert(null != traceSource, "");
Fx.Assert(null != instance, "");
IWmiInstance[] traceListeners = new IWmiInstance[traceSource.Listeners.Count];
for (int i = 0; i < traceSource.Listeners.Count; i++)
{
TraceListener traceListener = traceSource.Listeners[i];
IWmiInstance traceListenerWmiInstance = instance.NewInstance(AdministrationStrings.TraceListener);
traceListenerWmiInstance.SetProperty(AdministrationStrings.Name, traceListener.Name);
List<IWmiInstance> traceListenerArguments = new List<IWmiInstance>(1);
Type type = traceListener.GetType();
string initializeData = (string)type.InvokeMember(AdministrationStrings.InitializeData, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, traceListener, null, CultureInfo.InvariantCulture);
string[] supportedAttributes = (string[])type.InvokeMember(AdministrationStrings.GetSupportedAttributes, BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, traceListener, null, CultureInfo.InvariantCulture);
IWmiInstance argumentWmiInstance = instance.NewInstance(AdministrationStrings.TraceListenerArgument);
argumentWmiInstance.SetProperty(AdministrationStrings.Name, AdministrationStrings.InitializeData);
argumentWmiInstance.SetProperty(AdministrationStrings.Value, initializeData);
traceListenerArguments.Add(argumentWmiInstance);
if (null != supportedAttributes)
{
foreach (string attribute in supportedAttributes)
{
argumentWmiInstance = instance.NewInstance(AdministrationStrings.TraceListenerArgument);
argumentWmiInstance.SetProperty(AdministrationStrings.Name, attribute);
argumentWmiInstance.SetProperty(AdministrationStrings.Value, traceListener.Attributes[attribute]);
traceListenerArguments.Add(argumentWmiInstance);
}
}
traceListenerWmiInstance.SetProperty(AdministrationStrings.TraceListenerArguments, traceListenerArguments.ToArray());
traceListeners[i] = traceListenerWmiInstance;
}
return traceListeners;
}
static void FillListenersInfo(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
TraceSource traceSource = DiagnosticUtility.DiagnosticTrace == null ? null : DiagnosticUtility.DiagnosticTrace.TraceSource;
if (null != traceSource)
{
instance.SetProperty(AdministrationStrings.ServiceModelTraceListeners, CreateListenersInfo(traceSource, instance));
}
traceSource = MessageLogger.MessageTraceSource;
if (null != traceSource)
{
instance.SetProperty(AdministrationStrings.MessageLoggingTraceListeners, CreateListenersInfo(traceSource, instance));
}
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are setting DiagnosticUtility.Level.",
Safe = "Demands UnmanagedCode permission to set the Trace level")]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecuritySafeCritical]
bool IWmiProvider.PutInstance(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
bool bFound = false;
if ((int)instance.GetProperty(AdministrationStrings.ProcessId) == AppDomainInfo.Current.ProcessId
&& String.Equals((string)instance.GetProperty(AdministrationStrings.Name), AppDomainInfo.Current.Name, StringComparison.Ordinal))
{
try
{
SourceLevels newLevel = (SourceLevels)Enum.Parse(typeof(SourceLevels), (string)instance.GetProperty(AdministrationStrings.TraceLevel));
if (DiagnosticUtility.Level != newLevel)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.WmiPut, SR.GetString(SR.TraceCodeWmiPut),
new WmiPutTraceRecord("DiagnosticTrace.Level",
DiagnosticUtility.Level,
newLevel), instance, null);
}
DiagnosticUtility.Level = newLevel;
}
bool logMalformedMessages = (bool)instance.GetProperty(AdministrationStrings.LogMalformedMessages);
if (MessageLogger.LogMalformedMessages != logMalformedMessages)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.WmiPut, SR.GetString(SR.TraceCodeWmiPut),
new WmiPutTraceRecord("MessageLogger.LogMalformedMessages",
MessageLogger.LogMalformedMessages,
logMalformedMessages), instance, null);
}
MessageLogger.LogMalformedMessages = logMalformedMessages;
}
bool logMessagesAtServiceLevel = (bool)instance.GetProperty(AdministrationStrings.LogMessagesAtServiceLevel);
if (MessageLogger.LogMessagesAtServiceLevel != logMessagesAtServiceLevel)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.WmiPut, SR.GetString(SR.TraceCodeWmiPut),
new WmiPutTraceRecord("MessageLogger.LogMessagesAtServiceLevel",
MessageLogger.LogMessagesAtServiceLevel,
logMessagesAtServiceLevel), instance, null);
}
MessageLogger.LogMessagesAtServiceLevel = logMessagesAtServiceLevel;
}
bool logMessagesAtTransportLevel = (bool)instance.GetProperty(AdministrationStrings.LogMessagesAtTransportLevel);
if (MessageLogger.LogMessagesAtTransportLevel != logMessagesAtTransportLevel)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.WmiPut, SR.GetString(SR.TraceCodeWmiPut),
new WmiPutTraceRecord("MessageLogger.LogMessagesAtTransportLevel",
MessageLogger.LogMessagesAtTransportLevel,
logMessagesAtTransportLevel), instance, null);
}
MessageLogger.LogMessagesAtTransportLevel = logMessagesAtTransportLevel;
}
}
catch (ArgumentException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WbemInvalidParameterException());
}
bFound = true;
}
return bFound;
}
}
}
| |
// Copyright 2015, Google Inc. 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.
// 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.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201502;
using System;
using System.Collections.Generic;
using System.IO;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201502 {
/// <summary>
/// This code example adds sitelinks to a campaign using feed services.
/// To create a campaign, run AddCampaign.cs. To add sitelinks using the
/// simpler ExtensionSetting services, see AddSitelinks.cs.
///
/// Tags: CampaignFeedService.mutate, FeedService.mutate, FeedItemService.mutate,
/// Tags: FeedMappingService.mutate
/// </summary>
public class AddSitelinksUsingFeeds : ExampleBase {
/// <summary>
/// Holds data about sitelinks in a feed.
/// </summary>
class SitelinksDataHolder {
/// <summary>
/// The sitelink feed item IDs.
/// </summary>
List<long> feedItemIds = new List<long>();
/// <summary>
/// Gets the sitelink feed item IDs.
/// </summary>
public List<long> FeedItemIds {
get {
return feedItemIds;
}
}
/// <summary>
/// Gets or sets the feed ID.
/// </summary>
public long FeedId {
get;
set;
}
/// <summary>
/// Gets or sets the link text feed attribute ID.
/// </summary>
public long LinkTextFeedAttributeId {
get;
set;
}
/// <summary>
/// Gets or sets the link URL feed attribute ID.
/// </summary>
public long LinkFinalUrlFeedAttributeId {
get;
set;
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args) {
AddSitelinksUsingFeeds codeExample = new AddSitelinksUsingFeeds();
Console.WriteLine(codeExample.Description);
try {
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
string feedName = "INSERT_FEED_NAME_HERE";
codeExample.Run(new AdWordsUser(), campaignId, feedName);
} catch (Exception ex) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(ex));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example adds sitelinks to a campaign using feed services. To create a " +
"campaign, run AddCampaign.cs. To add sitelinks using the simpler ExtensionSetting " +
"services, see AddSitelinks.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">Id of the campaign with which sitelinks are associated.
/// </param>
/// <param name="feedName">Name of the feed to be created.</param>
public void Run(AdWordsUser user, long campaignId, string feedName) {
SitelinksDataHolder sitelinksData = new SitelinksDataHolder();
createSitelinksFeed(user, sitelinksData, feedName);
createSitelinksFeedItems(user, sitelinksData);
createSitelinksFeedMapping(user, sitelinksData);
createSitelinksCampaignFeed(user, sitelinksData, campaignId);
}
private static void createSitelinksFeed(AdWordsUser user, SitelinksDataHolder sitelinksData,
string feedName) {
// Get the FeedService.
FeedService feedService = (FeedService) user.GetService(AdWordsService.v201502.FeedService);
// Create attributes.
FeedAttribute textAttribute = new FeedAttribute();
textAttribute.type = FeedAttributeType.STRING;
textAttribute.name = "Link Text";
FeedAttribute finalUrlAttribute = new FeedAttribute();
finalUrlAttribute.type = FeedAttributeType.URL_LIST;
finalUrlAttribute.name = "Link URL";
// Create the feed.
Feed sitelinksFeed = new Feed();
sitelinksFeed.name = feedName;
sitelinksFeed.attributes = new FeedAttribute[] {textAttribute, finalUrlAttribute};
sitelinksFeed.origin = FeedOrigin.USER;
// Create operation.
FeedOperation operation = new FeedOperation();
operation.operand = sitelinksFeed;
operation.@operator = Operator.ADD;
// Add the feed.
FeedReturnValue result = feedService.mutate(new FeedOperation[] {operation});
Feed savedFeed = result.value[0];
sitelinksData.FeedId = savedFeed.id;
FeedAttribute[] savedAttributes = savedFeed.attributes;
sitelinksData.LinkTextFeedAttributeId = savedAttributes[0].id;
sitelinksData.LinkFinalUrlFeedAttributeId = savedAttributes[1].id;
Console.WriteLine("Feed with name {0} and ID {1} with linkTextAttributeId {2}"
+ " and linkFinalUrlAttributeId {3} was created.", savedFeed.name, savedFeed.id,
savedAttributes[0].id, savedAttributes[1].id);
}
private static void createSitelinksFeedItems(
AdWordsUser user, SitelinksDataHolder siteLinksData) {
// Get the FeedItemService.
FeedItemService feedItemService =
(FeedItemService) user.GetService(AdWordsService.v201502.FeedItemService);
// Create operations to add FeedItems.
FeedItemOperation home =
newSitelinkFeedItemAddOperation(siteLinksData,
"Home", "http://www.example.com");
FeedItemOperation stores =
newSitelinkFeedItemAddOperation(siteLinksData,
"Stores", "http://www.example.com/stores");
FeedItemOperation onSale =
newSitelinkFeedItemAddOperation(siteLinksData,
"On Sale", "http://www.example.com/sale");
FeedItemOperation support =
newSitelinkFeedItemAddOperation(siteLinksData,
"Support", "http://www.example.com/support");
FeedItemOperation products =
newSitelinkFeedItemAddOperation(siteLinksData,
"Products", "http://www.example.com/prods");
FeedItemOperation aboutUs =
newSitelinkFeedItemAddOperation(siteLinksData,
"About Us", "http://www.example.com/about");
FeedItemOperation[] operations =
new FeedItemOperation[] {home, stores, onSale, support, products, aboutUs};
FeedItemReturnValue result = feedItemService.mutate(operations);
foreach (FeedItem item in result.value) {
Console.WriteLine("FeedItem with feedItemId {0} was added.", item.feedItemId);
siteLinksData.FeedItemIds.Add(item.feedItemId);
}
}
// See the Placeholder reference page for a list of all the placeholder types and fields.
// https://developers.google.com/adwords/api/docs/appendix/placeholders.html
private const int PLACEHOLDER_SITELINKS = 1;
// See the Placeholder reference page for a list of all the placeholder types and fields.
private const int PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = 1;
private const int PLACEHOLDER_FIELD_SITELINK_FINAL_URL = 5;
private static void createSitelinksFeedMapping(
AdWordsUser user, SitelinksDataHolder sitelinksData) {
// Get the FeedItemService.
FeedMappingService feedMappingService =
(FeedMappingService) user.GetService(AdWordsService.v201502.FeedMappingService);
// Map the FeedAttributeIds to the fieldId constants.
AttributeFieldMapping linkTextFieldMapping = new AttributeFieldMapping();
linkTextFieldMapping.feedAttributeId = sitelinksData.LinkTextFeedAttributeId;
linkTextFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_LINK_TEXT;
AttributeFieldMapping linkFinalUrlFieldMapping = new AttributeFieldMapping();
linkFinalUrlFieldMapping.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId;
linkFinalUrlFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_FINAL_URL;
// Create the FieldMapping and operation.
FeedMapping feedMapping = new FeedMapping();
feedMapping.placeholderType = PLACEHOLDER_SITELINKS;
feedMapping.feedId = sitelinksData.FeedId;
feedMapping.attributeFieldMappings =
new AttributeFieldMapping[] {linkTextFieldMapping, linkFinalUrlFieldMapping};
FeedMappingOperation operation = new FeedMappingOperation();
operation.operand = feedMapping;
operation.@operator = Operator.ADD;
// Save the field mapping.
FeedMappingReturnValue result =
feedMappingService.mutate(new FeedMappingOperation[] {operation});
foreach (FeedMapping savedFeedMapping in result.value) {
Console.WriteLine(
"Feed mapping with ID {0} and placeholderType {1} was saved for feed with ID {2}.",
savedFeedMapping.feedMappingId, savedFeedMapping.placeholderType,
savedFeedMapping.feedId);
}
}
private static void createSitelinksCampaignFeed(AdWordsUser user,
SitelinksDataHolder sitelinksData, long campaignId) {
// Get the CampaignFeedService.
CampaignFeedService campaignFeedService =
(CampaignFeedService) user.GetService(AdWordsService.v201502.CampaignFeedService);
// Construct a matching function that associates the sitelink feeditems
// to the campaign, and set the device preference to Mobile. See the
// matching function guide at
// https://developers.google.com/adwords/api/docs/guides/feed-matching-functions
// for more details.
string matchingFunctionString = string.Format(@"
AND(
IN(FEED_ITEM_ID, {{{0}}}),
EQUALS(CONTEXT.DEVICE, 'Mobile')
)",
string.Join(",", sitelinksData.FeedItemIds));
CampaignFeed campaignFeed = new CampaignFeed() {
feedId = sitelinksData.FeedId,
campaignId = campaignId,
matchingFunction = new Function() {
functionString = matchingFunctionString
},
// Specifying placeholder types on the CampaignFeed allows the same feed
// to be used for different placeholders in different Campaigns.
placeholderTypes = new int[] { PLACEHOLDER_SITELINKS }
};
CampaignFeedOperation operation = new CampaignFeedOperation();
operation.operand = campaignFeed;
operation.@operator = Operator.ADD;
CampaignFeedReturnValue result =
campaignFeedService.mutate(new CampaignFeedOperation[] {operation});
foreach (CampaignFeed savedCampaignFeed in result.value) {
Console.WriteLine("Campaign with ID {0} was associated with feed with ID {1}",
savedCampaignFeed.campaignId, savedCampaignFeed.feedId);
}
}
private static FeedItemOperation newSitelinkFeedItemAddOperation(
SitelinksDataHolder sitelinksData, String text, String finalUrl) {
// Create the FeedItemAttributeValues for our text values.
FeedItemAttributeValue linkTextAttributeValue = new FeedItemAttributeValue();
linkTextAttributeValue.feedAttributeId = sitelinksData.LinkTextFeedAttributeId;
linkTextAttributeValue.stringValue = text;
FeedItemAttributeValue linkFinalUrlAttributeValue = new FeedItemAttributeValue();
linkFinalUrlAttributeValue.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId;
linkFinalUrlAttributeValue.stringValues = new string[] { finalUrl };
// Create the feed item and operation.
FeedItem item = new FeedItem();
item.feedId = sitelinksData.FeedId;
item.attributeValues =
new FeedItemAttributeValue[] {linkTextAttributeValue, linkFinalUrlAttributeValue};
FeedItemOperation operation = new FeedItemOperation();
operation.operand = item;
operation.@operator = Operator.ADD;
return operation;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.Linq;
using Microsoft.Research.AbstractDomains;
using System.Collections.Generic;
using Microsoft.Research.DataStructures;
using Microsoft.Research.AbstractDomains.Numerical;
using System.Diagnostics.Contracts;
using Microsoft.Research.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Research.CodeAnalysis
{
public static partial class AnalysisWrapper
{
public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
/// <summary>
/// Analysis that determines how an expressions refines to an array
/// </summary>
public class EnumAnalysisWrapperPlugIn :
GenericPlugInAnalysisForComposedAnalysis
{
#region State
private readonly EnumAnalysis enumAnalysis;
#endregion
#region Constructor
public EnumAnalysisWrapperPlugIn(EnumAnalysis enumAnalysis, int id, string methodName,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver,
ILogOptions options, Predicate<APC> cachePCs)
: base(id, methodName, mdriver, new PlugInAnalysisOptions(options), cachePCs)
{
Contract.Requires(enumAnalysis != null);
this.enumAnalysis = enumAnalysis;
}
#endregion
#region Select and MakeState
[Pure]
public EnumDefined<BoxedVariable<Variable>, Type, BoxedExpression> Select(ArrayState state)
{
Contract.Requires(state != null);
Contract.Requires(this.Id < state.PluginsCount);
Contract.Ensures(Contract.Result<EnumDefined<BoxedVariable<Variable>, Type, BoxedExpression>>() != null);
var untyped = state.PluginAbstractStateAt(this.Id);
var selected = untyped as EnumDefined<BoxedVariable<Variable>, Type, BoxedExpression>;
Contract.Assume(selected != null);
return selected;
}
public ArrayState MakeState(EnumDefined<BoxedVariable<Variable>, Type, BoxedExpression> newSubState, ArrayState oldState)
{
return oldState.UpdatePluginAt(this.Id, newSubState);
}
#endregion
#region Transfer functions --- just wrappers for the standalone enum analysis
public override ArrayState Entry(APC pc, Method method, ArrayState data)
{
return MakeState(this.enumAnalysis.Entry(pc, method, Select(data)), data);
}
public override ArrayState Assume(APC pc, string tag, Variable source, object provenance, ArrayState data)
{
var newData = data;
var newSubState = this.enumAnalysis.Assume(pc, tag, source, provenance, Select(data));
// At this point, we may know more on enums, so let's push them to the numerical domain
if (newSubState.IsNormal())
{
var mdDecoder = this.DecoderForMetaData;
var numericalDomain = data.Numerical;
foreach (var pair in newSubState.DefinedVariables)
{
List<int> typeValues;
// TODO: We may be smarted, and avoid recomputing the enum values if we already saw the type
var type = pair.One;
if (mdDecoder.IsEnumWithoutFlagAttribute(type) && mdDecoder.TryGetEnumValues(type, out typeValues))
{
// Assume the variable is in the enum
numericalDomain.AssumeInDisInterval(pair.Two, DisInterval.For(typeValues));
}
}
newData = newData.UpdateNumerical(numericalDomain);
}
return MakeState(newSubState, newData);
}
public override ArrayState Assert(APC pc, string tag, Variable condition, object provenance, ArrayState data)
{
return MakeState(this.enumAnalysis.Assert(pc, tag, condition, provenance, Select(data)), data);
}
public override ArrayState Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, ArrayState data)
{
return MakeState(this.enumAnalysis.Call<TypeList, ArgList>(pc, method, tail, virt, extraVarargs, dest, args, Select(data)), data);
}
public override ArrayState Stelem(APC pc, Type type, Variable array, Variable index, Variable value, ArrayState data)
{
return MakeState(this.enumAnalysis.Stelem(pc, type, array, index, value, Select(data)), data);
}
public override ArrayState Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, ArrayState data)
{
return MakeState(this.enumAnalysis.Ldelem(pc, type, dest, array, index, Select(data)), data);
}
public override ArrayState Starg(APC pc, Parameter argument, Variable source, ArrayState data)
{
return MakeState(this.enumAnalysis.Starg(pc, argument, source, Select(data)), data);
}
public override ArrayState Ldarg(APC pc, Parameter argument, bool isOld, Variable dest, ArrayState data)
{
return MakeState(this.enumAnalysis.Ldarg(pc, argument, isOld, dest, Select(data)), data);
}
public override ArrayState Stind(APC pc, Type type, bool @volatile, Variable ptr, Variable value, ArrayState data)
{
return MakeState(this.enumAnalysis.Stind(pc, type, @volatile, ptr, value, Select(data)), data);
}
public override ArrayState Ldind(APC pc, Type type, bool @volatile, Variable dest, Variable ptr, ArrayState data)
{
return MakeState(this.enumAnalysis.Ldind(pc, type, @volatile, dest, ptr, Select(data)), data);
}
public override ArrayState Stloc(APC pc, Local local, Variable source, ArrayState data)
{
return MakeState(this.enumAnalysis.Stloc(pc, local, source, Select(data)), data);
}
public override ArrayState Ldloc(APC pc, Local local, Variable dest, ArrayState data)
{
return MakeState(this.enumAnalysis.Ldloc(pc, local, dest, Select(data)), data);
}
public override ArrayState Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, ArrayState data)
{
return MakeState(this.enumAnalysis.Stfld(pc, field, @volatile, obj, value, Select(data)), data);
}
public override ArrayState Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, ArrayState data)
{
return MakeState(this.enumAnalysis.Ldfld(pc, field, @volatile, dest, obj, Select(data)), data);
}
#endregion
#region Overridden
public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> InitialState
{
get { return this.enumAnalysis.GetTopValue(); }
}
public override ArrayState.AdditionalStates Kind
{
get { return ArrayState.AdditionalStates.Enum; }
}
public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> AssignInParallel(Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert, List<Pair<NormalizedExpression<BoxedVariable<Variable>>, NormalizedExpression<BoxedVariable<Variable>>>> equalities, ArrayState state)
{
Contract.Assume(state != null);
Contract.Assume(refinedMap != null, "missing preconditions in base class");
Contract.Assume(convert != null, "missing preconditions in base class");
return this.enumAnalysis.Rename(Select(state), refinedMap);
}
public override IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, ArrayState> fixpoint)
{
return new EnumPlugingFactQuery(this, fixpoint);
}
#endregion
#region FactQuery
public class EnumPlugingFactQuery : IFactQuery<BoxedExpression, Variable>
{
#region State
private readonly EnumAnalysisWrapperPlugIn analysis;
private readonly IFixpointInfo<APC, ArrayState> fixpoint;
#endregion
#region Constructor
public EnumPlugingFactQuery(EnumAnalysisWrapperPlugIn analysis, IFixpointInfo<APC, ArrayState> fixpoint)
{
Contract.Requires(analysis != null);
Contract.Requires(fixpoint != null);
this.analysis = analysis;
this.fixpoint = fixpoint;
}
#endregion
#region implementation of the interface
public ProofOutcome IsNull(APC pc, BoxedExpression expr)
{
return ProofOutcome.Top;
}
public ProofOutcome IsNonNull(APC pc, BoxedExpression expr)
{
return ProofOutcome.Top;
}
public ProofOutcome IsTrue(APC pc, BoxedExpression condition)
{
return ProofOutcome.Top;
}
public ProofOutcome IsTrue(APC pc, Question question)
{
return ProofOutcome.Top;
}
public ProofOutcome IsTrueImply(APC pc, FList<BoxedExpression> posAssumptions, FList<BoxedExpression> negAssumptions, BoxedExpression goal)
{
return ProofOutcome.Top;
}
public ProofOutcome IsGreaterEqualToZero(APC pc, BoxedExpression expr)
{
return ProofOutcome.Top;
}
public ProofOutcome IsLessThan(APC pc, BoxedExpression left, BoxedExpression right)
{
return ProofOutcome.Top;
}
public ProofOutcome IsNonZero(APC pc, BoxedExpression condition)
{
return ProofOutcome.Top;
}
public ProofOutcome HaveSameFloatType(APC pc, BoxedExpression left, BoxedExpression right)
{
return ProofOutcome.Top;
}
public bool TryGetFloatType(APC pc, BoxedExpression exp, out ConcreteFloat type)
{
type = default(ConcreteFloat);
return false;
}
public IEnumerable<Variable> LowerBounds(APC pc, BoxedExpression exp, bool strict)
{
yield break;
}
public IEnumerable<Variable> UpperBounds(APC pc, BoxedExpression exp, bool strict)
{
yield break;
}
public IEnumerable<BoxedExpression> LowerBoundsAsExpressions(APC pc, BoxedExpression exp, bool strict)
{
yield break;
}
public IEnumerable<BoxedExpression> UpperBoundsAsExpressions(APC pc, BoxedExpression exp, bool strict)
{
yield break;
}
public Pair<long, long> BoundsFor(APC pc, BoxedExpression exp)
{
return new Pair<long, long>(Int64.MinValue, Int64.MaxValue);
}
public ProofOutcome IsVariableDefinedForType(APC pc, Variable v, object typeAsObject)
{
if (!(typeAsObject is Type))
{
return ProofOutcome.Top;
}
var type = (Type)typeAsObject;
ProofOutcome outcome;
ArrayState preState;
if (this.fixpoint.PreState(pc, out preState) &&
((outcome = this.analysis.Select(preState).CheckIfVariableIsDefined(new BoxedVariable<Variable>(v), type).ToProofOutcome()) != ProofOutcome.Top))
{
return outcome;
}
var varType = this.analysis.Context.ValueContext.GetType(this.analysis.MethodDriver.CFG.Post(pc), v);
if (varType.IsNormal && varType.Value.Equals(type))
{
return ProofOutcome.True;
}
return ProofOutcome.Top;
}
public ProofOutcome IsNull(APC pc, Variable value)
{
return ProofOutcome.Top;
}
public ProofOutcome IsNonNull(APC pc, Variable value)
{
return ProofOutcome.Top;
}
public bool IsUnreachable(APC pc)
{
return false;
}
public FList<BoxedExpression> InvariantAt(APC pc, FList<Variable> variables = null, bool replaceVarsWithAccessPaths = true)
{
return FList<BoxedExpression>.Empty;
}
#endregion
}
#endregion
}
}
}
}
| |
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// 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.Diagnostics;
using System.Runtime.InteropServices;
using OpenTK.Graphics;
namespace OpenTK.Platform.Windows
{
public class WinGraphicsMode : IGraphicsMode
{
private enum AccelerationType
{
// Software acceleration
None = 0,
// Partial acceleration (Direct3D emulation)
MCD,
// Full acceleration
ICD,
}
private readonly IntPtr Device;
public WinGraphicsMode(IntPtr device)
{
if (device == IntPtr.Zero)
{
throw new ArgumentException();
}
Device = device;
}
public GraphicsMode SelectGraphicsMode(ColorFormat color, int depth, int stencil, int samples,
ColorFormat accum, int buffers, bool stereo)
{
GraphicsMode mode = new GraphicsMode(color, depth, stencil, samples, accum, buffers, stereo);
GraphicsMode created_mode = ChoosePixelFormatARB(Device, mode);
// If ChoosePixelFormatARB failed, iterate through all acceleration types in turn (ICD, MCD, None)
// This should fix issue #2224, which causes OpenTK to fail on VMs without hardware acceleration.
created_mode = created_mode ?? ChoosePixelFormatPFD(Device, mode, AccelerationType.ICD);
created_mode = created_mode ?? ChoosePixelFormatPFD(Device, mode, AccelerationType.MCD);
created_mode = created_mode ?? ChoosePixelFormatPFD(Device, mode, AccelerationType.None);
if (created_mode == null)
{
throw new GraphicsModeException("The requested GraphicsMode is not supported");
}
return created_mode;
}
// Queries pixel formats through the WGL_ARB_pixel_format extension
// This method only returns accelerated formats. If no format offers
// hardware acceleration (e.g. we are running in a VM or in a remote desktop
// connection), this method will return 0 formats and we will fall back to
// ChoosePixelFormatPFD.
private GraphicsMode ChoosePixelFormatARB(IntPtr device, GraphicsMode desired_mode)
{
GraphicsMode created_mode = null;
GraphicsMode mode = new GraphicsMode(desired_mode);
if (Wgl.SupportsExtension("WGL_ARB_pixel_format") &&
Wgl.SupportsFunction("wglChoosePixelFormatARB"))
{
int[] format = new int[1];
int count;
List<int> attributes = new List<int>();
bool retry = false;
do
{
attributes.Clear();
attributes.Add((int)WGL_ARB_pixel_format.AccelerationArb);
attributes.Add((int)WGL_ARB_pixel_format.FullAccelerationArb);
attributes.Add((int)WGL_ARB_pixel_format.DrawToWindowArb);
attributes.Add(1);
if (mode.ColorFormat.Red > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.RedBitsArb);
attributes.Add(mode.ColorFormat.Red);
}
if (mode.ColorFormat.Green > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.GreenBitsArb);
attributes.Add(mode.ColorFormat.Green);
}
if (mode.ColorFormat.Blue > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.BlueBitsArb);
attributes.Add(mode.ColorFormat.Blue);
}
if (mode.ColorFormat.Alpha > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.AlphaBitsArb);
attributes.Add(mode.ColorFormat.Alpha);
}
if (mode.Depth > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.DepthBitsArb);
attributes.Add(mode.Depth);
}
if (mode.Stencil > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.StencilBitsArb);
attributes.Add(mode.Stencil);
}
if (mode.AccumulatorFormat.Red > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.AccumRedBitsArb);
attributes.Add(mode.AccumulatorFormat.Red);
}
if (mode.AccumulatorFormat.Green > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.AccumGreenBitsArb);
attributes.Add(mode.AccumulatorFormat.Green);
}
if (mode.AccumulatorFormat.Blue > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.AccumBlueBitsArb);
attributes.Add(mode.AccumulatorFormat.Blue);
}
if (mode.AccumulatorFormat.Alpha > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.AccumAlphaBitsArb);
attributes.Add(mode.AccumulatorFormat.Alpha);
}
if (mode.Samples > 0 &&
Wgl.SupportsExtension("WGL_ARB_multisample"))
{
attributes.Add((int)WGL_ARB_multisample.SampleBuffersArb);
attributes.Add(1);
attributes.Add((int)WGL_ARB_multisample.SamplesArb);
attributes.Add(mode.Samples);
}
if (mode.Buffers > 0)
{
attributes.Add((int)WGL_ARB_pixel_format.DoubleBufferArb);
attributes.Add(mode.Buffers > 1 ? 1 : 0);
}
if (mode.Stereo)
{
attributes.Add((int)WGL_ARB_pixel_format.StereoArb);
attributes.Add(1);
}
attributes.Add(0);
attributes.Add(0);
if (Wgl.Arb.ChoosePixelFormat(device, attributes.ToArray(), null, format.Length, format, out count)
&& count > 0)
{
created_mode = DescribePixelFormatARB(device, format[0]);
retry = false;
}
else
{
Debug.Print("[WGL] ChoosePixelFormatARB failed with {0}", Marshal.GetLastWin32Error());
retry = Utilities.RelaxGraphicsMode(ref mode);
}
}
while (retry);
}
else
{
Debug.WriteLine("[WGL] ChoosePixelFormatARB not supported on this context");
}
return created_mode;
}
private static bool Compare(int got, int requested, ref int distance)
{
bool valid = true;
if (got == 0 && requested != 0)
{
// mode does not support the requested feature.
valid = false;
}
else if (got >= requested)
{
// mode supports the requested feature,
// calculate the distance from an "ideal" mode
// that matches this feature exactly.
distance += got - requested;
}
else
{
// mode supports the requested feature,
// but at a suboptimal level. For example:
// - requsted AA = 8x, got 4x
// - requested color = 32bpp, got 16bpp
// We can still use this mode but only if
// no better mode exists.
const int penalty = 8;
distance += penalty * Math.Abs(got - requested);
}
return valid;
}
private static AccelerationType GetAccelerationType(ref PixelFormatDescriptor pfd)
{
AccelerationType type = AccelerationType.ICD;
if ((pfd.Flags & PixelFormatDescriptorFlags.GENERIC_FORMAT) != 0)
{
if ((pfd.Flags & PixelFormatDescriptorFlags.GENERIC_ACCELERATED) != 0)
{
type = AccelerationType.MCD;
}
else
{
type = AccelerationType.None;
}
}
return type;
}
private GraphicsMode ChoosePixelFormatPFD(IntPtr device, GraphicsMode mode, AccelerationType requested_acceleration_type)
{
PixelFormatDescriptor pfd = new PixelFormatDescriptor();
PixelFormatDescriptorFlags flags = 0;
flags |= PixelFormatDescriptorFlags.DRAW_TO_WINDOW;
flags |= PixelFormatDescriptorFlags.SUPPORT_OPENGL;
if (mode.Stereo)
{
flags |= PixelFormatDescriptorFlags.STEREO;
}
if (System.Environment.OSVersion.Version.Major >= 6 &&
requested_acceleration_type != AccelerationType.None)
{
// Request a compositor-capable mode when running on
// Vista+ and using hardware acceleration. Without this,
// some modes will cause the compositor to turn off,
// which is very annoying to the user.
// Note: compositor-capable modes require hardware
// acceleration. Don't set this flag when running
// with software acceleration (e.g. over Remote Desktop
// as described in bug https://github.com/opentk/opentk/issues/35)
flags |= PixelFormatDescriptorFlags.SUPPORT_COMPOSITION;
}
int count = Functions.DescribePixelFormat(device, 1, API.PixelFormatDescriptorSize, ref pfd);
int best = 0;
int best_dist = int.MaxValue;
for (int index = 1; index <= count; index++)
{
int dist = 0;
bool valid = Functions.DescribePixelFormat(device, index, API.PixelFormatDescriptorSize, ref pfd) != 0;
valid &= GetAccelerationType(ref pfd) == requested_acceleration_type;
valid &= (pfd.Flags & flags) == flags;
valid &= pfd.PixelType == PixelType.RGBA; // indexed modes not currently supported
// heavily penalize single-buffered modes when the user requests double buffering
if ((pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) == 0 && mode.Buffers > 1)
{
dist += 1000;
}
valid &= Compare(pfd.ColorBits, mode.ColorFormat.BitsPerPixel, ref dist);
valid &= Compare(pfd.RedBits, mode.ColorFormat.Red, ref dist);
valid &= Compare(pfd.GreenBits, mode.ColorFormat.Green, ref dist);
valid &= Compare(pfd.BlueBits, mode.ColorFormat.Blue, ref dist);
valid &= Compare(pfd.AlphaBits, mode.ColorFormat.Alpha, ref dist);
valid &= Compare(pfd.AccumBits, mode.AccumulatorFormat.BitsPerPixel, ref dist);
valid &= Compare(pfd.AccumRedBits, mode.AccumulatorFormat.Red, ref dist);
valid &= Compare(pfd.AccumGreenBits, mode.AccumulatorFormat.Green, ref dist);
valid &= Compare(pfd.AccumBlueBits, mode.AccumulatorFormat.Blue, ref dist);
valid &= Compare(pfd.AccumAlphaBits, mode.AccumulatorFormat.Alpha, ref dist);
valid &= Compare(pfd.DepthBits, mode.Depth, ref dist);
valid &= Compare(pfd.StencilBits, mode.Stencil, ref dist);
if (valid && dist < best_dist)
{
best = index;
best_dist = dist;
}
}
return DescribePixelFormatPFD(device, ref pfd, best);
}
private static GraphicsMode DescribePixelFormatPFD(IntPtr device, ref PixelFormatDescriptor pfd,
int pixelformat)
{
GraphicsMode created_mode = null;
if (Functions.DescribePixelFormat(device, pixelformat, pfd.Size, ref pfd) > 0)
{
created_mode = new GraphicsMode(
new IntPtr(pixelformat),
new ColorFormat(pfd.RedBits, pfd.GreenBits, pfd.BlueBits, pfd.AlphaBits),
pfd.DepthBits,
pfd.StencilBits,
0, // MSAA not supported when using PixelFormatDescriptor
new ColorFormat(pfd.AccumRedBits, pfd.AccumGreenBits, pfd.AccumBlueBits, pfd.AccumAlphaBits),
(pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) != 0 ? 2 : 1,
(pfd.Flags & PixelFormatDescriptorFlags.STEREO) != 0);
}
return created_mode;
}
private GraphicsMode DescribePixelFormatARB(IntPtr device, int pixelformat)
{
GraphicsMode created_mode = null;
// See http://www.opengl.org/registry/specs/ARB/wgl_pixel_format.txt for more details
if (Wgl.SupportsFunction("wglGetPixelFormatAttribivARB"))
{
// Define the list of attributes we are interested in.
// The results will be stored in the 'values' array below.
int[] attribs = new int[]
{
(int)WGL_ARB_pixel_format.AccelerationArb,
(int)WGL_ARB_pixel_format.RedBitsArb,
(int)WGL_ARB_pixel_format.GreenBitsArb,
(int)WGL_ARB_pixel_format.BlueBitsArb,
(int)WGL_ARB_pixel_format.AlphaBitsArb,
(int)WGL_ARB_pixel_format.ColorBitsArb,
(int)WGL_ARB_pixel_format.DepthBitsArb,
(int)WGL_ARB_pixel_format.StencilBitsArb,
(int)WGL_ARB_multisample.SampleBuffersArb,
(int)WGL_ARB_multisample.SamplesArb,
(int)WGL_ARB_pixel_format.AccumRedBitsArb,
(int)WGL_ARB_pixel_format.AccumGreenBitsArb,
(int)WGL_ARB_pixel_format.AccumBlueBitsArb,
(int)WGL_ARB_pixel_format.AccumAlphaBitsArb,
(int)WGL_ARB_pixel_format.AccumBitsArb,
(int)WGL_ARB_pixel_format.DoubleBufferArb,
(int)WGL_ARB_pixel_format.StereoArb,
0
};
// Allocate storage for the results of GetPixelFormatAttrib queries
int[] values = new int[attribs.Length];
// Get the format attributes for this pixel format
if (!Wgl.Arb.GetPixelFormatAttrib(device, pixelformat, 0, attribs.Length - 1, attribs, values))
{
Debug.Print("[Warning] Failed to detect attributes for PixelFormat: {0}.", pixelformat);
}
// Skip formats that don't offer full hardware acceleration
WGL_ARB_pixel_format acceleration = (WGL_ARB_pixel_format)values[0];
if (acceleration == WGL_ARB_pixel_format.FullAccelerationArb)
{
// Construct a new GraphicsMode to describe this format
created_mode = new GraphicsMode(new IntPtr(pixelformat),
new ColorFormat(values[1], values[2], values[3], values[4]),
values[6],
values[7],
values[8] != 0 ? values[9] : 0,
new ColorFormat(values[10], values[11], values[12], values[13]),
values[15] == 1 ? 2 : 1,
values[16] == 1 ? true : false);
}
}
return created_mode;
}
}
}
| |
// 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;
namespace System.Linq.Expressions.Tests
{
partial class ExpressionCatalog
{
private static IEnumerable<Expression> ArrayIndex()
{
var arr1 = Expression.Constant(new[] { 2, 3, 5 });
for (var i = -1; i <= 3; i++)
{
yield return Expression.ArrayIndex(arr1, Expression.Constant(i));
}
var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } });
for (var i = -1; i <= 2; i++)
{
for (var j = -1; i <= 3; i++)
{
yield return Expression.ArrayIndex(arr2, Expression.Constant(i), Expression.Constant(j));
}
}
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> ArrayIndex_WithLog()
{
var arr1 = Expression.Constant(new[] { 2, 3, 5 });
var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } });
yield return WithLog(ExpressionType.ArrayIndex, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int));
var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString());
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.ArrayIndex(arr1, ReturnWithLog(log, 1))
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
yield return WithLog(ExpressionType.ArrayIndex, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int));
var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString());
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.ArrayIndex(arr2, ReturnWithLog(log, 1), ReturnWithLog(log, 2))
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
}
private static IEnumerable<Expression> ArrayAccess()
{
var arr1 = Expression.Constant(new[] { 2, 3, 5 });
for (var i = -1; i <= 3; i++)
{
yield return Expression.ArrayAccess(arr1, Expression.Constant(i));
}
var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } });
for (var i = -1; i <= 2; i++)
{
for (var j = -1; i <= 3; i++)
{
yield return Expression.ArrayAccess(arr2, Expression.Constant(i), Expression.Constant(j));
}
}
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> ArrayAccess_WithLog()
{
var arr1 = Expression.Constant(new[] { 2, 3, 5 });
var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } });
yield return WithLog(ExpressionType.Index, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int));
var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString());
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.ArrayAccess(arr1, ReturnWithLog(log, 1))
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
yield return WithLog(ExpressionType.Index, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int));
var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString());
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.ArrayAccess(arr2, ReturnWithLog(log, 1), ReturnWithLog(log, 2))
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
}
private static IEnumerable<Expression> ArrayLength()
{
yield return Expression.ArrayLength(Expression.Constant(new object[0]));
yield return Expression.ArrayLength(Expression.Constant(new int[1]));
yield return Expression.ArrayLength(Expression.Constant(new string[42]));
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> NewArrayInit()
{
var expr = (Expression<Func<int>>)(() => new[] { 2, 3, 5, 7 }.Sum());
yield return new KeyValuePair<ExpressionType, Expression>(ExpressionType.NewArrayInit, expr.Body);
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> NewArrayInit_WithLog()
{
yield return WithLog(ExpressionType.NewArrayInit, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int[]));
var newArrTemplate = (Expression<Func<int[]>>)(() => new[] { 2, 3, 5, 7 });
var toStringTemplate = (Expression<Func<int[], string>>)(xs => string.Join(", ", xs));
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.Invoke(
ReturnAllConstants(log, newArrTemplate)
)
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
}
private static IEnumerable<Expression> NewArrayBounds()
{
foreach (var e in new[]
{
Expression.NewArrayBounds(typeof(int), Expression.Constant(-1)),
Expression.NewArrayBounds(typeof(int), Expression.Constant(0)),
Expression.NewArrayBounds(typeof(int), Expression.Constant(1), Expression.Constant(-1)),
Expression.NewArrayBounds(typeof(int), Expression.Constant(1), Expression.Constant(0)),
})
{
yield return e;
}
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> NewArrayBounds_WithLog()
{
yield return WithLog(ExpressionType.NewArrayBounds, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int[]));
var toStringTemplate = (Expression<Func<int[], string>>)(xs => string.Join(", ", xs));
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.NewArrayBounds(
typeof(int),
ReturnWithLog(log, 1)
)
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
yield return WithLog(ExpressionType.NewArrayBounds, (log, summary) =>
{
var valueParam = Expression.Parameter(typeof(int[,]));
var toStringTemplate = (Expression<Func<int[,], string>>)(xs => string.Join(", ", xs));
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
return
Expression.Block(
new[] { valueParam },
Expression.Assign(
valueParam,
Expression.NewArrayBounds(
typeof(int),
ReturnWithLog(log, 1),
ReturnWithLog(log, 2)
)
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(toStringTemplate, valueParam),
summary
)
);
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Text.Tests
{
// Encoding.GetChars(byte[],Int32,Int32,char[],Int32)
public class EncodingGetChars3
{
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
#region PositiveTest
[Fact]
public void PosTest1()
{
byte[] bytes = new byte[0];
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[] { _generator.GetChar(-55) };
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
Assert.Equal(0, intVal);
Assert.Equal(1, chars.Length);
}
[Fact]
public void PosTest2()
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[] { _generator.GetChar(-55) };
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
Assert.Equal(0, intVal);
Assert.Equal(1, chars.Length);
}
[Fact]
public void PosTest3()
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
Assert.Equal(myStr.Length, intVal);
Assert.Equal(myStr.Length, chars.Length);
}
[Fact]
public void PosTest4()
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length + myStr.Length];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length - 1);
string subchars = null;
for (int i = 0; i < myStr.Length - 1; i++)
{
subchars += chars[i].ToString();
}
Assert.Equal(myStr.Length, intVal);
Assert.Equal("\0\0\0\0", subchars);
}
[Fact]
public void PosTest5()
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length - 2;
char[] chars = new char[myStr.Length - 1];
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
string strVal = new string(chars);
Assert.Equal((myStr.Length - 1), intVal);
Assert.Equal("za\u0306\u01fd", strVal);
}
#endregion
#region NegativeTest
// NegTest1:the byte array is null
[Fact]
public void NegTest1()
{
byte[] bytes = null;
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = new char[0];
Assert.Throws<ArgumentNullException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
});
}
// NegTest2:the char array is null
[Fact]
public void NegTest2()
{
byte[] bytes = new byte[0];
Encoding myEncode = Encoding.GetEncoding("utf-16");
int byteIndex = 0;
int bytecount = 0;
char[] chars = null;
Assert.Throws<ArgumentNullException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
});
}
// NegTest3:the char array has no enough capacity to hold the chars
[Fact]
public void NegTest3()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[0];
Assert.Throws<ArgumentException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
});
}
// NegTest4:the byteIndex is less than zero
[Fact]
public void NegTest4()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = -1;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
});
}
// NegTest5:the bytecount is less than zero
[Fact]
public void NegTest5()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = -1;
char[] chars = new char[myStr.Length];
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, 0);
});
}
// NegTest6:the charIndex is less than zero
[Fact]
public void NegTest6()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, -1);
});
}
// NegTest7:the charIndex is not valid index in chars array
[Fact]
public void NegTest7()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length;
char[] chars = new char[myStr.Length];
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1);
});
}
// NegTest8:the byteIndex and bytecount do not denote valid range of the bytes array
[Fact]
public void NegTest8()
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int byteIndex = 0;
int bytecount = bytes.Length + 1;
char[] chars = new char[myStr.Length];
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
int intVal = myEncode.GetChars(bytes, byteIndex, bytecount, chars, myStr.Length + 1);
});
}
#endregion
}
}
| |
// Created by Javier Berlana on 9/23/11.
// Copyright (c) 2011, Javier Berlana
// Ported to C# by James Clancey, Xamarin
//
// 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.
//
namespace XamarinStore
{
using System;
using System.Collections.Generic;
using System.Drawing;
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
public class JBKenBurnsView : UIView
{
#region Constants
private const float enlargeRatio = 1.1f;
private const int imageBuffer = 1;
#endregion
#region Fields
public List<UIImage> Images = new List<UIImage>();
private readonly Queue<UIView> Views = new Queue<UIView>();
private readonly Random random = new Random();
private int currentIndex;
private NSTimer timer;
#endregion
#region Constructors and Destructors
public JBKenBurnsView()
{
this.ImageDuration = 12;
this.ShouldLoop = true;
this.IsLandscape = true;
this.BackgroundColor = UIColor.Clear;
this.Layer.MasksToBounds = true;
this.IsActive = false;
}
#endregion
#region Public Events
public event EventHandler Finished;
public event Action<int> ImageIndexChanged;
#endregion
#region Public Properties
public int CurrentIndex
{
get
{
return this.currentIndex;
}
set
{
this.currentIndex = value;
if (this.Images.Count < this.currentIndex)
{
this.Animate();
}
}
}
public double ImageDuration { get; set; }
public bool IsActive { get; private set; }
public bool IsLandscape { get; set; }
public bool ShouldLoop { get; set; }
#endregion
#region Public Methods and Operators
public void Animate()
{
this.IsActive = true;
if (this.timer != null)
{
this.timer.Invalidate();
}
this.timer = NSTimer.CreateRepeatingScheduledTimer(this.ImageDuration, this.NextImage);
this.timer.Fire();
}
#endregion
#region Methods
private void NextImage()
{
if (this.Images.Count == 0 || this.currentIndex >= this.Images.Count && !this.ShouldLoop)
{
if (this.Finished != null)
{
this.Finished(this, EventArgs.Empty);
}
return;
}
if (this.currentIndex >= this.Images.Count)
{
this.currentIndex = 0;
}
var image = this.Images[this.currentIndex];
this.currentIndex++;
if (image == null)
{
if (image == null || image.Size == Size.Empty)
{
return;
}
}
float resizeRatio = -1;
float widthDiff = -1;
float heightDiff = -1;
float originX = -1;
float originY = -1;
float zoomInX = -1;
float zoomInY = -1;
float moveX = -1;
float moveY = -1;
var frameWidth = this.IsLandscape ? this.Bounds.Width : this.Bounds.Height;
var frameHeight = this.IsLandscape ? this.Bounds.Height : this.Bounds.Width;
// Wider than screen
var imageWidth = image.Size.Width == 0 ? 100 : image.Size.Width;
var imageHeight = image.Size.Height == 0 ? 100 : image.Size.Height;
if (imageWidth > frameWidth)
{
widthDiff = imageWidth - frameWidth;
// Higher than screen
if (imageHeight > frameHeight)
{
heightDiff = imageHeight - frameHeight;
if (widthDiff > heightDiff)
{
resizeRatio = frameHeight / imageHeight;
}
else
{
resizeRatio = frameWidth / imageWidth;
}
// No higher than screen [OK]
}
else
{
heightDiff = frameHeight - imageHeight;
if (widthDiff > heightDiff)
{
resizeRatio = frameWidth / imageWidth;
}
else
{
resizeRatio = this.Bounds.Height / imageHeight;
}
}
// No wider than screen
}
else
{
widthDiff = frameWidth - imageWidth;
// Higher than screen [OK]
if (imageHeight > frameHeight)
{
heightDiff = imageHeight - frameHeight;
if (widthDiff > heightDiff)
{
resizeRatio = imageHeight / frameHeight;
}
else
{
resizeRatio = frameWidth / imageWidth;
}
// No higher than screen [OK]
}
else
{
heightDiff = frameHeight - imageHeight;
if (widthDiff > heightDiff)
{
resizeRatio = frameWidth / imageWidth;
}
else
{
resizeRatio = frameHeight / imageHeight;
}
}
}
// Resize the image.
var optimusWidth = (imageWidth * resizeRatio) * enlargeRatio;
var optimusHeight = (imageHeight * resizeRatio) * enlargeRatio;
var imageView = new UIView { Frame = new RectangleF(0, 0, optimusWidth, optimusHeight), BackgroundColor = UIColor.Clear, };
var maxMoveX = Math.Min(optimusWidth - frameWidth, 50f);
var maxMoveY = Math.Min(optimusHeight - frameHeight, 50f) * 2 / 3;
float rotation = (this.random.Next(9)) / 100;
switch (this.random.Next(3))
{
case 0:
originX = 0;
originY = 0;
zoomInX = 1.25f;
zoomInY = 1.25f;
moveX = -maxMoveX;
moveY = -maxMoveY;
break;
case 1:
originX = 0;
originY = 0; // Math.Max(frameHeight - (optimusHeight),frameHeight * 1/3);
zoomInX = 1.1f;
zoomInY = 1.1f;
moveX = -maxMoveX;
moveY = maxMoveY;
break;
case 2:
originX = frameWidth - optimusWidth;
originY = 0;
zoomInX = 1.3f;
zoomInY = 1.3f;
moveX = maxMoveX;
moveY = -maxMoveY;
break;
default:
originX = frameWidth - optimusWidth;
originY = 0; //Math.Max(frameHeight - (optimusHeight),frameHeight * 1/3);
zoomInX = 1.2f;
zoomInY = 1.2f;
moveX = maxMoveX;
moveY = maxMoveY;
break;
}
var picLayer = new CALayer { Contents = image.CGImage, AnchorPoint = PointF.Empty, Bounds = imageView.Bounds, Position = new PointF(originX, originY) };
imageView.Layer.AddSublayer(picLayer);
var animation = new CATransition { Duration = 1, Type = CAAnimation.TransitionFade, };
this.Layer.AddAnimation(animation, null);
this.Views.Enqueue(imageView);
while (this.Views.Count > imageBuffer)
{
this.Views.Dequeue().RemoveFromSuperview();
}
this.AddSubview(imageView);
Animate(
this.ImageDuration + 2,
0,
UIViewAnimationOptions.CurveEaseIn,
() =>
{
var t = CGAffineTransform.MakeRotation(rotation);
t.Translate(moveX, moveY);
t.Scale(zoomInX, zoomInY);
imageView.Transform = t;
},
null);
if (this.ImageIndexChanged != null)
{
this.ImageIndexChanged(this.currentIndex);
}
}
#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.Collections.Generic;
namespace System.Collections.Generic
{
/*============================================================
**
** Class: LowLevelDictionary<TKey, TValue>
**
** Private version of Dictionary<> for internal System.Private.CoreLib use. This
** permits sharing more source between BCL and System.Private.CoreLib (as well as the
** fact that Dictionary<> is just a useful class in general.)
**
** This does not strive to implement the full api surface area
** (but any portion it does implement should match the real Dictionary<>'s
** behavior.)
**
===========================================================*/
internal partial class LowLevelDictionary<TKey, TValue>
{
private const int DefaultSize = 17;
public LowLevelDictionary()
: this(DefaultSize, new DefaultComparer<TKey>())
{
}
public LowLevelDictionary(int capacity)
: this(capacity, new DefaultComparer<TKey>())
{
}
public LowLevelDictionary(IEqualityComparer<TKey> comparer) : this(DefaultSize, comparer)
{
}
public LowLevelDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_comparer = comparer;
Clear(capacity);
}
public int Count
{
get
{
return _numEntries;
}
}
public TValue this[TKey key]
{
get
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry == null)
throw new KeyNotFoundException();
return entry._value;
}
set
{
if (key == null)
throw new ArgumentNullException(nameof(key));
_version++;
Entry entry = Find(key);
if (entry != null)
entry._value = value;
else
UncheckedAdd(key, value);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry != null)
{
value = entry._value;
return true;
}
return false;
}
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry != null)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
_version++;
UncheckedAdd(key, value);
}
public void Clear(int capacity = DefaultSize)
{
_version++;
_buckets = new Entry[capacity];
_numEntries = 0;
}
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
int bucket = GetBucket(key);
Entry prev = null;
Entry entry = _buckets[bucket];
while (entry != null)
{
if (_comparer.Equals(key, entry._key))
{
if (prev == null)
{
_buckets[bucket] = entry._next;
}
else
{
prev._next = entry._next;
}
_version++;
_numEntries--;
return true;
}
prev = entry;
entry = entry._next;
}
return false;
}
private Entry Find(TKey key)
{
int bucket = GetBucket(key);
Entry entry = _buckets[bucket];
while (entry != null)
{
if (_comparer.Equals(key, entry._key))
return entry;
entry = entry._next;
}
return null;
}
private Entry UncheckedAdd(TKey key, TValue value)
{
Entry entry = new Entry();
entry._key = key;
entry._value = value;
int bucket = GetBucket(key);
entry._next = _buckets[bucket];
_buckets[bucket] = entry;
_numEntries++;
if (_numEntries > (_buckets.Length * 2))
ExpandBuckets();
return entry;
}
private void ExpandBuckets()
{
try
{
int newNumBuckets = _buckets.Length * 2 + 1;
Entry[] newBuckets = new Entry[newNumBuckets];
for (int i = 0; i < _buckets.Length; i++)
{
Entry entry = _buckets[i];
while (entry != null)
{
Entry nextEntry = entry._next;
int bucket = GetBucket(entry._key, newNumBuckets);
entry._next = newBuckets[bucket];
newBuckets[bucket] = entry;
entry = nextEntry;
}
}
_buckets = newBuckets;
}
catch (OutOfMemoryException)
{
}
}
private int GetBucket(TKey key, int numBuckets = 0)
{
int h = _comparer.GetHashCode(key);
h &= 0x7fffffff;
return (h % (numBuckets == 0 ? _buckets.Length : numBuckets));
}
private sealed class Entry
{
public TKey _key;
public TValue _value;
public Entry _next;
}
private Entry[] _buckets;
private int _numEntries;
private int _version;
private IEqualityComparer<TKey> _comparer;
// This comparator is used if no comparator is supplied. It emulates the behavior of EqualityComparer<T>.Default.
private sealed class DefaultComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
if (x == null)
return y == null;
IEquatable<T> iequatable = x as IEquatable<T>;
if (iequatable != null)
return iequatable.Equals(y);
return ((object)x).Equals(y);
}
public int GetHashCode(T obj)
{
return ((object)obj).GetHashCode();
}
}
}
}
| |
/*
Copyright (c) 2017 Ahmed Kh. Zamil
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.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using Esiur.Net.Sockets;
using Esiur.Data;
using Esiur.Misc;
using Esiur.Core;
using Esiur.Net.Packets;
using System.Security.Cryptography.X509Certificates;
using Esiur.Resource;
namespace Esiur.Net.HTTP;
public class HTTPServer : NetworkServer<HTTPConnection>, IResource
{
Dictionary<string, HTTPSession> sessions = new Dictionary<string, HTTPSession>();
HTTPFilter[] filters = new HTTPFilter[0];
public Instance Instance
{
get;
set;
}
[Attribute]
public virtual string IP
{
get;
set;
}
[Attribute]
public virtual ushort Port
{
get;
set;
}
//[Attribute]
//public virtual uint Timeout
//{
// get;
// set;
//}
//[Attribute]
//public virtual uint Clock
//{
// get;
// set;
//}
[Attribute]
public virtual uint MaxPost
{
get;
set;
}
[Attribute]
public virtual bool SSL
{
get;
set;
}
[Attribute]
public virtual string Certificate
{
get;
set;
}
public HTTPSession CreateSession(string id, int timeout)
{
var s = new HTTPSession();
s.Set(id, timeout);
sessions.Add(id, s);
return s;
}
public static string MakeCookie(string Item, string Value, DateTime Expires, string Domain, string Path, bool HttpOnly)
{
//Set-Cookie: ckGeneric=CookieBody; expires=Sun, 30-Dec-2001 21:00:00 GMT; domain=.com.au; path=/
//Set-Cookie: SessionID=another; expires=Fri, 29 Jun 2006 20:47:11 UTC; path=/
string Cookie = Item + "=" + Value;
if (Expires.Ticks != 0)
{
Cookie += "; expires=" + Expires.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
}
if (Domain != null)
{
Cookie += "; domain=" + Domain;
}
if (Path != null)
{
Cookie += "; path=" + Path;
}
if (HttpOnly)
{
Cookie += "; HttpOnly";
}
return Cookie;
}
protected override void ClientDisconnected(HTTPConnection connection)
{
foreach (var filter in filters)
filter.ClientDisconnected(connection);
}
internal bool Execute(HTTPConnection sender)
{
foreach (var resource in filters)
if (resource.Execute(sender).Wait(30000))
return true;
return false;
}
//public delegate void HTTPGetHandler(HTTPConnection connection, object[] params values);
public void MapGet(string pattern, Delegate handler)
{
// if (p)
}
/*
protected override void SessionEnded(NetworkSession session)
{
// verify wether there are no active connections related to the session
foreach (HTTPConnection c in Connections)//.Values)
{
if (c.Session == session)
{
session.Refresh();
return;
}
}
foreach (Instance instance in Instance.Children)
{
var f = (HTTPFilter)instance.Resource;
f.SessionExpired((HTTPSession)session);
}
base.SessionEnded((HTTPSession)session);
//Sessions.Remove(Session.ID);
//Session.Dispose();
}
*/
/*
public int TTL
{
get
{
return Timeout;// mTimeout;
}
}
*/
public async AsyncReply<bool> Trigger(ResourceTrigger trigger)
{
if (trigger == ResourceTrigger.Initialize)
{
//var ip = (IPAddress)Instance.Attributes["ip"];
//var port = (int)Instance.Attributes["port"];
//var ssl = (bool)Instance.Attributes["ssl"];
//var cert = (string)Instance.Attributes["certificate"];
//if (ip == null) ip = IPAddress.Any;
Sockets.ISocket listener;
IPAddress ipAdd;
if (IP == null)
ipAdd = IPAddress.Any;
else
ipAdd = IPAddress.Parse(IP);
if (SSL)
listener = new SSLSocket(new IPEndPoint(ipAdd, Port), new X509Certificate2(Certificate));
else
listener = new TCPSocket(new IPEndPoint(ipAdd, Port));
Start(listener);
}
else if (trigger == ResourceTrigger.Terminate)
{
Stop();
}
else if (trigger == ResourceTrigger.SystemReload)
{
await Trigger(ResourceTrigger.Terminate);
await Trigger(ResourceTrigger.Initialize);
}
else if (trigger == ResourceTrigger.SystemInitialized)
{
filters = await Instance.Children<HTTPFilter>();
}
return true;
}
public override void Add(HTTPConnection connection)
{
connection.Server = this;
base.Add(connection);
}
public override void Remove(HTTPConnection connection)
{
connection.Server = null;
base.Remove(connection);
}
protected override void ClientConnected(HTTPConnection connection)
{
if (filters.Length == 0)
{
connection.Close();
return;
}
foreach (var resource in filters)
{
resource.ClientConnected(connection);
}
}
/*
public int LocalPort
{
get
{
return cServer.LocalPort;
}
}
*/
/*
public HTTPServer(int Port)
{
cServer = new TServer();
cServer.LocalPort = Port;
cServer.StartServer();
cServer.ClientConnected += new TServer.eClientConnected(ClientConnected);
cServer.ClientDisConnected += new TServer.eClientDisConnected(ClientDisConnected);
cServer.ClientIsSwitching += new TServer.eClientIsSwitching(ClientIsSwitching);
cServer.DataReceived += new TServer.eDataReceived(DataReceived);
}*/
//~HTTPServer()
//{
// cServer.StopServer();
//}
}
| |
/* ====================================================================
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 NPOI.XSSF.Model;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.XSSF.UserModel.Extensions;
using NUnit.Framework;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Drawing;
using NPOI.HSSF.Util;
using NPOI.XSSF.UserModel;
using NPOI.XSSF;
namespace TestCases.XSSF.UserModel
{
[TestFixture]
public class TestXSSFCellStyle
{
private StylesTable stylesTable;
private CT_Border ctBorderA;
private CT_Fill ctFill;
private CT_Font ctFont;
private CT_Xf cellStyleXf;
private CT_Xf cellXf;
private CT_CellXfs cellXfs;
private XSSFCellStyle cellStyle;
private CT_Stylesheet ctStylesheet;
[SetUp]
public void SetUp()
{
stylesTable = new StylesTable();
ctStylesheet = stylesTable.GetCTStylesheet();
ctBorderA = new CT_Border();
XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA);
long borderId = stylesTable.PutBorder(borderA);
Assert.AreEqual(1, borderId);
XSSFCellBorder borderB = new XSSFCellBorder();
Assert.AreEqual(1, stylesTable.PutBorder(borderB));
ctFill = new CT_Fill();
XSSFCellFill fill = new XSSFCellFill(ctFill);
long fillId = stylesTable.PutFill(fill);
Assert.AreEqual(2, fillId);
ctFont = new CT_Font();
XSSFFont font = new XSSFFont(ctFont);
long fontId = stylesTable.PutFont(font);
Assert.AreEqual(1, fontId);
cellStyleXf = ctStylesheet.AddNewCellStyleXfs().AddNewXf();
cellStyleXf.borderId = 1;
cellStyleXf.fillId = 1;
cellStyleXf.fontId = 1;
cellXfs = ctStylesheet.AddNewCellXfs();
cellXf = cellXfs.AddNewXf();
cellXf.xfId = (1);
cellXf.borderId = (1);
cellXf.fillId = (1);
cellXf.fontId = (1);
stylesTable.PutCellStyleXf(cellStyleXf);
stylesTable.PutCellXf(cellXf);
cellStyle = new XSSFCellStyle(1, 1, stylesTable, null);
Assert.IsNotNull(stylesTable.GetFillAt(1).GetCTFill().patternFill);
Assert.AreEqual(ST_PatternType.darkGray, stylesTable.GetFillAt(1).GetCTFill().patternFill.patternType);
}
[Test]
public void TestGetSetBorderBottom()
{
//default values
Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom);
int num = stylesTable.GetBorders().Count;
cellStyle.BorderBottom = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom);
//a new border has been Added
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.AreEqual(ST_BorderStyle.medium, ctBorder.bottom.style);
num = stylesTable.GetBorders().Count;
//setting the same border multiple times should not change borderId
for (int i = 0; i < 3; i++)
{
cellStyle.BorderBottom = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom);
}
Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
Assert.AreSame(ctBorder, stylesTable.GetBorderAt(borderId).GetCTBorder());
//setting border to none Removes the <bottom> element
cellStyle.BorderBottom = (BorderStyle.None);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
borderId = (int)cellStyle.GetCoreXf().borderId;
ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.IsFalse(ctBorder.IsSetBottom());
}
[Test]
public void TestSetServeralBordersOnSameCell()
{
Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight);
Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft);
Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop);
Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom);
Assert.AreEqual(2, stylesTable.GetBorders().Count);
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BottomBorderColor = HSSFColor.Black.Index;
cellStyle.BorderLeft = BorderStyle.DashDotDot;
cellStyle.LeftBorderColor = HSSFColor.Green.Index;
cellStyle.BorderRight = BorderStyle.Hair;
cellStyle.RightBorderColor = HSSFColor.Blue.Index;
cellStyle.BorderTop = BorderStyle.MediumDashed;
cellStyle.TopBorderColor = HSSFColor.Orange.Index;
//only one border style should be generated
Assert.AreEqual(3, stylesTable.GetBorders().Count);
}
[Ignore("not found in poi")]
[Test]
public void TestGetSetBorderDiagonal()
{
Assert.AreEqual(BorderDiagonal.None, cellStyle.BorderDiagonal);
int num = stylesTable.GetBorders().Count;
cellStyle.BorderDiagonalLineStyle = BorderStyle.Medium;
cellStyle.BorderDiagonalColor = HSSFColor.Red.Index;
cellStyle.BorderDiagonal = BorderDiagonal.Backward;
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderDiagonalLineStyle);
//a new border has been added
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the created border
uint borderId = cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.AreEqual(ST_BorderStyle.medium, ctBorder.diagonal.style);
num = stylesTable.GetBorders().Count;
//setting the same border multiple times should not change borderId
for (int i = 0; i < 3; i++)
{
cellStyle.BorderDiagonal = BorderDiagonal.Backward;
Assert.AreEqual(BorderDiagonal.Backward, cellStyle.BorderDiagonal);
}
Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder());
cellStyle.BorderDiagonal = (BorderDiagonal.None);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
borderId = cellStyle.GetCoreXf().borderId;
ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.IsFalse(ctBorder.IsSetDiagonal());
}
[Test]
public void TestGetSetBorderRight()
{
//default values
Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight);
int num = stylesTable.GetBorders().Count;
cellStyle.BorderRight = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight);
//a new border has been Added
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
uint borderId = cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.AreEqual(ST_BorderStyle.medium, ctBorder.right.style);
num = stylesTable.GetBorders().Count;
//setting the same border multiple times should not change borderId
for (int i = 0; i < 3; i++)
{
cellStyle.BorderRight = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight);
}
Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder());
//setting border to none Removes the <right> element
cellStyle.BorderRight = (BorderStyle.None);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
borderId = cellStyle.GetCoreXf().borderId;
ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.IsFalse(ctBorder.IsSetRight());
}
[Test]
public void TestGetSetBorderLeft()
{
//default values
Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft);
int num = stylesTable.GetBorders().Count;
cellStyle.BorderLeft = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft);
//a new border has been Added
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
uint borderId = cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.AreEqual(ST_BorderStyle.medium, ctBorder.left.style);
num = stylesTable.GetBorders().Count;
//setting the same border multiple times should not change borderId
for (int i = 0; i < 3; i++)
{
cellStyle.BorderLeft = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft);
}
Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder());
//setting border to none Removes the <left> element
cellStyle.BorderLeft = (BorderStyle.None);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
borderId = cellStyle.GetCoreXf().borderId;
ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.IsFalse(ctBorder.IsSetLeft());
}
[Test]
public void TestGetSetBorderTop()
{
//default values
Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop);
int num = stylesTable.GetBorders().Count;
cellStyle.BorderTop = BorderStyle.Medium;
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop);
//a new border has been Added
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
uint borderId = cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.AreEqual(ST_BorderStyle.medium, ctBorder.top.style);
num = stylesTable.GetBorders().Count;
//setting the same border multiple times should not change borderId
for (int i = 0; i < 3; i++)
{
cellStyle.BorderTop = BorderStyle.Medium;
Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop);
}
Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId);
Assert.AreEqual(num, stylesTable.GetBorders().Count);
Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder());
//setting border to none Removes the <top> element
cellStyle.BorderTop = BorderStyle.None;
Assert.AreEqual(num, stylesTable.GetBorders().Count);
borderId = cellStyle.GetCoreXf().borderId;
ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.IsFalse(ctBorder.IsSetTop());
}
private void TestGetSetBorderXMLBean(BorderStyle border, ST_BorderStyle expected)
{
cellStyle.BorderTop = border;
Assert.AreEqual(border, cellStyle.BorderTop);
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.AreEqual(expected, ctBorder.top.style);
}
// Border Styles, in BorderStyle/ST_BorderStyle enum order
[Test]
public void TestGetSetBorderNone() {
cellStyle.BorderTop = BorderStyle.None;
Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop);
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.IsNull(ctBorder.top);
// no border style and ST_BorderStyle.NONE are equivalent
// POI prefers to unset the border style than explicitly set it ST_BorderStyle.NONE
}
[Test]
public void TestGetSetBorderThin()
{
TestGetSetBorderXMLBean(BorderStyle.Thin, ST_BorderStyle.thin);
}
[Test]
public void TestGetSetBorderMedium()
{
TestGetSetBorderXMLBean(BorderStyle.Medium, ST_BorderStyle.medium);
}
[Test]
public void TestGetSetBorderDashed()
{
TestGetSetBorderXMLBean(BorderStyle.Dashed, ST_BorderStyle.dashed);
}
[Test]
public void TestGetSetBorderDotted()
{
TestGetSetBorderXMLBean(BorderStyle.Dotted, ST_BorderStyle.dotted);
}
[Test]
public void TestGetSetBorderThick()
{
TestGetSetBorderXMLBean(BorderStyle.Thick, ST_BorderStyle.thick);
}
[Test]
public void TestGetSetBorderDouble()
{
TestGetSetBorderXMLBean(BorderStyle.Double, ST_BorderStyle.@double);
}
[Test]
public void TestGetSetBorderHair()
{
TestGetSetBorderXMLBean(BorderStyle.Hair, ST_BorderStyle.hair);
}
[Test]
public void TestGetSetBorderMediumDashed()
{
TestGetSetBorderXMLBean(BorderStyle.MediumDashed, ST_BorderStyle.mediumDashed);
}
[Test]
public void TestGetSetBorderDashDot()
{
TestGetSetBorderXMLBean(BorderStyle.DashDot, ST_BorderStyle.dashDot);
}
[Test]
public void TestGetSetBorderMediumDashDot()
{
TestGetSetBorderXMLBean(BorderStyle.MediumDashDot, ST_BorderStyle.mediumDashDot);
}
[Test]
public void TestGetSetBorderDashDotDot()
{
TestGetSetBorderXMLBean(BorderStyle.DashDotDot, ST_BorderStyle.dashDotDot);
}
[Test]
public void TestGetSetBorderMediumDashDotDot()
{
TestGetSetBorderXMLBean(BorderStyle.MediumDashDotDot, ST_BorderStyle.mediumDashDotDot);
}
[Test]
public void TestGetSetBorderSlantDashDot()
{
TestGetSetBorderXMLBean(BorderStyle.SlantedDashDot, ST_BorderStyle.slantDashDot);
}
[Test]
public void TestGetSetBottomBorderColor()
{
//defaults
Assert.AreEqual(IndexedColors.Black.Index, cellStyle.BottomBorderColor);
Assert.IsNull(cellStyle.BottomBorderXSSFColor);
int num = stylesTable.GetBorders().Count;
XSSFColor clr;
//setting indexed color
cellStyle.BottomBorderColor = (IndexedColors.BlueGrey.Index);
Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.BottomBorderColor);
clr = cellStyle.BottomBorderXSSFColor;
Assert.IsTrue(clr.GetCTColor().IsSetIndexed());
Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed);
//a new border was Added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
uint borderId = cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder();
Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.bottom.color.indexed);
//setting XSSFColor
num = stylesTable.GetBorders().Count;
clr = new XSSFColor(Color.Cyan);
cellStyle.SetBottomBorderColor(clr);
Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.BottomBorderXSSFColor.GetCTColor().ToString());
byte[] rgb = cellStyle.BottomBorderXSSFColor.GetRgb();
Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb());
//another border was Added to the styles table
Assert.AreEqual(num, stylesTable.GetBorders().Count);
//passing null unsets the color
cellStyle.SetBottomBorderColor(null);
Assert.IsNull(cellStyle.BottomBorderXSSFColor);
}
[Test]
public void TestGetSetTopBorderColor()
{
//defaults
Assert.AreEqual(IndexedColors.Black.Index, cellStyle.TopBorderColor);
Assert.IsNull(cellStyle.TopBorderXSSFColor);
int num = stylesTable.GetBorders().Count;
XSSFColor clr;
//setting indexed color
cellStyle.TopBorderColor = (IndexedColors.BlueGrey.Index);
Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.TopBorderColor);
clr = cellStyle.TopBorderXSSFColor;
Assert.IsTrue(clr.GetCTColor().IsSetIndexed());
Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed);
//a new border was added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.top.color.indexed);
//setting XSSFColor
num = stylesTable.GetBorders().Count;
clr = new XSSFColor(Color.Cyan);
cellStyle.SetTopBorderColor(clr);
Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.TopBorderXSSFColor.GetCTColor().ToString());
byte[] rgb = cellStyle.TopBorderXSSFColor.GetRgb();
Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0], rgb[1], rgb[2]).ToArgb());
//another border was added to the styles table
Assert.AreEqual(num, stylesTable.GetBorders().Count);
//passing null unsets the color
cellStyle.SetTopBorderColor(null);
Assert.IsNull(cellStyle.TopBorderXSSFColor);
}
[Test]
public void TestGetSetLeftBorderColor()
{
//defaults
Assert.AreEqual(IndexedColors.Black.Index, cellStyle.LeftBorderColor);
Assert.IsNull(cellStyle.LeftBorderXSSFColor);
int num = stylesTable.GetBorders().Count;
XSSFColor clr;
//setting indexed color
cellStyle.LeftBorderColor = (IndexedColors.BlueGrey.Index);
Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.LeftBorderColor);
clr = cellStyle.LeftBorderXSSFColor;
Assert.IsTrue(clr.GetCTColor().IsSetIndexed());
Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed);
//a new border was Added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.left.color.indexed);
//setting XSSFColor
num = stylesTable.GetBorders().Count;
clr = new XSSFColor(Color.Cyan);
cellStyle.SetLeftBorderColor(clr);
Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.LeftBorderXSSFColor.GetCTColor().ToString());
byte[] rgb = cellStyle.LeftBorderXSSFColor.GetRgb();
Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb());
//another border was Added to the styles table
Assert.AreEqual(num, stylesTable.GetBorders().Count);
//passing null unsets the color
cellStyle.SetLeftBorderColor(null);
Assert.IsNull(cellStyle.LeftBorderXSSFColor);
}
[Test]
public void TestGetSetRightBorderColor()
{
//defaults
Assert.AreEqual(IndexedColors.Black.Index, cellStyle.RightBorderColor);
Assert.IsNull(cellStyle.RightBorderXSSFColor);
int num = stylesTable.GetBorders().Count;
XSSFColor clr;
//setting indexed color
cellStyle.RightBorderColor = (IndexedColors.BlueGrey.Index);
Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.RightBorderColor);
clr = cellStyle.RightBorderXSSFColor;
Assert.IsTrue(clr.GetCTColor().IsSetIndexed());
Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed);
//a new border was Added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetBorders().Count);
//id of the Created border
int borderId = (int)cellStyle.GetCoreXf().borderId;
Assert.IsTrue(borderId > 0);
//check Changes in the underlying xml bean
CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder();
Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.right.color.indexed);
//setting XSSFColor
num = stylesTable.GetBorders().Count;
clr = new XSSFColor(Color.Cyan);
cellStyle.SetRightBorderColor(clr);
Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.RightBorderXSSFColor.GetCTColor().ToString());
byte[] rgb = cellStyle.RightBorderXSSFColor.GetRgb();
Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb());
//another border was Added to the styles table
Assert.AreEqual(num, stylesTable.GetBorders().Count);
//passing null unsets the color
cellStyle.SetRightBorderColor(null);
Assert.IsNull(cellStyle.RightBorderXSSFColor);
}
[Test]
public void TestGetSetFillBackgroundColor()
{
Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor);
Assert.IsNull(cellStyle.FillBackgroundColorColor);
XSSFColor clr;
int num = stylesTable.GetFills().Count;
//setting indexed color
cellStyle.FillBackgroundColor = (IndexedColors.Red.Index);
Assert.AreEqual(IndexedColors.Red.Index, cellStyle.FillBackgroundColor);
clr = (XSSFColor)cellStyle.FillBackgroundColorColor;
Assert.IsTrue(clr.GetCTColor().IsSetIndexed());
Assert.AreEqual(IndexedColors.Red.Index, clr.Indexed);
//a new fill was Added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetFills().Count);
//id of the Created border
int FillId = (int)cellStyle.GetCoreXf().fillId;
Assert.IsTrue(FillId > 0);
//check changes in the underlying xml bean
CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill();
Assert.AreEqual((uint)IndexedColors.Red.Index, ctFill.GetPatternFill().bgColor.indexed);
//setting XSSFColor
num = stylesTable.GetFills().Count;
clr = new XSSFColor(Color.Cyan);
cellStyle.SetFillBackgroundColor(clr); // TODO this testcase assumes that cellStyle creates a new CT_Fill, but the implementation changes the existing style. - do not know whats right 8-(
Assert.AreEqual(clr.GetCTColor().ToString(), ((XSSFColor)cellStyle.FillBackgroundColorColor).GetCTColor().ToString());
byte[] rgb = ((XSSFColor)cellStyle.FillBackgroundColorColor).GetRgb();
Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb());
//another border was added to the styles table
Assert.AreEqual(num + 1, stylesTable.GetFills().Count);
//passing null unsets the color
cellStyle.SetFillBackgroundColor(null);
Assert.IsNull(cellStyle.FillBackgroundColorColor);
Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor);
}
[Test]
public void TestDefaultStyles()
{
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFCellStyle style1 = (XSSFCellStyle)wb1.CreateCellStyle();
Assert.AreEqual(IndexedColors.Automatic.Index, style1.FillBackgroundColor);
Assert.IsNull(style1.FillBackgroundColorColor);
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb1));
//compatibility with HSSF
HSSFWorkbook wb2 = new HSSFWorkbook();
HSSFCellStyle style2 = (HSSFCellStyle)wb2.CreateCellStyle();
Assert.AreEqual(style2.FillBackgroundColor, style1.FillBackgroundColor);
Assert.AreEqual(style2.FillForegroundColor, style1.FillForegroundColor);
Assert.AreEqual(style2.FillPattern, style1.FillPattern);
Assert.AreEqual(style2.LeftBorderColor, style1.LeftBorderColor);
Assert.AreEqual(style2.TopBorderColor, style1.TopBorderColor);
Assert.AreEqual(style2.RightBorderColor, style1.RightBorderColor);
Assert.AreEqual(style2.BottomBorderColor, style1.BottomBorderColor);
Assert.AreEqual(style2.BorderBottom, style1.BorderBottom);
Assert.AreEqual(style2.BorderLeft, style1.BorderLeft);
Assert.AreEqual(style2.BorderRight, style1.BorderRight);
Assert.AreEqual(style2.BorderTop, style1.BorderTop);
wb2.Close();
}
[Ignore("test")]
public void TestGetFillForegroundColor()
{
XSSFWorkbook wb = new XSSFWorkbook();
StylesTable styles = wb.GetStylesSource();
Assert.AreEqual(1, wb.NumCellStyles);
Assert.AreEqual(2, styles.GetFills().Count);
XSSFCellStyle defaultStyle = (XSSFCellStyle)wb.GetCellStyleAt((short)0);
Assert.AreEqual(IndexedColors.Automatic.Index, defaultStyle.FillForegroundColor);
Assert.AreEqual(null, defaultStyle.FillForegroundColorColor);
Assert.AreEqual(FillPattern.NoFill, defaultStyle.FillPattern);
XSSFCellStyle customStyle = (XSSFCellStyle)wb.CreateCellStyle();
customStyle.FillPattern = (FillPattern.SolidForeground);
Assert.AreEqual(FillPattern.SolidForeground, customStyle.FillPattern);
Assert.AreEqual(3, styles.GetFills().Count);
customStyle.FillForegroundColor = (IndexedColors.BrightGreen.Index);
Assert.AreEqual(IndexedColors.BrightGreen.Index, customStyle.FillForegroundColor);
Assert.AreEqual(4, styles.GetFills().Count);
for (int i = 0; i < 3; i++)
{
XSSFCellStyle style = (XSSFCellStyle)wb.CreateCellStyle();
style.FillPattern = (FillPattern.SolidForeground);
Assert.AreEqual(FillPattern.SolidForeground, style.FillPattern);
Assert.AreEqual(4, styles.GetFills().Count);
style.FillForegroundColor = (IndexedColors.BrightGreen.Index);
Assert.AreEqual(IndexedColors.BrightGreen.Index, style.FillForegroundColor);
Assert.AreEqual(4, styles.GetFills().Count);
}
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb));
}
[Test]
public void TestGetFillPattern()
{
//???
//assertEquals(STPatternType.INT_DARK_GRAY-1, cellStyle.getFillPattern());
Assert.AreEqual((int)ST_PatternType.darkGray, (int)cellStyle.FillPattern);
int num = stylesTable.GetFills().Count;
cellStyle.FillPattern = (FillPattern.SolidForeground);
Assert.AreEqual(FillPattern.SolidForeground, cellStyle.FillPattern);
Assert.AreEqual(num + 1, stylesTable.GetFills().Count);
int FillId = (int)cellStyle.GetCoreXf().fillId;
Assert.IsTrue(FillId > 0);
//check Changes in the underlying xml bean
CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill();
Assert.AreEqual(ST_PatternType.solid, ctFill.GetPatternFill().patternType);
//setting the same fill multiple time does not update the styles table
for (int i = 0; i < 3; i++)
{
cellStyle.FillPattern = (FillPattern.SolidForeground);
}
Assert.AreEqual(num + 1, stylesTable.GetFills().Count);
cellStyle.FillPattern = (FillPattern.NoFill);
Assert.AreEqual(FillPattern.NoFill, cellStyle.FillPattern);
FillId = (int)cellStyle.GetCoreXf().fillId;
ctFill = stylesTable.GetFillAt(FillId).GetCTFill();
Assert.IsFalse(ctFill.GetPatternFill().IsSetPatternType());
}
[Test]
public void TestGetFont()
{
Assert.IsNotNull(cellStyle.GetFont());
}
[Test]
public void TestGetSetHidden()
{
Assert.IsFalse(cellStyle.IsHidden);
cellStyle.IsHidden = (true);
Assert.IsTrue(cellStyle.IsHidden);
cellStyle.IsHidden = (false);
Assert.IsFalse(cellStyle.IsHidden);
}
[Test]
public void TestGetSetLocked()
{
Assert.IsTrue(cellStyle.IsLocked);
cellStyle.IsLocked = (true);
Assert.IsTrue(cellStyle.IsLocked);
cellStyle.IsLocked = (false);
Assert.IsFalse(cellStyle.IsLocked);
}
[Test]
public void TestGetSetIndent()
{
Assert.AreEqual((short)0, cellStyle.Indention);
cellStyle.Indention = ((short)3);
Assert.AreEqual((short)3, cellStyle.Indention);
cellStyle.Indention = ((short)13);
Assert.AreEqual((short)13, cellStyle.Indention);
}
[Test]
public void TestGetSetAlignement()
{
Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().horizontalSpecified);
Assert.AreEqual(HorizontalAlignment.General, cellStyle.Alignment);
cellStyle.Alignment = HorizontalAlignment.Left;
Assert.AreEqual(HorizontalAlignment.Left, cellStyle.Alignment);
Assert.AreEqual(ST_HorizontalAlignment.left, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal);
cellStyle.Alignment = (HorizontalAlignment.Justify);
Assert.AreEqual(HorizontalAlignment.Justify, cellStyle.Alignment);
Assert.AreEqual(ST_HorizontalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal);
cellStyle.Alignment = (HorizontalAlignment.Center);
Assert.AreEqual(HorizontalAlignment.Center, cellStyle.Alignment);
Assert.AreEqual(ST_HorizontalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal);
}
[Test]
public void TestGetSetVerticalAlignment()
{
Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment);
Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().verticalSpecified);
cellStyle.VerticalAlignment = (VerticalAlignment.Top);
Assert.AreEqual(VerticalAlignment.Top, cellStyle.VerticalAlignment);
Assert.AreEqual(ST_VerticalAlignment.top, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical);
cellStyle.VerticalAlignment = (VerticalAlignment.Center);
Assert.AreEqual(VerticalAlignment.Center, cellStyle.VerticalAlignment);
Assert.AreEqual(ST_VerticalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical);
cellStyle.VerticalAlignment = VerticalAlignment.Justify;
Assert.AreEqual(VerticalAlignment.Justify, cellStyle.VerticalAlignment);
Assert.AreEqual(ST_VerticalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical);
cellStyle.VerticalAlignment = (VerticalAlignment.Bottom);
Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment);
Assert.AreEqual(ST_VerticalAlignment.bottom, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical);
}
[Test]
public void TestGetSetWrapText()
{
Assert.IsFalse(cellStyle.WrapText);
cellStyle.WrapText = (true);
Assert.IsTrue(cellStyle.WrapText);
cellStyle.WrapText = (false);
Assert.IsFalse(cellStyle.WrapText);
}
/**
* Cloning one XSSFCellStyle onto Another, same XSSFWorkbook
*/
[Test]
public void TestCloneStyleSameWB()
{
XSSFWorkbook wb = new XSSFWorkbook();
Assert.AreEqual(1, wb.NumberOfFonts);
XSSFFont fnt = (XSSFFont)wb.CreateFont();
fnt.FontName = ("TestingFont");
Assert.AreEqual(2, wb.NumberOfFonts);
XSSFCellStyle orig = (XSSFCellStyle)wb.CreateCellStyle();
orig.Alignment = (HorizontalAlignment.Right);
orig.SetFont(fnt);
orig.DataFormat = (short)18;
Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
Assert.AreEqual(fnt, orig.GetFont());
Assert.AreEqual(18, orig.DataFormat);
XSSFCellStyle clone = (XSSFCellStyle)wb.CreateCellStyle();
Assert.AreNotEqual(HorizontalAlignment.Right, clone.Alignment);
Assert.AreNotEqual(fnt, clone.GetFont());
Assert.AreNotEqual(18, clone.DataFormat);
clone.CloneStyleFrom(orig);
Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
Assert.AreEqual(fnt, clone.GetFont());
Assert.AreEqual(18, clone.DataFormat);
Assert.AreEqual(2, wb.NumberOfFonts);
clone.Alignment = HorizontalAlignment.Left;
clone.DataFormat = 17;
Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
Assert.AreEqual(18, orig.DataFormat);
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb));
}
/**
* Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks
*/
[Test]
public void TestCloneStyleDiffWB()
{
XSSFWorkbook wbOrig = new XSSFWorkbook();
Assert.AreEqual(1, wbOrig.NumberOfFonts);
Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count);
XSSFFont fnt = (XSSFFont)wbOrig.CreateFont();
fnt.FontName = ("TestingFont");
Assert.AreEqual(2, wbOrig.NumberOfFonts);
Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count);
XSSFDataFormat fmt = (XSSFDataFormat)wbOrig.CreateDataFormat();
fmt.GetFormat("MadeUpOne");
fmt.GetFormat("MadeUpTwo");
XSSFCellStyle orig = (XSSFCellStyle)wbOrig.CreateCellStyle();
orig.Alignment = (HorizontalAlignment.Right);
orig.SetFont(fnt);
orig.DataFormat = (fmt.GetFormat("Test##"));
Assert.IsTrue(HorizontalAlignment.Right == orig.Alignment);
Assert.IsTrue(fnt == orig.GetFont());
Assert.IsTrue(fmt.GetFormat("Test##") == orig.DataFormat);
Assert.AreEqual(2, wbOrig.NumberOfFonts);
Assert.AreEqual(3, wbOrig.GetStylesSource().GetNumberFormats().Count);
// Now a style on another workbook
XSSFWorkbook wbClone = new XSSFWorkbook();
Assert.AreEqual(1, wbClone.NumberOfFonts);
Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count);
Assert.AreEqual(1, wbClone.NumCellStyles);
XSSFDataFormat fmtClone = (XSSFDataFormat)wbClone.CreateDataFormat();
XSSFCellStyle clone = (XSSFCellStyle)wbClone.CreateCellStyle();
Assert.AreEqual(1, wbClone.NumberOfFonts);
Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count);
Assert.IsFalse(HorizontalAlignment.Right == clone.Alignment);
Assert.IsFalse("TestingFont" == clone.GetFont().FontName);
clone.CloneStyleFrom(orig);
Assert.AreEqual(2, wbClone.NumberOfFonts);
Assert.AreEqual(2, wbClone.NumCellStyles);
Assert.AreEqual(1, wbClone.GetStylesSource().GetNumberFormats().Count);
Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
Assert.AreEqual("TestingFont", clone.GetFont().FontName);
Assert.AreEqual(fmtClone.GetFormat("Test##"), clone.DataFormat);
Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##"));
// Save it and re-check
XSSFWorkbook wbReload = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wbClone);
Assert.AreEqual(2, wbReload.NumberOfFonts);
Assert.AreEqual(2, wbReload.NumCellStyles);
Assert.AreEqual(1, wbReload.GetStylesSource().GetNumberFormats().Count);
XSSFCellStyle reload = (XSSFCellStyle)wbReload.GetCellStyleAt((short)1);
Assert.AreEqual(HorizontalAlignment.Right, reload.Alignment);
Assert.AreEqual("TestingFont", reload.GetFont().FontName);
Assert.AreEqual(fmtClone.GetFormat("Test##"), reload.DataFormat);
Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##"));
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbOrig));
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbClone));
}
/**
* Avoid ArrayIndexOutOfBoundsException when creating cell style
* in a workbook that has an empty xf table.
*/
[Test]
public void TestBug52348()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("52348.xlsx");
StylesTable st = workbook.GetStylesSource();
Assert.AreEqual(0, st.StyleXfsSize);
XSSFCellStyle style = workbook.CreateCellStyle() as XSSFCellStyle; // no exception at this point
Assert.IsNull(style.GetStyleXf());
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(workbook));
}
/**
* Avoid ArrayIndexOutOfBoundsException when getting cell style
* in a workbook that has an empty xf table.
*/
[Test]
public void TestBug55650()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("52348.xlsx");
StylesTable st = workbook.GetStylesSource();
Assert.AreEqual(0, st.StyleXfsSize);
// no exception at this point
XSSFCellStyle style = workbook.GetSheetAt(0).GetRow(0).GetCell(0).CellStyle as XSSFCellStyle;
Assert.IsNull(style.GetStyleXf());
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(workbook));
}
[Test]
public void TestShrinkToFit()
{
// Existing file
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("ShrinkToFit.xlsx");
ISheet s = wb.GetSheetAt(0);
IRow r = s.GetRow(0);
ICellStyle cs = r.GetCell(0).CellStyle;
Assert.AreEqual(true, cs.ShrinkToFit);
// New file
XSSFWorkbook wbOrig = new XSSFWorkbook();
s = wbOrig.CreateSheet();
r = s.CreateRow(0);
cs = wbOrig.CreateCellStyle();
cs.ShrinkToFit = (/*setter*/false);
r.CreateCell(0).CellStyle = (/*setter*/cs);
cs = wbOrig.CreateCellStyle();
cs.ShrinkToFit = (/*setter*/true);
r.CreateCell(1).CellStyle = (/*setter*/cs);
// Write out1, Read, and check
wb = XSSFTestDataSamples.WriteOutAndReadBack(wbOrig) as XSSFWorkbook;
s = wb.GetSheetAt(0);
r = s.GetRow(0);
Assert.AreEqual(false, r.GetCell(0).CellStyle.ShrinkToFit);
Assert.AreEqual(true, r.GetCell(1).CellStyle.ShrinkToFit);
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb));
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbOrig));
}
[Test]
public void TestSetColor()
{
IWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
//CreationHelper ch = wb.GetCreationHelper();
IDataFormat format = wb.CreateDataFormat();
ICell cell = row.CreateCell(1);
cell.SetCellValue("somEvalue");
ICellStyle cellStyle = wb.CreateCellStyle();
cellStyle.DataFormat = (/*setter*/format.GetFormat("###0"));
cellStyle.FillBackgroundColor = (/*setter*/IndexedColors.DarkBlue.Index);
cellStyle.FillForegroundColor = (/*setter*/IndexedColors.DarkBlue.Index);
cellStyle.FillPattern = FillPattern.SolidForeground;
cellStyle.Alignment = HorizontalAlignment.Right;
cellStyle.VerticalAlignment = VerticalAlignment.Top;
cell.CellStyle = (/*setter*/cellStyle);
/*OutputStream stream = new FileOutputStream("C:\\temp\\CellColor.xlsx");
try {
wb.Write(stream);
} finally {
stream.Close();
}*/
IWorkbook wbBack = XSSFTestDataSamples.WriteOutAndReadBack(wb);
ICell cellBack = wbBack.GetSheetAt(0).GetRow(0).GetCell(1);
Assert.IsNotNull(cellBack);
ICellStyle styleBack = cellBack.CellStyle;
Assert.AreEqual(IndexedColors.DarkBlue.Index, styleBack.FillBackgroundColor);
Assert.AreEqual(IndexedColors.DarkBlue.Index, styleBack.FillForegroundColor);
Assert.AreEqual(HorizontalAlignment.Right, styleBack.Alignment);
Assert.AreEqual(VerticalAlignment.Top, styleBack.VerticalAlignment);
Assert.AreEqual(FillPattern.SolidForeground, styleBack.FillPattern);
wbBack.Close();
wb.Close();
}
public static void copyStyles(IWorkbook reference, IWorkbook target)
{
int numberOfStyles = reference.NumCellStyles;
// don't copy default style (style index 0)
for (int i = 1; i < numberOfStyles; i++)
{
ICellStyle referenceStyle = reference.GetCellStyleAt(i);
ICellStyle targetStyle = target.CreateCellStyle();
targetStyle.CloneStyleFrom(referenceStyle);
}
/*System.out.println("Reference : "+reference.NumCellStyles);
System.out.println("Target : "+target.NumCellStyles);*/
}
[Test]
public void Test58084()
{
IWorkbook reference = XSSFTestDataSamples.OpenSampleWorkbook("template.xlsx");
IWorkbook target = new XSSFWorkbook();
copyStyles(reference, target);
Assert.AreEqual(reference.NumCellStyles, target.NumCellStyles);
ISheet sheet = target.CreateSheet();
IRow row = sheet.CreateRow(0);
int col = 0;
for (short i = 1; i < target.NumCellStyles; i++)
{
ICell cell = row.CreateCell(col++);
cell.SetCellValue("Coucou" + i);
cell.CellStyle = (target.GetCellStyleAt(i));
}
/*OutputStream out = new FileOutputStream("C:\\temp\\58084.xlsx");
target.write(out);
out.close();*/
IWorkbook copy = XSSFTestDataSamples.WriteOutAndReadBack(target);
// previously this Assert.Failed because the border-element was not copied over
var xxx = copy.GetCellStyleAt((short)1).BorderBottom;
copy.Close();
target.Close();
reference.Close();
}
[Test]
public void Test58043()
{
Assert.AreEqual(0, cellStyle.Rotation);
cellStyle.Rotation = ((short)89);
Assert.AreEqual(89, cellStyle.Rotation);
cellStyle.Rotation = ((short)90);
Assert.AreEqual(90, cellStyle.Rotation);
cellStyle.Rotation = ((short)179);
Assert.AreEqual(179, cellStyle.Rotation);
cellStyle.Rotation = ((short)180);
Assert.AreEqual(180, cellStyle.Rotation);
// negative values are mapped to the correct values for compatibility between HSSF and XSSF
cellStyle.Rotation = ((short)-1);
Assert.AreEqual(91, cellStyle.Rotation);
cellStyle.Rotation = ((short)-89);
Assert.AreEqual(179, cellStyle.Rotation);
cellStyle.Rotation = ((short)-90);
Assert.AreEqual(180, cellStyle.Rotation);
}
[Test]
public void Bug58996_UsedToWorkIn3_11_ButNotIn3_13()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFCellStyle cellStyle = workbook.CreateCellStyle() as XSSFCellStyle;
cellStyle.FillForegroundColorColor = (null);
Assert.IsNull(cellStyle.FillForegroundColorColor);
cellStyle.FillBackgroundColorColor = (null);
Assert.IsNull(cellStyle.FillBackgroundColorColor);
cellStyle.FillPattern = FillPattern.NoFill;;
Assert.AreEqual(FillPattern.NoFill, cellStyle.FillPattern);
cellStyle.SetBottomBorderColor(null);
Assert.IsNull(cellStyle.BottomBorderXSSFColor);
cellStyle.SetTopBorderColor(null);
Assert.IsNull(cellStyle.TopBorderXSSFColor);
cellStyle.SetLeftBorderColor(null);
Assert.IsNull(cellStyle.LeftBorderXSSFColor);
cellStyle.SetRightBorderColor(null);
Assert.IsNull(cellStyle.RightBorderXSSFColor);
}
}
}
| |
// 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;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Name used for AGGDECLs in the symbol table.
// AggregateSymbol - a symbol representing an aggregate type. These are classes,
// interfaces, and structs. Parent is a namespace or class. Children are methods,
// properties, and member variables, and types (including its own AGGTYPESYMs).
internal class AggregateSymbol : NamespaceOrAggregateSymbol
{
public Type AssociatedSystemType;
public Assembly AssociatedAssembly;
// This InputFile is some infile for the assembly containing this AggregateSymbol.
// It is used for fast access to the filter BitSet and assembly ID.
private InputFile _infile;
// The instance type. Created when first needed.
private AggregateType _atsInst;
private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused.
private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct.
private TypeArray _ifaces; // The explicit base interfaces for a class or interface.
private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces.
private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations.
private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes.
private TypeManager _pTypeManager; // This is so AGGTYPESYMs can instantiate their baseClass and ifacesAll members on demand.
// First UD conversion operator. This chain is for this type only (not base types).
// The hasConversion flag indicates whether this or any base types have UD conversions.
private MethodSymbol _pConvFirst;
// ------------------------------------------------------------------------
//
// Put members that are bits under here in a contiguous section.
//
// ------------------------------------------------------------------------
private AggKindEnum _aggKind;
private bool _isLayoutError; // Whether there is a cycle in the layout for the struct
// Where this came from - fabricated, source, import
// Fabricated AGGs have isSource == true but hasParseTree == false.
// N.B.: in incremental builds, it is quite possible for
// isSource==TRUE and hasParseTree==FALSE. Be
// sure you use the correct variable for what you are trying to do!
private bool _isSource; // This class is defined in source, although the
// source might not be being read during this compile.
// Predefined
private bool _isPredefined; // A special predefined type.
private PredefinedType _iPredef; // index of the predefined type, if isPredefined.
// Flags
private bool _isAbstract; // Can it be instantiated?
private bool _isSealed; // Can it be derived from?
// Attribute
private bool _isUnmanagedStruct; // Set if the struct is known to be un-managed (for unsafe code). Set in FUNCBREC.
private bool _isManagedStruct; // Set if the struct is known to be managed (for unsafe code). Set during import.
// Constructors
private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args
// private struct members should not be checked for assignment or references
private bool _hasExternReference;
// User defined operators
private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate).
private bool _isComImport; // Does it have [ComImport]
private bool _isAnonymousType; // true if the class is an anonymous type
// When this is unset we don't know if we have conversions. When this
// is set it indicates if this type or any base type has user defined
// conversion operators
private bool? _hasConversion;
// ----------------------------------------------------------------------------
// AggregateSymbol
// ----------------------------------------------------------------------------
public AggregateSymbol GetBaseAgg()
{
return _pBaseClass?.getAggregate();
}
public AggregateType getThisType()
{
if (_atsInst == null)
{
Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested());
AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null;
_atsInst = _pTypeManager.GetAggregate(this, pOuterType, GetTypeVars());
}
//Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count);
return _atsInst;
}
public void InitFromInfile(InputFile infile)
{
_infile = infile;
_isSource = infile.isSource;
}
public bool FindBaseAgg(AggregateSymbol agg)
{
for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg())
{
if (aggT == agg)
return true;
}
return false;
}
public NamespaceOrAggregateSymbol Parent
{
get { return parent.AsNamespaceOrAggregateSymbol(); }
}
private new AggregateDeclaration DeclFirst()
{
return (AggregateDeclaration)base.DeclFirst();
}
public AggregateDeclaration DeclOnly()
{
//Debug.Assert(DeclFirst() != null && DeclFirst().DeclNext() == null);
return DeclFirst();
}
public bool InAlias(KAID aid)
{
Debug.Assert(_infile != null);
//Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID());
Debug.Assert(0 <= aid);
if (aid < KAID.kaidMinModule)
return _infile.InAlias(aid);
return (aid == GetModuleID());
}
private KAID GetModuleID()
{
return 0;
}
public KAID GetAssemblyID()
{
Debug.Assert(_infile != null);
//Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID());
return _infile.GetAssemblyID();
}
public bool IsUnresolved()
{
return _infile != null && _infile.GetAssemblyID() == KAID.kaidUnresolved;
}
public bool isNested()
{
return parent != null && parent.IsAggregateSymbol();
}
public AggregateSymbol GetOuterAgg()
{
return parent != null && parent.IsAggregateSymbol() ? parent.AsAggregateSymbol() : null;
}
public bool isPredefAgg(PredefinedType pt)
{
return _isPredefined && (PredefinedType)_iPredef == pt;
}
// ----------------------------------------------------------------------------
// The following are the Accessor functions for AggregateSymbol.
// ----------------------------------------------------------------------------
public AggKindEnum AggKind()
{
return (AggKindEnum)_aggKind;
}
public void SetAggKind(AggKindEnum aggKind)
{
// NOTE: When importing can demote types:
// - enums with no underlying type go to struct
// - delegates which are abstract or have no .ctor/Invoke method goto class
_aggKind = aggKind;
//An interface is always abstract
if (aggKind == AggKindEnum.Interface)
{
SetAbstract(true);
}
}
public bool IsClass()
{
return AggKind() == AggKindEnum.Class;
}
public bool IsDelegate()
{
return AggKind() == AggKindEnum.Delegate;
}
public bool IsInterface()
{
return AggKind() == AggKindEnum.Interface;
}
public bool IsStruct()
{
return AggKind() == AggKindEnum.Struct;
}
public bool IsEnum()
{
return AggKind() == AggKindEnum.Enum;
}
public bool IsValueType()
{
return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum;
}
public bool IsRefType()
{
return AggKind() == AggKindEnum.Class ||
AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate;
}
public bool IsStatic()
{
return (_isAbstract && _isSealed);
}
public bool IsAnonymousType()
{
return _isAnonymousType;
}
public void SetAnonymousType(bool isAnonymousType)
{
_isAnonymousType = isAnonymousType;
}
public bool IsAbstract()
{
return _isAbstract;
}
public void SetAbstract(bool @abstract)
{
_isAbstract = @abstract;
}
public bool IsPredefined()
{
return _isPredefined;
}
public void SetPredefined(bool predefined)
{
_isPredefined = predefined;
}
public PredefinedType GetPredefType()
{
return (PredefinedType)_iPredef;
}
public void SetPredefType(PredefinedType predef)
{
_iPredef = predef;
}
public bool IsLayoutError()
{
return _isLayoutError == true;
}
public void SetLayoutError(bool layoutError)
{
_isLayoutError = layoutError;
}
public bool IsSealed()
{
return _isSealed == true;
}
public void SetSealed(bool @sealed)
{
_isSealed = @sealed;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasConversion(SymbolLoader pLoader)
{
pLoader.RuntimeBinderSymbolTable.AddConversionsForType(AssociatedSystemType);
if (!_hasConversion.HasValue)
{
// ok, we tried defining all the conversions, and we didn't get anything
// for this type. However, we will still think this type has conversions
// if it's base type has conversions.
_hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(pLoader);
}
return _hasConversion.Value;
}
////////////////////////////////////////////////////////////////////////////////
public void SetHasConversion()
{
_hasConversion = true;
}
////////////////////////////////////////////////////////////////////////////////
private bool IsUnmanagedStruct()
{
return _isUnmanagedStruct;
}
public void SetUnmanagedStruct(bool unmanagedStruct)
{
_isUnmanagedStruct = unmanagedStruct;
}
public bool IsManagedStruct()
{
return _isManagedStruct == true;
}
public void SetManagedStruct(bool managedStruct)
{
_isManagedStruct = managedStruct;
}
public bool IsKnownManagedStructStatus()
{
Debug.Assert(IsStruct());
Debug.Assert(!IsManagedStruct() || !IsUnmanagedStruct());
return IsManagedStruct() || IsUnmanagedStruct();
}
public bool HasPubNoArgCtor()
{
return _hasPubNoArgCtor == true;
}
public void SetHasPubNoArgCtor(bool hasPubNoArgCtor)
{
_hasPubNoArgCtor = hasPubNoArgCtor;
}
public bool HasExternReference()
{
return _hasExternReference == true;
}
public void SetHasExternReference(bool hasExternReference)
{
_hasExternReference = hasExternReference;
}
public bool IsSkipUDOps()
{
return _isSkipUDOps == true;
}
public void SetSkipUDOps(bool skipUDOps)
{
_isSkipUDOps = skipUDOps;
}
public void SetComImport(bool comImport)
{
_isComImport = comImport;
}
public bool IsSource()
{
return _isSource == true;
}
public TypeArray GetTypeVars()
{
return _typeVarsThis;
}
public void SetTypeVars(TypeArray typeVars)
{
if (typeVars == null)
{
_typeVarsThis = null;
_typeVarsAll = null;
}
else
{
TypeArray outerTypeVars;
if (GetOuterAgg() != null)
{
Debug.Assert(GetOuterAgg().GetTypeVars() != null);
Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null);
outerTypeVars = GetOuterAgg().GetTypeVarsAll();
}
else
{
outerTypeVars = BSYMMGR.EmptyTypeArray();
}
_typeVarsThis = typeVars;
_typeVarsAll = _pTypeManager.ConcatenateTypeArrays(outerTypeVars, typeVars);
}
}
public TypeArray GetTypeVarsAll()
{
return _typeVarsAll;
}
public AggregateType GetBaseClass()
{
return _pBaseClass;
}
public void SetBaseClass(AggregateType baseClass)
{
_pBaseClass = baseClass;
}
public AggregateType GetUnderlyingType()
{
return _pUnderlyingType;
}
public void SetUnderlyingType(AggregateType underlyingType)
{
_pUnderlyingType = underlyingType;
}
public TypeArray GetIfaces()
{
return _ifaces;
}
public void SetIfaces(TypeArray ifaces)
{
_ifaces = ifaces;
}
public TypeArray GetIfacesAll()
{
return _ifacesAll;
}
public void SetIfacesAll(TypeArray ifacesAll)
{
_ifacesAll = ifacesAll;
}
public TypeManager GetTypeManager()
{
return _pTypeManager;
}
public void SetTypeManager(TypeManager typeManager)
{
_pTypeManager = typeManager;
}
public MethodSymbol GetFirstUDConversion()
{
return _pConvFirst;
}
public void SetFirstUDConversion(MethodSymbol conv)
{
_pConvFirst = conv;
}
public bool InternalsVisibleTo(Assembly assembly)
{
return _pTypeManager.InternalsVisibleTo(AssociatedAssembly, assembly);
}
}
}
| |
namespace PokerTell.PokerHand.Tests.Mapping
{
using System;
using Base;
using Infrastructure.Enumerations.PokerHand;
using Infrastructure.Interfaces.PokerHand;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using PokerTell.PokerHand.Analyzation;
using UnitTests.Tools;
public class ConvertedPokerPlayerMapTests : InMemoryDatabaseTest
{
public ConvertedPokerPlayerMapTests()
: base(typeof(ConvertedPokerPlayer).Assembly)
{
}
IConvertedPokerPlayer _player;
IConvertedPokerHand _hand;
const string Name = "someName";
const string Site = "someSite";
[SetUp]
public void _Init()
{
_session.Clear();
new SchemaExport(_configuration).Execute(false, true, false, _session.Connection, null);
_hand = new ConvertedPokerHand("someSite", 1, DateTime.MinValue, 2, 1, 2);
var playerIdentity = new PlayerIdentity(Name, Site);
_session.Save(playerIdentity);
_player = new ConvertedPokerPlayer
{
PlayerIdentity = playerIdentity
};
}
[Test]
public void SaveParentHand_UnsavedPlayer_SetsId()
{
_hand.AddPlayer(_player);
_session.Save(_hand);
_player.Id.ShouldNotBeEqualTo(UnsavedValue);
}
[Test]
public void Get_SavedPlayer_RestoresPlayerPosition()
{
_player.Position = 1;
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.Position.ShouldBeEqualTo(_player.Position);
}
[Test]
public void Get_SavedPlayer_RestoresPlayerHolecards()
{
_player.Holecards = "someHolecards";
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.Holecards.ShouldBeEqualTo(_player.Holecards);
}
[Test]
public void Get_SavedPlayer_RestoresPlayerName()
{
_player.Name = "someName";
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.Name.ShouldBeEqualTo(_player.Name);
}
[Test]
public void Get_SavedPlayer_RestoresMBefore()
{
_player.MBefore = 1;
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.MBefore.ShouldBeEqualTo(_player.MBefore);
}
[Test]
public void Get_SavedPlayer_RestoresStategicPosition()
{
_player.Position = 1;
_player.SetStrategicPosition(_hand.TotalPlayers);
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.StrategicPosition.ShouldBeEqualTo(_player.StrategicPosition);
}
[Test]
public void Get_SavedPlayer_RestoresInPositionArray()
{
_player.InPosition[(int)Streets.PreFlop] = true;
_player.InPosition[(int)Streets.Flop] = true;
_player.InPosition[(int)Streets.Turn] = true;
_player.InPosition[(int)Streets.River] = true;
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.InPosition.ShouldBeEqualTo(_player.InPosition);
}
[Test]
public void Get_SavedPlayer_RestoresRoundsArray()
{
var sampleRound = new ConvertedPokerRound()
.Add(new ConvertedPokerAction(ActionTypes.B, 1.0));
_player
.Add(sampleRound)
.Add(sampleRound)
.Add(sampleRound)
.Add(sampleRound);
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.Rounds.ShouldBeEqualTo(_player.Rounds);
}
[Test]
public void Get_SavedPlayer_RestoresActionSequencesArray()
{
_player.ActionSequences[(int)Streets.PreFlop] = ActionSequences.HeroF;
_player.ActionSequences[(int)Streets.Flop] = ActionSequences.HeroB;
_player.ActionSequences[(int)Streets.Turn] = ActionSequences.HeroXOppBHeroF;
_player.ActionSequences[(int)Streets.River] = ActionSequences.HeroB;
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.ActionSequences.ShouldBeEqualTo(_player.ActionSequences);
}
[Test]
public void Get_SavedPlayer_RestoresBetSizeIndexesArray()
{
_player.BetSizeIndexes[(int)Streets.Flop] = 1;
_player.BetSizeIndexes[(int)Streets.Turn] = 2;
_player.BetSizeIndexes[(int)Streets.River] = 3;
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
IConvertedPokerPlayer retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.BetSizeIndexes.ShouldBeEqualTo(_player.BetSizeIndexes);
}
[Test]
public void Get_SavedPlayer_RestoresPlayerParentHandAsProxy()
{
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.ParentHand.GetType().Name.Contains("Proxy").ShouldBeTrue();
}
[Test]
public void Get_SavedPlayer_ProxiedParentHandIsEqualToPlayersHand()
{
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
FlushAndClearSession();
var proxiedHandRetrieved = _session.Get<ConvertedPokerHand>(retrievedPlayer.ParentHand.Id);
proxiedHandRetrieved.ShouldBeEqualTo(_hand);
}
[Test]
public void Get_SavedHandWithOnePlayer_RestoresPlayersPlayerIdentityAsProxy()
{
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
retrievedPlayer.PlayerIdentity.GetType().Name.Contains("Proxy").ShouldBeTrue();
}
[Test]
public void Get_SavedPlayer_ProxiedPlayerIdentityIsEqualToPlayersPlayerIdentity()
{
_hand.AddPlayer(_player);
_session.Save(_hand);
FlushAndClearSession();
var retrievedPlayer = _session.Get<ConvertedPokerPlayer>(_player.Id);
FlushAndClearSession();
var proxiedIdentityRetrieved = _session.Get<PlayerIdentity>(retrievedPlayer.PlayerIdentity.Id);
proxiedIdentityRetrieved.ShouldBeEqualTo(_player.PlayerIdentity);
}
}
}
| |
/*
* 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.
*/
/* Revised Aug, Sept 2009 by Kitto Flora. ODEDynamics.cs replaces
* ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised:
* ODEPrim.cs contains methods dealing with Prim editing, Prim
* characteristics and Kinetic motion.
* ODEDynamics.cs contains methods dealing with Prim Physical motion
* (dynamics) and the associated settings. Old Linear and angular
* motors for dynamic motion have been replace with MoveLinear()
* and MoveAngular(); 'Physical' is used only to switch ODE dynamic
* simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to
* switch between 'VEHICLE' parameter use and general dynamics
* settings use.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using log4net;
using OpenMetaverse;
using Ode.NET;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.OdePlugin
{
public class ODEDynamics
{
public Vehicle Type
{
get { return m_type; }
}
public IntPtr Body
{
get { return m_body; }
}
private int frcount = 0; // Used to limit dynamics debug output to
// every 100th frame
// private OdeScene m_parentScene = null;
private IntPtr m_body = IntPtr.Zero;
private IntPtr m_jointGroup = IntPtr.Zero;
private IntPtr m_aMotor = IntPtr.Zero;
// Vehicle properties
private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind
// private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier
private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings:
// HOVER_TERRAIN_ONLY
// HOVER_GLOBAL_HEIGHT
// NO_DEFLECTION_UP
// HOVER_WATER_ONLY
// HOVER_UP_ONLY
// LIMIT_MOTOR_UP
// LIMIT_ROLL_ONLY
// Linear properties
private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time
private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL
private Vector3 m_dir = Vector3.Zero; // velocity applied to body
private Vector3 m_linearFrictionTimescale = Vector3.Zero;
private float m_linearMotorDecayTimescale = 0;
private float m_linearMotorTimescale = 0;
private Vector3 m_lastLinearVelocityVector = Vector3.Zero;
// private bool m_LinearMotorSetLastFrame = false;
// private Vector3 m_linearMotorOffset = Vector3.Zero;
//Angular properties
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
// private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body
//Deflection properties
// private float m_angularDeflectionEfficiency = 0;
// private float m_angularDeflectionTimescale = 0;
// private float m_linearDeflectionEfficiency = 0;
// private float m_linearDeflectionTimescale = 0;
//Banking properties
// private float m_bankingEfficiency = 0;
// private float m_bankingMix = 0;
// private float m_bankingTimescale = 0;
//Hover and Buoyancy properties
private float m_VhoverHeight = 0f;
private float m_VhoverEfficiency = 0f;
private float m_VhoverTimescale = 0f;
private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height
private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle.
// Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity)
// KF: So far I have found no good method to combine a script-requested .Z velocity and gravity.
// Therefore only m_VehicleBuoyancy=1 (0g) will use the script-requested .Z velocity.
//Attractor properties
private float m_verticalAttractionEfficiency = 1.0f; // damped
private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor.
internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionEfficiency = pValue;
break;
case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_angularDeflectionTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorDecayTimescale = pValue;
break;
case Vehicle.ANGULAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_angularMotorTimescale = pValue;
break;
case Vehicle.BANKING_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingEfficiency = pValue;
break;
case Vehicle.BANKING_MIX:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingMix = pValue;
break;
case Vehicle.BANKING_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_bankingTimescale = pValue;
break;
case Vehicle.BUOYANCY:
if (pValue < -1f) pValue = -1f;
if (pValue > 1f) pValue = 1f;
m_VehicleBuoyancy = pValue;
break;
case Vehicle.HOVER_EFFICIENCY:
if (pValue < 0f) pValue = 0f;
if (pValue > 1f) pValue = 1f;
m_VhoverEfficiency = pValue;
break;
case Vehicle.HOVER_HEIGHT:
m_VhoverHeight = pValue;
break;
case Vehicle.HOVER_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_VhoverTimescale = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionEfficiency = pValue;
break;
case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
// m_linearDeflectionTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorDecayTimescale = pValue;
break;
case Vehicle.LINEAR_MOTOR_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_linearMotorTimescale = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
if (pValue < 0.1f) pValue = 0.1f; // Less goes unstable
if (pValue > 1.0f) pValue = 1.0f;
m_verticalAttractionEfficiency = pValue;
break;
case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
if (pValue < 0.01f) pValue = 0.01f;
m_verticalAttractionTimescale = pValue;
break;
// These are vector properties but the engine lets you use a single float value to
// set all of the components to the same value
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
m_linearMotorDirectionLASTSET = new Vector3(pValue, pValue, pValue);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
break;
}
}//end ProcessFloatVehicleParam
internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
{
switch (pParam)
{
case Vehicle.ANGULAR_FRICTION_TIMESCALE:
m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.ANGULAR_MOTOR_DIRECTION:
m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
// Limit requested angular speed to 2 rps= 4 pi rads/sec
if(m_angularMotorDirection.X > 12.56f) m_angularMotorDirection.X = 12.56f;
if(m_angularMotorDirection.X < - 12.56f) m_angularMotorDirection.X = - 12.56f;
if(m_angularMotorDirection.Y > 12.56f) m_angularMotorDirection.Y = 12.56f;
if(m_angularMotorDirection.Y < - 12.56f) m_angularMotorDirection.Y = - 12.56f;
if(m_angularMotorDirection.Z > 12.56f) m_angularMotorDirection.Z = 12.56f;
if(m_angularMotorDirection.Z < - 12.56f) m_angularMotorDirection.Z = - 12.56f;
m_angularMotorApply = 10;
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_DIRECTION:
m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
case Vehicle.LINEAR_MOTOR_OFFSET:
// m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
break;
}
}//end ProcessVectorVehicleParam
internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
{
switch (pParam)
{
case Vehicle.REFERENCE_FRAME:
// m_referenceFrame = pValue;
break;
}
}//end ProcessRotationVehicleParam
internal void ProcessTypeChange(Vehicle pType)
{
// Set Defaults For Type
m_type = pType;
switch (pType)
{
case Vehicle.TYPE_SLED:
m_linearFrictionTimescale = new Vector3(30, 1, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1000;
m_linearMotorDecayTimescale = 120;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1000;
m_angularMotorDecayTimescale = 120;
m_VhoverHeight = 0;
m_VhoverEfficiency = 1;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 1;
// m_linearDeflectionTimescale = 1;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 1000;
// m_bankingEfficiency = 0;
// m_bankingMix = 1;
// m_bankingTimescale = 10;
// m_referenceFrame = Quaternion.Identity;
m_flags &=
~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
break;
case Vehicle.TYPE_CAR:
m_linearFrictionTimescale = new Vector3(100, 2, 1000);
m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 1;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 1;
m_angularMotorDecayTimescale = 0.8f;
m_VhoverHeight = 0;
m_VhoverEfficiency = 0;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// // m_linearDeflectionEfficiency = 1;
// // m_linearDeflectionTimescale = 2;
// // m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 10;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 10f;
// m_bankingEfficiency = -0.2f;
// m_bankingMix = 1;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.HOVER_UP_ONLY |
VehicleFlag.LIMIT_MOTOR_UP);
break;
case Vehicle.TYPE_BOAT:
m_linearFrictionTimescale = new Vector3(10, 3, 2);
m_angularFrictionTimescale = new Vector3(10,10,10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 2;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 0.5f;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 0.5f;
m_verticalAttractionTimescale = 5f;
// m_bankingEfficiency = -0.3f;
// m_bankingMix = 0.8f;
// m_bankingTimescale = 1;
// m_referenceFrame = Quaternion.Identity;
m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.LIMIT_ROLL_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.HOVER_WATER_ONLY |
VehicleFlag.LIMIT_MOTOR_UP);
break;
case Vehicle.TYPE_AIRPLANE:
m_linearFrictionTimescale = new Vector3(200, 10, 5);
m_angularFrictionTimescale = new Vector3(20, 20, 20);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 2;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 4;
m_angularMotorDecayTimescale = 4;
m_VhoverHeight = 0;
m_VhoverEfficiency = 0.5f;
m_VhoverTimescale = 1000;
m_VehicleBuoyancy = 0;
// m_linearDeflectionEfficiency = 0.5f;
// m_linearDeflectionTimescale = 3;
// m_angularDeflectionEfficiency = 1;
// m_angularDeflectionTimescale = 2;
m_verticalAttractionEfficiency = 0.9f;
m_verticalAttractionTimescale = 2f;
// m_bankingEfficiency = 1;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 2;
// m_referenceFrame = Quaternion.Identity;
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
break;
case Vehicle.TYPE_BALLOON:
m_linearFrictionTimescale = new Vector3(5, 5, 5);
m_angularFrictionTimescale = new Vector3(10, 10, 10);
m_linearMotorDirection = Vector3.Zero;
m_linearMotorTimescale = 5;
m_linearMotorDecayTimescale = 60;
m_angularMotorDirection = Vector3.Zero;
m_angularMotorTimescale = 6;
m_angularMotorDecayTimescale = 10;
m_VhoverHeight = 5;
m_VhoverEfficiency = 0.8f;
m_VhoverTimescale = 10;
m_VehicleBuoyancy = 1;
// m_linearDeflectionEfficiency = 0;
// m_linearDeflectionTimescale = 5;
// m_angularDeflectionEfficiency = 0;
// m_angularDeflectionTimescale = 5;
m_verticalAttractionEfficiency = 1f;
m_verticalAttractionTimescale = 100f;
// m_bankingEfficiency = 0;
// m_bankingMix = 0.7f;
// m_bankingTimescale = 5;
// m_referenceFrame = Quaternion.Identity;
m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
VehicleFlag.HOVER_UP_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
break;
}
}//end SetDefaultsForType
internal void Enable(IntPtr pBody, OdeScene pParentScene)
{
if (m_type == Vehicle.TYPE_NONE)
return;
m_body = pBody;
}
internal void Step(float pTimestep, OdeScene pParentScene)
{
if (m_body == IntPtr.Zero || m_type == Vehicle.TYPE_NONE)
return;
frcount++; // used to limit debug comment output
if (frcount > 100)
frcount = 0;
MoveLinear(pTimestep, pParentScene);
MoveAngular(pTimestep);
}// end Step
private void MoveLinear(float pTimestep, OdeScene _pParentScene)
{
if (!m_linearMotorDirection.ApproxEquals(Vector3.Zero, 0.01f)) // requested m_linearMotorDirection is significant
{
if(!d.BodyIsEnabled (Body)) d.BodyEnable (Body);
// add drive to body
Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale/pTimestep);
m_lastLinearVelocityVector += (addAmount*10); // lastLinearVelocityVector is the current body velocity vector?
// This will work temporarily, but we really need to compare speed on an axis
// KF: Limit body velocity to applied velocity?
if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X))
m_lastLinearVelocityVector.X = m_linearMotorDirectionLASTSET.X;
if (Math.Abs(m_lastLinearVelocityVector.Y) > Math.Abs(m_linearMotorDirectionLASTSET.Y))
m_lastLinearVelocityVector.Y = m_linearMotorDirectionLASTSET.Y;
if (Math.Abs(m_lastLinearVelocityVector.Z) > Math.Abs(m_linearMotorDirectionLASTSET.Z))
m_lastLinearVelocityVector.Z = m_linearMotorDirectionLASTSET.Z;
// decay applied velocity
Vector3 decayfraction = ((Vector3.One/(m_linearMotorDecayTimescale/pTimestep)));
//Console.WriteLine("decay: " + decayfraction);
m_linearMotorDirection -= m_linearMotorDirection * decayfraction * 0.5f;
//Console.WriteLine("actual: " + m_linearMotorDirection);
}
else
{ // requested is not significant
// if what remains of applied is small, zero it.
if (m_lastLinearVelocityVector.ApproxEquals(Vector3.Zero, 0.01f))
m_lastLinearVelocityVector = Vector3.Zero;
}
// convert requested object velocity to world-referenced vector
m_dir = m_lastLinearVelocityVector;
d.Quaternion rot = d.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object
m_dir *= rotq; // apply obj rotation to velocity vector
// add Gravity andBuoyancy
// KF: So far I have found no good method to combine a script-requested
// .Z velocity and gravity. Therefore only 0g will used script-requested
// .Z velocity. >0g (m_VehicleBuoyancy < 1) will used modified gravity only.
Vector3 grav = Vector3.Zero;
if(m_VehicleBuoyancy < 1.0f)
{
// There is some gravity, make a gravity force vector
// that is applied after object velocity.
d.Mass objMass;
d.BodyGetMass(Body, out objMass);
// m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g;
grav.Z = _pParentScene.gravityz * objMass.mass * (1f - m_VehicleBuoyancy);
// Preserve the current Z velocity
d.Vector3 vel_now = d.BodyGetLinearVel(Body);
m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity
} // else its 1.0, no gravity.
// Check if hovering
if( (m_flags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0)
{
// We should hover, get the target height
d.Vector3 pos = d.BodyGetPosition(Body);
if((m_flags & VehicleFlag.HOVER_WATER_ONLY) == VehicleFlag.HOVER_WATER_ONLY)
{
m_VhoverTargetHeight = _pParentScene.GetWaterLevel() + m_VhoverHeight;
}
else if((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) == VehicleFlag.HOVER_TERRAIN_ONLY)
{
m_VhoverTargetHeight = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight;
}
else if((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) == VehicleFlag.HOVER_GLOBAL_HEIGHT)
{
m_VhoverTargetHeight = m_VhoverHeight;
}
if((m_flags & VehicleFlag.HOVER_UP_ONLY) == VehicleFlag.HOVER_UP_ONLY)
{
// If body is aready heigher, use its height as target height
if(pos.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = pos.Z;
}
// m_VhoverEfficiency = 0f; // 0=boucy, 1=Crit.damped
// m_VhoverTimescale = 0f; // time to acheive height
// pTimestep is time since last frame,in secs
float herr0 = pos.Z - m_VhoverTargetHeight;
// Replace Vertical speed with correction figure if significant
if(Math.Abs(herr0) > 0.01f )
{
d.Mass objMass;
d.BodyGetMass(Body, out objMass);
m_dir.Z = - ( (herr0 * pTimestep * 50.0f) / m_VhoverTimescale);
//KF: m_VhoverEfficiency is not yet implemented
}
else
{
m_dir.Z = 0f;
}
}
// Apply velocity
d.BodySetLinearVel(Body, m_dir.X, m_dir.Y, m_dir.Z);
// apply gravity force
d.BodyAddForce(Body, grav.X, grav.Y, grav.Z);
// apply friction
Vector3 decayamount = Vector3.One / (m_linearFrictionTimescale / pTimestep);
m_lastLinearVelocityVector -= m_lastLinearVelocityVector * decayamount;
} // end MoveLinear()
private void MoveAngular(float pTimestep)
{
/*
private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor
private int m_angularMotorApply = 0; // application frame counter
private float m_angularMotorVelocity = 0; // current angular motor velocity (ramps up and down)
private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate
private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate
private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate
private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body
*/
// Get what the body is doing, this includes 'external' influences
d.Vector3 angularVelocity = d.BodyGetAngularVel(Body);
// Vector3 angularVelocity = Vector3.Zero;
if (m_angularMotorApply > 0)
{
// ramp up to new value
// current velocity += error / ( time to get there / step interval )
// requested speed - last motor speed
m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep);
m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep);
m_angularMotorApply--; // This is done so that if script request rate is less than phys frame rate the expected
// velocity may still be acheived.
}
else
{
// no motor recently applied, keep the body velocity
/* m_angularMotorVelocity.X = angularVelocity.X;
m_angularMotorVelocity.Y = angularVelocity.Y;
m_angularMotorVelocity.Z = angularVelocity.Z; */
// and decay the velocity
m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep);
} // end motor section
// Vertical attractor section
Vector3 vertattr = Vector3.Zero;
if(m_verticalAttractionTimescale < 300)
{
float VAservo = 0.2f / (m_verticalAttractionTimescale * pTimestep);
// get present body rotation
d.Quaternion rot = d.BodyGetQuaternion(Body);
Quaternion rotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W);
// make a vector pointing up
Vector3 verterr = Vector3.Zero;
verterr.Z = 1.0f;
// rotate it to Body Angle
verterr = verterr * rotq;
// verterr.X and .Y are the World error ammounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1.
// As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go
// negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body.
if (verterr.Z < 0.0f)
{
verterr.X = 2.0f - verterr.X;
verterr.Y = 2.0f - verterr.Y;
}
// Error is 0 (no error) to +/- 2 (max error)
// scale it by VAservo
verterr = verterr * VAservo;
//if(frcount == 0) Console.WriteLine("VAerr=" + verterr);
// As the body rotates around the X axis, then verterr.Y increases; Rotated around Y then .X increases, so
// Change Body angular velocity X based on Y, and Y based on X. Z is not changed.
vertattr.X = verterr.Y;
vertattr.Y = - verterr.X;
vertattr.Z = 0f;
// scaling appears better usingsquare-law
float bounce = 1.0f - (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency);
vertattr.X += bounce * angularVelocity.X;
vertattr.Y += bounce * angularVelocity.Y;
} // else vertical attractor is off
// m_lastVertAttractor = vertattr;
// Bank section tba
// Deflection section tba
// Sum velocities
m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection
if (!m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f))
{
if(!d.BodyIsEnabled (Body)) d.BodyEnable (Body);
}
else
{
m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero.
}
// apply friction
Vector3 decayamount = Vector3.One / (m_angularFrictionTimescale / pTimestep);
m_lastAngularVelocity -= m_lastAngularVelocity * decayamount;
// Apply to the body
d.BodySetAngularVel (Body, m_lastAngularVelocity.X, m_lastAngularVelocity.Y, m_lastAngularVelocity.Z);
} //end MoveAngular
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Uno.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Acr.UserDialogs;
using MvvmCross;
using MvvmCross.Commands;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
using Plugin.BLE.Abstractions;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Abstractions.EventArgs;
using Plugin.BLE.Abstractions.Extensions;
namespace BLE.Client.ViewModels
{
public class CharacteristicDetailViewModel : BaseViewModel
{
private readonly IUserDialogs _userDialogs;
private bool _updatesStarted;
public ICharacteristic Characteristic { get; private set; }
public string CharacteristicValue => Characteristic?.Value.ToHexString().Replace("-", " ");
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public string UpdateButtonText => _updatesStarted ? "Stop updates" : "Start updates";
public string Permissions
{
get
{
if (Characteristic == null)
return string.Empty;
return (Characteristic.CanRead ? "Read " : "") +
(Characteristic.CanWrite ? "Write " : "") +
(Characteristic.CanUpdate ? "Update" : "");
}
}
public CharacteristicDetailViewModel(IAdapter adapter, IUserDialogs userDialogs) : base(adapter)
{
_userDialogs = userDialogs;
}
public override async void Prepare(MvxBundle parameters)
{
base.Prepare(parameters);
Characteristic = await GetCharacteristicFromBundleAsync(parameters);
}
public override void ViewAppeared()
{
base.ViewAppeared();
if (Characteristic != null)
{
return;
}
var navigation = Mvx.IoCProvider.Resolve<IMvxNavigationService>();
navigation.Close(this);
}
public override void ViewDisappeared()
{
base.ViewDisappeared();
if (Characteristic != null)
{
StopUpdates();
}
}
public MvxCommand ReadCommand => new MvxCommand(ReadValueAsync);
private async void ReadValueAsync()
{
if (Characteristic == null)
return;
try
{
_userDialogs.ShowLoading("Reading characteristic value...");
await Characteristic.ReadAsync();
await RaisePropertyChanged(() => CharacteristicValue);
Messages.Insert(0, $"Read value {CharacteristicValue}");
}
catch (Exception ex)
{
_userDialogs.HideLoading();
await _userDialogs.AlertAsync(ex.Message);
Messages.Insert(0, $"Error {ex.Message}");
}
finally
{
_userDialogs.HideLoading();
}
}
public MvxCommand WriteCommand => new MvxCommand(WriteValueAsync);
private async void WriteValueAsync()
{
try
{
var result =
await
_userDialogs.PromptAsync("Input a value (as hex whitespace separated)", "Write value",
placeholder: CharacteristicValue);
if (!result.Ok)
return;
var data = GetBytes(result.Text);
_userDialogs.ShowLoading("Write characteristic value");
await Characteristic.WriteAsync(data);
_userDialogs.HideLoading();
await RaisePropertyChanged(() => CharacteristicValue);
Messages.Insert(0, $"Wrote value {CharacteristicValue}");
}
catch (Exception ex)
{
_userDialogs.HideLoading();
await _userDialogs.AlertAsync(ex.Message);
}
}
private static byte[] GetBytes(string text)
{
return text.Split(' ').Where(token => !string.IsNullOrEmpty(token)).Select(token => Convert.ToByte(token, 16)).ToArray();
}
public MvxCommand ToggleUpdatesCommand => new MvxCommand((() =>
{
if (_updatesStarted)
{
StopUpdates();
}
else
{
StartUpdates();
}
}));
private async void StartUpdates()
{
try
{
_updatesStarted = true;
Characteristic.ValueUpdated -= CharacteristicOnValueUpdated;
Characteristic.ValueUpdated += CharacteristicOnValueUpdated;
await Characteristic.StartUpdatesAsync();
Messages.Insert(0, $"Start updates");
await RaisePropertyChanged(() => UpdateButtonText);
}
catch (Exception ex)
{
await _userDialogs.AlertAsync(ex.Message);
}
}
private async void StopUpdates()
{
try
{
_updatesStarted = false;
await Characteristic.StopUpdatesAsync();
Characteristic.ValueUpdated -= CharacteristicOnValueUpdated;
Messages.Insert(0, $"Stop updates");
await RaisePropertyChanged(() => UpdateButtonText);
}
catch (Exception ex)
{
await _userDialogs.AlertAsync(ex.Message);
}
}
private void CharacteristicOnValueUpdated(object sender, CharacteristicUpdatedEventArgs characteristicUpdatedEventArgs)
{
Messages.Insert(0, $"{DateTime.Now.TimeOfDay} - Updated: {CharacteristicValue}");
RaisePropertyChanged(() => CharacteristicValue);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BenchmarkDotNet.Running;
using Benchmarks.MapReduce;
using Benchmarks.Serialization;
using Benchmarks.Ping;
using Benchmarks.Transactions;
using Benchmarks.GrainStorage;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Toolchains.CsProj;
namespace Benchmarks
{
class Program
{
private static readonly Dictionary<string, Action> _benchmarks = new Dictionary<string, Action>
{
["MapReduce"] = () =>
{
RunBenchmark(
"Running MapReduce benchmark",
() =>
{
var mapReduceBenchmark = new MapReduceBenchmark();
mapReduceBenchmark.BenchmarkSetup();
return mapReduceBenchmark;
},
benchmark => benchmark.Bench().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["Serialization"] = () =>
{
BenchmarkRunner.Run<SerializationBenchmarks>();
},
["Transactions.Memory"] = () =>
{
RunBenchmark(
"Running Transactions benchmark",
() =>
{
var benchmark = new TransactionBenchmark(2, 20000, 5000);
benchmark.MemorySetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["Transactions.Memory.Throttled"] = () =>
{
RunBenchmark(
"Running Transactions benchmark",
() =>
{
var benchmark = new TransactionBenchmark(2, 200000, 15000);
benchmark.MemoryThrottledSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["Transactions.Azure"] = () =>
{
RunBenchmark(
"Running Transactions benchmark",
() =>
{
var benchmark = new TransactionBenchmark(2, 20000, 5000);
benchmark.AzureSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["Transactions.Azure.Throttled"] = () =>
{
RunBenchmark(
"Running Transactions benchmark",
() =>
{
var benchmark = new TransactionBenchmark(2, 200000, 15000);
benchmark.AzureThrottledSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["Transactions.Azure.Overloaded"] = () =>
{
RunBenchmark(
"Running Transactions benchmark",
() =>
{
var benchmark = new TransactionBenchmark(2, 200000, 15000);
benchmark.AzureSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["SequentialPing"] = () =>
{
BenchmarkRunner.Run<PingBenchmark>();
},
["ConcurrentPing"] = () =>
{
{
Console.WriteLine("## Client to Silo ##");
var test = new PingBenchmark(numSilos: 1, startClient: true);
test.PingConcurrent().GetAwaiter().GetResult();
test.Shutdown().GetAwaiter().GetResult();
}
GC.Collect();
{
Console.WriteLine("## Client to 2 Silos ##");
var test = new PingBenchmark(numSilos: 2, startClient: true);
test.PingConcurrent().GetAwaiter().GetResult();
test.Shutdown().GetAwaiter().GetResult();
}
GC.Collect();
{
Console.WriteLine("## Hosted Client ##");
var test = new PingBenchmark(numSilos: 1, startClient: false);
test.PingConcurrentHostedClient().GetAwaiter().GetResult();
test.Shutdown().GetAwaiter().GetResult();
}
GC.Collect();
{
// All calls are cross-silo because the calling silo doesn't have any grain classes.
Console.WriteLine("## Silo to Silo ##");
var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true);
test.PingConcurrentHostedClient().GetAwaiter().GetResult();
test.Shutdown().GetAwaiter().GetResult();
}
},
["ConcurrentPing_OneSilo"] = () =>
{
new PingBenchmark(numSilos: 1, startClient: true).PingConcurrent().GetAwaiter().GetResult();
},
["ConcurrentPing_TwoSilos"] = () =>
{
new PingBenchmark(numSilos: 2, startClient: true).PingConcurrent().GetAwaiter().GetResult();
},
["ConcurrentPing_HostedClient"] = () =>
{
new PingBenchmark(numSilos: 1, startClient: false).PingConcurrentHostedClient().GetAwaiter().GetResult();
},
["ConcurrentPing_SiloToSilo"] = () =>
{
new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient().GetAwaiter().GetResult();
},
["PingForever"] = () =>
{
new PingBenchmark().PingForever().GetAwaiter().GetResult();
},
["PingPongForever"] = () =>
{
new PingBenchmark().PingPongForever().GetAwaiter().GetResult();
},
["GrainStorage.Memory"] = () =>
{
RunBenchmark(
"Running grain storage benchmark against memory",
() =>
{
var benchmark = new GrainStorageBenchmark();
benchmark.MemorySetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["GrainStorage.AzureTable"] = () =>
{
RunBenchmark(
"Running grain storage benchmark against Azure Table",
() =>
{
var benchmark = new GrainStorageBenchmark();
benchmark.AzureTableSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
["GrainStorage.AzureBlob"] = () =>
{
RunBenchmark(
"Running grain storage benchmark against Azure Blob",
() =>
{
var benchmark = new GrainStorageBenchmark();
benchmark.AzureBlobSetup();
return benchmark;
},
benchmark => benchmark.RunAsync().GetAwaiter().GetResult(),
benchmark => benchmark.Teardown());
},
};
// requires benchmark name or 'All' word as first parameter
static void Main(string[] args)
{
if (args.Length > 0 && args[0].Equals("all", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Running full benchmarks suite");
_benchmarks.Select(pair => pair.Value).ToList().ForEach(action => action());
return;
}
if (args.Length == 0 || !_benchmarks.ContainsKey(args[0]))
{
Console.WriteLine("Please, select benchmark, list of available:");
_benchmarks
.Select(pair => pair.Key)
.ToList()
.ForEach(Console.WriteLine);
Console.WriteLine("All");
return;
}
_benchmarks[args[0]]();
}
private static void RunBenchmark<T>(string name, Func<T> init, Action<T> benchmarkAction, Action<T> tearDown)
{
Console.WriteLine(name);
var bench = init();
var stopWatch = Stopwatch.StartNew();
benchmarkAction(bench);
Console.WriteLine($"Elapsed milliseconds: {stopWatch.ElapsedMilliseconds}");
Console.WriteLine("Press any key to continue ...");
tearDown(bench);
Console.ReadLine();
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* All rights reserved.
*
* - 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.
* - Neither the name of the Second Life Reverse Engineering Team 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 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 OWNER 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.Net;
using System.IO;
using System.Threading;
namespace libsecondlife.Capabilities
{
public class CapsBase
{
#region Callback Data Classes
public class OpenWriteCompletedEventArgs
{
public Stream Result;
public Exception Error;
public bool Cancelled;
public object UserState;
public OpenWriteCompletedEventArgs(Stream result, Exception error, bool cancelled, object userState)
{
Result = result;
Error = error;
Cancelled = cancelled;
UserState = userState;
}
}
public class UploadDataCompletedEventArgs
{
public byte[] Result;
public Exception Error;
public bool Cancelled;
public object UserState;
public UploadDataCompletedEventArgs(byte[] result, Exception error, bool cancelled, object userState)
{
Result = result;
Error = error;
Cancelled = cancelled;
UserState = userState;
}
}
public class DownloadDataCompletedEventArgs
{
public byte[] Result;
public Exception Error;
public bool Cancelled;
public object UserState;
}
public class DownloadStringCompletedEventArgs
{
public Uri Address;
public string Result;
public Exception Error;
public bool Cancelled;
public object UserState;
public DownloadStringCompletedEventArgs(Uri address, string result, Exception error, bool cancelled, object userState)
{
Address = address;
Result = result;
Error = error;
Cancelled = cancelled;
UserState = userState;
}
}
public class DownloadProgressChangedEventArgs
{
public long BytesReceived;
public int ProgressPercentage;
public long TotalBytesToReceive;
public object UserState;
public DownloadProgressChangedEventArgs(long bytesReceived, long totalBytesToReceive, object userToken)
{
BytesReceived = bytesReceived;
ProgressPercentage = (int)(((float)bytesReceived / (float)totalBytesToReceive) * 100f);
TotalBytesToReceive = totalBytesToReceive;
UserState = userToken;
}
}
public class UploadProgressChangedEventArgs
{
public long BytesReceived;
public long BytesSent;
public int ProgressPercentage;
public long TotalBytesToReceive;
public long TotalBytesToSend;
public object UserState;
public UploadProgressChangedEventArgs(long bytesReceived, long totalBytesToReceive, long bytesSent, long totalBytesToSend, object userState)
{
BytesReceived = bytesReceived;
TotalBytesToReceive = totalBytesToReceive;
ProgressPercentage = (int)(((float)bytesSent / (float)totalBytesToSend) * 100f);
BytesSent = bytesSent;
TotalBytesToSend = totalBytesToSend;
UserState = userState;
}
}
#endregion Callback Data Classes
public delegate void OpenWriteCompletedEventHandler(object sender, OpenWriteCompletedEventArgs e);
public delegate void UploadDataCompletedEventHandler(object sender, UploadDataCompletedEventArgs e);
public delegate void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs e);
public delegate void DownloadProgressChangedEventHandler(object sender, DownloadProgressChangedEventArgs e);
public delegate void UploadProgressChangedEventHandler(object sender, UploadProgressChangedEventArgs e);
public event OpenWriteCompletedEventHandler OpenWriteCompleted;
public event UploadDataCompletedEventHandler UploadDataCompleted;
public event DownloadStringCompletedEventHandler DownloadStringCompleted;
public event DownloadProgressChangedEventHandler DownloadProgressChanged;
public event UploadProgressChangedEventHandler UploadProgressChanged;
public WebHeaderCollection Headers = new WebHeaderCollection();
public IWebProxy Proxy;
public Uri Location { get { return location; } }
public bool IsBusy { get { return isBusy; } }
public WebHeaderCollection ResponseHeaders { get { return responseHeaders; } }
protected WebHeaderCollection responseHeaders;
protected Uri location;
protected bool isBusy;
protected Thread asyncThread;
protected System.Text.Encoding encoding = System.Text.Encoding.Default;
public CapsBase(Uri location)
{
this.location = location;
}
public void OpenWriteAsync(Uri address)
{
OpenWriteAsync(address, null, null);
}
public void OpenWriteAsync(Uri address, string method)
{
OpenWriteAsync(address, method, null);
}
public void OpenWriteAsync(Uri address, string method, object userToken)
{
if (address == null)
throw new ArgumentNullException("address");
SetBusy();
asyncThread = new Thread(delegate(object state)
{
object[] args = (object[])state;
WebRequest request = null;
try
{
request = SetupRequest((Uri)args[0]);
Stream stream = request.GetRequestStream();
OnOpenWriteCompleted(new OpenWriteCompletedEventArgs(
stream, null, false, args[2]));
}
catch (ThreadInterruptedException)
{
if (request != null)
request.Abort();
OnOpenWriteCompleted(new OpenWriteCompletedEventArgs(
null, null, true, args[2]));
}
catch (Exception e)
{
OnOpenWriteCompleted(new OpenWriteCompletedEventArgs(
null, e, false, args[2]));
}
});
object[] cbArgs = new object[] { address, method, userToken };
asyncThread.Start(cbArgs);
}
public void UploadDataAsync(Uri address, byte[] data)
{
UploadDataAsync(address, null, data, null);
}
public void UploadDataAsync(Uri address, string method, byte[] data)
{
UploadDataAsync(address, method, data, null);
}
public void UploadDataAsync(Uri address, string method, byte[] data, object userToken)
{
if (address == null)
throw new ArgumentNullException("address");
if (data == null)
throw new ArgumentNullException("data");
SetBusy();
asyncThread = new Thread(delegate(object state)
{
object[] args = (object[])state;
byte[] data2;
try
{
data2 = UploadDataCore((Uri)args[0], (string)args[1], (byte[])args[2], args[3]);
OnUploadDataCompleted(
new UploadDataCompletedEventArgs(data2, null, false, args[3]));
}
catch (ThreadInterruptedException)
{
OnUploadDataCompleted(
new UploadDataCompletedEventArgs(null, null, true, args[3]));
}
catch (Exception e)
{
OnUploadDataCompleted(
new UploadDataCompletedEventArgs(null, e, false, args[3]));
}
});
object[] cbArgs = new object[] { address, method, data, userToken };
asyncThread.Start(cbArgs);
}
public void DownloadStringAsync (Uri address)
{
DownloadStringAsync (address, null);
}
public void DownloadStringAsync(Uri address, object userToken)
{
if (address == null)
throw new ArgumentNullException("address");
SetBusy();
asyncThread = new Thread(delegate(object state)
{
object[] args = (object[])state;
try
{
string data = encoding.GetString(DownloadDataCore((Uri)args[0], args[1]));
OnDownloadStringCompleted(
new DownloadStringCompletedEventArgs(location, data, null, false, args[1]));
}
catch (ThreadInterruptedException)
{
OnDownloadStringCompleted(
new DownloadStringCompletedEventArgs(location, null, null, true, args[1]));
}
catch (Exception e)
{
OnDownloadStringCompleted(
new DownloadStringCompletedEventArgs(location, null, e, false, args[1]));
}
});
object[] cbArgs = new object[] { address, userToken };
asyncThread.Start(cbArgs);
}
public void CancelAsync()
{
if (asyncThread == null)
return;
Thread t = asyncThread;
CompleteAsync();
t.Interrupt();
}
protected void CompleteAsync()
{
isBusy = false;
asyncThread = null;
}
protected void SetBusy()
{
CheckBusy();
isBusy = true;
}
protected void CheckBusy()
{
if (isBusy)
throw new NotSupportedException("CapsBase does not support concurrent I/O operations.");
}
protected Stream ProcessResponse(WebResponse response)
{
responseHeaders = response.Headers;
return response.GetResponseStream();
}
protected byte[] ReadAll(Stream stream, int length, object userToken, bool uploading)
{
MemoryStream ms = null;
bool nolength = (length == -1);
int size = ((nolength) ? 8192 : length);
if (nolength)
ms = new MemoryStream();
long total = 0;
int nread = 0;
int offset = 0;
byte[] buffer = new byte[size];
while ((nread = stream.Read(buffer, offset, size)) != 0)
{
if (nolength)
{
ms.Write(buffer, 0, nread);
}
else
{
offset += nread;
size -= nread;
}
if (uploading)
{
if (UploadProgressChanged != null)
{
total += nread;
UploadProgressChanged(this, new UploadProgressChangedEventArgs(nread, length, 0, 0, userToken));
}
}
else
{
if (DownloadProgressChanged != null)
{
total += nread;
DownloadProgressChanged(this, new DownloadProgressChangedEventArgs(nread, length, userToken));
}
}
}
if (nolength)
return ms.ToArray();
return buffer;
}
protected WebRequest SetupRequest(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
if (request == null)
throw new ArgumentException("Could not create an HttpWebRequest from the given Uri", "address");
location = uri;
if (Proxy != null)
request.Proxy = Proxy;
request.Method = "POST";
if (Headers != null && Headers.Count != 0)
{
string expect = Headers["Expect"];
string contentType = Headers["Content-Type"];
string accept = Headers["Accept"];
string connection = Headers["Connection"];
string userAgent = Headers["User-Agent"];
string referer = Headers["Referer"];
if (!String.IsNullOrEmpty(expect))
request.Expect = expect;
if (!String.IsNullOrEmpty(accept))
request.Accept = accept;
if (!String.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!String.IsNullOrEmpty(connection))
request.Connection = connection;
if (!String.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (!String.IsNullOrEmpty(referer))
request.Referer = referer;
}
// Disable keep-alive by default
request.KeepAlive = false;
// Set the closed connection (idle) time to one second
request.ServicePoint.MaxIdleTime = 1000;
// Disable stupid Expect-100: Continue header
request.ServicePoint.Expect100Continue = false;
// Crank up the max number of connections (default is 2!)
request.ServicePoint.ConnectionLimit = 20;
return request;
}
protected WebRequest SetupRequest(Uri uri, string method)
{
WebRequest request = SetupRequest(uri);
request.Method = method;
return request;
}
protected byte[] UploadDataCore(Uri address, string method, byte[] data, object userToken)
{
HttpWebRequest request = (HttpWebRequest)SetupRequest(address);
// Re-enable Keep-Alive
//request.KeepAlive = true;
try
{
int contentLength = data.Length;
request.ContentLength = contentLength;
using (Stream stream = request.GetRequestStream())
{
// Most uploads are very small chunks of data, use an optimized path for these
if (contentLength < 4096)
{
stream.Write(data, 0, contentLength);
}
else
{
// Upload chunks directly instead of buffering to memory
request.AllowWriteStreamBuffering = false;
MemoryStream ms = new MemoryStream(data);
byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)contentLength))];
int bytesRead = 0;
while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
if (UploadProgressChanged != null)
{
UploadProgressChanged(this, new UploadProgressChangedEventArgs(0, 0, bytesRead, contentLength, userToken));
}
}
ms.Close();
}
}
WebResponse response = request.GetResponse();
Stream st = ProcessResponse(response);
return ReadAll(st, (int)response.ContentLength, userToken, true);
}
catch (ThreadInterruptedException)
{
if (request != null)
request.Abort();
throw;
}
}
protected byte[] DownloadDataCore(Uri address, object userToken)
{
WebRequest request = null;
try
{
request = SetupRequest(address, "GET");
WebResponse response = request.GetResponse();
Stream st = ProcessResponse(response);
return ReadAll(st, (int)response.ContentLength, userToken, false);
}
catch (ThreadInterruptedException)
{
if (request != null)
request.Abort();
throw;
}
catch (Exception ex)
{
throw new WebException("An error occurred performing a WebClient request.", ex);
}
}
protected virtual void OnOpenWriteCompleted(OpenWriteCompletedEventArgs args)
{
CompleteAsync();
if (OpenWriteCompleted != null)
OpenWriteCompleted(this, args);
}
protected virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs args)
{
CompleteAsync();
if (UploadDataCompleted != null)
UploadDataCompleted(this, args);
}
protected virtual void OnDownloadStringCompleted(DownloadStringCompletedEventArgs args)
{
CompleteAsync();
if (DownloadStringCompleted != null)
DownloadStringCompleted(this, args);
}
}
}
| |
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using Microsoft.Xna.Framework.Media;
#endif
// Generated Usings
using FrbDemoDuckHunt.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
namespace FrbDemoDuckHunt.Screens
{
public partial class GameScreen : Screen
{
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
public enum VariableState
{
Uninitialized = 0, //This exists so that the first set call actually does something
Unknown = 1, //This exists so that if the entity is actually a child entity and has set a child state, you will get this
Intro = 2,
StartDucks = 3,
DucksFlying = 4,
DucksEscaping = 5,
PostDucks = 6,
StartIntro = 7,
DogAnimation = 8,
CheckEndOfRound = 9,
AnimateEndOfRound = 10,
AnimatingEndOfRound = 11,
ContinueAnimation = 12,
Lose = 13
}
protected int mCurrentState = 0;
public VariableState CurrentState
{
get
{
if (Enum.IsDefined(typeof(VariableState), mCurrentState))
{
return (VariableState)mCurrentState;
}
else
{
return VariableState.Unknown;
}
}
set
{
mCurrentState = (int)value;
switch(CurrentState)
{
case VariableState.Uninitialized:
break;
case VariableState.Unknown:
break;
case VariableState.Intro:
break;
case VariableState.StartDucks:
break;
case VariableState.DucksFlying:
break;
case VariableState.DucksEscaping:
break;
case VariableState.PostDucks:
break;
case VariableState.StartIntro:
break;
case VariableState.DogAnimation:
break;
case VariableState.CheckEndOfRound:
break;
case VariableState.AnimateEndOfRound:
break;
case VariableState.AnimatingEndOfRound:
break;
case VariableState.ContinueAnimation:
break;
case VariableState.Lose:
break;
}
}
}
private FrbDemoDuckHunt.Entities.Dog DogInstance;
private FrbDemoDuckHunt.Entities.Background BackgroundInstance;
private FrbDemoDuckHunt.Entities.GameInterface GameInterfaceInstance;
private FrbDemoDuckHunt.Entities.Shot ShotInstance;
private FrbDemoDuckHunt.Entities.Duck DuckInstance;
private FrbDemoDuckHunt.Entities.Duck DuckInstance2;
private FrbDemoDuckHunt.Entities.Score ScoreInstance;
private FrbDemoDuckHunt.Entities.Score ScoreInstance2;
public int MinDuckY = 0;
public int MaxDuckY = 100;
public int MinDuckX = -100;
public int MaxDuckX = 100;
public float StartDuckY = -60f;
public float InitialDuckSpeed = 70f;
public float InitialFlightTime = 8f;
public GameScreen()
: base("GameScreen")
{
}
public override void Initialize(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
DogInstance = new FrbDemoDuckHunt.Entities.Dog(ContentManagerName, false);
DogInstance.Name = "DogInstance";
BackgroundInstance = new FrbDemoDuckHunt.Entities.Background(ContentManagerName, false);
BackgroundInstance.Name = "BackgroundInstance";
GameInterfaceInstance = new FrbDemoDuckHunt.Entities.GameInterface(ContentManagerName, false);
GameInterfaceInstance.Name = "GameInterfaceInstance";
ShotInstance = new FrbDemoDuckHunt.Entities.Shot(ContentManagerName, false);
ShotInstance.Name = "ShotInstance";
DuckInstance = new FrbDemoDuckHunt.Entities.Duck(ContentManagerName, false);
DuckInstance.Name = "DuckInstance";
DuckInstance2 = new FrbDemoDuckHunt.Entities.Duck(ContentManagerName, false);
DuckInstance2.Name = "DuckInstance2";
ScoreInstance = new FrbDemoDuckHunt.Entities.Score(ContentManagerName, false);
ScoreInstance.Name = "ScoreInstance";
ScoreInstance2 = new FrbDemoDuckHunt.Entities.Score(ContentManagerName, false);
ScoreInstance2.Name = "ScoreInstance2";
PostInitialize();
base.Initialize(addToManagers);
if (addToManagers)
{
AddToManagers();
}
}
// Generated AddToManagers
public override void AddToManagers ()
{
base.AddToManagers();
AddToManagersBottomUp();
CustomInitialize();
}
public override void Activity(bool firstTimeCalled)
{
// Generated Activity
if (!IsPaused)
{
DogInstance.Activity();
BackgroundInstance.Activity();
GameInterfaceInstance.Activity();
ShotInstance.Activity();
DuckInstance.Activity();
DuckInstance2.Activity();
ScoreInstance.Activity();
ScoreInstance2.Activity();
}
else
{
}
base.Activity(firstTimeCalled);
if (!IsActivityFinished)
{
CustomActivity(firstTimeCalled);
}
// After Custom Activity
}
public override void Destroy()
{
// Generated Destroy
if (DogInstance != null)
{
DogInstance.Destroy();
DogInstance.Detach();
}
if (BackgroundInstance != null)
{
BackgroundInstance.Destroy();
BackgroundInstance.Detach();
}
if (GameInterfaceInstance != null)
{
GameInterfaceInstance.Destroy();
GameInterfaceInstance.Detach();
}
if (ShotInstance != null)
{
ShotInstance.Destroy();
ShotInstance.Detach();
}
if (DuckInstance != null)
{
DuckInstance.Destroy();
DuckInstance.Detach();
}
if (DuckInstance2 != null)
{
DuckInstance2.Destroy();
DuckInstance2.Detach();
}
if (ScoreInstance != null)
{
ScoreInstance.Destroy();
ScoreInstance.Detach();
}
if (ScoreInstance2 != null)
{
ScoreInstance2.Destroy();
ScoreInstance2.Detach();
}
base.Destroy();
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
if (DogInstance.Parent == null)
{
DogInstance.X = 20f;
}
else
{
DogInstance.RelativeX = 20f;
}
if (DogInstance.Parent == null)
{
DogInstance.Y = -60f;
}
else
{
DogInstance.RelativeY = -60f;
}
if (DogInstance.Parent == null)
{
DogInstance.Z = -0.9f;
}
else
{
DogInstance.RelativeZ = -0.9f;
}
if (BackgroundInstance.Parent == null)
{
BackgroundInstance.Z = -1f;
}
else
{
BackgroundInstance.RelativeZ = -1f;
}
DuckInstance.Visible = true;
if (DuckInstance.Parent == null)
{
DuckInstance.Z = -2f;
}
else
{
DuckInstance.RelativeZ = -2f;
}
if (DuckInstance2.Parent == null)
{
DuckInstance2.X = 50f;
}
else
{
DuckInstance2.RelativeX = 50f;
}
DuckInstance2.Visible = true;
if (DuckInstance2.Parent == null)
{
DuckInstance2.Z = -2f;
}
else
{
DuckInstance2.RelativeZ = -2f;
}
if (ScoreInstance.Parent == null)
{
ScoreInstance.Z = -3f;
}
else
{
ScoreInstance.RelativeZ = -3f;
}
ScoreInstance.Visible = true;
if (ScoreInstance2.Parent == null)
{
ScoreInstance2.Z = -3f;
}
else
{
ScoreInstance2.RelativeZ = -3f;
}
ScoreInstance2.Visible = false;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp ()
{
CameraSetup.ResetCamera(SpriteManager.Camera);
DogInstance.AddToManagers(mLayer);
DogInstance.CurrentState = FrbDemoDuckHunt.Entities.Dog.VariableState.OneDuck;
if (DogInstance.Parent == null)
{
DogInstance.X = 20f;
}
else
{
DogInstance.RelativeX = 20f;
}
if (DogInstance.Parent == null)
{
DogInstance.Y = -60f;
}
else
{
DogInstance.RelativeY = -60f;
}
if (DogInstance.Parent == null)
{
DogInstance.Z = -0.9f;
}
else
{
DogInstance.RelativeZ = -0.9f;
}
BackgroundInstance.AddToManagers(mLayer);
if (BackgroundInstance.Parent == null)
{
BackgroundInstance.Z = -1f;
}
else
{
BackgroundInstance.RelativeZ = -1f;
}
GameInterfaceInstance.AddToManagers(mLayer);
ShotInstance.AddToManagers(mLayer);
DuckInstance.AddToManagers(mLayer);
DuckInstance.Visible = true;
if (DuckInstance.Parent == null)
{
DuckInstance.Z = -2f;
}
else
{
DuckInstance.RelativeZ = -2f;
}
DuckInstance2.AddToManagers(mLayer);
DuckInstance2.CurrentState = FrbDemoDuckHunt.Entities.Duck.VariableState.FlyUpLeft;
if (DuckInstance2.Parent == null)
{
DuckInstance2.X = 50f;
}
else
{
DuckInstance2.RelativeX = 50f;
}
DuckInstance2.Visible = true;
if (DuckInstance2.Parent == null)
{
DuckInstance2.Z = -2f;
}
else
{
DuckInstance2.RelativeZ = -2f;
}
ScoreInstance.AddToManagers(mLayer);
if (ScoreInstance.Parent == null)
{
ScoreInstance.Z = -3f;
}
else
{
ScoreInstance.RelativeZ = -3f;
}
ScoreInstance.Visible = true;
ScoreInstance2.AddToManagers(mLayer);
if (ScoreInstance2.Parent == null)
{
ScoreInstance2.Z = -3f;
}
else
{
ScoreInstance2.RelativeZ = -3f;
}
ScoreInstance2.Visible = false;
MinDuckY = 0;
MaxDuckY = 100;
MinDuckX = -100;
MaxDuckX = 100;
StartDuckY = -60f;
InitialDuckSpeed = 70f;
InitialFlightTime = 8f;
}
public virtual void ConvertToManuallyUpdated ()
{
DogInstance.ConvertToManuallyUpdated();
BackgroundInstance.ConvertToManuallyUpdated();
GameInterfaceInstance.ConvertToManuallyUpdated();
ShotInstance.ConvertToManuallyUpdated();
DuckInstance.ConvertToManuallyUpdated();
DuckInstance2.ConvertToManuallyUpdated();
ScoreInstance.ConvertToManuallyUpdated();
ScoreInstance2.ConvertToManuallyUpdated();
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
FrbDemoDuckHunt.Entities.Dog.LoadStaticContent(contentManagerName);
FrbDemoDuckHunt.Entities.Background.LoadStaticContent(contentManagerName);
FrbDemoDuckHunt.Entities.GameInterface.LoadStaticContent(contentManagerName);
FrbDemoDuckHunt.Entities.Shot.LoadStaticContent(contentManagerName);
FrbDemoDuckHunt.Entities.Duck.LoadStaticContent(contentManagerName);
FrbDemoDuckHunt.Entities.Score.LoadStaticContent(contentManagerName);
CustomLoadStaticContent(contentManagerName);
}
static VariableState mLoadingState = VariableState.Uninitialized;
public static VariableState LoadingState
{
get
{
return mLoadingState;
}
set
{
mLoadingState = value;
}
}
public FlatRedBall.Instructions.Instruction InterpolateToState (VariableState stateToInterpolateTo, double secondsToTake)
{
switch(stateToInterpolateTo)
{
case VariableState.Intro:
break;
case VariableState.StartDucks:
break;
case VariableState.DucksFlying:
break;
case VariableState.DucksEscaping:
break;
case VariableState.PostDucks:
break;
case VariableState.StartIntro:
break;
case VariableState.DogAnimation:
break;
case VariableState.CheckEndOfRound:
break;
case VariableState.AnimateEndOfRound:
break;
case VariableState.AnimatingEndOfRound:
break;
case VariableState.ContinueAnimation:
break;
case VariableState.Lose:
break;
}
var instruction = new FlatRedBall.Instructions.DelegateInstruction<VariableState>(StopStateInterpolation, stateToInterpolateTo);
instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + secondsToTake;
FlatRedBall.Instructions.InstructionManager.Add(instruction);
return instruction;
}
public void StopStateInterpolation (VariableState stateToStop)
{
switch(stateToStop)
{
case VariableState.Intro:
break;
case VariableState.StartDucks:
break;
case VariableState.DucksFlying:
break;
case VariableState.DucksEscaping:
break;
case VariableState.PostDucks:
break;
case VariableState.StartIntro:
break;
case VariableState.DogAnimation:
break;
case VariableState.CheckEndOfRound:
break;
case VariableState.AnimateEndOfRound:
break;
case VariableState.AnimatingEndOfRound:
break;
case VariableState.ContinueAnimation:
break;
case VariableState.Lose:
break;
}
CurrentState = stateToStop;
}
public void InterpolateBetween (VariableState firstState, VariableState secondState, float interpolationValue)
{
#if DEBUG
if (float.IsNaN(interpolationValue))
{
throw new Exception("interpolationValue cannot be NaN");
}
#endif
switch(firstState)
{
case VariableState.Intro:
break;
case VariableState.StartDucks:
break;
case VariableState.DucksFlying:
break;
case VariableState.DucksEscaping:
break;
case VariableState.PostDucks:
break;
case VariableState.StartIntro:
break;
case VariableState.DogAnimation:
break;
case VariableState.CheckEndOfRound:
break;
case VariableState.AnimateEndOfRound:
break;
case VariableState.AnimatingEndOfRound:
break;
case VariableState.ContinueAnimation:
break;
case VariableState.Lose:
break;
}
switch(secondState)
{
case VariableState.Intro:
break;
case VariableState.StartDucks:
break;
case VariableState.DucksFlying:
break;
case VariableState.DucksEscaping:
break;
case VariableState.PostDucks:
break;
case VariableState.StartIntro:
break;
case VariableState.DogAnimation:
break;
case VariableState.CheckEndOfRound:
break;
case VariableState.AnimateEndOfRound:
break;
case VariableState.AnimatingEndOfRound:
break;
case VariableState.ContinueAnimation:
break;
case VariableState.Lose:
break;
}
if (interpolationValue < 1)
{
mCurrentState = (int)firstState;
}
else
{
mCurrentState = (int)secondState;
}
}
public override void MoveToState (int state)
{
this.CurrentState = (VariableState)state;
}
/// <summary>Sets the current state, and pushes that state onto the back stack.</summary>
public void PushState (VariableState state)
{
this.CurrentState = state;
#if !MONOGAME
ScreenManager.PushStateToStack((int)this.CurrentState);
#endif
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
return null;
}
public static object GetFile (string memberName)
{
return null;
}
object GetMember (string memberName)
{
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.Diagnostics;
using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
// disable warning about unused weakref
#pragma warning disable 414
internal interface PinnedObject
{
void CleanUp();
bool IsPinned();
}
namespace GCSimulator
{
public enum LifeTimeENUM
{
Short,
Medium,
Long
}
public interface LifeTime
{
LifeTimeENUM LifeTime
{
get;
set;
}
}
public interface LifeTimeStrategy
{
int NextObject(LifeTimeENUM lifeTime);
bool ShouldDie(LifeTime o, int index);
}
/// <summary>
/// This interfact abstract the object contaienr , allowing us to specify differnt datastructures
/// implementation.
/// The only restriction on the ObjectContainer is that the objects contained in it must implement
/// LifeTime interface.
/// Right now we have a simple array container as a stock implementation for that. for more information
/// see code:#ArrayContainer
/// </summary>
/// <param name="o"></param>
/// <param name="index"></param>
public interface ObjectContainer<T> where T : LifeTime
{
void Init(int numberOfObjects);
void AddObjectAt(T o, int index);
T GetObject(int index);
T SetObjectAt(T o, int index);
int Count
{
get;
}
}
public sealed class BinaryTreeObjectContainer<T> : ObjectContainer<T> where T : LifeTime
{
private class Node
{
public Node LeftChild;
public Node RightChild;
public int id;
public T Data;
}
private Node _root;
private int _count;
public BinaryTreeObjectContainer()
{
_root = null;
_count = 0;
}
public void Init(int numberOfObjects)
{
if (numberOfObjects <= 0)
{
return;
}
_root = new Node();
_root.id = 0;
// the total number of objects in a binary search tree = (2^n+1) - 1
// where n is the depth of the tree
int depth = (int)Math.Log(numberOfObjects, 2);
_count = numberOfObjects;
_root.LeftChild = CreateTree(depth, 1);
_root.RightChild = CreateTree(depth, 2);
}
public void AddObjectAt(T o, int index)
{
Node node = Find(index, _root);
if (node != null)
{
node.Data = o;
}
}
public T GetObject(int index)
{
Node node = Find(index, _root);
if (node == null)
{
return default(T);
}
return node.Data;
}
public T SetObjectAt(T o, int index)
{
Node node = Find(index, _root);
if (node == null)
{
return default(T);
}
T old = node.Data;
node.Data = o;
return old;
}
public int Count
{
get
{
return _count;
}
}
private Node CreateTree(int depth, int id)
{
if (depth <= 0 || id >= Count)
{
return null;
}
Node node = new Node();
node.id = id;
node.LeftChild = CreateTree(depth - 1, id * 2 + 1);
node.RightChild = CreateTree(depth - 1, id * 2 + 2);
return node;
}
private Node Find(int id, Node node)
{
// we want to implement find and try to avoid creating temp objects..
// Our Tree is fixed size, we don;t allow modifying the actual
// tree by adding or deleting nodes ( that would be more
// interesting, but would give us inconsistent perf numbers.
// Traverse the tree ( slow, but avoids allocation ), we can write
// another tree that is a BST, or use SortedList<T,T> which uses
// BST as the implementation
if (node == null)
return null;
if (id == node.id)
return node;
Node retNode = null;
// find in the left child
retNode = Find(id, node.LeftChild);
// if not found, try the right child.
if (retNode == null)
retNode = Find(id, node.RightChild);
return retNode;
}
}
//#ArrayContainer Simple Array Stock Implemntation for ObjectContainer
public sealed class ArrayObjectContainer<T> : ObjectContainer<T> where T : LifeTime
{
private T[] _objContainer = null;
public void Init(int numberOfObjects)
{
_objContainer = new T[numberOfObjects];
}
public void AddObjectAt(T o, int index)
{
_objContainer[index] = o;
}
public T GetObject(int index)
{
return _objContainer[index];
}
public T SetObjectAt(T o, int index)
{
T old = _objContainer[index];
_objContainer[index] = o;
return old;
}
public int Count
{
get
{
return _objContainer.Length;
}
}
}
public delegate void ObjectDiedEventHandler(LifeTime o, int index);
public sealed class ObjectLifeTimeManager
{
private LifeTimeStrategy _strategy;
private ObjectContainer<LifeTime> _objectContainer = null;
//
public void SetObjectContainer(ObjectContainer<LifeTime> objectContainer)
{
_objectContainer = objectContainer;
}
public event ObjectDiedEventHandler objectDied;
public void Init(int numberObjects)
{
_objectContainer.Init(numberObjects);
//objContainer = new object[numberObjects];
}
public LifeTimeStrategy LifeTimeStrategy
{
set
{
_strategy = value;
}
}
public void AddObject(LifeTime o, int index)
{
_objectContainer.AddObjectAt(o, index);
//objContainer[index] = o;
}
public void Run()
{
LifeTime objLifeTime;
for (int i = 0; i < _objectContainer.Count; ++i)
{
objLifeTime = _objectContainer.GetObject(i);
//object o = objContainer[i];
//objLifeTime = o as LifeTime;
if (_strategy.ShouldDie(objLifeTime, i))
{
int index = _strategy.NextObject(objLifeTime.LifeTime);
LifeTime oldObject = _objectContainer.SetObjectAt(null, index);
//objContainer[index] = null;
// fire the event
objectDied(oldObject, index);
}
}
}
}
internal class RandomLifeTimeStrategy : LifeTimeStrategy
{
private int _counter = 0;
private int _mediumLifeTime = 30;
private int _shortLifeTime = 3;
private int _mediumDataCount = 1000000;
private int _shortDataCount = 5000;
private Random _rand = new Random(123456);
public RandomLifeTimeStrategy(int mediumlt, int shortlt, int mdc, int sdc)
{
_mediumLifeTime = mediumlt;
_shortLifeTime = shortlt;
_mediumDataCount = mdc;
_shortDataCount = sdc;
}
public int MediumLifeTime
{
set
{
_mediumLifeTime = value;
}
}
public int ShortLifeTime
{
set
{
_shortLifeTime = value;
}
}
public int NextObject(LifeTimeENUM lifeTime)
{
switch (lifeTime)
{
case LifeTimeENUM.Short:
return _rand.Next() % _shortDataCount;
case LifeTimeENUM.Medium:
return (_rand.Next() % _mediumDataCount) + _shortDataCount;
case LifeTimeENUM.Long:
return 0;
}
return 0;
}
public bool ShouldDie(LifeTime o, int index)
{
_counter++;
LifeTimeENUM lifeTime = o.LifeTime;
switch (lifeTime)
{
case LifeTimeENUM.Short:
if (_counter % _shortLifeTime == 0)
return true;
break;
case LifeTimeENUM.Medium:
if (_counter % _mediumLifeTime == 0)
return true;
break;
case LifeTimeENUM.Long:
return false;
}
return false;
}
}
/// <summary>
/// we might want to implement a different strategy that decide the life time of the object based on the time
/// elabsed since the last object acceess.
///
/// </summary>
internal class TimeBasedLifeTimeStrategy : LifeTimeStrategy
{
private int _lastMediumTickCount = Environment.TickCount;
private int _lastShortTickCount = Environment.TickCount;
private int _lastMediumIndex = 0;
private int _lastShortIndex = 0;
public int NextObject(LifeTimeENUM lifeTime)
{
switch (lifeTime)
{
case LifeTimeENUM.Short:
return _lastShortIndex;
case LifeTimeENUM.Medium:
return _lastMediumIndex;
case LifeTimeENUM.Long:
return 0;
}
return 0;
}
public bool ShouldDie(LifeTime o, int index)
{
LifeTimeENUM lifeTime = o.LifeTime;
// short objects will live for 20 seconds, long objects will live for more.
switch (lifeTime)
{
case LifeTimeENUM.Short:
if (Environment.TickCount - _lastShortTickCount > 1) // this is in accureat enumber, since
// we will be finsh iterating throuh the short life time object in less than 1 ms , so we need
// to switch either to QueryPeroformanceCounter, or to block the loop for some time through
// Thread.Sleep, the other solution is to increase the number of objects a lot.
{
_lastShortTickCount = Environment.TickCount;
_lastShortIndex = index;
return true;
}
break;
case LifeTimeENUM.Medium:
if (Environment.TickCount - _lastMediumTickCount > 20)
{
_lastMediumTickCount = Environment.TickCount;
_lastMediumIndex = index;
return true;
}
break;
case LifeTimeENUM.Long:
break;
}
return false;
}
}
internal class ObjectWrapper : LifeTime, PinnedObject
{
private bool _pinned;
private bool _weakReferenced;
private GCHandle _gcHandle;
private LifeTimeENUM _lifeTime;
private WeakReference _weakRef;
private byte[] _data;
private int _dataSize;
public int DataSize
{
set
{
_dataSize = value;
_data = new byte[_dataSize];
if (_pinned)
{
_gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned);
}
if (_weakReferenced)
{
_weakRef = new WeakReference(_data);
_data = null;
}
}
}
public LifeTimeENUM LifeTime
{
get
{
return _lifeTime;
}
set
{
_lifeTime = value;
}
}
public bool IsPinned()
{
return _pinned;
}
public bool IsWeak()
{
return _weakReferenced;
}
public void CleanUp()
{
if (_gcHandle.IsAllocated)
{
_gcHandle.Free();
}
}
public ObjectWrapper(bool runFinalizer, bool pinned, bool weakReferenced)
{
_pinned = pinned;
_weakReferenced = weakReferenced;
if (!runFinalizer)
{
GC.SuppressFinalize(this);
}
}
~ObjectWrapper()
{
// DO SOMETHING UNCONVENTIONAL IN FINALIZER
_data = new byte[_dataSize];
CleanUp();
}
}
internal class ClientSimulator
{
[ThreadStatic]
private static ObjectLifeTimeManager s_lifeTimeManager;
private static int s_meanAllocSize = 17;
private static int s_mediumLifeTime = 30;
private static int s_shortLifeTime = 3;
private static int s_mediumDataSize = s_meanAllocSize;
private static int s_shortDataSize = s_meanAllocSize;
private static int s_mediumDataCount = 1000000;
private static int s_shortDataCount = 5000;
private static int s_countIters = 500;
private static float s_percentPinned = 0.1F;
private static float s_percentWeak = 0.0F;
private static int s_numThreads = 1;
private static bool s_runFinalizer = false;
private static string s_strategy = "Random";
private static string s_objectGraph = "List";
private static List<Thread> s_threadList = new List<Thread>();
private static Stopwatch s_stopWatch = new Stopwatch();
private static Object s_objLock = new Object();
private static uint s_currentIterations = 0;
//keep track of the collection count for generations 0, 1, 2
private static int[] s_currentCollections = new int[3];
private static int s_outputFrequency = 0; //after how many iterations the data is printed
private static System.TimeSpan s_totalTime;
public static int Main(string[] args)
{
s_stopWatch.Start();
for (int i = 0; i < 3; i++)
{
s_currentCollections[i] = 0;
}
if (!ParseArgs(args))
return 101;
// Run the test.
for (int i = 0; i < s_numThreads; ++i)
{
Thread thread = new Thread(RunTest);
s_threadList.Add(thread);
thread.Start();
}
foreach (Thread t in s_threadList)
{
t.Join();
}
return 100;
}
public static void RunTest()
{
// Allocate the objects.
s_lifeTimeManager = new ObjectLifeTimeManager();
LifeTimeStrategy ltStrategy;
int threadMediumLifeTime = s_mediumLifeTime;
int threadShortLifeTime = s_shortLifeTime;
int threadMediumDataSize = s_mediumDataSize;
int threadShortDataSize = s_shortDataSize;
int threadMediumDataCount = s_mediumDataCount;
int threadShortDataCount = s_shortDataCount;
float threadPercentPinned = s_percentPinned;
float threadPercentWeak = s_percentWeak;
bool threadRunFinalizer = s_runFinalizer;
string threadStrategy = s_strategy;
string threadObjectGraph = s_objectGraph;
if (threadObjectGraph.ToLower() == "tree")
{
s_lifeTimeManager.SetObjectContainer(new BinaryTreeObjectContainer<LifeTime>());
}
else
{
s_lifeTimeManager.SetObjectContainer(new ArrayObjectContainer<LifeTime>());
}
s_lifeTimeManager.Init(threadShortDataCount + threadMediumDataCount);
if (threadStrategy.ToLower() == "random")
{
ltStrategy = new RandomLifeTimeStrategy(threadMediumLifeTime, threadShortLifeTime, threadMediumDataCount, threadShortDataCount);
}
else
{
// may be we need to specify the elapsed time.
ltStrategy = new TimeBasedLifeTimeStrategy();
}
s_lifeTimeManager.LifeTimeStrategy = ltStrategy;
s_lifeTimeManager.objectDied += new ObjectDiedEventHandler(objectDied);
for (int i = 0; i < threadShortDataCount + threadMediumDataCount; ++i)
{
bool pinned = false;
if (threadPercentPinned != 0)
{
pinned = (i % ((int)(1 / threadPercentPinned)) == 0);
}
bool weak = false;
if (threadPercentWeak != 0)
{
weak = (i % ((int)(1 / threadPercentWeak)) == 0);
}
ObjectWrapper oWrapper = new ObjectWrapper(threadRunFinalizer, pinned, weak);
if (i < threadShortDataCount)
{
oWrapper.DataSize = threadShortDataSize;
oWrapper.LifeTime = LifeTimeENUM.Short;
}
else
{
oWrapper.DataSize = threadMediumDataSize;
oWrapper.LifeTime = LifeTimeENUM.Medium;
}
s_lifeTimeManager.AddObject(oWrapper, i);
}
lock (s_objLock)
{
Console.WriteLine("Thread {0} Running With Configuration: ", System.Threading.Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("==============================");
Console.WriteLine("[Thread] Medium Lifetime " + threadMediumLifeTime);
Console.WriteLine("[Thread] Short Lifetime " + threadShortLifeTime);
Console.WriteLine("[Thread] Medium Data Size " + threadMediumDataSize);
Console.WriteLine("[Thread] Short Data Size " + threadShortDataSize);
Console.WriteLine("[Thread] Medium Data Count " + threadMediumDataCount);
Console.WriteLine("[Thread] Short Data Count " + threadShortDataCount);
Console.WriteLine("[Thread] % Pinned " + threadPercentPinned);
Console.WriteLine("[Thread] % Weak " + threadPercentWeak);
Console.WriteLine("[Thread] RunFinalizers " + threadRunFinalizer);
Console.WriteLine("[Thread] Strategy " + threadStrategy);
Console.WriteLine("[Thread] Object Graph " + threadObjectGraph);
Console.WriteLine("==============================");
}
for (int i = 0; i < s_countIters; ++i)
{
// Run the test.
s_lifeTimeManager.Run();
if (s_outputFrequency > 0)
{
lock (s_objLock)
{
s_currentIterations++;
if (s_currentIterations % s_outputFrequency == 0)
{
Console.WriteLine("Iterations = {0}", s_currentIterations);
Console.WriteLine("AllocatedMemory = {0} bytes", GC.GetTotalMemory(false));
//get the number of collections and the elapsed time for this group of iterations
int[] collectionCount = new int[3];
for (int j = 0; j < 3; j++)
{
collectionCount[j] = GC.CollectionCount(j);
}
int[] newCollections = new int[3];
for (int j = 0; j < 3; j++)
{
newCollections[j] = collectionCount[j] - s_currentCollections[j];
}
//update the running count of collections
for (int j = 0; j < 3; j++)
{
s_currentCollections[j] = collectionCount[j];
}
Console.WriteLine("Gen 0 Collections = {0}", newCollections[0]);
Console.WriteLine("Gen 1 Collections = {0}", newCollections[1]);
Console.WriteLine("Gen 2 Collections = {0}", newCollections[2]);
s_stopWatch.Stop();
Console.Write("Elapsed time: ");
System.TimeSpan tSpan = s_stopWatch.Elapsed;
if (tSpan.Days > 0)
Console.Write("{0} days, ", tSpan.Days);
if (tSpan.Hours > 0)
Console.Write("{0} hours, ", tSpan.Hours);
if (tSpan.Minutes > 0)
Console.Write("{0} minutes, ", tSpan.Minutes);
Console.Write("{0} seconds, ", tSpan.Seconds);
Console.Write("{0} milliseconds", tSpan.Milliseconds);
s_totalTime += tSpan;
s_stopWatch.Reset();
s_stopWatch.Start();
Console.Write(" (Total time: ");
if (s_totalTime.Days > 0)
Console.Write("{0} days, ", s_totalTime.Days);
if (s_totalTime.Hours > 0)
Console.Write("{0} hours, ", s_totalTime.Hours);
if (s_totalTime.Minutes > 0)
Console.Write("{0} minutes, ", s_totalTime.Minutes);
Console.Write("{0} seconds, ", s_totalTime.Seconds);
Console.WriteLine("{0} milliseconds)", s_totalTime.Milliseconds);
Console.WriteLine("----------------------------------");
}
}
}
}
}
private static void objectDied(LifeTime lifeTime, int index)
{
// put a new fresh object instead;
ObjectWrapper oWrapper = lifeTime as ObjectWrapper;
oWrapper.CleanUp();
oWrapper = new ObjectWrapper(s_runFinalizer, oWrapper.IsPinned(), oWrapper.IsWeak());
oWrapper.LifeTime = lifeTime.LifeTime;
oWrapper.DataSize = lifeTime.LifeTime == LifeTimeENUM.Short ? s_shortDataSize : s_mediumDataSize;
s_lifeTimeManager.AddObject(oWrapper, index);
}
/// <summary>
/// Parse the arguments, no error checking is done yet.
/// TODO: Add more error checking.
///
/// Populate variables with defaults, then overwrite them with config settings. Finally overwrite them with command line parameters
/// </summary>
public static bool ParseArgs(string[] args)
{
s_countIters = 500;
try
{
for (int i = 0; i < args.Length; ++i)
{
string currentArg = args[i];
string currentArgValue;
if (currentArg.StartsWith("-") || currentArg.StartsWith("/"))
{
currentArg = currentArg.Substring(1);
}
else
{
Console.WriteLine("Error! Unexpected argument {0}", currentArg);
return false;
}
if (currentArg.StartsWith("?"))
{
Usage();
System.Environment.FailFast("displayed help");
}
else if (currentArg.StartsWith("iter") || currentArg.Equals("i")) // number of iterations
{
currentArgValue = args[++i];
s_countIters = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("datasize") || currentArg.Equals("dz"))
{
currentArgValue = args[++i];
s_mediumDataSize = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("sdatasize") || currentArg.Equals("sdz"))
{
currentArgValue = args[++i];
s_shortDataSize = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("datacount") || currentArg.Equals("dc"))
{
currentArgValue = args[++i];
s_mediumDataCount = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("sdatacount") || currentArg.Equals("sdc"))
{
currentArgValue = args[++i];
s_shortDataCount = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("lifetime") || currentArg.Equals("lt"))
{
currentArgValue = args[++i];
s_shortLifeTime = Int32.Parse(currentArgValue);
s_mediumLifeTime = s_shortLifeTime * 10;
}
else if (currentArg.StartsWith("threads") || currentArg.Equals("t"))
{
currentArgValue = args[++i];
s_numThreads = Int32.Parse(currentArgValue);
}
else if (currentArg.StartsWith("fin") || currentArg.Equals("f"))
{
s_runFinalizer = true;
}
else if (currentArg.StartsWith("datapinned") || currentArg.StartsWith("dp")) // percentage data pinned
{
currentArgValue = args[++i];
s_percentPinned = float.Parse(currentArgValue, System.Globalization.CultureInfo.InvariantCulture);
if (s_percentPinned < 0 || s_percentPinned > 1)
{
Console.WriteLine("Error! datapinned should be a number from 0 to 1");
return false;
}
}
else if (currentArg.StartsWith("strategy")) //strategy that if the object died or not
{
currentArgValue = args[++i];
if ((currentArgValue.ToLower() == "random") || (currentArgValue.ToLower() == "time"))
s_strategy = currentArgValue;
else
{
Console.WriteLine("Error! Unexpected argument for strategy: {0}", currentArgValue);
return false;
}
}
else if (currentArg.StartsWith("dataweak") || currentArg.StartsWith("dw"))
{
currentArgValue = args[++i];
s_percentWeak = float.Parse(currentArgValue, System.Globalization.CultureInfo.InvariantCulture);
if (s_percentWeak < 0 || s_percentWeak > 1)
{
Console.WriteLine("Error! dataweak should be a number from 0 to 1");
return false;
}
}
else if (currentArg.StartsWith("objectgraph") || currentArg.StartsWith("og"))
{
currentArgValue = args[++i];
if ((currentArgValue.ToLower() == "tree") || (currentArgValue.ToLower() == "list"))
s_objectGraph = currentArgValue;
else
{
Console.WriteLine("Error! Unexpected argument for objectgraph: {0}", currentArgValue);
return false;
}
}
else if (currentArg.Equals("out")) //output frequency
{
currentArgValue = args[++i];
s_outputFrequency = int.Parse(currentArgValue);
}
else
{
Console.WriteLine("Error! Unexpected argument {0}", currentArg);
return false;
}
}
}
catch (System.Exception e)
{
Console.WriteLine("Incorrect arguments");
Console.WriteLine(e.ToString());
return false;
}
return true;
}
public static void Usage()
{
Console.WriteLine("GCSimulator [-?] [options]");
Console.WriteLine("\nOptions");
Console.WriteLine("\nGlobal:");
Console.WriteLine("-? Display the usage and exit");
Console.WriteLine("-i [-iter] <num iterations> : specify number of iterations for the test, default is " + s_countIters);
Console.WriteLine("\nThreads:");
Console.WriteLine("-t [-threads] <number of threads> : specifiy number of threads, default is " + s_numThreads);
Console.WriteLine("\nData:");
Console.WriteLine("-dz [-datasize] <data size> : specify the data size in bytes, default is " + s_mediumDataSize);
Console.WriteLine("-sdz [sdatasize] <data size> : specify the short lived data size in bytes, default is " + s_shortDataSize);
Console.WriteLine("-dc [datacount] <data count> : specify the medium lived data count, default is " + s_mediumDataCount);
Console.WriteLine("-sdc [sdatacount] <data count> : specify the short lived data count, default is " + s_shortDataCount);
Console.WriteLine("-lt [-lifetime] <number> : specify the life time of the objects, default is " + s_shortLifeTime);
Console.WriteLine("-f [-fin] : specify whether to do allocation in finalizer or not, default is no");
Console.WriteLine("-dp [-datapinned] <percent of data pinned> : specify the percentage of data that we want to pin (number from 0 to 1), default is " + s_percentPinned);
Console.WriteLine("-dw [-dataweak] <percent of data weak referenced> : specify the percentage of data that we want to weak reference, (number from 0 to 1) default is " + s_percentWeak);
Console.WriteLine("-strategy < indicate the strategy for deciding when the objects should die, right now we support only Random and Time strategy, default is Random");
Console.WriteLine("-og [-objectgraph] <List|Tree> : specify whether to use a List- or Tree-based object graph, default is " + s_objectGraph);
Console.WriteLine("-out <iterations> : after how many iterations to output data");
}
}
}
| |
/*
* 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 Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.DataStructures;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Plugin;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Interop;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Native Ignite wrapper.
/// </summary>
internal class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite
{
/// <summary>
/// Operation codes for PlatformProcessorImpl calls.
/// </summary>
private enum Op
{
GetCache = 1,
CreateCache = 2,
GetOrCreateCache = 3,
CreateCacheFromConfig = 4,
GetOrCreateCacheFromConfig = 5,
DestroyCache = 6,
GetAffinity = 7,
GetDataStreamer = 8,
GetTransactions = 9,
GetClusterGroup = 10,
GetExtension = 11,
GetAtomicLong = 12,
GetAtomicReference = 13,
GetAtomicSequence = 14,
GetIgniteConfiguration = 15,
GetCacheNames = 16,
CreateNearCache = 17,
GetOrCreateNearCache = 18,
LoggerIsLevelEnabled = 19,
LoggerLog = 20,
GetBinaryProcessor = 21,
ReleaseStart = 22,
AddCacheConfiguration = 23,
SetBaselineTopologyVersion = 24,
SetBaselineTopologyNodes = 25,
GetBaselineTopology = 26,
DisableWal = 27,
EnableWal = 28,
IsWalEnabled = 29,
SetTxTimeoutOnPartitionMapExchange = 30
}
/** */
private readonly IgniteConfiguration _cfg;
/** Grid name. */
private readonly string _name;
/** Unmanaged node. */
private readonly IPlatformTargetInternal _proc;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Initial projection. */
private readonly ClusterGroupImpl _prj;
/** Binary. */
private readonly Binary.Binary _binary;
/** Binary processor. */
private readonly BinaryProcessor _binaryProc;
/** Lifecycle handlers. */
private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers;
/** Local node. */
private IClusterNode _locNode;
/** Callbacks */
private readonly UnmanagedCallbacks _cbs;
/** Node info cache. */
private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes =
new ConcurrentDictionary<Guid, ClusterNodeImpl>();
/** Client reconnect task completion source. */
private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource =
new TaskCompletionSource<bool>();
/** Plugin processor. */
private readonly PluginProcessor _pluginProcessor;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="name">Grid name.</param>
/// <param name="proc">Interop processor.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="lifecycleHandlers">Lifecycle beans.</param>
/// <param name="cbs">Callbacks.</param>
public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh,
IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc)
{
Debug.Assert(cfg != null);
Debug.Assert(proc != null);
Debug.Assert(marsh != null);
Debug.Assert(lifecycleHandlers != null);
Debug.Assert(cbs != null);
_cfg = cfg;
_name = name;
_proc = proc;
_marsh = marsh;
_lifecycleHandlers = lifecycleHandlers;
_cbs = cbs;
marsh.Ignite = this;
_prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null);
_binary = new Binary.Binary(marsh);
_binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor));
cbs.Initialize(this);
// Set reconnected task to completed state for convenience.
_clientReconnectTaskCompletionSource.SetResult(false);
SetCompactFooter();
_pluginProcessor = new PluginProcessor(this);
}
/// <summary>
/// Sets the compact footer setting.
/// </summary>
private void SetCompactFooter()
{
if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl))
{
// If there is a Spring config, use setting from Spring,
// since we ignore .NET config in legacy mode.
var cfg0 = GetConfiguration().BinaryConfiguration;
if (cfg0 != null)
_marsh.CompactFooter = cfg0.CompactFooter;
}
}
/// <summary>
/// On-start routine.
/// </summary>
internal void OnStart()
{
PluginProcessor.OnIgniteStart();
foreach (var lifecycleBean in _lifecycleHandlers)
lifecycleBean.OnStart(this);
}
/** <inheritdoc /> */
public string Name
{
get { return _name; }
}
/** <inheritdoc /> */
public ICluster GetCluster()
{
return this;
}
/** <inheritdoc /> */
IIgnite IClusterGroup.Ignite
{
get { return this; }
}
/** <inheritdoc /> */
public IClusterGroup ForLocal()
{
return _prj.ForNodes(GetLocalNode());
}
/** <inheritdoc /> */
public ICompute GetCompute()
{
return _prj.ForServers().GetCompute();
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
IgniteArgumentCheck.NotNull(p, "p");
return _prj.ForPredicate(p);
}
/** <inheritdoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
return _prj.ForAttribute(name, val);
}
/** <inheritdoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return _prj.ForCacheNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForDataNodes(string name)
{
return _prj.ForDataNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForClientNodes(string name)
{
return _prj.ForClientNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForRemotes()
{
return _prj.ForRemotes();
}
/** <inheritdoc /> */
public IClusterGroup ForDaemons()
{
return _prj.ForDaemons();
}
/** <inheritdoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
IgniteArgumentCheck.NotNull(node, "node");
return _prj.ForHost(node);
}
/** <inheritdoc /> */
public IClusterGroup ForRandom()
{
return _prj.ForRandom();
}
/** <inheritdoc /> */
public IClusterGroup ForOldest()
{
return _prj.ForOldest();
}
/** <inheritdoc /> */
public IClusterGroup ForYoungest()
{
return _prj.ForYoungest();
}
/** <inheritdoc /> */
public IClusterGroup ForDotNet()
{
return _prj.ForDotNet();
}
/** <inheritdoc /> */
public IClusterGroup ForServers()
{
return _prj.ForServers();
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetNodes()
{
return _prj.GetNodes();
}
/** <inheritdoc /> */
public IClusterNode GetNode(Guid id)
{
return _prj.GetNode(id);
}
/** <inheritdoc /> */
public IClusterNode GetNode()
{
return _prj.GetNode();
}
/** <inheritdoc /> */
public IClusterMetrics GetMetrics()
{
return _prj.GetMetrics();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy",
Justification = "Proxy does not need to be disposed.")]
public void Dispose()
{
Ignition.Stop(Name, true);
}
/// <summary>
/// Internal stop routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
internal void Stop(bool cancel)
{
var jniTarget = _proc as PlatformJniTarget;
if (jniTarget == null)
{
throw new IgniteException("Ignition.Stop is not supported in thin client.");
}
UU.IgnitionStop(Name, cancel);
_cbs.Cleanup();
}
/// <summary>
/// Called before node has stopped.
/// </summary>
internal void BeforeNodeStop()
{
var handler = Stopping;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called after node has stopped.
/// </summary>
internal void AfterNodeStop()
{
foreach (var bean in _lifecycleHandlers)
bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop);
var handler = Stopped;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration)
{
return GetOrCreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.GetOrCreateCacheFromConfig);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name));
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration)
{
return CreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.CreateCacheFromConfig);
}
/// <summary>
/// Gets or creates the cache.
/// </summary>
private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration, Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name");
configuration.Validate(Logger);
var cacheTarget = DoOutOpObject((int) op, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
configuration.Write(w, ClientSocket.CurrentProtocolVersion);
if (nearConfiguration != null)
{
w.WriteBoolean(true);
nearConfiguration.Write(w);
}
else
{
w.WriteBoolean(false);
}
});
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public void DestroyCache(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
DoOutOp((int) Op.DestroyCache, w => w.WriteString(name));
}
/// <summary>
/// Gets cache from specified native cache object.
/// </summary>
/// <param name="nativeCache">Native cache.</param>
/// <param name="keepBinary">Keep binary flag.</param>
/// <returns>
/// New instance of cache wrapping specified native cache.
/// </returns>
public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false)
{
return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false, false);
}
/** <inheritdoc /> */
public IClusterNode GetLocalNode()
{
return _locNode ?? (_locNode =
GetNodes().FirstOrDefault(x => x.IsLocal) ??
ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal));
}
/** <inheritdoc /> */
public bool PingNode(Guid nodeId)
{
return _prj.PingNode(nodeId);
}
/** <inheritdoc /> */
public long TopologyVersion
{
get { return _prj.TopologyVersion; }
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetTopology(long ver)
{
return _prj.Topology(ver);
}
/** <inheritdoc /> */
public void ResetMetrics()
{
_prj.ResetMetrics();
}
/** <inheritdoc /> */
public Task<bool> ClientReconnectTask
{
get { return _clientReconnectTaskCompletionSource.Task; }
}
/** <inheritdoc /> */
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetDataStreamer<TK, TV>(cacheName, false);
}
/// <summary>
/// Gets the data streamer.
/// </summary>
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary)
{
var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w =>
{
w.WriteString(cacheName);
w.WriteBoolean(keepBinary);
});
return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary);
}
/// <summary>
/// Gets the public Ignite interface.
/// </summary>
public IIgnite GetIgnite()
{
return this;
}
/** <inheritdoc /> */
public IBinary GetBinary()
{
return _binary;
}
/** <inheritdoc /> */
public ICacheAffinity GetAffinity(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName));
return new CacheAffinityImpl(aff, false);
}
/** <inheritdoc /> */
public ITransactions GetTransactions()
{
return new TransactionsImpl(this, DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id);
}
/** <inheritdoc /> */
public IMessaging GetMessaging()
{
return _prj.GetMessaging();
}
/** <inheritdoc /> */
public IEvents GetEvents()
{
return _prj.GetEvents();
}
/** <inheritdoc /> */
public IServices GetServices()
{
return _prj.ForServers().GetServices();
}
/** <inheritdoc /> */
public IAtomicLong GetAtomicLong(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeLong == null)
return null;
return new AtomicLong(nativeLong, name);
}
/** <inheritdoc /> */
public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeSeq == null)
return null;
return new AtomicSequence(nativeSeq, name);
}
/** <inheritdoc /> */
public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w =>
{
w.WriteString(name);
w.WriteObject(initialValue);
w.WriteBoolean(create);
});
return refTarget == null ? null : new AtomicReference<T>(refTarget, name);
}
/** <inheritdoc /> */
public IgniteConfiguration GetConfiguration()
{
return DoInOp((int) Op.GetIgniteConfiguration,
s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg,
ClientSocket.CurrentProtocolVersion));
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.CreateNearCache);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.GetOrCreateNearCache);
}
/** <inheritdoc /> */
public ICollection<string> GetCacheNames()
{
return Target.OutStream((int) Op.GetCacheNames, r =>
{
var res = new string[r.ReadInt()];
for (var i = 0; i < res.Length; i++)
res[i] = r.ReadString();
return (ICollection<string>) res;
});
}
/** <inheritdoc /> */
public ILogger Logger
{
get { return _cbs.Log; }
}
/** <inheritdoc /> */
public event EventHandler Stopping;
/** <inheritdoc /> */
public event EventHandler Stopped;
/** <inheritdoc /> */
public event EventHandler ClientDisconnected;
/** <inheritdoc /> */
public event EventHandler<ClientReconnectEventArgs> ClientReconnected;
/** <inheritdoc /> */
public T GetPlugin<T>(string name) where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return PluginProcessor.GetProvider(name).GetPlugin<T>();
}
/** <inheritdoc /> */
public void ResetLostPartitions(IEnumerable<string> cacheNames)
{
IgniteArgumentCheck.NotNull(cacheNames, "cacheNames");
_prj.ResetLostPartitions(cacheNames);
}
/** <inheritdoc /> */
public void ResetLostPartitions(params string[] cacheNames)
{
ResetLostPartitions((IEnumerable<string>) cacheNames);
}
/** <inheritdoc /> */
#pragma warning disable 618
public ICollection<IMemoryMetrics> GetMemoryMetrics()
{
return _prj.GetMemoryMetrics();
}
/** <inheritdoc /> */
public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName)
{
IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName");
return _prj.GetMemoryMetrics(memoryPolicyName);
}
#pragma warning restore 618
/** <inheritdoc /> */
public void SetActive(bool isActive)
{
_prj.SetActive(isActive);
}
/** <inheritdoc /> */
public bool IsActive()
{
return _prj.IsActive();
}
/** <inheritdoc /> */
public void SetBaselineTopology(long topologyVersion)
{
DoOutInOp((int) Op.SetBaselineTopologyVersion, topologyVersion);
}
/** <inheritdoc /> */
public void SetBaselineTopology(IEnumerable<IBaselineNode> nodes)
{
IgniteArgumentCheck.NotNull(nodes, "nodes");
DoOutOp((int) Op.SetBaselineTopologyNodes, w =>
{
var pos = w.Stream.Position;
w.WriteInt(0);
var cnt = 0;
foreach (var node in nodes)
{
cnt++;
BaselineNode.Write(w, node);
}
w.Stream.WriteInt(pos, cnt);
});
}
/** <inheritdoc /> */
public ICollection<IBaselineNode> GetBaselineTopology()
{
return DoInOp((int) Op.GetBaselineTopology,
s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r)));
}
/** <inheritdoc /> */
public void DisableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.DisableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public void EnableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.EnableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public bool IsWalEnabled(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return DoOutOp((int) Op.IsWalEnabled, w => w.WriteString(cacheName)) == True;
}
public void SetTxTimeoutOnPartitionMapExchange(TimeSpan timeout)
{
DoOutOp((int) Op.SetTxTimeoutOnPartitionMapExchange,
(BinaryWriter w) => w.WriteLong((long) timeout.TotalMilliseconds));
}
/** <inheritdoc /> */
#pragma warning disable 618
public IPersistentStoreMetrics GetPersistentStoreMetrics()
{
return _prj.GetPersistentStoreMetrics();
}
#pragma warning restore 618
/** <inheritdoc /> */
public ICollection<IDataRegionMetrics> GetDataRegionMetrics()
{
return _prj.GetDataRegionMetrics();
}
/** <inheritdoc /> */
public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName)
{
return _prj.GetDataRegionMetrics(memoryPolicyName);
}
/** <inheritdoc /> */
public IDataStorageMetrics GetDataStorageMetrics()
{
return _prj.GetDataStorageMetrics();
}
/** <inheritdoc /> */
public void AddCacheConfiguration(CacheConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
DoOutOp((int) Op.AddCacheConfiguration,
s => configuration.Write(BinaryUtils.Marshaller.StartMarshal(s), ClientSocket.CurrentProtocolVersion));
}
/// <summary>
/// Gets or creates near cache.
/// </summary>
private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration,
Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
var cacheTarget = DoOutOpObject((int) op, w =>
{
w.WriteString(name);
configuration.Write(w);
});
return GetCache<TK, TV>(cacheTarget);
}
/// <summary>
/// Gets internal projection.
/// </summary>
/// <returns>Projection.</returns>
public ClusterGroupImpl ClusterGroup
{
get { return _prj; }
}
/// <summary>
/// Gets the binary processor.
/// </summary>
public IBinaryProcessor BinaryProcessor
{
get { return _binaryProc; }
}
/// <summary>
/// Configuration.
/// </summary>
public IgniteConfiguration Configuration
{
get { return _cfg; }
}
/// <summary>
/// Handle registry.
/// </summary>
public HandleRegistry HandleRegistry
{
get { return _cbs.HandleRegistry; }
}
/// <summary>
/// Updates the node information from stream.
/// </summary>
/// <param name="memPtr">Stream ptr.</param>
public void UpdateNodeInfo(long memPtr)
{
var stream = IgniteManager.Memory.Get(memPtr).GetStream();
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
var node = new ClusterNodeImpl(reader);
node.Init(this);
_nodes[node.Id] = node;
}
/// <summary>
/// Returns instance of Ignite Transactions to mark a transaction with a special label.
/// </summary>
/// <param name="label"></param>
/// <returns><see cref="ITransactions"/></returns>
internal ITransactions GetTransactionsWithLabel(string label)
{
Debug.Assert(label != null);
var platformTargetInternal = DoOutOpObject((int) Op.GetTransactions, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
w.WriteString(label);
});
return new TransactionsImpl(this, platformTargetInternal, GetLocalNode().Id);
}
/// <summary>
/// Gets the node from cache.
/// </summary>
/// <param name="id">Node id.</param>
/// <returns>Cached node.</returns>
public ClusterNodeImpl GetNode(Guid? id)
{
return id == null ? null : _nodes[id.Value];
}
/// <summary>
/// Gets the interop processor.
/// </summary>
internal IPlatformTargetInternal InteropProcessor
{
get { return _proc; }
}
/// <summary>
/// Called when local client node has been disconnected from the cluster.
/// </summary>
internal void OnClientDisconnected()
{
_clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>();
var handler = ClientDisconnected;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called when local client node has been reconnected to the cluster.
/// </summary>
/// <param name="clusterRestarted">Cluster restarted flag.</param>
internal void OnClientReconnected(bool clusterRestarted)
{
_clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted);
var handler = ClientReconnected;
if (handler != null)
handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted));
}
/// <summary>
/// Gets the plugin processor.
/// </summary>
public PluginProcessor PluginProcessor
{
get { return _pluginProcessor; }
}
/// <summary>
/// Notify processor that it is safe to use.
/// </summary>
internal void ProcessorReleaseStart()
{
Target.InLongOutLong((int) Op.ReleaseStart, 0);
}
/// <summary>
/// Checks whether log level is enabled in Java logger.
/// </summary>
internal bool LoggerIsLevelEnabled(LogLevel logLevel)
{
return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True;
}
/// <summary>
/// Logs to the Java logger.
/// </summary>
internal void LoggerLog(LogLevel level, string msg, string category, string err)
{
Target.InStreamOutLong((int) Op.LoggerLog, w =>
{
w.WriteInt((int) level);
w.WriteString(msg);
w.WriteString(category);
w.WriteString(err);
});
}
/// <summary>
/// Gets the platform plugin extension.
/// </summary>
internal IPlatformTarget GetExtension(int id)
{
return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Should;
using Xunit;
namespace AutoMapper.UnitTests
{
namespace BidirectionalRelationships
{
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship : AutoMapperSpecBase
{
private ParentDto _dto;
private int _beforeMapCount = 0;
private int _afterMapCount = 0;
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ParentModel, ParentDto>()
.BeforeMap((src, dest) => _beforeMapCount++)
.AfterMap((src, dest) => _afterMapCount++);
cfg.CreateMap<ChildModel, ChildDto>();
});
Mapper.AssertConfigurationIsValid();
}
protected override void Because_of()
{
var parent = new ParentModel { ID = "PARENT_ONE" };
parent.AddChild(new ChildModel { ID = "CHILD_ONE" });
parent.AddChild(new ChildModel { ID = "CHILD_TWO" });
_dto = Mapper.Map<ParentModel, ParentDto>(parent);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Children[0].Parent.ShouldBeSameAs(_dto);
_dto.Children[1].Parent.ShouldBeSameAs(_dto);
}
[Fact]
public void Before_and_After_for_the_parent_should_be_called_once()
{
_beforeMapCount.ShouldEqual(1);
_afterMapCount.ShouldEqual(1);
}
public class ParentModel
{
public ParentModel()
{
Children = new List<ChildModel>();
}
public string ID { get; set; }
public IList<ChildModel> Children { get; private set; }
public void AddChild(ChildModel child)
{
child.Parent = this;
Children.Add(child);
}
}
public class ChildModel
{
public string ID { get; set; }
public ParentModel Parent { get; set; }
}
public class ParentDto
{
public string ID { get; set; }
public IList<ChildDto> Children { get; set; }
}
public class ChildDto
{
public string ID { get; set; }
public ParentDto Parent { get; set; }
}
}
//public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship_using_CustomMapper_StackOverflow : AutoMapperSpecBase
//{
// private ParentDto _dto;
// private ParentModel _parent;
// protected override void Establish_context()
// {
// _parent = new ParentModel
// {
// ID = 2
// };
// List<ChildModel> childModels = new List<ChildModel>
// {
// new ChildModel
// {
// ID = 1,
// Parent = _parent
// }
// };
// Dictionary<int, ParentModel> parents = childModels.ToDictionary(x => x.ID, x => x.Parent);
// Mapper.CreateMap<int, ParentDto>().ConvertUsing(new ChildIdToParentDtoConverter(parents));
// Mapper.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels));
// Mapper.CreateMap<ParentModel, ParentDto>()
// .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.ID));
// Mapper.CreateMap<ChildModel, ChildDto>();
// Mapper.AssertConfigurationIsValid();
// }
// protected override void Because_of()
// {
// _dto = Mapper.Map<ParentModel, ParentDto>(_parent);
// }
// [Fact(Skip = "This test breaks the Test Runner")]
// public void Should_preserve_the_parent_child_relationship_on_the_destination()
// {
// _dto.Children[0].Parent.ID.ShouldEqual(_dto.ID);
// }
// public class ChildIdToParentDtoConverter : TypeConverter<int, ParentDto>
// {
// private readonly Dictionary<int, ParentModel> _parentModels;
// public ChildIdToParentDtoConverter(Dictionary<int, ParentModel> parentModels)
// {
// _parentModels = parentModels;
// }
// protected override ParentDto ConvertCore(int childId)
// {
// ParentModel parentModel = _parentModels[childId];
// MappingEngine mappingEngine = (MappingEngine)Mapper.Engine;
// return mappingEngine.Map<ParentModel, ParentDto>(parentModel);
// }
// }
// public class ParentIdToChildDtoListConverter : TypeConverter<int, List<ChildDto>>
// {
// private readonly IList<ChildModel> _childModels;
// public ParentIdToChildDtoListConverter(IList<ChildModel> childModels)
// {
// _childModels = childModels;
// }
// protected override List<ChildDto> ConvertCore(int childId)
// {
// List<ChildModel> childModels = _childModels.Where(x => x.Parent.ID == childId).ToList();
// MappingEngine mappingEngine = (MappingEngine)Mapper.Engine;
// return mappingEngine.Map<List<ChildModel>, List<ChildDto>>(childModels);
// }
// }
// public class ParentModel
// {
// public int ID { get; set; }
// }
// public class ChildModel
// {
// public int ID { get; set; }
// public ParentModel Parent { get; set; }
// }
// public class ParentDto
// {
// public int ID { get; set; }
// public List<ChildDto> Children { get; set; }
// }
// public class ChildDto
// {
// public int ID { get; set; }
// public ParentDto Parent { get; set; }
// }
//}
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_many_child_relationship_using_CustomMapper_with_context : AutoMapperSpecBase
{
private ParentDto _dto;
private ParentModel _parent;
protected override void Establish_context()
{
_parent = new ParentModel
{
ID = 2
};
List<ChildModel> childModels = new List<ChildModel>
{
new ChildModel
{
ID = 1,
Parent = _parent
}
};
Dictionary<int, ParentModel> parents = childModels.ToDictionary(x => x.ID, x => x.Parent);
Mapper.Initialize(cfg =>
{
cfg.CreateMap<int, ParentDto>().ConvertUsing(new ChildIdToParentDtoConverter(parents));
cfg.CreateMap<int, List<ChildDto>>().ConvertUsing(new ParentIdToChildDtoListConverter(childModels));
cfg.CreateMap<ParentModel, ParentDto>()
.ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.ID));
cfg.CreateMap<ChildModel, ChildDto>();
});
Mapper.AssertConfigurationIsValid();
}
protected override void Because_of()
{
_dto = Mapper.Map<ParentModel, ParentDto>(_parent);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Children[0].Parent.ID.ShouldEqual(_dto.ID);
}
public class ChildIdToParentDtoConverter : ITypeConverter<int, ParentDto>
{
private readonly Dictionary<int, ParentModel> _parentModels;
public ChildIdToParentDtoConverter(Dictionary<int, ParentModel> parentModels)
{
_parentModels = parentModels;
}
public ParentDto Convert(ResolutionContext resolutionContext)
{
int childId = (int) resolutionContext.SourceValue;
ParentModel parentModel = _parentModels[childId];
MappingEngine mappingEngine = (MappingEngine)Mapper.Engine;
return mappingEngine.Map<ParentModel, ParentDto>(resolutionContext, parentModel);
}
}
public class ParentIdToChildDtoListConverter : ITypeConverter<int, List<ChildDto>>
{
private readonly IList<ChildModel> _childModels;
public ParentIdToChildDtoListConverter(IList<ChildModel> childModels)
{
_childModels = childModels;
}
public List<ChildDto> Convert(ResolutionContext resolutionContext)
{
int childId = (int)resolutionContext.SourceValue;
List<ChildModel> childModels = _childModels.Where(x => x.Parent.ID == childId).ToList();
MappingEngine mappingEngine = (MappingEngine)Mapper.Engine;
return mappingEngine.Map<List<ChildModel>, List<ChildDto>>(resolutionContext, childModels);
}
}
public class ParentModel
{
public int ID { get; set; }
}
public class ChildModel
{
public int ID { get; set; }
public ParentModel Parent { get; set; }
}
public class ParentDto
{
public int ID { get; set; }
public List<ChildDto> Children { get; set; }
}
public class ChildDto
{
public int ID { get; set; }
public ParentDto Parent { get; set; }
}
}
public class When_mapping_to_a_destination_with_a_bidirectional_parent_one_to_one_child_relationship : AutoMapperSpecBase
{
private FooDto _dto;
protected override void Establish_context()
{
Mapper.CreateMap<Foo, FooDto>();
Mapper.CreateMap<Bar, BarDto>();
Mapper.AssertConfigurationIsValid();
}
protected override void Because_of()
{
var foo = new Foo
{
Bar = new Bar
{
Value = "something"
}
};
foo.Bar.Foo = foo;
_dto = Mapper.Map<Foo, FooDto>(foo);
}
[Fact]
public void Should_preserve_the_parent_child_relationship_on_the_destination()
{
_dto.Bar.Foo.ShouldBeSameAs(_dto);
}
public class Foo
{
public Bar Bar { get; set; }
}
public class Bar
{
public Foo Foo { get; set; }
public string Value { get; set; }
}
public class FooDto
{
public BarDto Bar { get; set; }
}
public class BarDto
{
public FooDto Foo { get; set; }
public string Value { get; set; }
}
}
public class When_mapping_to_a_destination_containing_two_dtos_mapped_from_the_same_source : AutoMapperSpecBase
{
private FooContainerModel _dto;
protected override void Establish_context()
{
Mapper.CreateMap<FooModel, FooScreenModel>();
Mapper.CreateMap<FooModel, FooInputModel>();
Mapper.CreateMap<FooModel, FooContainerModel>()
.ForMember(dest => dest.Input, opt => opt.MapFrom(src => src))
.ForMember(dest => dest.Screen, opt => opt.MapFrom(src => src));
Mapper.AssertConfigurationIsValid();
}
protected override void Because_of()
{
var model = new FooModel { Id = 3 };
_dto = Mapper.Map<FooModel, FooContainerModel>(model);
}
[Fact]
public void Should_not_preserve_identity_when_destinations_are_incompatible()
{
_dto.ShouldBeType<FooContainerModel>();
_dto.Input.ShouldBeType<FooInputModel>();
_dto.Screen.ShouldBeType<FooScreenModel>();
_dto.Input.Id.ShouldEqual(3);
_dto.Screen.Id.ShouldEqual("3");
}
public class FooContainerModel
{
public FooInputModel Input { get; set; }
public FooScreenModel Screen { get; set; }
}
public class FooScreenModel
{
public string Id { get; set; }
}
public class FooInputModel
{
public long Id { get; set; }
}
public class FooModel
{
public long Id { get; set; }
}
}
public class When_mapping_with_a_bidirectional_relationship_that_includes_arrays : AutoMapperSpecBase
{
private ParentDto _dtoParent;
protected override void Establish_context()
{
var parent1 = new Parent { Name = "Parent 1" };
var child1 = new Child { Name = "Child 1" };
parent1.Children.Add(child1);
child1.Parents.Add(parent1);
Mapper.CreateMap<Parent, ParentDto>();
Mapper.CreateMap<Child, ChildDto>();
_dtoParent = Mapper.Map<Parent, ParentDto>(parent1);
}
[Fact]
public void Should_map_successfully()
{
object.ReferenceEquals(_dtoParent.Children[0].Parents[0], _dtoParent).ShouldBeTrue();
}
public class Parent
{
public Guid Id { get; private set; }
public string Name { get; set; }
public List<Child> Children { get; set; }
public Parent()
{
Id = Guid.NewGuid();
Children = new List<Child>();
}
public bool Equals(Parent other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Parent)) return false;
return Equals((Parent) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class Child
{
public Guid Id { get; private set; }
public string Name { get; set; }
public List<Parent> Parents { get; set; }
public Child()
{
Id = Guid.NewGuid();
Parents = new List<Parent>();
}
public bool Equals(Child other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Child)) return false;
return Equals((Child) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class ParentDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ChildDto> Children { get; set; }
public ParentDto()
{
Children = new List<ChildDto>();
}
}
public class ChildDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ParentDto> Parents { get; set; }
public ChildDto()
{
Parents = new List<ParentDto>();
}
}
}
public class When_disabling_instance_cache_for_instances : AutoMapperSpecBase
{
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Tag> ChildTags { get; set; }
protected bool Equals(Tag other)
{
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Tag) obj);
}
public override int GetHashCode()
{
return Id;
}
}
[Fact]
public void Test()
{
var tags = new List<Tag>
{
new Tag
{
Id = 1,
Name = "Tag 1",
ChildTags = new List<Tag>
{
new Tag
{
Id = 2,
Name = "Tag 2",
ChildTags = new List<Tag>
{
new Tag {Id = 3, Name = "Tag 3"},
new Tag {Id = 4, Name = "Tag 4"}
}
}
}
},
new Tag {Id = 1, Name = "Tag 1"},
new Tag
{
Id = 3,
Name = "Tag 3",
ChildTags = new List<Tag>
{
new Tag {Id = 4, Name = "Tag 4"}
}
}
};
Mapper.CreateMap<Tag, Tag>().ForMember(dest => dest.ChildTags, opt => opt.MapFrom(src => src.ChildTags));
var result = Mapper.Map<IList<Tag>, IList<Tag>>(tags, opt => opt.DisableCache = true);
result[1].ChildTags.Count().ShouldEqual(0);
result[2].ChildTags.Count().ShouldEqual(1);
result[2].ChildTags.First().Id.ShouldEqual(4);
}
}
}
}
| |
/*
* ====================================================================
* 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 NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
namespace NPOI.XSSF.UserModel
{
/**
* @author Yegor Kozlov
*/
public class XSSFFontFormatting : IFontFormatting
{
CT_Font _font;
/*package*/
internal XSSFFontFormatting(CT_Font font)
{
_font = font;
}
/**
* Get the type of super or subscript for the font
*
* @return super or subscript option
* @see #SS_NONE
* @see #SS_SUPER
* @see #SS_SUB
*/
public FontSuperScript EscapementType
{
get
{
if (_font.sizeOfVertAlignArray() == 0) return FontSuperScript.None;
CT_VerticalAlignFontProperty prop = _font.GetVertAlignArray(0);
return (FontSuperScript)(prop.val - 1);
}
set
{
_font.SetVertAlignArray(null);
if (value != FontSuperScript.None)
{
_font.AddNewVertAlign().val = (ST_VerticalAlignRun)(value + 1);
}
}
}
/**
* @return font color index
*/
public short FontColorIndex
{
get
{
if (_font.sizeOfColorArray() == 0) return -1;
int idx = 0;
CT_Color color = _font.GetColorArray(0);
if (color.IsSetIndexed()) idx = (int)color.indexed;
return (short)idx;
}
set
{
_font.SetColorArray(null);
if (value != -1)
{
var clr=_font.AddNewColor();
clr.indexed = (uint)(value);
clr.indexedSpecified = true;
}
}
}
/**
*
* @return xssf color wrapper or null if color info is missing
*/
public XSSFColor GetXSSFColor()
{
if (_font.sizeOfColorArray() == 0) return null;
return new XSSFColor(_font.GetColorArray(0));
}
/**
* Gets the height of the font in 1/20th point units
*
* @return fontheight (in points/20); or -1 if not modified
*/
public int FontHeight
{
get
{
if (_font.sizeOfSzArray() == 0) return -1;
CT_FontSize sz = _font.GetSzArray(0);
return (short)(20 * sz.val);
}
set
{
_font.SetSzArray(null);
if (value != -1)
{
_font.AddNewSz().val = (double)value / 20;
}
}
}
/**
* Get the type of underlining for the font
*
* @return font underlining type
*
* @see #U_NONE
* @see #U_SINGLE
* @see #U_DOUBLE
* @see #U_SINGLE_ACCOUNTING
* @see #U_DOUBLE_ACCOUNTING
*/
public FontUnderlineType UnderlineType
{
get
{
if (_font.sizeOfUArray() == 0) return FontUnderlineType.None;
CT_UnderlineProperty u = _font.GetUArray(0);
switch (u.val)
{
case ST_UnderlineValues.single: return FontUnderlineType.Single;
case ST_UnderlineValues.@double: return FontUnderlineType.Double;
case ST_UnderlineValues.singleAccounting: return FontUnderlineType.SingleAccounting;
case ST_UnderlineValues.doubleAccounting: return FontUnderlineType.DoubleAccounting;
default: return FontUnderlineType.None;
}
}
set
{
_font.SetUArray(null);
if (value != FontUnderlineType.None)
{
FontUnderline fenum = FontUnderline.ValueOf(value);
ST_UnderlineValues val = (ST_UnderlineValues)(fenum.Value);
_font.AddNewU().val = val;
}
}
}
/**
* Get whether the font weight is Set to bold or not
*
* @return bold - whether the font is bold or not
*/
public bool IsBold
{
get
{
return _font.sizeOfBArray() == 1 && _font.GetBArray(0).val;
}
}
/**
* @return true if font style was Set to <i>italic</i>
*/
public bool IsItalic
{
get
{
return _font.sizeOfIArray() == 1 && _font.GetIArray(0).val;
}
}
/**
* Set font style options.
*
* @param italic - if true, Set posture style to italic, otherwise to normal
* @param bold if true, Set font weight to bold, otherwise to normal
*/
public void SetFontStyle(bool italic, bool bold)
{
_font.SetIArray(null);
_font.SetBArray(null);
if (italic) _font.AddNewI().val = true;
if (bold) _font.AddNewB().val = true;
}
/**
* Set font style options to default values (non-italic, non-bold)
*/
public void ResetFontStyle()
{
_font = new CT_Font();
}
}
}
| |
namespace QText {
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) {
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() {
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.mnu = new System.Windows.Forms.ToolStrip();
this.mnuNew = new System.Windows.Forms.ToolStripButton();
this.mnuSaveNow = new System.Windows.Forms.ToolStripButton();
this.mnuRename = new System.Windows.Forms.ToolStripButton();
this.tls_0 = new System.Windows.Forms.ToolStripSeparator();
this.mnuPrintDefault = new System.Windows.Forms.ToolStripSplitButton();
this.mnuPrint = new System.Windows.Forms.ToolStripMenuItem();
this.mnuPrintPreview = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator();
this.mnuPrintSetup = new System.Windows.Forms.ToolStripMenuItem();
this.tls_1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuCut = new System.Windows.Forms.ToolStripButton();
this.mnuCopy = new System.Windows.Forms.ToolStripButton();
this.mnuPaste = new System.Windows.Forms.ToolStripButton();
this.ToolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFont = new System.Windows.Forms.ToolStripButton();
this.mnuBold = new System.Windows.Forms.ToolStripButton();
this.mnuItalic = new System.Windows.Forms.ToolStripButton();
this.mnuUnderline = new System.Windows.Forms.ToolStripButton();
this.mnuStrikeout = new System.Windows.Forms.ToolStripButton();
this.mnuRtfSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuListBullets = new System.Windows.Forms.ToolStripButton();
this.mnuListNumbers = new System.Windows.Forms.ToolStripButton();
this.mnuRtfSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuUndo = new System.Windows.Forms.ToolStripButton();
this.mnuRedo = new System.Windows.Forms.ToolStripButton();
this.ToolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFind = new System.Windows.Forms.ToolStripSplitButton();
this.mnuFindFind = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFindFindNext = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFindGoto = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAlwaysOnTop = new System.Windows.Forms.ToolStripButton();
this.mnuApp = new System.Windows.Forms.ToolStripDropDownButton();
this.mnuAppOptions = new System.Windows.Forms.ToolStripMenuItem();
this.mnuApp0 = new System.Windows.Forms.ToolStripSeparator();
this.mnuAppFeedback = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAppUpgrade = new System.Windows.Forms.ToolStripMenuItem();
this.mnuApp1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuAppAbout = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFolder = new System.Windows.Forms.ToolStripDropDownButton();
this.tmrUpdateToolbar = new System.Windows.Forms.Timer(this.components);
this.tmrQuickSave = new System.Windows.Forms.Timer(this.components);
this.mnxText = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxTextUndo = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextRedo = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextBox0 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextCut = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextCopy = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextPaste = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextBoxCutCopyPasteAsTextSeparator = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextCutPlain = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextCopyPlain = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextPastePlain = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextSelectAll = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextFont = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextBold = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextItalic = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextUnderline = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextStrikeout = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextResetFont = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextRtfSeparator = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextSelection = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextSelectionUpper = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextSelectionLower = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextSelectionTitle = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextSelectionDrGrammar = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextSelectionSpelling = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextLines = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextLinesSortAsc = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextLinesSortDesc = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTextLinesTrim = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextInsertDateTime = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextInsertDateTimeBoth = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextInsertTime = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTextInsertDate = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTab = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxTabNew = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTab0 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTabReopen = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabSaveNow = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTab1 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTabRename = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabMoveTo = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabMoveToDummy = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabDelete = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabConvert = new System.Windows.Forms.ToolStripSeparator();
this.mnxTabZoomReset = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabConvertPlain = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabConvertRich = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabEncrypt = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabChangePassword = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabDecrypt = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTab2 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTabPrintPreview = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTabPrint = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripMenuItem14 = new System.Windows.Forms.ToolStripSeparator();
this.mnxTabOpenContainingFolder = new System.Windows.Forms.ToolStripMenuItem();
this.bwCheckForUpgrade = new System.ComponentModel.BackgroundWorker();
this.tip = new System.Windows.Forms.ToolTip(this.components);
this.tabFiles = new QText.TabFiles();
this.mnu.SuspendLayout();
this.mnxText.SuspendLayout();
this.mnxTab.SuspendLayout();
this.SuspendLayout();
//
// mnu
//
this.mnu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.mnu.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuNew,
this.mnuSaveNow,
this.mnuRename,
this.tls_0,
this.mnuPrintDefault,
this.tls_1,
this.mnuCut,
this.mnuCopy,
this.mnuPaste,
this.ToolStripSeparator1,
this.mnuFont,
this.mnuBold,
this.mnuItalic,
this.mnuUnderline,
this.mnuStrikeout,
this.mnuRtfSeparator1,
this.mnuListBullets,
this.mnuListNumbers,
this.mnuRtfSeparator2,
this.mnuUndo,
this.mnuRedo,
this.ToolStripSeparator3,
this.mnuFind,
this.mnuAlwaysOnTop,
this.mnuApp,
this.ToolStripSeparator2,
this.mnuFolder});
this.mnu.Location = new System.Drawing.Point(0, 0);
this.mnu.Name = "mnu";
this.mnu.Padding = new System.Windows.Forms.Padding(1, 0, 1, 0);
this.mnu.Size = new System.Drawing.Size(702, 27);
this.mnu.TabIndex = 1;
//
// mnuNew
//
this.mnuNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuNew.Image = global::QText.Properties.Resources.mnuNew_16;
this.mnuNew.Name = "mnuNew";
this.mnuNew.Size = new System.Drawing.Size(24, 24);
this.mnuNew.Text = "New (Ctrl+N)";
this.mnuNew.ToolTipText = "New tab (Ctrl+N)";
this.mnuNew.Click += new System.EventHandler(this.mnuNew_Click);
//
// mnuSaveNow
//
this.mnuSaveNow.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuSaveNow.Image = global::QText.Properties.Resources.mnuSave_16;
this.mnuSaveNow.Name = "mnuSaveNow";
this.mnuSaveNow.Size = new System.Drawing.Size(24, 24);
this.mnuSaveNow.Tag = "mnuSave";
this.mnuSaveNow.Text = "Save now (Ctrl+S)";
this.mnuSaveNow.ToolTipText = "Save now (Ctrl+S)";
this.mnuSaveNow.Click += new System.EventHandler(this.mnuSaveNow_Click);
//
// mnuRename
//
this.mnuRename.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuRename.Image = global::QText.Properties.Resources.mnuRename_16;
this.mnuRename.Name = "mnuRename";
this.mnuRename.Size = new System.Drawing.Size(24, 24);
this.mnuRename.Text = "Rename (F2)";
this.mnuRename.ToolTipText = "Rename tab (F2)";
this.mnuRename.Click += new System.EventHandler(this.mnuRename_Click);
//
// tls_0
//
this.tls_0.Name = "tls_0";
this.tls_0.Size = new System.Drawing.Size(6, 27);
//
// mnuPrintDefault
//
this.mnuPrintDefault.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuPrintDefault.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuPrint,
this.mnuPrintPreview,
this.toolStripMenuItem6,
this.mnuPrintSetup});
this.mnuPrintDefault.Image = global::QText.Properties.Resources.mnuPrint_16;
this.mnuPrintDefault.Name = "mnuPrintDefault";
this.mnuPrintDefault.Size = new System.Drawing.Size(39, 24);
this.mnuPrintDefault.Tag = "mnuPrint";
this.mnuPrintDefault.Text = "Print (Ctrl+P)";
this.mnuPrintDefault.ToolTipText = "Print (Ctrl+P)";
this.mnuPrintDefault.ButtonClick += new System.EventHandler(this.mnuPrint_Click);
//
// mnuPrint
//
this.mnuPrint.Image = global::QText.Properties.Resources.mnuPrint_16;
this.mnuPrint.Name = "mnuPrint";
this.mnuPrint.ShortcutKeyDisplayString = "Ctrl+P";
this.mnuPrint.Size = new System.Drawing.Size(169, 26);
this.mnuPrint.Text = "Print";
this.mnuPrint.Click += new System.EventHandler(this.mnuPrint_Click);
//
// mnuPrintPreview
//
this.mnuPrintPreview.Image = global::QText.Properties.Resources.mnuPrintPreview_16;
this.mnuPrintPreview.Name = "mnuPrintPreview";
this.mnuPrintPreview.Size = new System.Drawing.Size(169, 26);
this.mnuPrintPreview.Text = "Print Preview";
this.mnuPrintPreview.Click += new System.EventHandler(this.mnuPrintPreview_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(166, 6);
//
// mnuPrintSetup
//
this.mnuPrintSetup.Image = global::QText.Properties.Resources.mnuPrintSetup_16;
this.mnuPrintSetup.Name = "mnuPrintSetup";
this.mnuPrintSetup.Size = new System.Drawing.Size(169, 26);
this.mnuPrintSetup.Text = "Page setup";
this.mnuPrintSetup.Click += new System.EventHandler(this.mnuPrintSetup_Click);
//
// tls_1
//
this.tls_1.Name = "tls_1";
this.tls_1.Size = new System.Drawing.Size(6, 27);
//
// mnuCut
//
this.mnuCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuCut.Image = global::QText.Properties.Resources.mnuCut_16;
this.mnuCut.Name = "mnuCut";
this.mnuCut.Size = new System.Drawing.Size(24, 24);
this.mnuCut.Text = "Cut";
this.mnuCut.ToolTipText = "Cut (Ctrl+X)";
this.mnuCut.Click += new System.EventHandler(this.mnuCut_Click);
//
// mnuCopy
//
this.mnuCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuCopy.Image = global::QText.Properties.Resources.mnuCopy_16;
this.mnuCopy.Name = "mnuCopy";
this.mnuCopy.Size = new System.Drawing.Size(24, 24);
this.mnuCopy.Text = "Copy";
this.mnuCopy.ToolTipText = "Copy (Ctrl+C)";
this.mnuCopy.Click += new System.EventHandler(this.mnuCopy_Click);
//
// mnuPaste
//
this.mnuPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuPaste.Image = global::QText.Properties.Resources.mnuPaste_16;
this.mnuPaste.Name = "mnuPaste";
this.mnuPaste.Size = new System.Drawing.Size(24, 24);
this.mnuPaste.Text = "Paste";
this.mnuPaste.ToolTipText = "Paste (Ctrl+V)";
this.mnuPaste.Click += new System.EventHandler(this.mnuPaste_Click);
//
// ToolStripSeparator1
//
this.ToolStripSeparator1.Name = "ToolStripSeparator1";
this.ToolStripSeparator1.Size = new System.Drawing.Size(6, 27);
//
// mnuFont
//
this.mnuFont.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuFont.Image = global::QText.Properties.Resources.mnuFont_16;
this.mnuFont.Name = "mnuFont";
this.mnuFont.Size = new System.Drawing.Size(24, 24);
this.mnuFont.Text = "Font";
this.mnuFont.Click += new System.EventHandler(this.mnuFont_Click);
//
// mnuBold
//
this.mnuBold.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuBold.Image = global::QText.Properties.Resources.mnuBold_16;
this.mnuBold.Name = "mnuBold";
this.mnuBold.Size = new System.Drawing.Size(24, 24);
this.mnuBold.Text = "Bold (Ctrl+B)";
this.mnuBold.ToolTipText = "Bold (Ctrl+B)";
this.mnuBold.Click += new System.EventHandler(this.mnuBold_Click);
//
// mnuItalic
//
this.mnuItalic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuItalic.Image = global::QText.Properties.Resources.mnuItalic_16;
this.mnuItalic.Name = "mnuItalic";
this.mnuItalic.Size = new System.Drawing.Size(24, 24);
this.mnuItalic.Text = "Italic (Ctrl+I)";
this.mnuItalic.ToolTipText = "Italic (Ctrl+I)";
this.mnuItalic.Click += new System.EventHandler(this.mnuItalic_Click);
//
// mnuUnderline
//
this.mnuUnderline.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuUnderline.Image = global::QText.Properties.Resources.mnuUnderline_16;
this.mnuUnderline.Name = "mnuUnderline";
this.mnuUnderline.Size = new System.Drawing.Size(24, 24);
this.mnuUnderline.Text = "Underline (Ctrl+U)";
this.mnuUnderline.ToolTipText = "Underline (Ctrl+U)";
this.mnuUnderline.Click += new System.EventHandler(this.mnuUnderline_Click);
//
// mnuStrikeout
//
this.mnuStrikeout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuStrikeout.Image = global::QText.Properties.Resources.mnuStrikeout_16;
this.mnuStrikeout.Name = "mnuStrikeout";
this.mnuStrikeout.Size = new System.Drawing.Size(24, 24);
this.mnuStrikeout.Text = "Strikeout";
this.mnuStrikeout.Click += new System.EventHandler(this.mnuStrikeout_Click);
//
// mnuRtfSeparator1
//
this.mnuRtfSeparator1.Name = "mnuRtfSeparator1";
this.mnuRtfSeparator1.Size = new System.Drawing.Size(6, 27);
//
// mnuListBullets
//
this.mnuListBullets.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuListBullets.Image = global::QText.Properties.Resources.mnuListBullets_16;
this.mnuListBullets.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuListBullets.Name = "mnuListBullets";
this.mnuListBullets.Size = new System.Drawing.Size(24, 24);
this.mnuListBullets.Text = "Bullet-point list";
this.mnuListBullets.Click += new System.EventHandler(this.mnuListBullets_Click);
//
// mnuListNumbers
//
this.mnuListNumbers.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuListNumbers.Image = global::QText.Properties.Resources.mnuListNumbers_16;
this.mnuListNumbers.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuListNumbers.Name = "mnuListNumbers";
this.mnuListNumbers.Size = new System.Drawing.Size(24, 24);
this.mnuListNumbers.Text = "Numbered list.";
this.mnuListNumbers.Click += new System.EventHandler(this.mnuListNumbers_Click);
//
// mnuRtfSeparator2
//
this.mnuRtfSeparator2.Name = "mnuRtfSeparator2";
this.mnuRtfSeparator2.Size = new System.Drawing.Size(6, 27);
//
// mnuUndo
//
this.mnuUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuUndo.Image = global::QText.Properties.Resources.mnuUndo_16;
this.mnuUndo.Name = "mnuUndo";
this.mnuUndo.Size = new System.Drawing.Size(24, 24);
this.mnuUndo.Text = "Undo (Ctrl+Z)";
this.mnuUndo.ToolTipText = "Undo (Ctrl+Z)";
this.mnuUndo.Click += new System.EventHandler(this.mnuUndo_Click);
//
// mnuRedo
//
this.mnuRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuRedo.Image = global::QText.Properties.Resources.mnuRedo_16;
this.mnuRedo.Name = "mnuRedo";
this.mnuRedo.Size = new System.Drawing.Size(24, 24);
this.mnuRedo.Text = "Redo (Ctrl+Y)";
this.mnuRedo.ToolTipText = "Redo (Ctrl+Y)";
this.mnuRedo.Click += new System.EventHandler(this.mnuRedo_Click);
//
// ToolStripSeparator3
//
this.ToolStripSeparator3.Name = "ToolStripSeparator3";
this.ToolStripSeparator3.Size = new System.Drawing.Size(6, 27);
//
// mnuFind
//
this.mnuFind.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuFind.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFindFind,
this.mnuFindFindNext,
this.toolStripMenuItem5,
this.mnuFindGoto});
this.mnuFind.Image = global::QText.Properties.Resources.mnuFind_16;
this.mnuFind.Name = "mnuFind";
this.mnuFind.Size = new System.Drawing.Size(39, 24);
this.mnuFind.Text = "Find (Ctrl+F)";
this.mnuFind.ToolTipText = "Find (Ctrl+F)";
this.mnuFind.ButtonClick += new System.EventHandler(this.mnuFind_ButtonClick);
this.mnuFind.DropDownOpening += new System.EventHandler(this.mnuFind_DropDownOpening);
//
// mnuFindFind
//
this.mnuFindFind.Image = global::QText.Properties.Resources.mnuFind_16;
this.mnuFindFind.Name = "mnuFindFind";
this.mnuFindFind.ShortcutKeyDisplayString = "Ctrl+F";
this.mnuFindFind.Size = new System.Drawing.Size(169, 26);
this.mnuFindFind.Tag = "mnuFind";
this.mnuFindFind.Text = "Find";
this.mnuFindFind.Click += new System.EventHandler(this.mnuFindFind_Click);
//
// mnuFindFindNext
//
this.mnuFindFindNext.Image = global::QText.Properties.Resources.mnuFindNext_16;
this.mnuFindFindNext.Name = "mnuFindFindNext";
this.mnuFindFindNext.ShortcutKeyDisplayString = "F3";
this.mnuFindFindNext.Size = new System.Drawing.Size(169, 26);
this.mnuFindFindNext.Tag = "mnuFindNext";
this.mnuFindFindNext.Text = "Find next";
this.mnuFindFindNext.Click += new System.EventHandler(this.mnuFindFindNext_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(166, 6);
//
// mnuFindGoto
//
this.mnuFindGoto.Name = "mnuFindGoto";
this.mnuFindGoto.ShortcutKeyDisplayString = "Ctrl+G";
this.mnuFindGoto.Size = new System.Drawing.Size(169, 26);
this.mnuFindGoto.Text = "Goto";
this.mnuFindGoto.Click += new System.EventHandler(this.mnuFindGoto_Click);
//
// mnuAlwaysOnTop
//
this.mnuAlwaysOnTop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuAlwaysOnTop.Image = global::QText.Properties.Resources.mnuAlwaysOnTop_16;
this.mnuAlwaysOnTop.Name = "mnuAlwaysOnTop";
this.mnuAlwaysOnTop.Size = new System.Drawing.Size(24, 24);
this.mnuAlwaysOnTop.Text = "Always on top (Ctrl+T)";
this.mnuAlwaysOnTop.ToolTipText = "Always on top (Ctrl+T)";
this.mnuAlwaysOnTop.Click += new System.EventHandler(this.mnuAlwaysOnTop_Click);
//
// mnuApp
//
this.mnuApp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.mnuApp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuApp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuAppOptions,
this.mnuApp0,
this.mnuAppFeedback,
this.mnuAppUpgrade,
this.mnuApp1,
this.mnuAppAbout});
this.mnuApp.Image = global::QText.Properties.Resources.mnuApp_16;
this.mnuApp.Name = "mnuApp";
this.mnuApp.Size = new System.Drawing.Size(34, 24);
//
// mnuAppOptions
//
this.mnuAppOptions.Name = "mnuAppOptions";
this.mnuAppOptions.Size = new System.Drawing.Size(206, 26);
this.mnuAppOptions.Text = "&Options";
this.mnuAppOptions.Click += new System.EventHandler(this.mnuAppOptions_Click);
//
// mnuApp0
//
this.mnuApp0.Name = "mnuApp0";
this.mnuApp0.Size = new System.Drawing.Size(203, 6);
//
// mnuAppFeedback
//
this.mnuAppFeedback.Name = "mnuAppFeedback";
this.mnuAppFeedback.Size = new System.Drawing.Size(206, 26);
this.mnuAppFeedback.Text = "Send &feedback";
this.mnuAppFeedback.Click += new System.EventHandler(this.mnuAppFeedback_Click);
//
// mnuAppUpgrade
//
this.mnuAppUpgrade.Name = "mnuAppUpgrade";
this.mnuAppUpgrade.Size = new System.Drawing.Size(206, 26);
this.mnuAppUpgrade.Text = "Check for &upgrade";
this.mnuAppUpgrade.Click += new System.EventHandler(this.mnuAppUpgrade_Click);
//
// mnuApp1
//
this.mnuApp1.Name = "mnuApp1";
this.mnuApp1.Size = new System.Drawing.Size(203, 6);
//
// mnuAppAbout
//
this.mnuAppAbout.Name = "mnuAppAbout";
this.mnuAppAbout.Size = new System.Drawing.Size(206, 26);
this.mnuAppAbout.Text = "&About";
this.mnuAppAbout.Click += new System.EventHandler(this.mnuAppAbout_Click);
//
// ToolStripSeparator2
//
this.ToolStripSeparator2.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.ToolStripSeparator2.Name = "ToolStripSeparator2";
this.ToolStripSeparator2.Size = new System.Drawing.Size(6, 27);
//
// mnuFolder
//
this.mnuFolder.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.mnuFolder.Image = global::QText.Properties.Resources.mnuFolder_16;
this.mnuFolder.Name = "mnuFolder";
this.mnuFolder.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.mnuFolder.Size = new System.Drawing.Size(92, 24);
this.mnuFolder.Text = "Default";
this.mnuFolder.ToolTipText = "Select folder";
this.mnuFolder.DropDownOpening += new System.EventHandler(this.mnuFolder_DropDownOpening);
//
// tmrUpdateToolbar
//
this.tmrUpdateToolbar.Tick += new System.EventHandler(this.tmrUpdateToolbar_Tick);
//
// tmrQuickSave
//
this.tmrQuickSave.Tick += new System.EventHandler(this.tmrQuickSave_Tick);
//
// mnxText
//
this.mnxText.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxText.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTextUndo,
this.mnxTextRedo,
this.mnxTextBox0,
this.mnxTextCut,
this.mnxTextCopy,
this.mnxTextPaste,
this.mnxTextBoxCutCopyPasteAsTextSeparator,
this.mnxTextCutPlain,
this.mnxTextCopyPlain,
this.mnxTextPastePlain,
this.toolStripMenuItem2,
this.mnxTextSelectAll,
this.ToolStripMenuItem4,
this.mnxTextFont,
this.mnxTextBold,
this.mnxTextItalic,
this.mnxTextUnderline,
this.mnxTextStrikeout,
this.mnxTextResetFont,
this.mnxTextRtfSeparator,
this.mnxTextSelection,
this.mnxTextLines,
this.mnxTextInsertDateTime});
this.mnxText.Name = "mnxTextBox";
this.mnxText.Size = new System.Drawing.Size(292, 502);
this.mnxText.Opening += new System.ComponentModel.CancelEventHandler(this.mnxText_Opening);
//
// mnxTextUndo
//
this.mnxTextUndo.Image = global::QText.Properties.Resources.mnuUndo_16;
this.mnxTextUndo.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextUndo.Name = "mnxTextUndo";
this.mnxTextUndo.ShortcutKeyDisplayString = "Ctrl+Z";
this.mnxTextUndo.Size = new System.Drawing.Size(291, 26);
this.mnxTextUndo.Tag = "mnuUndo";
this.mnxTextUndo.Text = "&Undo";
this.mnxTextUndo.Click += new System.EventHandler(this.mnuUndo_Click);
//
// mnxTextRedo
//
this.mnxTextRedo.Image = global::QText.Properties.Resources.mnuRedo_16;
this.mnxTextRedo.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextRedo.Name = "mnxTextRedo";
this.mnxTextRedo.ShortcutKeyDisplayString = "Ctrl+Y";
this.mnxTextRedo.Size = new System.Drawing.Size(291, 26);
this.mnxTextRedo.Tag = "mnuRedo";
this.mnxTextRedo.Text = "&Redo";
this.mnxTextRedo.Click += new System.EventHandler(this.mnuRedo_Click);
//
// mnxTextBox0
//
this.mnxTextBox0.Name = "mnxTextBox0";
this.mnxTextBox0.Size = new System.Drawing.Size(288, 6);
//
// mnxTextCut
//
this.mnxTextCut.Image = global::QText.Properties.Resources.mnuCut_16;
this.mnxTextCut.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextCut.Name = "mnxTextCut";
this.mnxTextCut.ShortcutKeyDisplayString = "Ctrl+X";
this.mnxTextCut.Size = new System.Drawing.Size(291, 26);
this.mnxTextCut.Tag = "mnuCut";
this.mnxTextCut.Text = "Cu&t";
this.mnxTextCut.Click += new System.EventHandler(this.mnuCut_Click);
//
// mnxTextCopy
//
this.mnxTextCopy.Image = global::QText.Properties.Resources.mnuCopy_16;
this.mnxTextCopy.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextCopy.Name = "mnxTextCopy";
this.mnxTextCopy.ShortcutKeyDisplayString = "Ctrl+C";
this.mnxTextCopy.Size = new System.Drawing.Size(291, 26);
this.mnxTextCopy.Tag = "mnuCopy";
this.mnxTextCopy.Text = "&Copy";
this.mnxTextCopy.Click += new System.EventHandler(this.mnuCopy_Click);
//
// mnxTextPaste
//
this.mnxTextPaste.Image = global::QText.Properties.Resources.mnuPaste_16;
this.mnxTextPaste.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextPaste.Name = "mnxTextPaste";
this.mnxTextPaste.ShortcutKeyDisplayString = "Ctrl+V";
this.mnxTextPaste.Size = new System.Drawing.Size(291, 26);
this.mnxTextPaste.Tag = "mnuPaste";
this.mnxTextPaste.Text = "&Paste";
this.mnxTextPaste.Click += new System.EventHandler(this.mnuPaste_Click);
//
// mnxTextBoxCutCopyPasteAsTextSeparator
//
this.mnxTextBoxCutCopyPasteAsTextSeparator.Name = "mnxTextBoxCutCopyPasteAsTextSeparator";
this.mnxTextBoxCutCopyPasteAsTextSeparator.Size = new System.Drawing.Size(288, 6);
//
// mnxTextCutPlain
//
this.mnxTextCutPlain.Image = global::QText.Properties.Resources.mnuCut_16;
this.mnxTextCutPlain.Name = "mnxTextCutPlain";
this.mnxTextCutPlain.ShortcutKeyDisplayString = "Ctrl+Shift+X";
this.mnxTextCutPlain.Size = new System.Drawing.Size(291, 26);
this.mnxTextCutPlain.Tag = "mnuCut";
this.mnxTextCutPlain.Text = "Cut as plain text";
this.mnxTextCutPlain.Click += new System.EventHandler(this.mnxTextCutPlain_Click);
//
// mnxTextCopyPlain
//
this.mnxTextCopyPlain.Image = global::QText.Properties.Resources.mnuCopy_16;
this.mnxTextCopyPlain.Name = "mnxTextCopyPlain";
this.mnxTextCopyPlain.ShortcutKeyDisplayString = "Ctrl+Shift+C";
this.mnxTextCopyPlain.Size = new System.Drawing.Size(291, 26);
this.mnxTextCopyPlain.Tag = "mnuCopy";
this.mnxTextCopyPlain.Text = "Copy as plain text";
this.mnxTextCopyPlain.Click += new System.EventHandler(this.mnxTextCopyPlain_Click);
//
// mnxTextPastePlain
//
this.mnxTextPastePlain.Image = global::QText.Properties.Resources.mnuPaste_16;
this.mnxTextPastePlain.Name = "mnxTextPastePlain";
this.mnxTextPastePlain.ShortcutKeyDisplayString = "Ctrl+Shift+V";
this.mnxTextPastePlain.Size = new System.Drawing.Size(291, 26);
this.mnxTextPastePlain.Tag = "mnuPaste";
this.mnxTextPastePlain.Text = "Paste as plain text";
this.mnxTextPastePlain.Click += new System.EventHandler(this.mnxTextPastePlain_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(288, 6);
//
// mnxTextSelectAll
//
this.mnxTextSelectAll.Name = "mnxTextSelectAll";
this.mnxTextSelectAll.ShortcutKeyDisplayString = "Ctrl+A";
this.mnxTextSelectAll.Size = new System.Drawing.Size(291, 26);
this.mnxTextSelectAll.Text = "Select &all";
this.mnxTextSelectAll.Click += new System.EventHandler(this.mnxTextSelectAll_Click);
//
// ToolStripMenuItem4
//
this.ToolStripMenuItem4.Name = "ToolStripMenuItem4";
this.ToolStripMenuItem4.Size = new System.Drawing.Size(288, 6);
//
// mnxTextFont
//
this.mnxTextFont.Image = global::QText.Properties.Resources.mnuFont_16;
this.mnxTextFont.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextFont.Name = "mnxTextFont";
this.mnxTextFont.Size = new System.Drawing.Size(291, 26);
this.mnxTextFont.Tag = "mnuFont";
this.mnxTextFont.Text = "&Font";
this.mnxTextFont.Click += new System.EventHandler(this.mnuFont_Click);
//
// mnxTextBold
//
this.mnxTextBold.Image = global::QText.Properties.Resources.mnuBold_16;
this.mnxTextBold.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextBold.Name = "mnxTextBold";
this.mnxTextBold.ShortcutKeyDisplayString = "Ctrl+B";
this.mnxTextBold.Size = new System.Drawing.Size(291, 26);
this.mnxTextBold.Tag = "mnuBold";
this.mnxTextBold.Text = "&Bold";
this.mnxTextBold.Click += new System.EventHandler(this.mnuBold_Click);
//
// mnxTextItalic
//
this.mnxTextItalic.Image = global::QText.Properties.Resources.mnuItalic_16;
this.mnxTextItalic.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTextItalic.Name = "mnxTextItalic";
this.mnxTextItalic.ShortcutKeyDisplayString = "Ctrl+I";
this.mnxTextItalic.Size = new System.Drawing.Size(291, 26);
this.mnxTextItalic.Tag = "mnuItalic";
this.mnxTextItalic.Text = "&Italic";
this.mnxTextItalic.Click += new System.EventHandler(this.mnuItalic_Click);
//
// mnxTextUnderline
//
this.mnxTextUnderline.Image = global::QText.Properties.Resources.mnuUnderline_16;
this.mnxTextUnderline.Name = "mnxTextUnderline";
this.mnxTextUnderline.ShortcutKeyDisplayString = "Ctrl+U";
this.mnxTextUnderline.Size = new System.Drawing.Size(291, 26);
this.mnxTextUnderline.Tag = "mnuUnderline";
this.mnxTextUnderline.Text = "&Underline";
this.mnxTextUnderline.Click += new System.EventHandler(this.mnuUnderline_Click);
//
// mnxTextStrikeout
//
this.mnxTextStrikeout.Image = global::QText.Properties.Resources.mnuStrikeout_16;
this.mnxTextStrikeout.Name = "mnxTextStrikeout";
this.mnxTextStrikeout.Size = new System.Drawing.Size(291, 26);
this.mnxTextStrikeout.Tag = "mnuStrikeout";
this.mnxTextStrikeout.Text = "S&trikeout";
this.mnxTextStrikeout.Click += new System.EventHandler(this.mnuStrikeout_Click);
//
// mnxTextResetFont
//
this.mnxTextResetFont.Name = "mnxTextResetFont";
this.mnxTextResetFont.Size = new System.Drawing.Size(291, 26);
this.mnxTextResetFont.Text = "Reset font to default";
this.mnxTextResetFont.Click += new System.EventHandler(this.mnuResetFont_Click);
//
// mnxTextRtfSeparator
//
this.mnxTextRtfSeparator.Name = "mnxTextRtfSeparator";
this.mnxTextRtfSeparator.Size = new System.Drawing.Size(288, 6);
//
// mnxTextSelection
//
this.mnxTextSelection.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTextSelectionUpper,
this.mnxTextSelectionLower,
this.mnxTextSelectionTitle,
this.mnxTextSelectionDrGrammar,
this.toolStripMenuItem1,
this.mnxTextSelectionSpelling});
this.mnxTextSelection.Name = "mnxTextSelection";
this.mnxTextSelection.Size = new System.Drawing.Size(291, 26);
this.mnxTextSelection.Text = "&Selection";
//
// mnxTextSelectionUpper
//
this.mnxTextSelectionUpper.Name = "mnxTextSelectionUpper";
this.mnxTextSelectionUpper.Size = new System.Drawing.Size(350, 26);
this.mnxTextSelectionUpper.Text = "Convert to &upper case";
this.mnxTextSelectionUpper.Click += new System.EventHandler(this.mnxTextSelectionUpper_Click);
//
// mnxTextSelectionLower
//
this.mnxTextSelectionLower.Name = "mnxTextSelectionLower";
this.mnxTextSelectionLower.Size = new System.Drawing.Size(350, 26);
this.mnxTextSelectionLower.Text = "Convert to &lower case";
this.mnxTextSelectionLower.Click += new System.EventHandler(this.mnxTextSelectionLower_Click);
//
// mnxTextSelectionTitle
//
this.mnxTextSelectionTitle.Name = "mnxTextSelectionTitle";
this.mnxTextSelectionTitle.Size = new System.Drawing.Size(350, 26);
this.mnxTextSelectionTitle.Text = "Convert to &title case";
this.mnxTextSelectionTitle.Click += new System.EventHandler(this.mnxTextSelectionTitle_Click);
//
// mnxTextSelectionDrGrammar
//
this.mnxTextSelectionDrGrammar.Name = "mnxTextSelectionDrGrammar";
this.mnxTextSelectionDrGrammar.Size = new System.Drawing.Size(350, 26);
this.mnxTextSelectionDrGrammar.Text = "Convert to title case (Dr. &Grammar rules)";
this.mnxTextSelectionDrGrammar.Click += new System.EventHandler(this.mnxTextSelectionDrGrammar_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(347, 6);
//
// mnxTextSelectionSpelling
//
this.mnxTextSelectionSpelling.Name = "mnxTextSelectionSpelling";
this.mnxTextSelectionSpelling.ShortcutKeyDisplayString = "Shift+F1";
this.mnxTextSelectionSpelling.Size = new System.Drawing.Size(350, 26);
this.mnxTextSelectionSpelling.Text = "Phonetic spelling";
this.mnxTextSelectionSpelling.Click += new System.EventHandler(this.mnxTextSelectionSpelling_Click);
//
// mnxTextLines
//
this.mnxTextLines.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTextLinesSortAsc,
this.mnxTextLinesSortDesc,
this.toolStripMenuItem3,
this.mnxTextLinesTrim});
this.mnxTextLines.Name = "mnxTextLines";
this.mnxTextLines.Size = new System.Drawing.Size(291, 26);
this.mnxTextLines.Text = "&Lines";
//
// mnxTextLinesSortAsc
//
this.mnxTextLinesSortAsc.Name = "mnxTextLinesSortAsc";
this.mnxTextLinesSortAsc.Size = new System.Drawing.Size(191, 26);
this.mnxTextLinesSortAsc.Text = "Sort &ascending";
this.mnxTextLinesSortAsc.Click += new System.EventHandler(this.mnxTextLinesSortAsc_Click);
//
// mnxTextLinesSortDesc
//
this.mnxTextLinesSortDesc.Name = "mnxTextLinesSortDesc";
this.mnxTextLinesSortDesc.Size = new System.Drawing.Size(191, 26);
this.mnxTextLinesSortDesc.Text = "Sort &descending";
this.mnxTextLinesSortDesc.Click += new System.EventHandler(this.mnxTextLinesSortDesc_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(188, 6);
//
// mnxTextLinesTrim
//
this.mnxTextLinesTrim.Name = "mnxTextLinesTrim";
this.mnxTextLinesTrim.Size = new System.Drawing.Size(191, 26);
this.mnxTextLinesTrim.Text = "&Trim";
this.mnxTextLinesTrim.Click += new System.EventHandler(this.mnxTextLinesTrim_Click);
//
// mnxTextInsertDateTime
//
this.mnxTextInsertDateTime.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTextInsertDateTimeBoth,
this.mnxTextInsertTime,
this.mnxTextInsertDate});
this.mnxTextInsertDateTime.Name = "mnxTextInsertDateTime";
this.mnxTextInsertDateTime.Size = new System.Drawing.Size(291, 26);
this.mnxTextInsertDateTime.Text = "Insert time/&date";
//
// mnxTextInsertDateTimeBoth
//
this.mnxTextInsertDateTimeBoth.Name = "mnxTextInsertDateTimeBoth";
this.mnxTextInsertDateTimeBoth.ShortcutKeyDisplayString = "F5";
this.mnxTextInsertDateTimeBoth.Size = new System.Drawing.Size(162, 26);
this.mnxTextInsertDateTimeBoth.Text = "&Both";
this.mnxTextInsertDateTimeBoth.Click += new System.EventHandler(this.mnxTextInsertDateTimeBoth_Click);
//
// mnxTextInsertTime
//
this.mnxTextInsertTime.Name = "mnxTextInsertTime";
this.mnxTextInsertTime.ShortcutKeyDisplayString = "Ctrl+:";
this.mnxTextInsertTime.Size = new System.Drawing.Size(162, 26);
this.mnxTextInsertTime.Text = "&Time";
this.mnxTextInsertTime.Click += new System.EventHandler(this.mnxTextInsertTime_Click);
//
// mnxTextInsertDate
//
this.mnxTextInsertDate.Name = "mnxTextInsertDate";
this.mnxTextInsertDate.ShortcutKeyDisplayString = "Ctrl+;";
this.mnxTextInsertDate.Size = new System.Drawing.Size(162, 26);
this.mnxTextInsertDate.Text = "&Date";
this.mnxTextInsertDate.Click += new System.EventHandler(this.mnxTextInsertDate_Click);
//
// mnxTab
//
this.mnxTab.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxTab.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTabNew,
this.mnxTab0,
this.mnxTabReopen,
this.mnxTabSaveNow,
this.mnxTab1,
this.mnxTabRename,
this.mnxTabMoveTo,
this.mnxTabDelete,
this.mnxTabConvert,
this.mnxTabZoomReset,
this.mnxTabConvertPlain,
this.mnxTabConvertRich,
this.mnxTabEncrypt,
this.mnxTabChangePassword,
this.mnxTabDecrypt,
this.mnxTab2,
this.mnxTabPrintPreview,
this.mnxTabPrint,
this.ToolStripMenuItem14,
this.mnxTabOpenContainingFolder});
this.mnxTab.Name = "mnxTab";
this.mnxTab.Size = new System.Drawing.Size(237, 424);
this.mnxTab.Closed += new System.Windows.Forms.ToolStripDropDownClosedEventHandler(this.mnxTab_Closed);
this.mnxTab.Opening += new System.ComponentModel.CancelEventHandler(this.mnxTab_Opening);
//
// mnxTabNew
//
this.mnxTabNew.Image = global::QText.Properties.Resources.mnuNew_16;
this.mnxTabNew.Name = "mnxTabNew";
this.mnxTabNew.ShortcutKeyDisplayString = "Ctrl+N";
this.mnxTabNew.Size = new System.Drawing.Size(236, 26);
this.mnxTabNew.Tag = "mnuNew";
this.mnxTabNew.Text = "&New";
this.mnxTabNew.Click += new System.EventHandler(this.mnuNew_Click);
//
// mnxTab0
//
this.mnxTab0.Name = "mnxTab0";
this.mnxTab0.Size = new System.Drawing.Size(233, 6);
//
// mnxTabReopen
//
this.mnxTabReopen.Name = "mnxTabReopen";
this.mnxTabReopen.ShortcutKeyDisplayString = "Ctrl+R";
this.mnxTabReopen.Size = new System.Drawing.Size(236, 26);
this.mnxTabReopen.Text = "Re&open";
this.mnxTabReopen.Click += new System.EventHandler(this.mnxTabReopen_Click);
//
// mnxTabSaveNow
//
this.mnxTabSaveNow.Image = global::QText.Properties.Resources.mnuSave_16;
this.mnxTabSaveNow.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTabSaveNow.Name = "mnxTabSaveNow";
this.mnxTabSaveNow.ShortcutKeyDisplayString = "Ctrl+S";
this.mnxTabSaveNow.Size = new System.Drawing.Size(236, 26);
this.mnxTabSaveNow.Tag = "mnuSave";
this.mnxTabSaveNow.Text = "&Save";
this.mnxTabSaveNow.Click += new System.EventHandler(this.mnuSaveNow_Click);
//
// mnxTab1
//
this.mnxTab1.Name = "mnxTab1";
this.mnxTab1.Size = new System.Drawing.Size(233, 6);
//
// mnxTabRename
//
this.mnxTabRename.Image = global::QText.Properties.Resources.mnuRename_16;
this.mnxTabRename.Name = "mnxTabRename";
this.mnxTabRename.ShortcutKeyDisplayString = "F2";
this.mnxTabRename.Size = new System.Drawing.Size(236, 26);
this.mnxTabRename.Tag = "mnuRename";
this.mnxTabRename.Text = "&Rename";
this.mnxTabRename.Click += new System.EventHandler(this.mnuRename_Click);
//
// mnxTabMoveTo
//
this.mnxTabMoveTo.AccessibleDescription = "";
this.mnxTabMoveTo.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTabMoveToDummy});
this.mnxTabMoveTo.Name = "mnxTabMoveTo";
this.mnxTabMoveTo.Size = new System.Drawing.Size(236, 26);
this.mnxTabMoveTo.Text = "Move to";
this.mnxTabMoveTo.DropDownOpening += new System.EventHandler(this.mnxTabMoveTo_DropDownOpening);
//
// mnxTabMoveToDummy
//
this.mnxTabMoveToDummy.Name = "mnxTabMoveToDummy";
this.mnxTabMoveToDummy.Size = new System.Drawing.Size(134, 26);
this.mnxTabMoveToDummy.Text = "dummy";
//
// mnxTabDelete
//
this.mnxTabDelete.Image = global::QText.Properties.Resources.mnuDelete_16;
this.mnxTabDelete.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTabDelete.Name = "mnxTabDelete";
this.mnxTabDelete.Size = new System.Drawing.Size(236, 26);
this.mnxTabDelete.Tag = "mnuDelete";
this.mnxTabDelete.Text = "&Delete";
this.mnxTabDelete.Click += new System.EventHandler(this.mnxTabDelete_Click);
//
// mnxTabConvert
//
this.mnxTabConvert.Name = "mnxTabConvert";
this.mnxTabConvert.Size = new System.Drawing.Size(233, 6);
//
// mnxTabZoomReset
//
this.mnxTabZoomReset.Name = "mnxTabZoomReset";
this.mnxTabZoomReset.ShortcutKeyDisplayString = "Ctrl+0";
this.mnxTabZoomReset.Size = new System.Drawing.Size(236, 26);
this.mnxTabZoomReset.Text = "Reset zoom";
this.mnxTabZoomReset.Click += new System.EventHandler(this.mnxTabZoomReset_Click);
//
// mnxTabConvertPlain
//
this.mnxTabConvertPlain.Name = "mnxTabConvertPlain";
this.mnxTabConvertPlain.Size = new System.Drawing.Size(236, 26);
this.mnxTabConvertPlain.Text = "Convert to plain text";
this.mnxTabConvertPlain.Click += new System.EventHandler(this.mnxTabConvertPlain_Click);
//
// mnxTabConvertRich
//
this.mnxTabConvertRich.Name = "mnxTabConvertRich";
this.mnxTabConvertRich.Size = new System.Drawing.Size(236, 26);
this.mnxTabConvertRich.Text = "Convert to rich text";
this.mnxTabConvertRich.Click += new System.EventHandler(this.mnxTabConvertRich_Click);
//
// mnxTabEncrypt
//
this.mnxTabEncrypt.Image = global::QText.Properties.Resources.mnuEncrypt_16;
this.mnxTabEncrypt.Name = "mnxTabEncrypt";
this.mnxTabEncrypt.Size = new System.Drawing.Size(236, 26);
this.mnxTabEncrypt.Tag = "mnuEncrypt";
this.mnxTabEncrypt.Text = "Encrypt";
this.mnxTabEncrypt.Click += new System.EventHandler(this.mnxTabEncrypt_Click);
//
// mnxTabChangePassword
//
this.mnxTabChangePassword.Image = global::QText.Properties.Resources.mnuPassword_16;
this.mnxTabChangePassword.Name = "mnxTabChangePassword";
this.mnxTabChangePassword.Size = new System.Drawing.Size(236, 26);
this.mnxTabChangePassword.Tag = "mnuPassword";
this.mnxTabChangePassword.Text = "Change password";
this.mnxTabChangePassword.Click += new System.EventHandler(this.mnxTabChangePassword_Click);
//
// mnxTabDecrypt
//
this.mnxTabDecrypt.Image = global::QText.Properties.Resources.mnuDecrypt_16;
this.mnxTabDecrypt.Name = "mnxTabDecrypt";
this.mnxTabDecrypt.Size = new System.Drawing.Size(236, 26);
this.mnxTabDecrypt.Tag = "mnuDecrypt";
this.mnxTabDecrypt.Text = "Decrypt";
this.mnxTabDecrypt.Click += new System.EventHandler(this.mnxTabDecrypt_Click);
//
// mnxTab2
//
this.mnxTab2.Name = "mnxTab2";
this.mnxTab2.Size = new System.Drawing.Size(233, 6);
//
// mnxTabPrintPreview
//
this.mnxTabPrintPreview.Image = global::QText.Properties.Resources.mnuPrintPreview_16;
this.mnxTabPrintPreview.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTabPrintPreview.Name = "mnxTabPrintPreview";
this.mnxTabPrintPreview.Size = new System.Drawing.Size(236, 26);
this.mnxTabPrintPreview.Tag = "mnuPrintPreview";
this.mnxTabPrintPreview.Text = "Prin&t preview";
this.mnxTabPrintPreview.Click += new System.EventHandler(this.mnuPrintPreview_Click);
//
// mnxTabPrint
//
this.mnxTabPrint.Image = global::QText.Properties.Resources.mnuPrint_16;
this.mnxTabPrint.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnxTabPrint.Name = "mnxTabPrint";
this.mnxTabPrint.ShortcutKeyDisplayString = "Ctrl+P";
this.mnxTabPrint.Size = new System.Drawing.Size(236, 26);
this.mnxTabPrint.Tag = "mnuPrint";
this.mnxTabPrint.Text = "&Print";
this.mnxTabPrint.Click += new System.EventHandler(this.mnuPrint_Click);
//
// ToolStripMenuItem14
//
this.ToolStripMenuItem14.Name = "ToolStripMenuItem14";
this.ToolStripMenuItem14.Size = new System.Drawing.Size(233, 6);
//
// mnxTabOpenContainingFolder
//
this.mnxTabOpenContainingFolder.Name = "mnxTabOpenContainingFolder";
this.mnxTabOpenContainingFolder.Size = new System.Drawing.Size(236, 26);
this.mnxTabOpenContainingFolder.Text = "Open containing folder";
this.mnxTabOpenContainingFolder.Click += new System.EventHandler(this.mnxTabOpenContainingFolder_Click);
//
// bwCheckForUpgrade
//
this.bwCheckForUpgrade.WorkerSupportsCancellation = true;
this.bwCheckForUpgrade.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwCheckForUpgrade_DoWork);
this.bwCheckForUpgrade.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwCheckForUpgrade_RunWorkerCompleted);
//
// tabFiles
//
this.tabFiles.ContextMenuStrip = this.mnxTab;
this.tabFiles.Cursor = System.Windows.Forms.Cursors.Default;
this.tabFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabFiles.Location = new System.Drawing.Point(0, 27);
this.tabFiles.Margin = new System.Windows.Forms.Padding(0);
this.tabFiles.Name = "tabFiles";
this.tabFiles.SelectedIndex = 0;
this.tabFiles.Size = new System.Drawing.Size(702, 326);
this.tabFiles.TabContextMenuStrip = this.mnxText;
this.tabFiles.TabIndex = 0;
this.tabFiles.SelectedIndexChanged += new System.EventHandler(this.tabFiles_SelectedIndexChanged);
this.tabFiles.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tabFiles_MouseDown);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(702, 353);
this.Controls.Add(this.tabFiles);
this.Controls.Add(this.mnu);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MinimumSize = new System.Drawing.Size(320, 200);
this.Name = "MainForm";
this.Text = "QText";
this.Activated += new System.EventHandler(this.Form_Activated);
this.Deactivate += new System.EventHandler(this.Form_Deactivate);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form_FormClosed);
this.Load += new System.EventHandler(this.Form_Load);
this.Shown += new System.EventHandler(this.Form_Shown);
this.VisibleChanged += new System.EventHandler(this.Form_VisibleChanged);
this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Form_MouseDoubleClick);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form_MouseDown);
this.Move += new System.EventHandler(this.Form_Move);
this.Resize += new System.EventHandler(this.Form_Resize);
this.mnu.ResumeLayout(false);
this.mnu.PerformLayout();
this.mnxText.ResumeLayout(false);
this.mnxTab.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.ToolStrip mnu;
internal System.Windows.Forms.ToolStripButton mnuNew;
internal System.Windows.Forms.ToolStripButton mnuSaveNow;
internal System.Windows.Forms.ToolStripButton mnuRename;
internal System.Windows.Forms.ToolStripSeparator tls_0;
internal System.Windows.Forms.ToolStripSeparator tls_1;
internal System.Windows.Forms.ToolStripButton mnuCut;
internal System.Windows.Forms.ToolStripButton mnuCopy;
internal System.Windows.Forms.ToolStripButton mnuPaste;
internal System.Windows.Forms.ToolStripSeparator ToolStripSeparator1;
internal System.Windows.Forms.ToolStripButton mnuFont;
internal System.Windows.Forms.ToolStripButton mnuBold;
internal System.Windows.Forms.ToolStripButton mnuItalic;
internal System.Windows.Forms.ToolStripButton mnuUnderline;
internal System.Windows.Forms.ToolStripButton mnuStrikeout;
internal System.Windows.Forms.ToolStripSeparator mnuRtfSeparator2;
internal System.Windows.Forms.ToolStripButton mnuUndo;
internal System.Windows.Forms.ToolStripButton mnuRedo;
internal System.Windows.Forms.ToolStripSeparator ToolStripSeparator3;
internal System.Windows.Forms.ToolStripButton mnuAlwaysOnTop;
internal System.Windows.Forms.Timer tmrUpdateToolbar;
internal System.Windows.Forms.Timer tmrQuickSave;
internal System.Windows.Forms.ContextMenuStrip mnxText;
internal System.Windows.Forms.ToolStripMenuItem mnxTextUndo;
internal System.Windows.Forms.ToolStripMenuItem mnxTextRedo;
internal System.Windows.Forms.ToolStripSeparator mnxTextBox0;
internal System.Windows.Forms.ToolStripMenuItem mnxTextCut;
internal System.Windows.Forms.ToolStripMenuItem mnxTextCopy;
internal System.Windows.Forms.ToolStripMenuItem mnxTextPaste;
internal System.Windows.Forms.ToolStripMenuItem mnxTextCutPlain;
internal System.Windows.Forms.ToolStripMenuItem mnxTextCopyPlain;
internal System.Windows.Forms.ToolStripMenuItem mnxTextPastePlain;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelectAll;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem4;
internal System.Windows.Forms.ToolStripMenuItem mnxTextFont;
internal System.Windows.Forms.ToolStripMenuItem mnxTextBold;
internal System.Windows.Forms.ToolStripMenuItem mnxTextItalic;
internal System.Windows.Forms.ToolStripMenuItem mnxTextUnderline;
internal System.Windows.Forms.ToolStripMenuItem mnxTextStrikeout;
internal System.Windows.Forms.ToolStripSeparator mnxTextRtfSeparator;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelection;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelectionUpper;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelectionLower;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelectionTitle;
internal System.Windows.Forms.ToolStripMenuItem mnxTextSelectionDrGrammar;
internal TabFiles tabFiles;
internal System.Windows.Forms.ToolStripDropDownButton mnuApp;
private System.Windows.Forms.ToolStripMenuItem mnuAppFeedback;
private System.Windows.Forms.ToolStripMenuItem mnuAppUpgrade;
private System.Windows.Forms.ToolStripSeparator mnuApp1;
private System.Windows.Forms.ToolStripMenuItem mnuAppAbout;
private System.Windows.Forms.ToolStripDropDownButton mnuFolder;
private System.Windows.Forms.ToolStripMenuItem mnxTextLines;
private System.Windows.Forms.ToolStripMenuItem mnxTextLinesSortAsc;
private System.Windows.Forms.ToolStripMenuItem mnxTextLinesSortDesc;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem mnxTextSelectionSpelling;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem mnxTextLinesTrim;
internal System.Windows.Forms.ToolStripSplitButton mnuFind;
private System.Windows.Forms.ToolStripMenuItem mnuFindFind;
private System.Windows.Forms.ToolStripMenuItem mnuFindGoto;
private System.Windows.Forms.ToolStripMenuItem mnuFindFindNext;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
internal System.Windows.Forms.ToolStripSplitButton mnuPrintDefault;
private System.Windows.Forms.ToolStripMenuItem mnuPrint;
private System.Windows.Forms.ToolStripMenuItem mnuPrintPreview;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem mnuPrintSetup;
internal System.Windows.Forms.ToolStripSeparator mnxTextBoxCutCopyPasteAsTextSeparator;
internal System.Windows.Forms.ContextMenuStrip mnxTab;
internal System.Windows.Forms.ToolStripMenuItem mnxTabNew;
internal System.Windows.Forms.ToolStripSeparator mnxTab0;
internal System.Windows.Forms.ToolStripMenuItem mnxTabReopen;
internal System.Windows.Forms.ToolStripMenuItem mnxTabSaveNow;
internal System.Windows.Forms.ToolStripSeparator mnxTab1;
internal System.Windows.Forms.ToolStripMenuItem mnxTabRename;
private System.Windows.Forms.ToolStripMenuItem mnxTabMoveTo;
private System.Windows.Forms.ToolStripMenuItem mnxTabMoveToDummy;
internal System.Windows.Forms.ToolStripMenuItem mnxTabDelete;
private System.Windows.Forms.ToolStripSeparator mnxTabConvert;
internal System.Windows.Forms.ToolStripMenuItem mnxTabConvertPlain;
internal System.Windows.Forms.ToolStripMenuItem mnxTabConvertRich;
private System.Windows.Forms.ToolStripMenuItem mnxTabZoomReset;
private System.Windows.Forms.ToolStripMenuItem mnxTabEncrypt;
private System.Windows.Forms.ToolStripMenuItem mnxTabChangePassword;
private System.Windows.Forms.ToolStripMenuItem mnxTabDecrypt;
internal System.Windows.Forms.ToolStripSeparator mnxTab2;
internal System.Windows.Forms.ToolStripMenuItem mnxTabPrintPreview;
internal System.Windows.Forms.ToolStripMenuItem mnxTabPrint;
internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem14;
internal System.Windows.Forms.ToolStripMenuItem mnxTabOpenContainingFolder;
private System.Windows.Forms.ToolStripMenuItem mnuAppOptions;
private System.Windows.Forms.ToolStripSeparator mnuApp0;
internal System.Windows.Forms.ToolStripSeparator ToolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem mnxTextResetFont;
private System.ComponentModel.BackgroundWorker bwCheckForUpgrade;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem mnxTextInsertDateTime;
private System.Windows.Forms.ToolStripMenuItem mnxTextInsertDateTimeBoth;
private System.Windows.Forms.ToolStripMenuItem mnxTextInsertTime;
private System.Windows.Forms.ToolStripMenuItem mnxTextInsertDate;
private System.Windows.Forms.ToolTip tip;
private System.Windows.Forms.ToolStripButton mnuListBullets;
private System.Windows.Forms.ToolStripButton mnuListNumbers;
private System.Windows.Forms.ToolStripSeparator mnuRtfSeparator1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.