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 AndDouble()
{
var test = new SimpleBinaryOpTest__AndDouble();
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__AndDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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<Double> _fld1;
public Vector256<Double> _fld2;
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<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndDouble testClass)
{
var result = Avx.And(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.And(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(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<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__AndDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.And(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_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 = Avx.And(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_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 = Avx.And(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_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(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.And(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(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<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.And(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((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.And(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((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndDouble();
var result = Avx.And(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__AndDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.And(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.And(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(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 = Avx.And(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 = Avx.And(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&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<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
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.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.And)}<Double>(Vector256<Double>, Vector256<Double>): {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.Collections.Generic;
using Should;
using NUnit.Framework;
namespace AutoMapper.UnitTests
{
namespace MemberResolution
{
public class When_mapping_derived_classes_in_arrays : AutoMapperSpecBase
{
private DtoObject[] _result;
public class ModelObject
{
public string BaseString { get; set; }
}
public class ModelSubObject : ModelObject
{
public string SubString { get; set; }
}
public class DtoObject
{
public string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new[]
{
new ModelObject {BaseString = "Base1"},
new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
Mapper
.CreateMap<ModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
Mapper.CreateMap<ModelSubObject, DtoSubObject>();
_result = (DtoObject[]) Mapper.Map(model, typeof (ModelObject[]), typeof (DtoObject[]));
}
[Test]
public void Should_map_both_the_base_and_sub_objects()
{
_result.Length.ShouldEqual(2);
_result[0].BaseString.ShouldEqual("Base1");
_result[1].BaseString.ShouldEqual("Base2");
}
[Test]
public void Should_map_to_the_correct_respective_dto_types()
{
_result[0].ShouldBeType(typeof (DtoObject));
_result[1].ShouldBeType(typeof (DtoSubObject));
}
}
public class When_mapping_derived_classes : AutoMapperSpecBase
{
private DtoObject _result;
public class ModelObject
{
public string BaseString { get; set; }
}
public class ModelSubObject : ModelObject
{
public string SubString { get; set; }
}
public class DtoObject
{
public string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper
.CreateMap<ModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
Mapper.CreateMap<ModelSubObject, DtoSubObject>();
}
protected override void Because_of()
{
var model = new ModelSubObject { BaseString = "Base2", SubString = "Sub2" };
_result = Mapper.Map<ModelObject, DtoObject>(model);
}
[Test]
public void Should_map_to_the_correct_dto_types()
{
_result.ShouldBeType(typeof(DtoSubObject));
}
}
public class When_mapping_derived_classes_from_intefaces_to_abstract : AutoMapperSpecBase
{
private DtoObject[] _result;
public interface IModelObject
{
string BaseString { get; set; }
}
public class ModelSubObject : IModelObject
{
public string SubString { get; set; }
public string BaseString { get; set; }
}
public abstract class DtoObject
{
public virtual string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new IModelObject[]
{
new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
Mapper.CreateMap<IModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
Mapper.CreateMap<ModelSubObject, DtoSubObject>();
_result = (DtoObject[]) Mapper.Map(model, typeof (IModelObject[]), typeof (DtoObject[]));
}
[Test]
public void Should_map_both_the_base_and_sub_objects()
{
_result.Length.ShouldEqual(1);
_result[0].BaseString.ShouldEqual("Base2");
}
[Test]
public void Should_map_to_the_correct_respective_dto_types()
{
_result[0].ShouldBeType(typeof (DtoSubObject));
((DtoSubObject) _result[0]).SubString.ShouldEqual("Sub2");
}
}
public class When_mapping_derived_classes_as_property_of_top_object : AutoMapperSpecBase
{
private DtoModel _result;
public class Model
{
public IModelObject Object { get; set; }
}
public interface IModelObject
{
string BaseString { get; set; }
}
public class ModelSubObject : IModelObject
{
public string SubString { get; set; }
public string BaseString { get; set; }
}
public class DtoModel
{
public DtoObject Object { get; set; }
}
public abstract class DtoObject
{
public virtual string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Model, DtoModel>();
Mapper.CreateMap<IModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
Mapper.CreateMap<ModelSubObject, DtoSubObject>();
}
[Test]
public void Should_map_object_to_sub_object()
{
var model = new Model
{
Object = new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
_result = Mapper.Map<Model, DtoModel>(model);
_result.Object.ShouldNotBeNull();
_result.Object.ShouldBeType<DtoSubObject>();
_result.Object.ShouldBeType<DtoSubObject>();
_result.Object.BaseString.ShouldEqual("Base2");
((DtoSubObject) _result.Object).SubString.ShouldEqual("Sub2");
}
}
public class When_mapping_dto_with_only_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate { get; set; }
public ModelSubObject Sub { get; set; }
public ModelSubObject Sub2 { get; set; }
public ModelSubObject SubWithExtraName { get; set; }
public ModelSubObject SubMissing { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set; }
public ModelSubSubObject SubSub { get; set; }
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set; }
}
public class ModelDto
{
public DateTime BaseDate { get; set; }
public string SubProperName { get; set; }
public string Sub2ProperName { get; set; }
public string SubWithExtraNameProperName { get; set; }
public string SubSubSubIAmACoolProperty { get; set; }
public string SubMissingSubSubIAmACoolProperty { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Test]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Test]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Test]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Test]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_mapping_dto_with_only_fields : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate;
public ModelSubObject Sub;
public ModelSubObject Sub2;
public ModelSubObject SubWithExtraName;
public ModelSubObject SubMissing;
}
public class ModelSubObject
{
public string ProperName;
public ModelSubSubObject SubSub;
}
public class ModelSubSubObject
{
public string IAmACoolProperty;
}
public class ModelDto
{
public DateTime BaseDate;
public string SubProperName;
public string Sub2ProperName;
public string SubWithExtraNameProperName;
public string SubSubSubIAmACoolProperty;
public string SubMissingSubSubIAmACoolProperty;
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Test]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Test]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Test]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Test]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_mapping_dto_with_fields_and_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate { get; set;}
public ModelSubObject Sub;
public ModelSubObject Sub2 { get; set;}
public ModelSubObject SubWithExtraName;
public ModelSubObject SubMissing { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set;}
public ModelSubSubObject SubSub;
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set;}
}
public class ModelDto
{
public DateTime BaseDate;
public string SubProperName;
public string Sub2ProperName { get; set;}
public string SubWithExtraNameProperName;
public string SubSubSubIAmACoolProperty;
public string SubMissingSubSubIAmACoolProperty { get; set;}
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Test]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Test]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Test]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Test]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_ignoring_a_dto_property_during_configuration : AutoMapperSpecBase
{
private TypeMap[] _allTypeMaps;
private Source _source;
public class Source
{
public string Value { get; set; }
}
public class Destination
{
public bool Ignored
{
get { return true; }
}
public string Value { get; set; }
}
[Test]
public void Should_not_report_it_as_unmapped()
{
Array.ForEach(_allTypeMaps, t => t.GetUnmappedPropertyNames().ShouldBeOfLength(0));
}
[Test]
public void Should_map_successfully()
{
var destination = Mapper.Map<Source, Destination>(_source);
destination.Value.ShouldEqual("foo");
destination.Ignored.ShouldBeTrue();
}
[Test]
public void Should_succeed_configration_check()
{
Mapper.AssertConfigurationIsValid();
}
protected override void Establish_context()
{
_source = new Source {Value = "foo"};
Mapper.CreateMap<Source, Destination>()
.ForMember(x => x.Ignored, opt => opt.Ignore());
_allTypeMaps = Mapper.GetAllTypeMaps();
}
}
public class When_mapping_dto_with_get_methods : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public string GetSomeCoolValue()
{
return "Cool value";
}
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string GetSomeOtherCoolValue()
{
return "Even cooler";
}
}
public class ModelDto
{
public string SomeCoolValue { get; set; }
public string SubSomeOtherCoolValue { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Sub = new ModelSubObject()
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_base_method_value()
{
_result.SomeCoolValue.ShouldEqual("Cool value");
}
[Test]
public void Should_map_second_level_method_value_off_of_property()
{
_result.SubSomeOtherCoolValue.ShouldEqual("Even cooler");
}
}
public class When_mapping_a_dto_with_names_matching_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public string SomeCoolValue()
{
return "Cool value";
}
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string SomeOtherCoolValue()
{
return "Even cooler";
}
}
public class ModelDto
{
public string SomeCoolValue { get; set; }
public string SubSomeOtherCoolValue { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Sub = new ModelSubObject()
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_base_method_value()
{
_result.SomeCoolValue.ShouldEqual("Cool value");
}
[Test]
public void Should_map_second_level_method_value_off_of_property()
{
_result.SubSomeOtherCoolValue.ShouldEqual("Even cooler");
}
}
public class When_mapping_with_a_dto_subtype : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string SomeValue { get; set; }
}
public class ModelDto
{
public ModelSubDto Sub { get; set; }
}
public class ModelSubDto
{
public string SomeValue { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>();
Mapper.CreateMap<ModelSubObject, ModelSubDto>();
var model = new ModelObject
{
Sub = new ModelSubObject
{
SomeValue = "Some value"
}
};
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_the_model_sub_type_to_the_dto_sub_type()
{
_result.Sub.ShouldNotBeNull();
_result.Sub.SomeValue.ShouldEqual("Some value");
}
}
public class When_mapping_a_dto_with_a_set_only_property_and_a_get_method : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelDto
{
public int SomeValue { get; set; }
}
public class ModelObject
{
private int _someValue;
public int SomeValue
{
set { _someValue = value; }
}
public int GetSomeValue()
{
return _someValue;
}
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>();
var model = new ModelObject();
model.SomeValue = 46;
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_map_the_get_method_to_the_dto()
{
_result.SomeValue.ShouldEqual(46);
}
}
public class When_mapping_using_a_custom_member_mappings : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public int Blarg { get; set; }
public string MoreBlarg { get; set; }
public int SomeMethodToGetMoreBlarg()
{
return 45;
}
public string SomeValue { get; set; }
public ModelSubObject SomeWeirdSubObject { get; set; }
public string IAmSomeMethod()
{
return "I am some method";
}
}
public class ModelSubObject
{
public int Narf { get; set; }
public ModelSubSubObject SubSub { get; set; }
public string SomeSubValue()
{
return "I am some sub value";
}
}
public class ModelSubSubObject
{
public int Norf { get; set; }
public string SomeSubSubValue()
{
return "I am some sub sub value";
}
}
public class ModelDto
{
public int Splorg { get; set; }
public string SomeValue { get; set; }
public string SomeMethod { get; set; }
public int SubNarf { get; set; }
public string SubValue { get; set; }
public int GrandChildInt { get; set; }
public string GrandChildString { get; set; }
public int BlargPlus3 { get; set; }
public int BlargMinus2 { get; set; }
public int MoreBlarg { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Blarg = 10,
SomeValue = "Some value",
SomeWeirdSubObject = new ModelSubObject
{
Narf = 5,
SubSub = new ModelSubSubObject
{
Norf = 15
}
},
MoreBlarg = "adsfdsaf"
};
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Splorg, opt => opt.MapFrom(m => m.Blarg))
.ForMember(dto => dto.SomeMethod, opt => opt.MapFrom(m => m.IAmSomeMethod()))
.ForMember(dto => dto.SubNarf, opt => opt.MapFrom(m => m.SomeWeirdSubObject.Narf))
.ForMember(dto => dto.SubValue, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SomeSubValue()))
.ForMember(dto => dto.GrandChildInt, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.Norf))
.ForMember(dto => dto.GrandChildString, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.SomeSubSubValue()))
.ForMember(dto => dto.MoreBlarg, opt => opt.MapFrom(m => m.SomeMethodToGetMoreBlarg()))
.ForMember(dto => dto.BlargPlus3, opt => opt.MapFrom(m => m.Blarg.Plus(3)))
.ForMember(dto => dto.BlargMinus2, opt => opt.MapFrom(m => m.Blarg - 2));
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_preserve_the_existing_mapping()
{
_result.SomeValue.ShouldEqual("Some value");
}
[Test]
public void Should_map_top_level_properties()
{
_result.Splorg.ShouldEqual(10);
}
[Test]
public void Should_map_methods_results()
{
_result.SomeMethod.ShouldEqual("I am some method");
}
[Test]
public void Should_map_children_properties()
{
_result.SubNarf.ShouldEqual(5);
}
[Test]
public void Should_map_children_methods()
{
_result.SubValue.ShouldEqual("I am some sub value");
}
[Test]
public void Should_map_grandchildren_properties()
{
_result.GrandChildInt.ShouldEqual(15);
}
[Test]
public void Should_map_grandchildren_methods()
{
_result.GrandChildString.ShouldEqual("I am some sub sub value");
}
[Test]
public void Should_map_blarg_plus_three_using_extension_method()
{
_result.BlargPlus3.ShouldEqual(13);
}
[Test]
public void Should_map_blarg_minus_2_using_lambda()
{
_result.BlargMinus2.ShouldEqual(8);
}
[Test]
public void Should_override_existing_matches_for_new_mappings()
{
_result.MoreBlarg.ShouldEqual(45);
}
}
public class When_mapping_using_custom_member_mappings_without_generics : AutoMapperSpecBase
{
private OrderDTO _result;
public class Order
{
public int Id { get; set; }
public string Status { get; set; }
public string Customer { get; set; }
public string ShippingCode { get; set; }
public string Zip { get; set; }
}
public class OrderDTO
{
public int Id { get; set; }
public string CurrentState { get; set; }
public string Contact { get; set; }
public string Tracking { get; set; }
public string Postal { get; set; }
}
public class StringCAPS : ValueResolver<string, string>
{
protected override string ResolveCore(string source)
{
return source.ToUpper();
}
}
public class StringLower : ValueResolver<string, string>
{
protected override string ResolveCore(string source)
{
return source.ToLower();
}
}
public class StringPadder : ValueResolver<string, string>
{
private readonly int _desiredLength;
public StringPadder(int desiredLength)
{
_desiredLength = desiredLength;
}
protected override string ResolveCore(string source)
{
return source.PadLeft(_desiredLength);
}
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap(typeof (Order), typeof (OrderDTO))
.ForMember("CurrentState", map => map.MapFrom("Status"))
.ForMember("Contact", map => map.ResolveUsing(new StringCAPS()).FromMember("Customer"))
.ForMember("Tracking", map => map.ResolveUsing(typeof(StringLower)).FromMember("ShippingCode"))
.ForMember("Postal", map => map.ResolveUsing<StringPadder>().ConstructedBy(() => new StringPadder(6)).FromMember("Zip"));
});
var order = new Order
{
Id = 7,
Status = "Pending",
Customer = "Buster",
ShippingCode = "AbcxY23",
Zip = "XYZ"
};
_result = Mapper.Map<Order, OrderDTO>(order);
}
[Test]
public void Should_preserve_existing_mapping()
{
_result.Id.ShouldEqual(7);
}
[Test]
public void Should_support_custom_source_member()
{
_result.CurrentState.ShouldEqual("Pending");
}
[Test]
public void Should_support_custom_resolver_on_custom_source_member()
{
_result.Contact.ShouldEqual("BUSTER");
}
[Test]
public void Should_support_custom_resolver_by_type_on_custom_source_member()
{
_result.Tracking.ShouldEqual("abcxy23");
}
[Test]
public void Should_support_custom_resolver_by_generic_type_with_constructor_on_custom_source_member()
{
_result.Postal.ShouldEqual(" XYZ");
}
}
[Description("This one should really pass validation"), Ignore("Not sure if this is really valid behavior")]
public class When_mapping_a_collection_to_a_more_type_specific_collection : NonValidatingSpecBase
{
private ModelDto _result;
public class Model
{
public List<Item> Items { get; set; }
}
public class Item
{
public string Prop { get; set; }
}
public class SubItem : Item
{
public string SubProp { get; set; }
}
public class ModelDto
{
public SubItemDto[] Items { get; set; }
}
public class ItemDto
{
public string Prop { get; set; }
}
public class SubItemDto : ItemDto
{
public string SubProp { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Model, ModelDto>();
Mapper.CreateMap<Item, ItemDto>();
Mapper.CreateMap<SubItem, SubItemDto>();
var model = new Model
{
Items = new List<Item>
{
new SubItem
{
Prop = "value1",
SubProp = "value2"
}
}
};
_result = Mapper.Map<Model, ModelDto>(model);
}
[Test]
public void Should_map_correctly_if_all_types_map()
{
_result.Items[0].Prop.ShouldEqual("value1");
_result.Items[0].SubProp.ShouldEqual("value2");
}
}
public class When_mapping_to_a_top_level_camelCased_destination_member : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int SomeValueWithPascalName { get; set; }
}
public class Destination
{
public int someValueWithPascalName { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
var source = new Source {SomeValueWithPascalName = 5};
_result = Mapper.Map<Source, Destination>(source);
}
[Test]
public void Should_match_to_PascalCased_source_member()
{
_result.someValueWithPascalName.ShouldEqual(5);
}
[Test]
public void Should_pass_configuration_check()
{
Mapper.AssertConfigurationIsValid();
}
}
public class When_mapping_to_a_self_referential_object : AutoMapperSpecBase
{
private CategoryDto _result;
public class Category
{
public string Name { get; set; }
public IList<Category> Children { get; set; }
}
public class CategoryDto
{
public string Name { get; set; }
public CategoryDto[] Children { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Category, CategoryDto>();
}
protected override void Because_of()
{
var category = new Category
{
Name = "Grandparent",
Children = new List<Category>()
{
new Category { Name = "Parent 1", Children = new List<Category>()
{
new Category { Name = "Child 1"},
new Category { Name = "Child 2"},
new Category { Name = "Child 3"},
}},
new Category { Name = "Parent 2", Children = new List<Category>()
{
new Category { Name = "Child 4"},
new Category { Name = "Child 5"},
new Category { Name = "Child 6"},
new Category { Name = "Child 7"},
}},
}
};
_result = Mapper.Map<Category, CategoryDto>(category);
}
[Test]
public void Should_pass_configuration_check()
{
Mapper.AssertConfigurationIsValid();
}
[Test]
public void Should_resolve_any_level_of_hierarchies()
{
_result.Name.ShouldEqual("Grandparent");
_result.Children.Length.ShouldEqual(2);
_result.Children[0].Children.Length.ShouldEqual(3);
_result.Children[1].Children.Length.ShouldEqual(4);
}
}
public class When_mapping_to_types_in_a_non_generic_manner : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap(typeof (Source), typeof (Destination));
}
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_allow_for_basic_mapping()
{
_result.Value.ShouldEqual(5);
}
}
public class When_matching_source_and_destination_members_with_underscored_members : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public SubSource some_source { get; set; }
}
public class SubSource
{
public int value { get; set; }
}
public class Destination
{
public int some_source_value { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {some_source = new SubSource {value = 8}});
}
[Test]
public void Should_use_underscores_as_tokenizers_to_flatten()
{
_destination.some_source_value.ShouldEqual(8);
}
}
public class When_source_members_contain_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int FooValue { get; set; }
public int GetOtherValue()
{
return 10;
}
}
public class Destination
{
public int Value { get; set; }
public int OtherValue { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizePrefixes("Foo");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {FooValue = 5});
}
[Test]
public void Registered_prefixes_ignored()
{
_destination.Value.ShouldEqual(5);
}
[Test]
public void Default_prefix_included()
{
_destination.OtherValue.ShouldEqual(10);
}
}
public class When_source_members_contain_postfixes_and_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int FooValueBar { get; set; }
public int GetOtherValue()
{
return 10;
}
}
public class Destination
{
public int Value { get; set; }
public int OtherValue { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizePrefixes("Foo");
cfg.RecognizePostfixes("Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { FooValueBar = 5 });
}
[Test]
public void Registered_prefixes_ignored()
{
_destination.Value.ShouldEqual(5);
}
[Test]
public void Default_prefix_included()
{
_destination.OtherValue.ShouldEqual(10);
}
}
public class When_source_member_names_match_with_underscores : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int I_amaCraAZZEE____Name { get; set; }
}
public class Destination
{
public int I_amaCraAZZEE____Name { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
_destination = Mapper.Map<Source, Destination>(new Source {I_amaCraAZZEE____Name = 5});
}
[Test]
public void Should_match_based_on_name()
{
_destination.I_amaCraAZZEE____Name.ShouldEqual(5);
}
}
public class When_recognizing_explicit_member_aliases : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Foo { get; set; }
}
public class Destination
{
public int Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizeAlias("Foo", "Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Foo = 5});
}
[Test]
public void Members_that_match_alias_should_be_matched()
{
_destination.Bar.ShouldEqual(5);
}
}
public class When_destination_members_contain_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int FooValue { get; set; }
public int BarValue2 { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizeDestinationPrefixes("Foo","Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Value = 5, Value2 = 10 });
}
[Test]
public void Registered_prefixes_ignored()
{
_destination.FooValue.ShouldEqual(5);
_destination.BarValue2.ShouldEqual(10);
}
}
}
#if SILVERLIGHT
[Ignore("Setting non-public members not supported with Silverlight DynamicMethod ctor")]
#endif
public class When_destination_type_has_private_members : AutoMapperSpecBase
{
private IDestination _destination;
public class Source
{
public int Value { get; set; }
}
public interface IDestination
{
int Value { get; }
}
public class Destination : IDestination
{
public Destination(int value)
{
Value = value;
}
private Destination()
{
}
public int Value { get; private set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_use_private_accessors_and_constructors()
{
_destination.Value.ShouldEqual(5);
}
}
public static class MapFromExtensions
{
public static int Plus(this int left, int right)
{
return left + right;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System.Collections.Generic;
using System.Buffers;
namespace System.Binary.Base64.Tests
{
public class Base64Tests
{
[Fact]
public void BasicEncodingDecoding()
{
var bytes = new byte[byte.MaxValue + 1];
for (int i = 0; i < byte.MaxValue + 1; i++)
{
bytes[i] = (byte)i;
}
for (int value = 0; value < 256; value++)
{
Span<byte> sourceBytes = bytes.AsSpan().Slice(0, value + 1);
Span<byte> encodedBytes = new byte[Base64.ComputeEncodedLength(sourceBytes.Length)];
Assert.Equal(TransformationStatus.Done, Base64.Encoder.Transform(sourceBytes, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal(encodedBytes.Length, encodedBytesCount);
string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray());
string expectedText = Convert.ToBase64String(bytes, 0, value + 1);
Assert.Equal(expectedText, encodedText);
if (encodedBytes.Length % 4 == 0)
{
Span<byte> decodedBytes = new byte[Base64.ComputeDecodedLength(encodedBytes)];
Assert.Equal(TransformationStatus.Done, Base64.Decoder.Transform(encodedBytes, decodedBytes, out consumed, out int decodedByteCount));
Assert.Equal(sourceBytes.Length, decodedByteCount);
Assert.True(sourceBytes.SequenceEqual(decodedBytes));
}
}
}
[Fact]
public void BasicEncoding()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeBytes(source, numBytes);
Span<byte> encodedBytes = new byte[Base64.ComputeEncodedLength(source.Length)];
Assert.Equal(TransformationStatus.Done, Base64.Encoder.Transform(source, encodedBytes, out int consumed, out int encodedBytesCount));
Assert.Equal(encodedBytes.Length, encodedBytesCount);
string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray());
string expectedText = Convert.ToBase64String(source.ToArray());
Assert.Equal(expectedText, encodedText);
}
}
[Fact]
public void EncodingOutputTooSmall()
{
Span<byte> source = new byte[750];
Base64TestHelper.InitalizeBytes(source);
int outputSize = 320;
int requiredSize = Base64.ComputeEncodedLength(source.Length);
Span<byte> encodedBytes = new byte[outputSize];
Assert.Equal(TransformationStatus.DestinationTooSmall,
Base64.Encoder.Transform(source, encodedBytes, out int consumed, out int written));
Assert.Equal(encodedBytes.Length, written);
Assert.Equal(encodedBytes.Length / 4 * 3, consumed);
encodedBytes = new byte[requiredSize - outputSize];
Assert.Equal(TransformationStatus.Done,
Base64.Encoder.Transform(source.Slice(consumed), encodedBytes, out consumed, out written));
Assert.Equal(encodedBytes.Length, written);
Assert.Equal(encodedBytes.Length / 4 * 3, consumed);
string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray());
string expectedText = Convert.ToBase64String(source.ToArray()).Substring(outputSize);
Assert.Equal(expectedText, encodedText);
}
[Fact]
public void BasicDecoding()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
while (numBytes % 4 != 0)
{
numBytes = rnd.Next(100, 1000 * 1000);
}
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeDecodableBytes(source, numBytes);
Span<byte> decodedBytes = new byte[Base64.ComputeDecodedLength(source)];
Assert.Equal(TransformationStatus.Done,
Base64.Decoder.Transform(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(decodedBytes.Length, decodedByteCount);
string expectedStr = Text.Encoding.ASCII.GetString(source.ToArray());
byte[] expectedText = Convert.FromBase64String(expectedStr);
Assert.True(expectedText.AsSpan().SequenceEqual(decodedBytes));
}
}
[Fact]
public void DecodingInvalidBytes()
{
int[] invalidBytes = Base64TestHelper.s_decodingMap.FindAllIndexOf(Base64TestHelper.s_invalidByte);
for (int j = 0; j < 8; j++)
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
Span<byte> decodedBytes = new byte[Base64.ComputeDecodedLength(source)];
for (int i = 0; i < invalidBytes.Length; i++)
{
// Don't test padding, which is tested in DecodingInvalidBytesPadding
if ((byte)invalidBytes[i] == Base64TestHelper.s_encodingPad) continue;
source[j] = (byte)invalidBytes[i];
Assert.Equal(TransformationStatus.InvalidData,
Base64.Decoder.Transform(source, decodedBytes, out int consumed, out int decodedByteCount));
}
}
}
[Fact]
public void DecodingInvalidBytesPadding()
{
// Only last 2 bytes can be padding, all other occurrence of padding is invalid
for (int j = 0; j < 7; j++)
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
Span<byte> decodedBytes = new byte[Base64.ComputeDecodedLength(source)];
source[j] = Base64TestHelper.s_encodingPad;
Assert.Equal(TransformationStatus.InvalidData,
Base64.Decoder.Transform(source, decodedBytes, out int consumed, out int decodedByteCount));
}
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
Span<byte> decodedBytes = new byte[Base64.ComputeDecodedLength(source)];
source[6] = Base64TestHelper.s_encodingPad;
source[7] = Base64TestHelper.s_encodingPad;
Assert.Equal(TransformationStatus.Done,
Base64.Decoder.Transform(source, decodedBytes, out int consumed, out int decodedByteCount));
source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
source[7] = Base64TestHelper.s_encodingPad;
Assert.Equal(TransformationStatus.Done,
Base64.Decoder.Transform(source, decodedBytes, out consumed, out decodedByteCount));
}
}
[Fact]
public void DecodingOutputTooSmall()
{
Span<byte> source = new byte[1000];
Base64TestHelper.InitalizeDecodableBytes(source);
int outputSize = 240;
int requiredSize = Base64.ComputeDecodedLength(source);
Span<byte> decodedBytes = new byte[outputSize];
Assert.Equal(TransformationStatus.DestinationTooSmall,
Base64.Decoder.Transform(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.Equal(decodedBytes.Length / 3 * 4, consumed);
decodedBytes = new byte[requiredSize - outputSize];
Assert.Equal(TransformationStatus.Done,
Base64.Decoder.Transform(source.Slice(consumed), decodedBytes, out consumed, out decodedByteCount));
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.Equal(decodedBytes.Length / 3 * 4, consumed);
string expectedStr = Text.Encoding.ASCII.GetString(source.ToArray());
byte[] expectedText = Convert.FromBase64String(expectedStr);
Assert.True(expectedText.AsSpan().Slice(outputSize).SequenceEqual(decodedBytes));
}
[Fact]
public void ComputeEncodedLength()
{
// (int.MaxValue - 4)/(4/3) => 1610612733, otherwise integer overflow
int[] input = { 0, 1, 2, 3, 4, 5, 6, 1610612728, 1610612729, 1610612730, 1610612731, 1610612732, 1610612733 };
int[] expected = { 0, 4, 4, 4, 8, 8, 8, 2147483640, 2147483640, 2147483640, 2147483644, 2147483644, 2147483644 };
for (int i = 0; i < input.Length; i++)
{
Assert.Equal(expected[i], Base64.ComputeEncodedLength(input[i]));
}
Assert.True(Base64.ComputeEncodedLength(1610612734) < 0); // integer overflow
}
[Fact]
public void ComputeDecodedLength()
{
Span<byte> sourceEmpty = Span<byte>.Empty;
Assert.Equal(0, Base64.ComputeDecodedLength(sourceEmpty));
int[] input = { 4, 8, 12, 16, 20 };
int[] expected = { 3, 6, 9, 12, 15 };
for (int i = 0; i < input.Length; i++)
{
int sourceLength = input[i];
Span<byte> source = new byte[sourceLength];
Assert.Equal(expected[i], Base64.ComputeDecodedLength(source));
source[sourceLength - 1] = Base64TestHelper.s_encodingPad; // single character padding
Assert.Equal(expected[i] - 1, Base64.ComputeDecodedLength(source));
source[sourceLength - 2] = Base64TestHelper.s_encodingPad; // two characters padding
Assert.Equal(expected[i] - 2, Base64.ComputeDecodedLength(source));
}
// int.MaxValue - (int.MaxValue % 4) => 2147483644, largest multiple of 4 less than int.MaxValue
// CLR default limit of 2 gigabytes (GB).
try
{
int sourceLength = 2000000000;
int expectedLength = 1500000000;
Span<byte> source = new byte[sourceLength];
Assert.Equal(expectedLength, Base64.ComputeDecodedLength(source));
source[sourceLength - 1] = Base64TestHelper.s_encodingPad; // single character padding
Assert.Equal(expectedLength - 1, Base64.ComputeDecodedLength(source));
source[sourceLength - 2] = Base64TestHelper.s_encodingPad; // two characters padding
Assert.Equal(expectedLength - 2, Base64.ComputeDecodedLength(source));
}
catch (OutOfMemoryException)
{
// do nothing
}
// Lengths that are not a multiple of 4.
int[] lengthsNotMultipleOfFour = { 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 1001, 1002, 1003 };
int[] expectedOutput = { 0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9, 9, 750, 750, 750 };
for (int i = 0; i < lengthsNotMultipleOfFour.Length; i++)
{
int sourceLength = lengthsNotMultipleOfFour[i];
Span<byte> source = new byte[sourceLength];
Assert.Equal(expectedOutput[i], Base64.ComputeDecodedLength(source));
source[sourceLength - 1] = Base64TestHelper.s_encodingPad;
Assert.Equal(expectedOutput[i], Base64.ComputeDecodedLength(source));
if (sourceLength > 1)
{
source[sourceLength - 2] = Base64TestHelper.s_encodingPad;
Assert.Equal(expectedOutput[i], Base64.ComputeDecodedLength(source));
}
}
}
[Fact]
public void DecodeInPlace()
{
var list = new List<byte>();
for (int value = 0; value < 256; value++)
{
list.Add((byte)value);
}
var testBytes = list.ToArray();
for (int value = 0; value < 256; value++)
{
var sourceBytes = testBytes.AsSpan().Slice(0, value + 1);
var buffer = new byte[Base64.ComputeEncodedLength(sourceBytes.Length)];
var bufferSlice = buffer.AsSpan();
Base64.Encoder.Transform(sourceBytes, bufferSlice, out int consumed, out int written);
var encodedText = Text.Encoding.ASCII.GetString(bufferSlice.ToArray());
var expectedText = Convert.ToBase64String(testBytes, 0, value + 1);
Assert.Equal(expectedText, encodedText);
Assert.Equal(TransformationStatus.Done, Base64.DecodeInPlace(bufferSlice, out int bytesConsumed, out int bytesWritten));
Assert.Equal(sourceBytes.Length, bytesWritten);
Assert.Equal(bufferSlice.Length, bytesConsumed);
for (int i = 0; i < bytesWritten; i++)
{
Assert.Equal(sourceBytes[i], bufferSlice[i]);
}
}
}
[Fact]
public void ValidInputOnlyMultiByte()
{
Span<byte> inputSpan = new byte[1000];
Base64TestHelper.InitalizeDecodableBytes(inputSpan);
int requiredLength = Base64.ComputeDecodedLength(inputSpan);
Span<byte> expected = new byte[requiredLength];
Assert.Equal(TransformationStatus.Done, Base64.Decoder.Transform(inputSpan, expected, out int bytesConsumed, out int bytesWritten));
byte[][] input = new byte[10][];
int[] split = { 100, 102, 98, 101, 2, 97, 101, 1, 2, 396 };
int sum = 0;
for (int i = 0; i < split.Length; i++)
{
int splitter = split[i];
input[i] = inputSpan.Slice(sum, splitter).ToArray();
sum += splitter;
}
Assert.Equal(1000, sum);
var output = new TestOutput();
Base64.Decoder.Pipe(ReadOnlyBytes.Create(input), output);
Assert.True(expected.SequenceEqual(output.GetBuffer.Slice(0, requiredLength)));
}
[Fact]
public void EncodeInPlace()
{
const int numberOfBytes = 15;
var list = new List<byte>();
for (int value = 0; value < numberOfBytes; value++)
{
list.Add((byte)value);
}
// padding
for (int i = 0; i < (numberOfBytes / 3) + 2; i++)
{
list.Add(0);
}
var testBytes = list.ToArray();
for (int numberOfBytesToTest = 1; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest++)
{
var copy = testBytes.Clone();
var expectedText = Convert.ToBase64String(testBytes, 0, numberOfBytesToTest);
Assert.True(Base64.EncodeInPlace(testBytes, numberOfBytesToTest, out int bytesWritten));
Assert.Equal(Base64.ComputeEncodedLength(numberOfBytesToTest), bytesWritten);
var encodedText = Text.Encoding.ASCII.GetString(testBytes, 0, bytesWritten);
Assert.Equal(expectedText, encodedText);
}
}
}
class TestOutput : IOutput
{
byte[] _buffer = new byte[1000];
int _written = 0;
public Span<byte> GetBuffer => _buffer;
public Span<byte> Buffer => _buffer.Slice(_written);
public void Advance(int bytes)
{
_written += bytes;
}
public void Enlarge(int desiredBufferLength = 0)
{
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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 additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Collections;
using System.Globalization;
namespace fyiReporting.RDL
{
///<summary>
/// Represent a report parameter (name, default value, runtime value,
///</summary>
[Serializable]
internal class ReportParameter : ReportLink
{
Name _Name; // Name of the parameter
// Note: Parameter names need only be
// unique within the containing Parameters collection
TypeCode _dt; // The data type of the parameter
bool _NumericType=false; // true if _dt is a numeric type
bool _Nullable; // Indicates the value for this parameter is allowed to be Null.
DefaultValue _DefaultValue; // Default value to use for the parameter (if not provided by the user)
// If no value is provided as a part of the
// definition or by the user, the value is
// null. Required if there is no Prompt and
// either Nullable is False or a ValidValues
// list is provided that does not contain Null
// (an omitted Value).
bool _AllowBlank; // Indicates the value for this parameter is
// allowed to be the empty string. Ignored
// if DataType is not string.
string _Prompt; // The user prompt to display when asking
// for parameter values
// If omitted, the user should not be
// prompted for a value for this parameter.
ValidValues _ValidValues; // Possible values for the parameter (for an
// end-user prompting interface)
bool _Hidden=false; // indicates parameter should not be showed to user
bool _MultiValue=false; // indicates parameter is a collection - expressed as 0 based arrays Parameters!p1.Value(0)
TrueFalseAutoEnum _UsedInQuery; // Enum True | False | Auto (default)
// Indicates whether or not the parameter is
// used in a query in the report. This is
// needed to determine if the queries need
// to be re-executed if the parameter
// changes. Auto indicates the
// UsedInQuery setting should be
// autodetected as follows: True if the
// parameter is referenced in any query
// value expression.
internal ReportParameter(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_Name=null;
_dt = TypeCode.Object;
_Nullable = false;
_DefaultValue=null;
_AllowBlank=false;
_Prompt=null;
_ValidValues=null;
_UsedInQuery = TrueFalseAutoEnum.Auto;
// Run thru the attributes
foreach(XmlAttribute xAttr in xNode.Attributes)
{
switch (xAttr.Name)
{
case "Name":
_Name = new Name(xAttr.Value);
break;
}
}
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataType":
_dt = DataType.GetStyle(xNodeLoop.InnerText, this.OwnerReport);
_NumericType = DataType.IsNumeric(_dt);
break;
case "Nullable":
_Nullable = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "DefaultValue":
_DefaultValue = new DefaultValue(r, this, xNodeLoop);
break;
case "AllowBlank":
_AllowBlank = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "Prompt":
_Prompt = xNodeLoop.InnerText;
break;
case "Hidden":
_Hidden = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
OwnerReport.rl.LogError(4, "ReportParameter element Hidden is currently ignored."); // TODO
break;
case "MultiValue":
_MultiValue = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "ValidValues":
_ValidValues = new ValidValues(r, this, xNodeLoop);
break;
case "UsedInQuery":
_UsedInQuery = TrueFalseAuto.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown ReportParameter element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_Name == null)
OwnerReport.rl.LogError(8, "ReportParameter name is required but not specified.");
if (_dt == TypeCode.Object)
OwnerReport.rl.LogError(8, string.Format("ReportParameter DataType is required but not specified or invalid for {0}.", _Name==null? "<unknown name>": _Name.Nm));
}
override internal void FinalPass()
{
if (_DefaultValue != null)
_DefaultValue.FinalPass();
if (_ValidValues != null)
_ValidValues.FinalPass();
return;
}
internal Name Name
{
get { return _Name; }
set { _Name = value; }
}
internal object GetRuntimeValue(Report rpt)
{
object rtv = rpt == null? null:
rpt.Cache.Get(this, "runtimevalue");
if (rtv != null)
return rtv;
if (_DefaultValue == null)
return null;
object[] result = _DefaultValue.GetValue(rpt);
if (result == null)
return null;
object v = result[0];
if (v is String && _NumericType)
v = ConvertStringToNumber((string) v);
rtv = Convert.ChangeType(v, _dt);
if (rpt != null)
rpt.Cache.Add(this, "runtimevalue", rtv);
return rtv;
}
internal ArrayList GetRuntimeValues(Report rpt)
{
ArrayList rtv = rpt == null ? null :
(ArrayList) rpt.Cache.Get(this, "rtvs");
if (rtv != null)
return rtv;
if (_DefaultValue == null)
return null;
object[] result = _DefaultValue.GetValue(rpt);
if (result == null)
return null;
ArrayList ar = new ArrayList(result.Length);
foreach (object v in result)
{
object nv = v;
if (nv is String && _NumericType)
nv = ConvertStringToNumber((string)nv);
ar.Add( Convert.ChangeType(nv, _dt));
}
if (rpt != null)
rpt.Cache.Add(this, "rtvs", ar);
return ar;
}
internal void SetRuntimeValue(Report rpt, object v)
{
if (this.MultiValue)
{ // ok to only set one parameter of multiValue; but we still save as MultiValue
ArrayList ar;
if (v is string)
{ // when the value is a string we parse it looking for multiple arguments
ParameterLexer pl = new ParameterLexer(v as string);
ar = pl.Lex();
}
else if (v is ICollection)
{ // when collection put it in local array
ar = new ArrayList(v as ICollection);
}
else
{
ar = new ArrayList(1);
ar.Add(v);
}
SetRuntimeValues(rpt, ar);
return;
}
object rtv;
if (!AllowBlank && _dt == TypeCode.String && (string) v == "")
throw new ArgumentException(string.Format("Empty string isn't allowed for {0}.", Name.Nm));
try
{
if (v is String && _NumericType)
v = ConvertStringToNumber((string) v);
rtv = Convert.ChangeType(v, _dt);
}
catch (Exception e)
{
// illegal parameter passed
string err = "Illegal parameter value for '" + Name.Nm + "' provided. Value =" + v.ToString();
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(string.Format("Unable to convert '{0}' to {1} for {2}", v, _dt, Name.Nm),e);
}
rpt.Cache.AddReplace(this, "runtimevalue", rtv);
}
internal void SetRuntimeValues(Report rpt, ArrayList vs)
{
if (!this.MultiValue)
throw new ArgumentException(string.Format("{0} is not a MultiValue parameter. SetRuntimeValues only valid for MultiValue parameters", this.Name.Nm));
ArrayList ar = new ArrayList(vs.Count);
foreach (object v in vs)
{
object rtv;
if (!AllowBlank && _dt == TypeCode.String && (string)v == "")
{
string err = string.Format("Empty string isn't allowed for {0}.", Name.Nm);
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(err);
}
try
{
object nv = v;
if (nv is String && _NumericType)
nv = ConvertStringToNumber((string)nv);
rtv = Convert.ChangeType(nv, _dt);
ar.Add(rtv);
}
catch (Exception e)
{
// illegal parameter passed
string err = "Illegal parameter value for '" + Name.Nm + "' provided. Value =" + v.ToString();
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(string.Format("Unable to convert '{0}' to {1} for {2}", v, _dt, Name.Nm), e);
}
}
rpt.Cache.AddReplace(this, "rtvs", ar);
}
private object ConvertStringToNumber(string newv)
{
// remove any commas, currency symbols (internationalized)
NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
newv = newv.Replace(nfi.NumberGroupSeparator, "");
newv = newv.Replace(nfi.CurrencySymbol, "");
return newv;
}
internal TypeCode dt
{
get { return _dt; }
set { _dt = value; }
}
internal bool Nullable
{
get { return _Nullable; }
set { _Nullable = value; }
}
internal bool Hidden
{
get { return _Hidden; }
set { _Hidden = value; }
}
internal bool MultiValue
{
get { return _MultiValue; }
set { _MultiValue = value; }
}
internal DefaultValue DefaultValue
{
get { return _DefaultValue; }
set { _DefaultValue = value; }
}
internal bool AllowBlank
{
get { return _AllowBlank; }
set { _AllowBlank = value; }
}
internal string Prompt
{
get { return _Prompt; }
set { _Prompt = value; }
}
internal ValidValues ValidValues
{
get { return _ValidValues; }
set { _ValidValues = value; }
}
internal TrueFalseAutoEnum UsedInQuery
{
get { return _UsedInQuery; }
set { _UsedInQuery = value; }
}
}
/// <summary>
/// Public class used to pass user provided report parameters.
/// </summary>
public class UserReportParameter
{
Report _rpt;
ReportParameter _rp;
object[] _DefaultValue;
string[] _DisplayValues;
object[] _DataValues;
internal UserReportParameter(Report rpt, ReportParameter rp)
{
_rpt = rpt;
_rp = rp;
}
/// <summary>
/// Name of the report paramenter.
/// </summary>
public string Name
{
get { return _rp.Name.Nm; }
}
/// <summary>
/// Type of the report parameter.
/// </summary>
public TypeCode dt
{
get { return _rp.dt; }
}
/// <summary>
/// Is parameter allowed to be null.
/// </summary>
public bool Nullable
{
get { return _rp.Nullable; }
}
/// <summary>
/// Default value(s) of the parameter.
/// </summary>
public object[] DefaultValue
{
get
{
if (_DefaultValue == null)
{
if (_rp.DefaultValue != null)
_DefaultValue = _rp.DefaultValue.ValuesCalc(this._rpt);
}
return _DefaultValue;
}
}
/// <summary>
/// Is parameter allowed to be the empty string?
/// </summary>
public bool AllowBlank
{
get { return _rp.AllowBlank; }
}
/// <summary>
/// Does parameters accept multiple values?
/// </summary>
public bool MultiValue
{
get { return _rp.MultiValue; }
}
/// <summary>
/// Text used to prompt for the parameter.
/// </summary>
public string Prompt
{
get { return _rp.Prompt; }
}
/// <summary>
/// The display values for the parameter. These may differ from the data values.
/// </summary>
public string[] DisplayValues
{
get
{
if (_DisplayValues == null)
{
if (_rp.ValidValues != null)
_DisplayValues = _rp.ValidValues.DisplayValues(_rpt);
}
return _DisplayValues;
}
}
/// <summary>
/// The data values of the parameter.
/// </summary>
public object[] DataValues
{
get
{
if (_DataValues == null)
{
if (_rp.ValidValues != null)
_DataValues = _rp.ValidValues.DataValues(this._rpt);
}
return _DataValues;
}
}
/// <summary>
/// Obtain the data value from a (potentially) display value
/// </summary>
/// <param name="dvalue">Display value</param>
/// <returns>The data value cooresponding to the display value.</returns>
private object GetDataValueFromDisplay(object dvalue)
{
object val = dvalue;
if (dvalue != null &&
DisplayValues != null &&
DataValues != null &&
DisplayValues.Length == DataValues.Length) // this should always be true
{ // if display values are provided then we may need to
// use the provided value with a display value and use
// the cooresponding data value
string sval = dvalue.ToString();
for (int index = 0; index < DisplayValues.Length; index++)
{
if (DisplayValues[index].CompareTo(sval) == 0)
{
val = DataValues[index];
break;
}
}
}
return val;
}
/// <summary>
/// The runtime value of the parameter.
/// </summary>
public object Value
{
get { return _rp.GetRuntimeValue(this._rpt); }
set
{
if (this.MultiValue && value is string)
{ // treat this as a multiValue request
Values = ParseValue(value as string);
return;
}
object dvalue = GetDataValueFromDisplay(value);
_rp.SetRuntimeValue(_rpt, dvalue);
}
}
/// <summary>
/// Take a string and parse it into multiple values
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
private ArrayList ParseValue(string v)
{
ParameterLexer pl = new ParameterLexer(v);
return pl.Lex();
}
/// <summary>
/// The runtime values of the parameter when MultiValue.
/// </summary>
public ArrayList Values
{
get { return _rp.GetRuntimeValues(this._rpt); }
set
{
ArrayList ar = new ArrayList(value.Count);
foreach (object v in value)
{
ar.Add(GetDataValueFromDisplay(v));
}
_rp.SetRuntimeValues(_rpt, ar);
}
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
[InheritRequired()]
public abstract partial class TCErrorCondition : TCXMLReaderBaseGeneral
{
public static string xmlStr = "<a></a>";
//[Variation("XmlReader.Create((string)null)", Param = 1)]
//[Variation("XmlReader.Create((TextReader)null)", Param = 2)]
//[Variation("XmlReader.Create((Stream)null)", Param = 3)]
//[Variation("XmlReader.Create((string)null, null)", Param = 4)]
//[Variation("XmlReader.Create((TextReader)null, null)", Param = 5)]
//[Variation("XmlReader.Create((Stream)null, null)", Param = 6)]
//[Variation("XmlReader.Create((XmlReader)null, null)", Param = 7)]
//[Variation("XmlReader.Create((Stream)null, null, (string) null)", Param = 8)]
//[Variation("XmlReader.Create((Stream)null, null, (XmlParserContext)null)", Param = 9)]
//[Variation("XmlReader.Create((string)null, null, null)", Param = 10)]
//[Variation("XmlReader.Create((TextReader)null, null, (string)null)", Param = 11)]
//[Variation("XmlReader.Create((TextReader)null, null, (XmlParserContext)null)", Param = 12)]
//[Variation("new XmlNamespaceManager(null)", Param = 13)]
//[Variation("XmlReader.IsName(null)", Param = 14)]
//[Variation("XmlReader.IsNameToken(null)", Param = 15)]
//[Variation("new XmlValidatingReader(null)", Param = 16)]
//[Variation("new XmlTextReader(null)", Param = 17)]
//[Variation("new XmlNodeReader(null)", Param = 18)]
public int v1()
{
int param = (int)CurVariation.Param;
try
{
switch (param)
{
case 1: ReaderHelper.Create((string)null); break;
case 2: ReaderHelper.Create((TextReader)null); break;
case 3: ReaderHelper.Create((Stream)null); break;
case 4: ReaderHelper.Create((string)null, null); break;
case 5: ReaderHelper.Create((TextReader)null, null); break;
case 6: ReaderHelper.Create((Stream)null, null); break;
case 7: ReaderHelper.Create((XmlReader)null, null); break;
case 8: ReaderHelper.Create((Stream)null, null, (string)null); break;
case 9: ReaderHelper.Create((Stream)null, null, (XmlParserContext)null); break;
case 10: ReaderHelper.Create((string)null, null, null); break;
case 11: ReaderHelper.Create((TextReader)null, null, (string)null); break;
case 12: ReaderHelper.Create((TextReader)null, null, (XmlParserContext)null); break;
case 13: new XmlNamespaceManager(null); break;
case 14: XmlReader.IsName(null); break;
case 15: XmlReader.IsNameToken(null); break;
default:
return TEST_PASS;
}
}
catch (ArgumentNullException)
{
try
{
switch (param)
{
case 1: ReaderHelper.Create((string)null); break;
case 2: ReaderHelper.Create((TextReader)null); break;
case 3: ReaderHelper.Create((Stream)null); break;
case 4: ReaderHelper.Create((string)null, null); break;
case 5: ReaderHelper.Create((TextReader)null, null); break;
case 6: ReaderHelper.Create((Stream)null, null); break;
case 7: ReaderHelper.Create((XmlReader)null, null); break;
case 8: ReaderHelper.Create((Stream)null, null, (string)null); break;
case 9: ReaderHelper.Create((Stream)null, null, (XmlParserContext)null); break;
case 10: ReaderHelper.Create((string)null, null, null); break;
case 11: ReaderHelper.Create((TextReader)null, null, (string)null); break;
case 12: ReaderHelper.Create((TextReader)null, null, (XmlParserContext)null); break;
default:
return TEST_PASS;
}
}
catch (ArgumentNullException) { return TEST_PASS; }
}
catch (NullReferenceException)
{
try
{
switch (param)
{
case 13: new XmlNamespaceManager(null); break;
case 14: XmlReader.IsName(null); break;
case 15: XmlReader.IsNameToken(null); break;
default:
return TEST_PASS;
}
}
catch (NullReferenceException) { return TEST_PASS; }
}
return TEST_FAIL;
}
//[Variation("XmlReader.Create(String.Empty)", Param = 1)]
//[Variation("XmlReader.Create(String.Empty, null)", Param = 2)]
//[Variation("XmlReader.Create(String.Empty, null, (XmlParserContext)null)", Param = 3)]
//[Variation("XmlReader.Create(new Stream(), null, (string)null)", Param = 4)]
//[Variation("XmlReader.Create(new Stream(), null, (XmlParserContext)null)", Param = 5)]
public int v1a()
{
int param = (int)CurVariation.Param;
try
{
switch (param)
{
case 1: ReaderHelper.Create(String.Empty); break;
case 2: ReaderHelper.Create(String.Empty, null); break;
case 3: ReaderHelper.Create(String.Empty, null, (XmlParserContext)null); break;
}
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 1: ReaderHelper.Create(String.Empty); break;
case 2: ReaderHelper.Create(String.Empty, null); break;
case 3: ReaderHelper.Create(String.Empty, null, (XmlParserContext)null); break;
}
}
catch (ArgumentException) { return TEST_PASS; }
}
return TEST_FAIL;
}
//[Variation("XmlReader.Create(Stream)", Param = 1)]
//[Variation("XmlReader.Create(String)", Param = 2)]
//[Variation("XmlReader.Create(TextReader)", Param = 3)]
//[Variation("XmlReader.Create(Stream, XmlReaderSettings)", Param = 4)]
//[Variation("XmlReader.Create(String, XmlReaderSettings)", Param = 5)]
//[Variation("XmlReader.Create(TextReader, XmlReaderSettings)", Param = 6)]
//[Variation("XmlReader.Create(XmlReader, XmlReaderSettings)", Param = 7)]
//[Variation("XmlReader.Create(Stream, XmlReaderSettings, string)", Param = 8)]
//[Variation("XmlReader.Create(Stream, XmlReaderSettings, XmlParserContext)", Param = 9)]
//[Variation("XmlReader.Create(String, XmlReaderSettings, XmlParserContext)", Param = 10)]
//[Variation("XmlReader.Create(TextReader, XmlReaderSettings, string)", Param = 11)]
//[Variation("XmlReader.Create(TextReader, XmlReaderSettings, XmlParserContext)", Param = 12)]
public int v1b()
{
int param = (int)CurVariation.Param;
XmlReaderSettings rs = new XmlReaderSettings();
XmlReader r = ReaderHelper.Create(new StringReader("<a/>"));
string uri = Path.Combine(TestData, "Common", "file_23.xml");
try
{
switch (param)
{
case 2: ReaderHelper.Create(uri); break;
case 3: ReaderHelper.Create(new StringReader("<a/>")); break;
case 5: ReaderHelper.Create(uri, rs); break;
case 6: ReaderHelper.Create(new StringReader("<a/>"), rs); break;
case 7: ReaderHelper.Create(r, rs); break;
case 10: ReaderHelper.Create(uri, rs, (XmlParserContext)null); break;
case 11: ReaderHelper.Create(new StringReader("<a/>"), rs, uri); break;
case 12: ReaderHelper.Create(new StringReader("<a/>"), rs, (XmlParserContext)null); break;
}
}
catch (FileNotFoundException) { return (IsXsltReader()) ? TEST_PASS : TEST_FAIL; }
return TEST_PASS;
}
//[Variation("XmlReader[null])", Param = 1)]
//[Variation("XmlReader[null, null]", Param = 2)]
//[Variation("XmlReader.GetAttribute(null)", Param = 3)]
//[Variation("XmlReader.GetAttribute(null, null)", Param = 4)]
//[Variation("XmlReader.MoveToAttribute(null)", Param = 5)]
//[Variation("XmlReader.MoveToAttribute(null, null)", Param = 6)]
//[Variation("XmlReader.ReadContentAsBase64(null, 0, 0)", Param = 7)]
//[Variation("XmlReader.ReadContentAsBinHex(null, 0, 0)", Param = 8)]
//[Variation("XmlReader.ReadElementContentAs(null, null, null, null)", Param = 9)]
//[Variation("XmlReader.ReadElementContentAs(null, null, 'a', null)", Param = 10)]
//[Variation("XmlReader.ReadElementContentAsBase64(null, 0, 0)", Param = 11)]
//[Variation("XmlReader.ReadElementContentAsBinHex(null, 0, 0)", Param = 12)]
//[Variation("XmlReader.ReadElementContentAsBoolean(null, null)", Param = 13)]
//[Variation("XmlReader.ReadElementContentAsBoolean('a', null)", Param = 14)]
//[Variation("XmlReader.ReadElementContentAsDateTime(null, null)", Param = 15)]
//[Variation("XmlReader.ReadElementContentAsDateTime('a', null)", Param = 16)]
//[Variation("XmlReader.ReadElementContentAsDecimal(null, null)", Param = 17)]
//[Variation("XmlReader.ReadElementContentAsDecimal('a', null)", Param = 18)]
//[Variation("XmlReader.ReadElementContentAsDouble(null, null)", Param = 19)]
//[Variation("XmlReader.ReadElementContentAsDouble('a', null)", Param = 20)]
//[Variation("XmlReader.ReadElementContentAsFloat(null, null)", Param = 21)]
//[Variation("XmlReader.ReadElementContentAsFloat('a', null)", Param = 22)]
//[Variation("XmlReader.ReadElementContentAsInt(null, null)", Param = 23)]
//[Variation("XmlReader.ReadElementContentAsInt('a', null)", Param = 24)]
//[Variation("XmlReader.ReadElementContentAsLong(null, null)", Param = 25)]
//[Variation("XmlReader.ReadElementContentAsLong('a', null)", Param = 26)]
//[Variation("XmlReader.ReadElementContentAsObject(null, null)", Param = 27)]
//[Variation("XmlReader.ReadElementContentAsObject('a', null)", Param = 28)]
//[Variation("XmlReader.ReadElementContentAsString(null, null)", Param = 29)]
//[Variation("XmlReader.ReadElementContentAsString('a', null)", Param = 30)]
//[Variation("XmlReader.ReadToDescendant(null)", Param = 31)]
//[Variation("XmlReader.ReadToDescendant(null, null)", Param = 32)]
//[Variation("XmlReader.ReadToDescendant('a', null)", Param = 33)]
//[Variation("XmlReader.ReadToFollowing(null)", Param = 34)]
//[Variation("XmlReader.ReadToFollowing(null, null)", Param = 35)]
//[Variation("XmlReader.ReadToFollowing('a', null)", Param = 36)]
//[Variation("XmlReader.ReadToNextSibling(null)", Param = 37)]
//[Variation("XmlReader.ReadToNextSibling(null, null)", Param = 38)]
//[Variation("XmlReader.ReadToNextSibling('a', null)", Param = 39)]
//[Variation("XmlReader.ReadValueChunk(null, 0, 0)", Param = 40)]
//[Variation("XmlReader.ReadContentAs(null, null)", Param = 41)]
public int v2()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>"));
string s = "";
try
{
switch (param)
{
case 1: s = DataReader[null]; break;
case 2: s = DataReader[null, null]; break;
case 3: s = DataReader.GetAttribute(null); break;
case 4: s = DataReader.GetAttribute(null, null); break;
case 5: DataReader.MoveToAttribute(null); break;
case 6: DataReader.MoveToAttribute(null, null); break;
case 7: DataReader.ReadContentAsBase64(null, 0, 0); break;
case 8: DataReader.ReadContentAsBinHex(null, 0, 0); break;
case 9: DataReader.ReadElementContentAs(null, null, null, null); break;
case 10: DataReader.ReadElementContentAs(null, null, "a", null); break;
case 11: DataReader.ReadElementContentAsBase64(null, 0, 0); break;
case 12: DataReader.ReadElementContentAsBinHex(null, 0, 0); break;
case 13: DataReader.ReadElementContentAsBoolean(null, null); break;
case 14: DataReader.ReadElementContentAsBoolean("a", null); break;
case 17: DataReader.ReadElementContentAsDecimal(null, null); break;
case 18: DataReader.ReadElementContentAsDecimal("a", null); break;
case 19: DataReader.ReadElementContentAsDouble(null, null); break;
case 20: DataReader.ReadElementContentAsDouble("a", null); break;
case 21: DataReader.ReadElementContentAsFloat(null, null); break;
case 22: DataReader.ReadElementContentAsFloat("a", null); break;
case 23: DataReader.ReadElementContentAsInt(null, null); break;
case 24: DataReader.ReadElementContentAsInt("a", null); break;
case 25: DataReader.ReadElementContentAsLong(null, null); break;
case 26: DataReader.ReadElementContentAsLong("a", null); break;
case 27: DataReader.ReadElementContentAsObject(null, null); break;
case 28: DataReader.ReadElementContentAsObject("a", null); break;
case 29: DataReader.Read(); DataReader.ReadElementContentAsString(null, null); break;
case 30: DataReader.Read(); DataReader.ReadElementContentAsString("a", null); break;
case 31: DataReader.ReadToDescendant(null); break;
case 32: DataReader.ReadToDescendant(null, null); break;
case 33: DataReader.ReadToDescendant("a", null); break;
case 34: DataReader.ReadToFollowing(null); break;
case 35: DataReader.ReadToFollowing(null, null); break;
case 36: DataReader.ReadToFollowing("a", null); break;
case 37: DataReader.ReadToNextSibling(null); break;
case 38: DataReader.ReadToNextSibling(null, null); break;
case 39: DataReader.ReadToNextSibling("a", null); break;
case 40: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(null, 0, 0); break;
case 41: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadContentAs(null, null); break;
}
}
catch (ArgumentNullException)
{
try
{
switch (param)
{
case 2: s = DataReader[null, null]; break;
case 4: s = DataReader.GetAttribute(null, null); break;
case 6: DataReader.MoveToAttribute(null, null); break;
case 7: DataReader.ReadContentAsBase64(null, 0, 0); break;
case 8: DataReader.ReadContentAsBinHex(null, 0, 0); break;
case 9: DataReader.ReadElementContentAs(null, null, null, null); break;
case 10: DataReader.ReadElementContentAs(null, null, "a", null); break;
case 11: DataReader.ReadElementContentAsBase64(null, 0, 0); break;
case 12: DataReader.ReadElementContentAsBinHex(null, 0, 0); break;
case 13: DataReader.ReadElementContentAsBoolean(null, null); break;
case 14: DataReader.ReadElementContentAsBoolean("a", null); break;
case 17: DataReader.ReadElementContentAsDecimal(null, null); break;
case 18: DataReader.ReadElementContentAsDecimal("a", null); break;
case 19: DataReader.ReadElementContentAsDouble(null, null); break;
case 20: DataReader.ReadElementContentAsDouble("a", null); break;
case 21: DataReader.ReadElementContentAsFloat(null, null); break;
case 22: DataReader.ReadElementContentAsFloat("a", null); break;
case 23: DataReader.ReadElementContentAsInt(null, null); break;
case 24: DataReader.ReadElementContentAsInt("a", null); break;
case 25: DataReader.ReadElementContentAsLong(null, null); break;
case 26: DataReader.ReadElementContentAsLong("a", null); break;
case 27: DataReader.ReadElementContentAsObject(null, null); break;
case 28: DataReader.ReadElementContentAsObject("a", null); break;
case 29: DataReader.ReadElementContentAsString(null, null); break;
case 30: DataReader.ReadElementContentAsString("a", null); break;
case 31: DataReader.ReadToDescendant(null); break;
case 32: DataReader.ReadToDescendant(null, null); break;
case 33: DataReader.ReadToDescendant("a", null); break;
case 34: DataReader.ReadToFollowing(null); break;
case 35: DataReader.ReadToFollowing(null, null); break;
case 36: DataReader.ReadToFollowing("a", null); break;
case 37: DataReader.ReadToNextSibling(null); break;
case 38: DataReader.ReadToNextSibling(null, null); break;
case 39: DataReader.ReadToNextSibling("a", null); break;
case 40: DataReader.ReadValueChunk(null, 0, 0); break;
case 41: DataReader.ReadContentAs(null, null); break;
}
}
catch (ArgumentNullException) { return TEST_PASS; }
catch (InvalidOperationException)
{
if (IsSubtreeReader())
return TEST_PASS;
}
}
catch (NotSupportedException)
{
if (IsCustomReader() && (param == 7 || param == 8 || param == 11 || param == 12 || param == 40))
return TEST_PASS;
if ((IsCharCheckingReader() || IsXmlTextReader()) && param == 40)
return TEST_PASS;
return TEST_FAIL;
}
catch (NullReferenceException)
{
try
{
switch (param)
{
case 1: s = DataReader[null]; break;
case 3: s = DataReader.GetAttribute(null); break;
case 5: DataReader.MoveToAttribute(null); break;
}
}
catch (NullReferenceException) { return TEST_PASS; }
}
finally
{
DataReader.Close();
}
return (IsCharCheckingReader() && (param == 7 || param == 8) || IsSubtreeReader()) ? TEST_PASS : TEST_FAIL;
}
//[Variation("XmlReader[-1]", Param = 1)]
//[Variation("XmlReader[0]", Param = 2)]
//[Variation("XmlReader.GetAttribute(-1)", Param = 3)]
//[Variation("XmlReader.GetAttribute(0)", Param = 4)]
//[Variation("XmlReader.MoveToAttribute(-1)", Param = 5)]
//[Variation("XmlReader.MoveToAttribute(0)", Param = 6)]
public int v3()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(xmlStr));
string s = "";
try
{
switch (param)
{
case 1: s = DataReader[-1]; break;
case 2: s = DataReader[0]; break;
case 3: s = DataReader.GetAttribute(-1); break;
case 4: s = DataReader.GetAttribute(0); break;
case 5: DataReader.MoveToAttribute(-1); break;
case 6: DataReader.MoveToAttribute(0); break;
}
}
catch (ArgumentOutOfRangeException)
{
try
{
switch (param)
{
case 1: s = DataReader[-1]; break;
case 2: s = DataReader[0]; break;
case 3: s = DataReader.GetAttribute(-1); break;
case 4: s = DataReader.GetAttribute(0); break;
case 5: DataReader.MoveToAttribute(-1); break;
case 6: DataReader.MoveToAttribute(0); break;
}
}
catch (ArgumentOutOfRangeException) { return TEST_PASS; }
}
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("nsm.AddNamespace('p', null)", Param = 1)]
//[Variation("nsm.RemoveNamespace('p', null)", Param = 2)]
public int v4()
{
int param = (int)CurVariation.Param;
string xml = @"<a>p:foo</a>";
ReloadSource(new StringReader(xml));
DataReader.Read(); DataReader.Read();
XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable);
try
{
if (param == 1)
nsm.AddNamespace("p", null);
else
nsm.RemoveNamespace("p", null);
}
catch (ArgumentNullException)
{
try
{
if (param == 1)
nsm.AddNamespace("p", null);
else
nsm.RemoveNamespace("p", null);
}
catch (ArgumentNullException) { return TEST_PASS; }
}
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("nsm.AddNamespace(null, 'ns1')", Param = 1)]
//[Variation("nsm.RemoveNamespace(null, 'ns1')", Param = 2)]
public int v5()
{
int param = (int)CurVariation.Param;
string xml = @"<a>p:foo</a>";
ReloadSource(new StringReader(xml));
DataReader.Read(); DataReader.Read();
XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable);
try
{
if (param == 1)
nsm.AddNamespace(null, "ns1");
else
nsm.RemoveNamespace(null, "ns1");
}
catch (ArgumentNullException)
{
try
{
if (param == 1)
nsm.AddNamespace(null, "ns1");
else
nsm.RemoveNamespace(null, "ns1");
}
catch (ArgumentNullException) { return TEST_PASS; }
}
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("DataReader.ReadContentAs(null, nsm)")]
public int v6()
{
string xml = @"<a>p:foo</a>";
ReloadSource(new StringReader(xml));
DataReader.Read(); DataReader.Read();
if (IsBinaryReader()) DataReader.Read();
XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable);
nsm.AddNamespace("p", "ns1");
try
{
XmlQualifiedName qname = (XmlQualifiedName)DataReader.ReadContentAs(null, nsm);
}
catch (ArgumentNullException)
{
try
{
XmlQualifiedName qname = (XmlQualifiedName)DataReader.ReadContentAs(null, nsm);
}
catch (ArgumentNullException) { return TEST_PASS; }
catch (InvalidOperationException)
{
if (IsSubtreeReader())
return TEST_PASS;
}
}
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("nsm.AddNamespace('xml', 'ns1')")]
public int v7()
{
string xml = @"<a>p:foo</a>";
ReloadSource(new StringReader(xml));
DataReader.Read(); DataReader.Read();
XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable);
try
{
nsm.AddNamespace("xml", "ns1");
}
catch (ArgumentException)
{
try
{
nsm.AddNamespace("xml", "ns1");
}
catch (ArgumentException) { return TEST_PASS; }
}
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("Test Integrity of all values after Error")]
public int V8()
{
ReloadSourceStr(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>");
try
{
DataReader.Read();
DataReader.MoveToFirstAttribute();
DataReader.ReadValueChunk(null, 0, 0);
}
catch (Exception)
{
CError.Compare(DataReader.AttributeCount, 2, "AttributeCount");
CError.Compare(DataReader.BaseURI, string.Empty, "BaseURI");
CError.Compare(DataReader.CanReadBinaryContent, IsCustomReader() ? false : true, "CanReadBinaryContent");
CError.Compare(DataReader.CanReadValueChunk, (IsCharCheckingReader() || IsCustomReader() || IsXmlTextReader()) ? false : true, "CanReadValueChunk");
CError.Compare(DataReader.Depth, 1, "Depth");
CError.Compare(DataReader.EOF, false, "EOF");
CError.Compare(DataReader.HasAttributes, true, "HasAttributes");
CError.Compare(DataReader.IsDefault, false, "IsDefault");
CError.Compare(DataReader.IsEmptyElement, false, "IsEmptyElement");
if (!(IsCustomReader()))
{
CError.Compare(DataReader.LineNumber, 1, "LN");
CError.Compare(DataReader.LinePosition, 4, "LP");
}
CError.Compare(DataReader.LocalName, "f", "LocalName");
CError.Compare(DataReader.Name, "xmlns:f", "Name");
CError.Compare(DataReader.NamespaceURI, "http://www.w3.org/2000/xmlns/", "NamespaceURI");
CError.Compare(DataReader.NodeType, XmlNodeType.Attribute, "NodeType");
CError.Compare(DataReader.Prefix, "xmlns", "Prefix");
CError.Compare(DataReader.Read(), true, "Read");
CError.Compare(DataReader.ReadInnerXml(), "<c xsi:type=\"f:mytype\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">some content</c>", "ReadInnerXml");
CError.Compare(DataReader.ReadOuterXml(), string.Empty, "ReadOuterXml");
CError.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState");
CError.Compare(DataReader.ReadToDescendant("b"), false, "ReadToDescendant");
CError.Compare(DataReader.ReadToFollowing("b"), false, "ReadToFollowing");
CError.Compare(DataReader.ReadToNextSibling("b"), false, "ReadToNextSibling");
if ((DataReader.Settings != null))
{
CError.Compare(DataReader.Settings.CheckCharacters, true, "CheckCharacters");
CError.Compare(DataReader.Settings.CloseInput, false, "CloseInput");
CError.Compare(DataReader.Settings.ConformanceLevel, ConformanceLevel.Fragment, "ConformanceLevel");
CError.Compare(DataReader.Settings.IgnoreComments, false, "IgnoreComments");
CError.Compare(DataReader.Settings.IgnoreProcessingInstructions, false, "IgnoreProcessingInstructions");
CError.Compare(DataReader.Settings.IgnoreWhitespace, false, "IgnoreWhitespace");
CError.Compare(DataReader.Settings.LineNumberOffset, 0, "LineNumberOffset");
CError.Compare(DataReader.Settings.LinePositionOffset, 0, "LinePositionOffset");
CError.Compare(DataReader.Settings.MaxCharactersInDocument, 0L, "MaxCharactersInDocument");
CError.Compare(DataReader.Settings.NameTable, null, "Settings.NameTable");
}
CError.Compare(DataReader.Value, string.Empty, "Value");
CError.Compare(DataReader.ValueType, typeof(System.String), "ValueType");
CError.Compare(DataReader.XmlLang, string.Empty, "XmlLang");
CError.Compare(DataReader.XmlSpace, XmlSpace.None, "XmlSpace");
CError.Compare(DataReader.GetAttribute("b"), null, "GetAttribute('b')");
CError.Compare(DataReader.Equals(null), false, "Equals(null)");
CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
CError.Compare(DataReader.LookupNamespace("b"), null, "LookupNamespace('b')");
CError.Compare(DataReader.MoveToAttribute("b"), false, "MoveToAttribute('b')");
CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, "MoveToContent()");
CError.Compare(DataReader.MoveToElement(), false, "MoveToElement()");
CError.Compare(DataReader.MoveToFirstAttribute(), false, "MoveToFirstAttribute()");
CError.Compare(DataReader.MoveToNextAttribute(), false, "MoveToNextAttribute()");
CError.Equals(DataReader.HasValue, false, "HasValue");
CError.Equals(DataReader.CanResolveEntity, true, "CanResolveEntity");
CError.Equals(DataReader.ReadAttributeValue(), false, "ReadAttributeValue()");
try
{
DataReader.ResolveEntity();
CError.Compare(false, "failed0");
}
catch (InvalidOperationException) { }
try
{
DataReader.ReadContentAsObject();
CError.Compare(false, "failed1");
}
catch (InvalidOperationException) { }
try
{
DataReader.ReadContentAsString();
CError.Compare(false, "failed2");
}
catch (InvalidOperationException) { }
}
return TEST_PASS;
}
//[Variation("2.Test Integrity of all values after Dispose")]
public int V9a()
{
ReloadSource();
DataReader.Dispose();
DataReader.Dispose();
DataReader.Dispose();
CError.Compare(DataReader.AttributeCount, 0, "AttributeCount");
CError.Compare(DataReader.BaseURI, string.Empty, "BaseURI");
CError.Compare(DataReader.CanReadBinaryContent, IsCustomReader() ? false : true, "CanReadBinaryContent");
CError.Compare(DataReader.CanReadValueChunk, (IsCharCheckingReader() || IsCustomReader() || IsXmlTextReader()) ? false : true, "CanReadValueChunk");
CError.Compare(DataReader.Depth, 0, "Depth");
CError.Compare(DataReader.EOF, IsSubtreeReader() ? true : false, "EOF");
CError.Compare(DataReader.HasAttributes, false, "HasAttributes");
CError.Compare(DataReader.IsDefault, false, "IsDefault");
CError.Compare(DataReader.IsEmptyElement, false, "IsEmptyElement");
if (!IsCustomReader())
{
CError.Compare(DataReader.LineNumber, 0, "LN");
CError.Compare(DataReader.LinePosition, 0, "LP");
}
CError.Compare(DataReader.LocalName, String.Empty, "LocalName");
CError.Compare(DataReader.Name, String.Empty, "Name");
CError.Compare(DataReader.NamespaceURI, String.Empty, "NamespaceURI");
CError.Compare(DataReader.NodeType, XmlNodeType.None, "NodeType");
CError.Compare(DataReader.Prefix, String.Empty, "Prefix");
CError.Compare(DataReader.Read(), IsCharCheckingReader(), "Read");
CError.Compare(DataReader.ReadInnerXml(), String.Empty, "ReadInnerXml");
CError.Compare(DataReader.ReadOuterXml(), String.Empty, "ReadOuterXml");
CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState");
CError.Compare(DataReader.ReadToDescendant("b"), false, "ReadToDescendant");
CError.Compare(DataReader.ReadToFollowing("b"), false, "ReadToFollowing");
CError.Compare(DataReader.ReadToNextSibling("b"), false, "ReadToNextSibling");
if ((DataReader.Settings != null))
{
CError.Compare(DataReader.Settings.CheckCharacters, true, "CheckCharacters");
CError.Compare(DataReader.Settings.CloseInput, false, "CloseInput");
CError.Compare(DataReader.Settings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel");
CError.Compare(DataReader.Settings.IgnoreComments, false, "IgnoreComments");
CError.Compare(DataReader.Settings.IgnoreProcessingInstructions, false, "IgnoreProcessingInstructions");
CError.Compare(DataReader.Settings.IgnoreWhitespace, false, "IgnoreWhitespace");
CError.Compare(DataReader.Settings.LineNumberOffset, 0, "LineNumberOffset");
CError.Compare(DataReader.Settings.LinePositionOffset, 0, "LinePositionOffset");
CError.Compare(DataReader.Settings.MaxCharactersInDocument, 0L, "MaxCharactersInDocument");
CError.Compare(DataReader.Settings.NameTable, null, "Settings.NameTable");
}
CError.Compare(DataReader.Value, string.Empty, "Value");
CError.Compare(DataReader.ValueType, typeof(System.String), "ValueType");
CError.Compare(DataReader.XmlLang, string.Empty, "XmlLang");
CError.Compare(DataReader.XmlSpace, XmlSpace.None, "XmlSpace");
CError.Compare(DataReader.GetAttribute("b"), null, "GetAttribute('b')");
CError.Compare(DataReader.Equals(null), false, "Equals(null)");
CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
CError.Compare(DataReader.LookupNamespace("b"), null, "LookupNamespace('b')");
CError.Compare(DataReader.MoveToAttribute("b"), false, "MoveToAttribute('b')");
CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, "MoveToContent()");
CError.Compare(DataReader.MoveToElement(), false, "MoveToElement()");
CError.Compare(DataReader.MoveToFirstAttribute(), false, "MoveToFirstAttribute()");
CError.Compare(DataReader.MoveToNextAttribute(), false, "MoveToNextAttribute()");
CError.Equals(DataReader.HasValue, false, "HasValue");
CError.Equals(DataReader.CanResolveEntity, true, "CanResolveEntity");
CError.Equals(DataReader.ReadAttributeValue(), false, "ReadAttributeValue()");
try
{
DataReader.ResolveEntity();
CError.Compare(false, "failed0");
}
catch (InvalidOperationException) { }
try
{
DataReader.ReadContentAsObject();
CError.Compare(false, "failed1");
}
catch (InvalidOperationException) { }
try
{
DataReader.ReadContentAsString();
CError.Compare(false, "failed2");
}
catch (InvalidOperationException) { }
return TEST_PASS;
}
//[Variation("XmlCharType::IsName, IsNmToken")]
public int v10()
{
CError.Compare(XmlReader.IsName("a"), "Error1");
CError.Compare(!XmlReader.IsName("@a"), "Error2");
CError.Compare(!XmlReader.IsName("b@a"), "Error3");
CError.Compare(XmlReader.IsNameToken("a"), "Error4");
CError.Compare(!XmlReader.IsNameToken("@a"), "Error5");
CError.Compare(!XmlReader.IsNameToken("b@a"), "Error6");
return TEST_PASS;
}
//[Variation("XmlReader[String.Empty])", Param = 1)]
//[Variation("XmlReader[String.Empty, String.Empty]", Param = 2)]
//[Variation("XmlReader.GetAttribute(String.Empty)", Param = 3)]
//[Variation("XmlReader.GetAttribute(String.Empty, String.Empty)", Param = 4)]
//[Variation("XmlReader.MoveToAttribute(String.Empty)", Param = 5)]
//[Variation("XmlReader.MoveToAttribute(String.Empty, String.Empty)", Param = 6)]
//[Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, String.Empty, String.Empty)", Param = 9)]
//[Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, 'a', String.Empty)", Param = 10)]
//[Variation("XmlReader.ReadElementContentAsBoolean(String.Empty, String.Empty)", Param = 13)]
//[Variation("XmlReader.ReadElementContentAsBoolean('a', String.Empty)", Param = 14)]
//[Variation("XmlReader.ReadElementContentAsDateTime(String.Empty, String.Empty)", Param = 15)]
//[Variation("XmlReader.ReadElementContentAsDateTime('a', String.Empty)", Param = 16)]
//[Variation("XmlReader.ReadElementContentAsDecimal(String.Empty, String.Empty)", Param = 17)]
//[Variation("XmlReader.ReadElementContentAsDecimal('a', String.Empty)", Param = 18)]
//[Variation("XmlReader.ReadElementContentAsDouble(String.Empty, String.Empty)", Param = 19)]
//[Variation("XmlReader.ReadElementContentAsDouble('a', String.Empty)", Param = 20)]
//[Variation("XmlReader.ReadElementContentAsFloat(String.Empty, String.Empty)", Param = 21)]
//[Variation("XmlReader.ReadElementContentAsFloat('a', String.Empty)", Param = 22)]
//[Variation("XmlReader.ReadElementContentAsInt(String.Empty, String.Empty)", Param = 23)]
//[Variation("XmlReader.ReadElementContentAsInt('a', String.Empty)", Param = 24)]
//[Variation("XmlReader.ReadElementContentAsLong(String.Empty, String.Empty)", Param = 25)]
//[Variation("XmlReader.ReadElementContentAsLong('a', String.Empty)", Param = 26)]
//[Variation("XmlReader.ReadElementContentAsObject(String.Empty, String.Empty)", Param = 27)]
//[Variation("XmlReader.ReadElementContentAsObject('a', String.Empty)", Param = 28)]
//[Variation("XmlReader.ReadElementContentAsString(String.Empty, String.Empty)", Param = 29)]
//[Variation("XmlReader.ReadElementContentAsString('a', String.Empty)", Param = 30)]
//[Variation("XmlReader.ReadToDescendant(String.Empty)", Param = 31)]
//[Variation("XmlReader.ReadToDescendant(String.Empty, String.Empty)", Param = 32)]
//[Variation("XmlReader.ReadToDescendant('a', String.Empty)", Param = 33)]
//[Variation("XmlReader.ReadToFollowing(String.Empty)", Param = 34)]
//[Variation("XmlReader.ReadToFollowing(String.Empty, String.Empty)", Param = 35)]
//[Variation("XmlReader.ReadToFollowing('a', String.Empty)", Param = 36)]
//[Variation("XmlReader.ReadToNextSibling(String.Empty)", Param = 37)]
//[Variation("XmlReader.ReadToNextSibling(String.Empty, String.Empty)", Param = 38)]
//[Variation("XmlReader.ReadToNextSibling('a', String.Empty)", Param = 39)]
public int v11()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(xmlStr));
DataReader.Read();
if (IsBinaryReader()) DataReader.Read();
string s = "";
switch (param)
{
case 1: s = DataReader[String.Empty]; return TEST_PASS;
case 2: s = DataReader[String.Empty, String.Empty]; return TEST_PASS;
case 3: s = DataReader.GetAttribute(String.Empty); return TEST_PASS;
case 4: s = DataReader.GetAttribute(String.Empty, String.Empty); return TEST_PASS;
case 5: DataReader.MoveToAttribute(String.Empty); return TEST_PASS;
case 6: DataReader.MoveToAttribute(String.Empty, String.Empty); return TEST_PASS;
case 10: DataReader.ReadElementContentAs(typeof(String), null, "a", String.Empty); return TEST_PASS;
case 28: DataReader.ReadElementContentAsObject("a", String.Empty); return TEST_PASS;
case 30: DataReader.ReadElementContentAsString("a", String.Empty); return TEST_PASS;
case 33: DataReader.ReadToDescendant("a", String.Empty); return TEST_PASS;
case 36: DataReader.ReadToFollowing("a", String.Empty); return TEST_PASS;
case 39: DataReader.ReadToNextSibling("a", String.Empty); return TEST_PASS;
}
try
{
switch (param)
{
case 9: DataReader.ReadElementContentAs(typeof(String), null, String.Empty, String.Empty); break;
case 13: DataReader.ReadElementContentAsBoolean(String.Empty, String.Empty); break;
case 14: DataReader.ReadElementContentAsBoolean("a", String.Empty); break;
case 17: DataReader.ReadElementContentAsDecimal(String.Empty, String.Empty); break;
case 18: DataReader.ReadElementContentAsDecimal("a", String.Empty); break;
case 19: DataReader.ReadElementContentAsDouble(String.Empty, String.Empty); break;
case 20: DataReader.ReadElementContentAsDouble("a", String.Empty); break;
case 21: DataReader.ReadElementContentAsFloat(String.Empty, String.Empty); break;
case 22: DataReader.ReadElementContentAsFloat("a", String.Empty); break;
case 23: DataReader.ReadElementContentAsInt(String.Empty, String.Empty); break;
case 24: DataReader.ReadElementContentAsInt("a", String.Empty); break;
case 25: DataReader.ReadElementContentAsLong(String.Empty, String.Empty); break;
case 26: DataReader.ReadElementContentAsLong("a", String.Empty); break;
case 27: DataReader.ReadElementContentAsObject(String.Empty, String.Empty); break;
case 29: DataReader.ReadElementContentAsString(String.Empty, String.Empty); break;
case 31: DataReader.ReadToDescendant(String.Empty); break;
case 32: DataReader.ReadToDescendant(String.Empty, String.Empty); break;
case 34: DataReader.ReadToFollowing(String.Empty); break;
case 35: DataReader.ReadToFollowing(String.Empty, String.Empty); break;
case 37: DataReader.ReadToNextSibling(String.Empty); break;
case 38: DataReader.ReadToNextSibling(String.Empty, String.Empty); break;
}
}
catch (ArgumentException)
{
try
{
switch (param)
{
case 9: DataReader.ReadElementContentAs(typeof(String), null, String.Empty, String.Empty); break;
case 13: DataReader.ReadElementContentAsBoolean(String.Empty, String.Empty); break;
case 14: DataReader.ReadElementContentAsBoolean("a", String.Empty); break;
case 17: DataReader.ReadElementContentAsDecimal(String.Empty, String.Empty); break;
case 18: DataReader.ReadElementContentAsDecimal("a", String.Empty); break;
case 19: DataReader.ReadElementContentAsDouble(String.Empty, String.Empty); break;
case 20: DataReader.ReadElementContentAsDouble("a", String.Empty); break;
case 21: DataReader.ReadElementContentAsFloat(String.Empty, String.Empty); break;
case 22: DataReader.ReadElementContentAsFloat("a", String.Empty); break;
case 23: DataReader.ReadElementContentAsInt(String.Empty, String.Empty); break;
case 24: DataReader.ReadElementContentAsInt("a", String.Empty); break;
case 25: DataReader.ReadElementContentAsLong(String.Empty, String.Empty); break;
case 26: DataReader.ReadElementContentAsLong("a", String.Empty); break;
case 27: DataReader.ReadElementContentAsObject(String.Empty, String.Empty); break;
case 29: DataReader.ReadElementContentAsString(String.Empty, String.Empty); break;
case 31: DataReader.ReadToDescendant(String.Empty); break;
case 32: DataReader.ReadToDescendant(String.Empty, String.Empty); break;
case 34: DataReader.ReadToFollowing(String.Empty); break;
case 35: DataReader.ReadToFollowing(String.Empty, String.Empty); break;
case 37: DataReader.ReadToNextSibling(String.Empty); break;
case 38: DataReader.ReadToNextSibling(String.Empty, String.Empty); break;
}
}
catch (ArgumentException) { return TEST_PASS; }
}
catch (NotSupportedException)
{
if (IsCustomReader() && (param == 7 || param == 8 || param == 11 || param == 12))
return TEST_PASS;
return TEST_FAIL;
}
catch (FormatException) { return TEST_PASS; }
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation(Desc = "XmlReaderSettings.ConformanceLevel - invalid values", Priority = 2)]
public int var12()
{
return TEST_SKIPPED;
}
//[Variation(Desc = "XmlReaderSettings.LineNumberOffset - invalid values", Param = 1)]
//[Variation(Desc = "XmlReaderSettings.LinePositionOffset - invalid values", Param = 2)]
public int var13()
{
int param = (int)CurVariation.Param;
XmlReaderSettings rs = new XmlReaderSettings();
if (param == 1)
rs.LineNumberOffset = -10;
else
rs.LinePositionOffset = -10;
return TEST_PASS;
}
//[Variation("XmlReader.ReadContentAsBase64(b, -1, 0)", Param = 1)]
//[Variation("XmlReader.ReadContentAsBinHex(b, -1, 0)", Param = 2)]
//[Variation("XmlReader.ReadContentAsBase64(b, 0, -1)", Param = 3)]
//[Variation("XmlReader.ReadContentAsBinHex(b, 0, -1)", Param = 4)]
//[Variation("XmlReader.ReadContentAsBase64(b, 0, 2)", Param = 5)]
//[Variation("XmlReader.ReadContentAsBinHex(b, 0, 2)", Param = 6)]
//[Variation("XmlReader.ReadElementContentAsBase64(b, -1, 0)", Param = 7)]
//[Variation("XmlReader.ReadElementContentAsBinHex(b, -1, 0)", Param = 8)]
//[Variation("XmlReader.ReadValueChunk(c, 0, -1)", Param = 9)]
//[Variation("XmlReader.ReadElementContentAsBase64(b, 0, -1)", Param = 10)]
//[Variation("XmlReader.ReadElementContentAsBinHex(b, 0, -1)", Param = 11)]
//[Variation("XmlReader.ReadValueChunk(c, 0, -1)", Param = 12)]
//[Variation("XmlReader.ReadElementContentAsBase64(b, 0, 2)", Param = 13)]
//[Variation("XmlReader.ReadElementContentAsBinHex(b, 0, 2)", Param = 14)]
//[Variation("XmlReader.ReadValueChunk(c, 0, 2)", Param = 15)]
//[Variation("XmlReader.ReadValueChunk(c, -1, 1)", Param = 16)]
public int v14()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>"));
char[] c = new char[1];
byte[] b = new byte[1];
try
{
switch (param)
{
case 1: DataReader.ReadContentAsBase64(b, -1, 0); break;
case 2: DataReader.ReadContentAsBinHex(b, -1, 0); break;
case 3: DataReader.ReadContentAsBase64(b, 0, -1); break;
case 4: DataReader.ReadContentAsBinHex(b, 0, -1); break;
case 5: DataReader.ReadContentAsBase64(b, 0, 2); break;
case 6: DataReader.ReadContentAsBinHex(b, 0, 2); break;
case 7: DataReader.ReadElementContentAsBase64(b, -1, 0); break;
case 8: DataReader.ReadElementContentAsBinHex(b, -1, 0); break;
case 9: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, -1); break;
case 10: DataReader.ReadElementContentAsBase64(b, 0, -10); break;
case 11: DataReader.ReadElementContentAsBinHex(b, 0, -1); break;
case 12: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, -1); break;
case 13: DataReader.ReadElementContentAsBase64(b, 0, 2); break;
case 14: DataReader.ReadElementContentAsBinHex(b, 0, 2); break;
case 15: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, 2); break;
case 16: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, -1, 2); break;
}
}
catch (ArgumentOutOfRangeException)
{
try
{
switch (param)
{
case 1: DataReader.ReadContentAsBase64(b, -1, 0); break;
case 2: DataReader.ReadContentAsBinHex(b, -1, 0); break;
case 3: DataReader.ReadContentAsBase64(b, 0, -1); break;
case 4: DataReader.ReadContentAsBinHex(b, 0, -1); break;
case 5: DataReader.ReadContentAsBase64(b, 0, 2); break;
case 6: DataReader.ReadContentAsBinHex(b, 0, 2); break;
case 7: DataReader.ReadElementContentAsBase64(b, -1, 0); break;
case 8: DataReader.ReadElementContentAsBinHex(b, -1, 0); break;
case 9: DataReader.ReadValueChunk(c, 0, -1); break;
case 10: DataReader.ReadElementContentAsBase64(b, 0, -10); break;
case 11: DataReader.ReadElementContentAsBinHex(b, 0, -1); break;
case 12: DataReader.ReadValueChunk(c, 0, -1); break;
case 13: DataReader.ReadElementContentAsBase64(b, 0, 2); break;
case 14: DataReader.ReadElementContentAsBinHex(b, 0, 2); break;
case 15: DataReader.ReadValueChunk(c, 0, 2); break;
case 16: DataReader.ReadValueChunk(c, -1, 2); break;
}
}
catch (ArgumentOutOfRangeException) { return TEST_PASS; }
}
catch (NotSupportedException) { if (IsCustomReader() || IsCharCheckingReader() || IsXmlTextReader()) return TEST_PASS; }
finally
{
DataReader.Close();
}
return ((IsCharCheckingReader() && param >= 1 && param <= 6) || IsSubtreeReader()) ? TEST_PASS : TEST_FAIL;
}
//[Variation(Desc = "DataReader.Settings.LineNumberOffset - readonly", Param = 1)]
//[Variation(Desc = "DataReader.Settings.LinePositionOffset - readonly", Param = 2)]
//[Variation(Desc = "DataReader.Settings.CheckCharacters - readonly", Param = 3)]
//[Variation(Desc = "DataReader.Settings.CloseInput - readonly", Param = 4)]
//[Variation(Desc = "DataReader.Settings.ConformanceLevel - readonly", Param = 5)]
//[Variation(Desc = "DataReader.Settings.IgnoreComments - readonly", Param = 6)]
//[Variation(Desc = "DataReader.Settings.IgnoreProcessingInstructions - readonly", Param = 7)]
//[Variation(Desc = "DataReader.Settings.IgnoreWhitespace - readonly", Param = 8)]
//[Variation(Desc = "DataReader.Settings.MaxCharactersInDocument - readonly", Param = 9)]
//[Variation(Desc = "DataReader.Settings.ProhibitDtd - readonly", Param = 10)]
//[Variation(Desc = "DataReader.Settings.XmlResolver - readonly", Param = 11)]
//[Variation(Desc = "DataReader.Settings.MaxCharactersFromEntities - readonly", Param = 12)]
//[Variation(Desc = "DataReader.Settings.DtdProcessing - readonly", Param = 13)]
public int var15()
{
if (IsCustomReader() || IsXmlTextReader()) return TEST_SKIPPED;
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>"));
try
{
switch (param)
{
case 1: DataReader.Settings.LineNumberOffset = -10; break;
case 2: DataReader.Settings.LinePositionOffset = -10; break;
case 3: DataReader.Settings.CheckCharacters = false; break;
case 4: DataReader.Settings.CloseInput = false; break;
case 5: DataReader.Settings.ConformanceLevel = ConformanceLevel.Fragment; break;
case 6: DataReader.Settings.IgnoreComments = false; break;
case 7: DataReader.Settings.IgnoreProcessingInstructions = false; break;
case 8: DataReader.Settings.IgnoreWhitespace = false; break;
case 9: DataReader.Settings.MaxCharactersInDocument = -10; break;
case 12: DataReader.Settings.MaxCharactersFromEntities = -10; break;
case 13: DataReader.Settings.DtdProcessing = (DtdProcessing)(-10); break;
}
}
catch (XmlException)
{
try
{
switch (param)
{
case 1: DataReader.Settings.LineNumberOffset = -10; break;
case 2: DataReader.Settings.LinePositionOffset = -10; break;
case 3: DataReader.Settings.CheckCharacters = false; break;
case 4: DataReader.Settings.CloseInput = false; break;
case 5: DataReader.Settings.ConformanceLevel = ConformanceLevel.Fragment; break;
case 6: DataReader.Settings.IgnoreComments = false; break;
case 7: DataReader.Settings.IgnoreProcessingInstructions = false; break;
case 8: DataReader.Settings.IgnoreWhitespace = false; break;
case 9: DataReader.Settings.MaxCharactersInDocument = -10; break;
case 12: DataReader.Settings.MaxCharactersFromEntities = -10; break;
case 13: DataReader.Settings.DtdProcessing = (DtdProcessing)(-10); break;
}
}
catch (XmlException) { return TEST_PASS; }
}
return TEST_FAIL;
}
//[Variation("Readcontentas in close state and call ReadContentAsBase64", Param = 1)]
//[Variation("Readcontentas in close state and call ReadContentAsBinHex", Param = 2)]
//[Variation("Readcontentas in close state and call ReadElementContentAsBase64", Param = 3)]
//[Variation("Readcontentas in close state and call ReadElementContentAsBinHex", Param = 4)]
//[Variation("Readcontentas in close state and call ReadValueChunk", Param = 5)]
//[Variation("XmlReader[a])", Param = 6)]
//[Variation("XmlReader[a, b]", Param = 7)]
//[Variation("XmlReader.GetAttribute(a)", Param = 8)]
//[Variation("XmlReader.GetAttribute(a, b)", Param = 9)]
//[Variation("XmlReader.MoveToAttribute(a)", Param = 10)]
//[Variation("XmlReader.MoveToAttribute(a, b)", Param = 11)]
//[Variation("XmlReader.ReadElementContentAs(typeof(String), null)", Param = 12)]
//[Variation("XmlReader.ReadElementContentAsObject()", Param = 13)]
//[Variation("XmlReader.ReadElementContentAsString()", Param = 14)]
//[Variation("XmlReader.ReadToDescendant(a, b)", Param = 15)]
//[Variation("XmlReader.ReadToFollowing(a, b)", Param = 16)]
//[Variation("XmlReader.ReadToNextSibling(a, b)", Param = 17)]
//[Variation("XmlReader.ReadElementContentAs(typeof(String), null)", Param = 18)]
//[Variation("XmlReader.ReadElementContentAsBoolean(a,b)", Param = 19)]
//[Variation("XmlReader.ReadElementContentAsBoolean()", Param = 20)]
//[Variation("XmlReader.ReadElementContentAsDateTime(a,b)", Param = 21)]
//[Variation("XmlReader.ReadElementContentAsDateTime()", Param = 22)]
//[Variation("XmlReader.ReadElementContentAsDecimal(a,b)", Param = 23)]
//[Variation("XmlReader.ReadElementContentAsDecimal()", Param = 24)]
//[Variation("XmlReader.ReadElementContentAsDouble(a,b)", Param = 25)]
//[Variation("XmlReader.ReadElementContentAsDouble()", Param = 26)]
//[Variation("XmlReader.ReadElementContentAsFloat(a,b)", Param = 27)]
//[Variation("XmlReader.ReadElementContentAsFloat()", Param = 28)]
//[Variation("XmlReader.ReadElementContentAsInt(a,b)", Param = 29)]
//[Variation("XmlReader.ReadElementContentAsInt()", Param = 30)]
//[Variation("XmlReader.ReadElementContentAsLong(a,b)", Param = 31)]
//[Variation("XmlReader.ReadElementContentAsLong()", Param = 32)]
//[Variation("XmlReader.ReadElementContentAsObject(a,b)", Param = 33)]
//[Variation("XmlReader.ReadElementContentAsString(a,b)", Param = 34)]
//[Variation("XmlReader.ReadToDescendant(a)", Param = 35)]
//[Variation("XmlReader.ReadToFollowing(a)", Param = 36)]
//[Variation("XmlReader.ReadToNextSibling(a)", Param = 37)]
//[Variation("XmlReader.ReadAttributeValue()", Param = 38)]
//[Variation("XmlReader.ResolveEntity()", Param = 39)]
public int V16()
{
int param = (int)CurVariation.Param;
byte[] buffer = new byte[3];
int[] skipParams = new int[] { 1, 2, 3, 4, 5, 35, 36, 37, 38 };
char[] chars = new char[3];
string s = "";
ReloadSource(new StringReader("<elem0>123 $%^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>"));
DataReader.Read();
DataReader.Close();
try
{
DataReader.ReadContentAs(typeof(string), null);
}
catch (InvalidOperationException)
{
try
{
switch (param)
{
case 1: CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 3), 0, "size"); break;
case 2: CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 3), 0, "size"); break;
case 3: CError.Compare(DataReader.ReadElementContentAsBase64(buffer, 0, 3), 0, "size"); break;
case 4: CError.Compare(DataReader.ReadElementContentAsBinHex(buffer, 0, 3), 0, "size"); break;
case 5: CError.Compare(DataReader.ReadValueChunk(chars, 0, 3), 0, "size"); break;
case 6: s = DataReader["a"]; return TEST_PASS;
case 7: s = DataReader["a", "b"]; return TEST_PASS;
case 8: s = DataReader.GetAttribute("a"); return TEST_PASS;
case 9: s = DataReader.GetAttribute("a", "b"); return TEST_PASS;
case 10: DataReader.MoveToAttribute("a"); return TEST_PASS;
case 11: DataReader.MoveToAttribute("a", "b"); return TEST_PASS;
case 12: DataReader.ReadElementContentAs(typeof(String), null, "a", "b"); return TEST_PASS;
case 13: DataReader.ReadElementContentAsObject(); return TEST_PASS;
case 14: DataReader.ReadElementContentAsString(); return TEST_PASS;
case 15: DataReader.ReadToDescendant("a", "b"); return TEST_PASS;
case 16: DataReader.ReadToFollowing("a", "b"); return TEST_PASS;
case 17: DataReader.ReadToNextSibling("a", "b"); return TEST_PASS;
case 18: DataReader.ReadElementContentAs(typeof(String), null); break;
case 19: DataReader.ReadElementContentAsBoolean("a", "b"); break;
case 20: DataReader.ReadElementContentAsBoolean(); break;
case 23: DataReader.ReadElementContentAsDecimal("a", "b"); break;
case 24: DataReader.ReadElementContentAsDecimal(); break;
case 25: DataReader.ReadElementContentAsDouble("a", "b"); break;
case 26: DataReader.ReadElementContentAsDouble(); break;
case 27: DataReader.ReadElementContentAsFloat("a", "b"); break;
case 28: DataReader.ReadElementContentAsFloat(); break;
case 29: DataReader.ReadElementContentAsInt("a", "b"); break;
case 30: DataReader.ReadElementContentAsInt(); break;
case 31: DataReader.ReadElementContentAsLong(); break;
case 32: DataReader.ReadElementContentAsLong("a", "b"); break;
case 33: DataReader.ReadElementContentAsObject("a", "b"); break;
case 34: DataReader.ReadElementContentAsString("a", "b"); break;
case 35: DataReader.ReadToDescendant("a"); break;
case 36: DataReader.ReadToFollowing("a"); break;
case 37: DataReader.ReadToNextSibling("a"); break;
case 38: DataReader.ReadAttributeValue(); break;
case 39: DataReader.ResolveEntity(); break;
}
}
catch (NotSupportedException) { return TEST_PASS; }
catch (InvalidOperationException) { return TEST_PASS; }
catch (XmlException) { return TEST_PASS; }
}
foreach (int p in skipParams)
{
if (param == p) return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("Assertion when creating validating reader from a XmlReader.Create reader")]
public int Dev10_67883()
{
return TEST_SKIPPED;
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://fluentvalidation.codeplex.com
#endregion
namespace FluentValidation.Tests.Mvc5 {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Internal;
using Moq;
using Mvc;
using NUnit.Framework;
using Validators;
[TestFixture]
public class ClientsideMessageTester {
InlineValidator<TestModel> validator;
ControllerContext controllerContext;
[SetUp]
public void Setup() {
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
validator = new InlineValidator<TestModel>();
controllerContext = CreateControllerContext();
}
[Test]
public void NotNull_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).NotNull();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must not be empty.");
}
[Test]
public void NotEmpty_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).NotEmpty();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' should not be empty.");
}
[Test]
public void RegexValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Matches("\\d");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' is not in the correct format.");
}
[Test]
public void EmailValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).EmailAddress();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' is not a valid email address.");
}
[Test]
public void LengthValidator_uses_simplified_message_for_clientside_validatation() {
validator.RuleFor(x => x.Name).Length(1, 10);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must be between 1 and 10 characters.");
}
[Test]
public void InclusiveBetween_validator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Id).InclusiveBetween(1, 10);
var clientRules = GetClientRules(x => x.Id);
clientRules.Any(x => x.ErrorMessage == "'Id' must be between 1 and 10.").ShouldBeTrue();
}
[Test]
public void EqualValidator_with_property_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Equal(x => x.Name2);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' should be equal to 'Name2'.");
}
[Test]
public void Should_not_munge_custom_message() {
validator.RuleFor(x => x.Name).Length(1, 10).WithMessage("Foo");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Foo");
}
[Test]
public void ExactLengthValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Length(5);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must be 5 characters in length.");
}
[Test]
public void Custom_validation_message_with_placeholders() {
validator.RuleFor(x => x.Name).NotNull().WithMessage("{PropertyName} is null.");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Name is null.");
}
[Test]
public void Custom_validation_message_for_length() {
validator.RuleFor(x => x.Name).Length(1, 5).WithMessage("Must be between {MinLength} and {MaxLength}.");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Must be between 1 and 5.");
}
[Test]
public void Supports_custom_clientside_rules_with_IClientValidatable() {
validator.RuleFor(x => x.Name).SetValidator(new TestPropertyValidator());
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("foo");
}
[Test]
public void CreditCard_creates_clientside_message() {
validator.RuleFor(x => x.Name).CreditCard();
var clientrule = GetClientRule(x => x.Name);
clientrule.ErrorMessage.ShouldEqual("'Name' is not a valid credit card number.");
}
[Test]
public void Overrides_property_name_for_clientside_rule() {
validator.RuleFor(x => x.Name).NotNull().WithName("Foo");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Foo' must not be empty.");
}
[Test]
public void Overrides_property_name_for_clientside_rule_using_localized_name() {
validator.RuleFor(x => x.Name).NotNull().WithLocalizedName(() => TestMessages.notnull_error);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Localised Error' must not be empty.");
}
[Test]
public void Overrides_property_name_for_non_nullable_value_type() {
validator.RuleFor(x => x.Id).NotNull().WithName("Foo");
var clientRule = GetClientRule(x => x.Id);
clientRule.ErrorMessage.ShouldEqual("'Foo' must not be empty.");
}
[Test]
public void Should_only_use_rules_from_Default_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
// Client-side rules are only generated from the default ruleset
// unless explicitly specified.
// so in this case, only the second NotNull should make it through
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(1);
rules.Single().ErrorMessage.ShouldEqual("second");
}
[Test]
public void Should_use_rules_from_specified_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
var filter = new RuleSetForClientSideMessagesAttribute("Foo");
filter.OnActionExecuting(new ActionExecutingContext { HttpContext = controllerContext.HttpContext });
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(1);
rules.Single().ErrorMessage.ShouldEqual("first");
}
[Test]
public void Should_use_rules_from_multiple_rulesets() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleSet("Bar", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("third");
var filter = new RuleSetForClientSideMessagesAttribute("Foo", "Bar");
filter.OnActionExecuting(new ActionExecutingContext {HttpContext = controllerContext.HttpContext});
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(2);
}
[Test]
public void Should_use_rules_from_default_ruleset_and_specified_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleSet("Bar", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("third");
var filter = new RuleSetForClientSideMessagesAttribute("Foo", "default");
filter.OnActionExecuting(new ActionExecutingContext { HttpContext = controllerContext.HttpContext });
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(2);
}
private ModelClientValidationRule GetClientRule(Expression<Func<TestModel, object>> expression) {
var propertyName = expression.GetMember().Name;
var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);
var factory = new Mock<IValidatorFactory>();
factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);
var provider = new FluentValidationModelValidatorProvider(factory.Object);
var propertyValidator = provider.GetValidators(metadata, controllerContext).Single();
var clientRule = propertyValidator.GetClientValidationRules().Single();
return clientRule;
}
private IEnumerable<ModelClientValidationRule> GetClientRules(Expression<Func<TestModel, object>> expression ) {
var propertyName = expression.GetMember().Name;
var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);
var factory = new Mock<IValidatorFactory>();
factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);
var provider = new FluentValidationModelValidatorProvider(factory.Object);
var propertyValidators = provider.GetValidators(metadata, controllerContext);
return (propertyValidators.SelectMany(x => x.GetClientValidationRules())).ToList();
}
private ControllerContext CreateControllerContext() {
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(x => x.Items).Returns(new Hashtable());
return new ControllerContext { HttpContext = httpContext.Object };
}
private class TestModel {
public string Name { get; set; }
public string Name2 { get; set; }
public int Id { get; set; }
}
private class TestPropertyValidator : PropertyValidator, IClientValidatable {
public TestPropertyValidator()
: base("foo") {
}
protected override bool IsValid(PropertyValidatorContext context) {
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
yield return new ModelClientValidationRule { ErrorMessage = this.ErrorMessageSource.GetString() };
}
}
}
}
| |
// 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.
/*=============================================================================
**
** Class: Stack
**
** Purpose: Represents a simple last-in-first-out (LIFO)
** non-generic collection of objects.
**
**
=============================================================================*/
using System.Diagnostics;
namespace System.Collections
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Stack : ICollection, ICloneable
{
private object[] _array; // Storage for stack elements. Do not rename (binary serialization)
private int _size; // Number of items in the stack. Do not rename (binary serialization)
private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization)
private const int _defaultCapacity = 10;
public Stack()
{
_array = new object[_defaultCapacity];
_size = 0;
_version = 0;
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (initialCapacity < _defaultCapacity)
initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
_array = new object[initialCapacity];
_size = 0;
_version = 0;
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
//
public Stack(ICollection col) : this((col == null ? 32 : col.Count))
{
if (col == null)
throw new ArgumentNullException(nameof(col));
IEnumerator en = col.GetEnumerator();
while (en.MoveNext())
Push(en.Current);
}
public virtual int Count
{
get
{
return _size;
}
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual object SyncRoot => this;
// Removes all Objects from the Stack.
public virtual void Clear()
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
_version++;
}
public virtual object Clone()
{
Stack s = new Stack(_size);
s._size = _size;
Array.Copy(_array, 0, s._array, 0, _size);
s._version = _version;
return s;
}
public virtual bool Contains(object obj)
{
int count = _size;
while (count-- > 0)
{
if (obj == null)
{
if (_array[count] == null)
return true;
}
else if (_array[count] != null && _array[count].Equals(obj))
{
return true;
}
}
return false;
}
// Copies the stack into an array.
public virtual void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < _size)
throw new ArgumentException(SR.Argument_InvalidOffLen);
int i = 0;
object[] objArray = array as object[];
if (objArray != null)
{
while (i < _size)
{
objArray[i + index] = _array[_size - i - 1];
i++;
}
}
else
{
while (i < _size)
{
array.SetValue(_array[_size - i - 1], i + index);
i++;
}
}
}
// Returns an IEnumerator for this Stack.
public virtual IEnumerator GetEnumerator()
{
return new StackEnumerator(this);
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public virtual object Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
return _array[_size - 1];
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public virtual object Pop()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
_version++;
object obj = _array[--_size];
_array[_size] = null; // Free memory quicker.
return obj;
}
// Pushes an item to the top of the stack.
//
public virtual void Push(object obj)
{
if (_size == _array.Length)
{
object[] newArray = new object[2 * _array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = obj;
_version++;
}
// Returns a synchronized Stack.
//
public static Stack Synchronized(Stack stack)
{
if (stack == null)
throw new ArgumentNullException(nameof(stack));
return new SyncStack(stack);
}
// Copies the Stack to an array, in the same order Pop would return the items.
public virtual object[] ToArray()
{
if (_size == 0)
return Array.Empty<Object>();
object[] objArray = new object[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private class SyncStack : Stack
{
private Stack _s;
private object _root;
internal SyncStack(Stack stack)
{
_s = stack;
_root = stack.SyncRoot;
}
public override bool IsSynchronized
{
get { return true; }
}
public override object SyncRoot
{
get
{
return _root;
}
}
public override int Count
{
get
{
lock (_root)
{
return _s.Count;
}
}
}
public override bool Contains(object obj)
{
lock (_root)
{
return _s.Contains(obj);
}
}
public override object Clone()
{
lock (_root)
{
return new SyncStack((Stack)_s.Clone());
}
}
public override void Clear()
{
lock (_root)
{
_s.Clear();
}
}
public override void CopyTo(Array array, int arrayIndex)
{
lock (_root)
{
_s.CopyTo(array, arrayIndex);
}
}
public override void Push(object value)
{
lock (_root)
{
_s.Push(value);
}
}
public override object Pop()
{
lock (_root)
{
return _s.Pop();
}
}
public override IEnumerator GetEnumerator()
{
lock (_root)
{
return _s.GetEnumerator();
}
}
public override object Peek()
{
lock (_root)
{
return _s.Peek();
}
}
public override object[] ToArray()
{
lock (_root)
{
return _s.ToArray();
}
}
}
private class StackEnumerator : IEnumerator, ICloneable
{
private Stack _stack;
private int _index;
private int _version;
private object _currentElement;
internal StackEnumerator(Stack stack)
{
_stack = stack;
_version = _stack._version;
_index = -2;
_currentElement = null;
}
public object Clone() => MemberwiseClone();
public virtual bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = null;
return retval;
}
public virtual object Current
{
get
{
if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _currentElement;
}
}
public virtual void Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = null;
}
}
internal class StackDebugView
{
private Stack _stack;
public StackDebugView(Stack stack)
{
if (stack == null)
throw new ArgumentNullException(nameof(stack));
_stack = stack;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object[] Items
{
get
{
return _stack.ToArray();
}
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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 (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using IronPython.CodeDom;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using Microsoft.Samples.VisualStudio.CodeDomCodeModel;
namespace Microsoft.Samples.VisualStudio.IronPythonLanguageService {
/// <summary>
/// This class is used to store the information about one specific instance
/// of EnvDTE.FileCodeModel.
/// </summary>
internal class FileCodeModelInfo {
private EnvDTE.FileCodeModel codeModel;
private uint itemId;
internal FileCodeModelInfo(EnvDTE.FileCodeModel codeModel, uint itemId) {
this.codeModel = codeModel;
this.itemId = itemId;
}
internal EnvDTE.FileCodeModel FileCodeModel {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get { return codeModel; }
}
internal uint ItemId {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get { return itemId; }
}
}
/// <summary>
/// This class implements an intellisense provider for Web projects.
/// An intellisense provider is a specialization of a language service where it is able to
/// run as a contained language. The main language service and main editor is usually the
/// HTML editor / language service, but a specific contained language is hosted for fragments
/// like the "script" tags.
/// This object must be COM visible because it will be Co-Created by the host language.
/// </summary>
[ComVisible(true)]
[Guid(PythonConstants.intellisenseProviderGuidString)]
public sealed class PythonIntellisenseProvider : IVsIntellisenseProject, IDisposable {
private class SourceFileInfo {
private string fileName;
private uint itemId;
private IVsIntellisenseProjectHost hostProject;
private EnvDTE.FileCodeModel fileCode;
private CodeDomProvider codeProvider;
public SourceFileInfo(string name, uint id) {
this.fileName = name;
this.itemId = id;
}
public IVsIntellisenseProjectHost HostProject {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get { return hostProject; }
set {
if (this.hostProject != value) {
fileCode = null;
}
this.hostProject = value;
}
}
public CodeDomProvider CodeProvider {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get { return codeProvider; }
set {
if (value != codeProvider) {
fileCode = null;
}
codeProvider = value;
}
}
public EnvDTE.FileCodeModel FileCodeModel {
get {
// Don't build the object more than once.
if (null != fileCode) {
return fileCode;
}
// Verify that the host project is set.
if (null == hostProject) {
throw new System.InvalidOperationException();
}
// Get the hierarchy from the host project.
object propValue;
ErrorHandler.ThrowOnFailure(hostProject.GetHostProperty((uint)HOSTPROPID.HOSTPROPID_HIERARCHY, out propValue));
IVsHierarchy hierarchy = propValue as IVsHierarchy;
if (null == hierarchy) {
return null;
}
// Try to get the extensibility object for the item.
// NOTE: here we assume that the __VSHPROPID.VSHPROPID_ExtObject property returns a VSLangProj.VSProjectItem
// or a EnvDTE.ProjectItem object. No other kind of extensibility is supported.
propValue = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out propValue));
EnvDTE.ProjectItem projectItem = null;
VSLangProj.VSProjectItem vsprojItem = propValue as VSLangProj.VSProjectItem;
if (null == vsprojItem) {
projectItem = propValue as EnvDTE.ProjectItem;
} else {
projectItem = vsprojItem.ProjectItem;
}
if (null == projectItem) {
return null;
}
fileCode = new CodeDomFileCodeModel(projectItem.DTE, projectItem, codeProvider, fileName);
return fileCode;
}
}
public uint ItemId {
get { return this.itemId; }
}
public string Name {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get { return fileName; }
}
}
private class FileCodeModelEnumerator : IEnumerable<FileCodeModelInfo> {
private List<SourceFileInfo> filesInfo;
private IVsIntellisenseProjectHost host;
private CodeDomProvider codeProvider;
public FileCodeModelEnumerator(IEnumerable<SourceFileInfo> files, IVsIntellisenseProjectHost hostProject, CodeDomProvider provider) {
filesInfo = new List<SourceFileInfo>(files);
host = hostProject;
codeProvider = provider;
}
public IEnumerator<FileCodeModelInfo> GetEnumerator() {
foreach (SourceFileInfo info in filesInfo) {
info.HostProject = host;
info.CodeProvider = codeProvider;
FileCodeModelInfo codeInfo = new FileCodeModelInfo(info.FileCodeModel, info.ItemId);
yield return codeInfo;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return (System.Collections.IEnumerator)this.GetEnumerator();
}
}
private IVsIntellisenseProjectHost hostProject;
private PythonContainedLanguageFactory languageFactory;
private List<string> references;
private Dictionary<uint, SourceFileInfo> files;
private PythonProvider pythonProvider;
public PythonIntellisenseProvider() {
System.Diagnostics.Debug.WriteLine("\n\tPythonIntellisenseProvider created\n");
references = new List<string>();
files = new Dictionary<uint, SourceFileInfo>();
}
public int AddAssemblyReference(string bstrAbsPath) {
string path = bstrAbsPath.ToUpper(CultureInfo.CurrentCulture);
if (!references.Contains(path)) {
references.Add(path);
if (null != pythonProvider) {
pythonProvider.AddReference(path);
}
}
return VSConstants.S_OK;
}
public void Dispose() {
Dispose(true);
}
private void Dispose(bool disposing) {
if (disposing) {
Close();
}
GC.SuppressFinalize(this);
}
public int AddFile(string bstrAbsPath, uint itemid) {
if (VSConstants.S_OK != IsCompilableFile(bstrAbsPath)) {
return VSConstants.S_OK;
}
if (!files.ContainsKey(itemid)) {
files.Add(itemid, new SourceFileInfo(bstrAbsPath, itemid));
}
return VSConstants.S_OK;
}
public int AddP2PReference(object pUnk) {
// Not supported.
return VSConstants.E_NOTIMPL;
}
public int Close() {
this.hostProject = null;
if (null != pythonProvider) {
pythonProvider.Dispose();
pythonProvider = null;
}
return VSConstants.S_OK;
}
public int GetCodeDomProviderName(out string pbstrProvider) {
pbstrProvider = PythonConstants.pythonCodeDomProviderName;
return VSConstants.S_OK;
}
public int GetCompilerReference(out object ppCompilerReference) {
ppCompilerReference = null;
return VSConstants.E_NOTIMPL;
}
public int GetContainedLanguageFactory(out IVsContainedLanguageFactory ppContainedLanguageFactory) {
if (null == languageFactory) {
languageFactory = new PythonContainedLanguageFactory(this);
}
ppContainedLanguageFactory = languageFactory;
return VSConstants.S_OK;
}
public int GetExternalErrorReporter(out IVsReportExternalErrors ppErrorReporter) {
// TODO: Handle the error reporter
ppErrorReporter = null;
return VSConstants.E_NOTIMPL;
}
public int GetFileCodeModel(object pProj, object pProjectItem, out object ppCodeModel) {
ppCodeModel = null;
return VSConstants.E_NOTIMPL;
//EnvDTE.ProjectItem projectItem = pProjectItem as EnvDTE.ProjectItem;
//if (null == projectItem) {
// throw new System.ArgumentException();
//}
//EnvDTE.Property prop = projectItem.Properties.Item("FullPath");
//if (null == prop) {
// throw new System.InvalidOperationException();
//}
//string itemPath = prop.Value as string;
//if (string.IsNullOrEmpty(itemPath)) {
// throw new System.InvalidOperationException();
//}
//SourceFileInfo fileInfo = null;
//foreach (SourceFileInfo sourceInfo in files.Values) {
// if (0 == string.Compare(sourceInfo.Name, itemPath, StringComparison.OrdinalIgnoreCase)) {
// fileInfo = sourceInfo;
// break;
// }
//}
//if (null == fileInfo) {
// throw new System.InvalidOperationException();
//}
//fileInfo.HostProject = hostProject;
//fileInfo.CodeProvider = CodeDomProvider;
//ppCodeModel = fileInfo.FileCodeModel;
//return VSConstants.S_OK;
}
public int GetProjectCodeModel(object pProj, out object ppCodeModel) {
ppCodeModel = null;
return VSConstants.E_NOTIMPL;
}
public int Init(IVsIntellisenseProjectHost pHost) {
this.hostProject = pHost;
return VSConstants.S_OK;
}
public int IsCompilableFile(string bstrFileName) {
string ext = System.IO.Path.GetExtension(bstrFileName);
if (0 == string.Compare(ext, PythonConstants.pythonFileExtension, StringComparison.OrdinalIgnoreCase)) {
return VSConstants.S_OK;
}
return VSConstants.S_FALSE;
}
public int IsSupportedP2PReference(object pUnk) {
// P2P references are not supported.
return VSConstants.S_FALSE;
}
public int IsWebFileRequiredByProject(out int pbReq) {
pbReq = 0;
return VSConstants.S_OK;
}
public int RefreshCompilerOptions() {
return VSConstants.S_OK;
}
public int RemoveAssemblyReference(string bstrAbsPath) {
string path = bstrAbsPath.ToUpper(CultureInfo.CurrentCulture);
if (references.Contains(path)) {
references.Remove(path);
pythonProvider = null;
}
return VSConstants.S_OK;
}
public int RemoveFile(string bstrAbsPath, uint itemid) {
if (files.ContainsKey(itemid)) {
files.Remove(itemid);
}
return VSConstants.S_OK;
}
public int RemoveP2PReference(object pUnk) {
return VSConstants.S_OK;
}
public int RenameFile(string bstrAbsPath, string bstrNewAbsPath, uint itemid) {
return VSConstants.S_OK;
}
public int ResumePostedNotifications() {
// No-Op
return VSConstants.S_OK;
}
public int StartIntellisenseEngine() {
// No-Op
return VSConstants.S_OK;
}
public int StopIntellisenseEngine() {
// No-Op
return VSConstants.S_OK;
}
public int SuspendPostedNotifications() {
// No-Op
return VSConstants.S_OK;
}
public int WaitForIntellisenseReady() {
// No-Op
return VSConstants.S_OK;
}
internal PythonProvider CodeDomProvider {
get {
if (null == pythonProvider) {
pythonProvider = new PythonProvider();
foreach (string assembly in references) {
pythonProvider.AddReference(assembly);
}
}
return pythonProvider;
}
}
internal IEnumerable<FileCodeModelInfo> FileCodeModels {
get {
List<SourceFileInfo> allFiles = new List<SourceFileInfo>(files.Values);
return new FileCodeModelEnumerator(allFiles, hostProject, CodeDomProvider);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
namespace Scintilla.Configuration.Legacy
{
[SerializableAttribute()]
public class StyleClass : ConfigItem
{
[XmlAttributeAttribute()]
public int key;
[XmlAttributeAttribute()]
public string name;
[XmlAttributeAttribute()]
public string fore;
[XmlAttributeAttribute()]
public string back;
[XmlAttributeAttribute()]
public string size;
[XmlAttributeAttribute()]
public string font;
[XmlAttributeAttribute()]
public string bold;
[XmlAttributeAttribute()]
public string eolfilled;
[XmlAttributeAttribute()]
public string italics;
[XmlAttributeAttribute("inherit-style")]
public string inheritstyle;
public StyleClass ParentClass
{
get
{
if( inheritstyle != null && !inheritstyle.Equals("") )
{
return _parent.MasterScintilla.GetStyleClass( inheritstyle );
}
// if it has no parent, the default class will be the parent.
// caution: it is not programmatically guaranteed that there is a default.
if( !name.Equals("default") )
return _parent.MasterScintilla.GetStyleClass( "default" );
return null;
}
}
public bool HasItalics
{
get
{
if( italics != null )
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasItalics;
return false;
}
}
public bool HasBold
{
get
{
if( bold != null)
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasBold;
return false;
}
}
public bool HasEolFilled
{
get
{
if( eolfilled != null)
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasEolFilled;
return false;
}
}
public bool HasFontName
{
get
{
if( font != null )
return true;
StyleClass p = ParentClass;
if( p != null)
return p.HasFontName;
return false;
}
}
public bool HasFontSize
{
get
{
if( size != null )
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasFontSize;
return false;
}
}
public bool HasBackgroundColor
{
get
{
if( back != null )
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasBackgroundColor;
return false;
}
}
public bool HasForegroundColor
{
get
{
if( fore != null )
return true;
StyleClass p = ParentClass;
if( p != null )
return p.HasForegroundColor;
return false;
}
}
public string FontName
{
get
{
if( font != null )
return ResolveString( font );
StyleClass p = ParentClass;
if( p != null )
return p.FontName;
return "courier"; // default courier?
}
}
public int FontSize
{
get
{
if( size != null )
return ResolveNumber( size );
StyleClass p = ParentClass;
if( p != null )
return p.FontSize;
return 10; // default 10 pt?
}
}
public int BackgroundColor
{
get
{
if( back != null )
return ResolveColor( back );
StyleClass p = ParentClass;
if( p != null )
return p.BackgroundColor;
return 0;
}
}
public int ForegroundColor
{
get
{
if( fore != null )
return ResolveColor( fore );
StyleClass p = ParentClass;
if( p != null )
return p.ForegroundColor;
return 0;
}
}
public bool IsItalics
{
get
{
if( italics!= null )
return italics.Equals( "true");
StyleClass p = ParentClass;
if( p != null)
return p.IsItalics;
return false;
}
}
public bool IsBold
{
get
{
if( bold != null )
return bold.Equals("true");
StyleClass p = ParentClass;
if( p != null)
return p.IsBold;
return false;
}
}
public bool IsEolFilled
{
get
{
if( eolfilled!= null )
return eolfilled.Equals("true");
StyleClass p = ParentClass;
if( p != null)
return p.IsEolFilled;
return false;
}
}
private int TO_COLORREF(int c)
{
return (((c & 0xff0000) >> 16) + ((c & 0x0000ff) << 16) + (c & 0x00ff00) );
}
public int ResolveColor(string aColor)
{
if( aColor != null )
{
Value v = _parent.MasterScintilla.GetValue(aColor);
while( v!=null )
{
aColor = v.val;
v = _parent.MasterScintilla.GetValue(aColor);
}
// first try known-color string
System.Drawing.Color c = System.Drawing.Color.FromName( aColor );
if( c.ToArgb() == 0 )
{
// didn't find, or is black.
//hex?
if( aColor.IndexOf( "0x" ) == 0 )
return TO_COLORREF(Int32.Parse( aColor.Substring( 2 ) , System.Globalization.NumberStyles.HexNumber ));
else //decimal
try
{
return TO_COLORREF(Int32.Parse( aColor ));
}
catch(Exception)
{
}
}
return TO_COLORREF( c.ToArgb() & 0x00ffffff );
}
return 0;
}
public int ResolveNumber(string number)
{
if( number != null )
{
Value v = _parent.MasterScintilla.GetValue(number);
while( v!=null )
{
number = v.val;
v = _parent.MasterScintilla.GetValue(number);
}
//hex?
if( number.IndexOf( "0x" ) == 0 )
return Int32.Parse( number.Substring( 2 ) , System.Globalization.NumberStyles.HexNumber );
else //decimal
try
{
return Int32.Parse( number );
}
catch( Exception)
{
}
}
return 0;
}
public string ResolveString(string number)
{
Value value = null;
if (number != null)
{
for (value = _parent.MasterScintilla.GetValue(number); value != null; value = _parent.MasterScintilla.GetValue(number))
{
number = value.val;
}
}
return number;
}
public StyleClass()
{
}
}
}
| |
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using CorDebugInterop;
using nanoFramework.Tools.Debugger;
using System.Collections;
using System.Diagnostics;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public class CorDebugThread : ICorDebugThread, ICorDebugThread2 /* -- this is needed for v2 exception handling -- InterceptCurrentException */
{
CorDebugProcess _process;
CorDebugChain _chain;
bool _fSuspended;
bool _fSuspendedSav; //for function eval, need to remember if this thread is suspended before suspending for function eval.
CorDebugValue _currentException;
CorDebugEval _eval;
CorDebugAppDomain _initialAppDomain;
public CorDebugThread(CorDebugProcess process, uint id, CorDebugEval eval)
{
_process = process;
ID = id;
_fSuspended = false;
_eval = eval;
}
public CorDebugEval CurrentEval { get; }
public bool Exited { get; set; }
public bool SuspendThreadEvents { get; set; }
public void AttachVirtualThread(CorDebugThread thread)
{
CorDebugThread threadLast = this.GetLastCorDebugThread();
threadLast.NextThread = thread;
thread.PreviousThread = threadLast;
_process.AddThread(thread);
Debug.Assert(Process.IsExecutionPaused);
threadLast._fSuspendedSav = threadLast._fSuspended;
threadLast.IsSuspended = true;
}
public bool RemoveVirtualThread(CorDebugThread thread)
{
//can only remove last thread
CorDebugThread threadLast = this.GetLastCorDebugThread();
Debug.Assert(threadLast.IsVirtualThread && !this.IsVirtualThread);
if (threadLast != thread)
return false;
CorDebugThread threadNextToLast = threadLast.PreviousThread;
threadNextToLast.NextThread = null;
threadNextToLast.IsSuspended = threadNextToLast._fSuspendedSav;
threadLast.PreviousThread = null;
//Thread will be removed from process.m_alThreads when the ThreadTerminated breakpoint is hit
return true;
}
public Engine Engine
{
[System.Diagnostics.DebuggerHidden]
get { return _process.Engine; }
}
public CorDebugProcess Process
{
[System.Diagnostics.DebuggerHidden]
get { return _process; }
}
public CorDebugAppDomain AppDomain
{
get
{
CorDebugAppDomain appDomain = _initialAppDomain;
if(!Exited)
{
CorDebugThread thread = GetLastCorDebugThread();
CorDebugFrame frame = thread.Chain.ActiveFrame;
appDomain = frame.AppDomain;
}
return appDomain;
}
}
public uint ID
{
[System.Diagnostics.DebuggerHidden]
get;
}
public void StoppedOnException()
{
_currentException = CorDebugValue.CreateValue(Engine.GetThreadException(ID), this.AppDomain);
}
//This is the only thread that cpde knows about
public CorDebugThread GetRealCorDebugThread()
{
CorDebugThread thread;
for (thread = this; thread.PreviousThread != null; thread = thread.PreviousThread) ;
return thread;
}
public CorDebugThread GetLastCorDebugThread()
{
CorDebugThread thread;
for (thread = this; thread.NextThread != null; thread = thread.NextThread) ;
return thread;
}
//Doubly-linked list of virtual threads. The head of the list is the real thread
//All other threads (at this point), should be the cause of a function eval
public CorDebugThread PreviousThread { get; set; }
public CorDebugThread NextThread { get; set; }
public bool IsVirtualThread { get { return _eval != null; } }
public bool IsLogicalThreadSuspended { get { return GetLastCorDebugThread().IsSuspended; } }
public bool IsSuspended
{
get { return _fSuspended; }
set
{
bool fSuspend = value;
if (fSuspend && !IsSuspended)
{
this.Engine.SuspendThread(ID);
}
else if (!fSuspend && IsSuspended)
{
this.Engine.ResumeThread(ID);
}
_fSuspended = fSuspend;
}
}
public CorDebugChain Chain
{
get
{
if (_chain == null)
{
Debugger.WireProtocol.Commands.Debugging_Thread_Stack.Reply ts = this.Engine.GetThreadStack(ID);
if (ts != null)
{
_fSuspended = (ts.m_flags & Debugger.WireProtocol.Commands.Debugging_Thread_Stack.Reply.TH_F_Suspended) != 0;
_chain = new CorDebugChain(this, ts.m_data);
if(_initialAppDomain == null)
{
CorDebugFrame initialFrame = _chain.GetFrameFromDepthnanoCLR( 0 );
_initialAppDomain = initialFrame.AppDomain;
}
}
}
return _chain;
}
}
public void RefreshChain()
{
if (_chain != null)
{
_chain.RefreshFrames();
}
}
public void ResumingExecution()
{
if (IsSuspended)
{
RefreshChain();
}
else
{
_chain = null;
_currentException = null;
}
}
#region ICorDebugThread Members
int ICorDebugThread.GetObject(out ICorDebugValue ppObject)
{
Debug.Assert(!IsVirtualThread);
RuntimeValue rv = Engine.GetThread(ID);
if (rv != null)
{
ppObject = CorDebugValue.CreateValue(rv, this.AppDomain);
}
else
{
ppObject = null;
}
return COM_HResults.S_OK;
}
int ICorDebugThread.GetDebugState(out CorDebugThreadState pState)
{
Debug.Assert(!IsVirtualThread);
pState = IsLogicalThreadSuspended ? CorDebugThreadState.THREAD_SUSPEND : CorDebugThreadState.THREAD_RUN;
return COM_HResults.S_OK;
}
int ICorDebugThread.CreateEval(out ICorDebugEval ppEval)
{
Debug.Assert(!IsVirtualThread);
ppEval = new CorDebugEval(this);
return COM_HResults.S_OK;
}
int ICorDebugThread.GetHandle(out uint phThreadHandle)
{
Debug.Assert(!IsVirtualThread);
//CorDebugThread.GetHandle is not implemented
phThreadHandle = 0;
return COM_HResults.S_OK;
}
int ICorDebugThread.SetDebugState(CorDebugThreadState state)
{
Debug.Assert(!IsVirtualThread);
//This isnt' quite right, there is a discrepancy between CorDebugThreadState and CorDebugUserState
//where the nanoCLR only has one thread state to differentiate between running, waiting, and stopped
IsSuspended = (state != CorDebugThreadState.THREAD_RUN);
return COM_HResults.S_OK;
}
int ICorDebugThread.GetProcess(out ICorDebugProcess ppProcess)
{
Debug.Assert(!IsVirtualThread);
ppProcess = _process;
return COM_HResults.S_OK;
}
int ICorDebugThread.EnumerateChains(out ICorDebugChainEnum ppChains)
{
Debug.Assert(!IsVirtualThread);
ArrayList chains = new ArrayList();
for (CorDebugThread thread = this.GetLastCorDebugThread(); thread != null; thread = thread.PreviousThread)
{
CorDebugChain chain = thread.Chain;
if (chain != null)
{
chains.Add(chain);
}
}
ppChains = new CorDebugEnum(chains, typeof(ICorDebugChain), typeof(ICorDebugChainEnum));
return COM_HResults.S_OK;
}
int ICorDebugThread.GetUserState(out CorDebugUserState pState)
{
Debug.Assert(!IsVirtualThread);
// CorDebugThread.GetUserState is not implemented
pState = 0;
return COM_HResults.S_OK;
}
int ICorDebugThread.GetRegisterSet(out ICorDebugRegisterSet ppRegisters)
{
Debug.Assert(!IsVirtualThread);
// CorDebugThread.GetRegisterSet is not implemented
ppRegisters = null;
return COM_HResults.E_NOTIMPL;
}
int ICorDebugThread.GetActiveFrame(out ICorDebugFrame ppFrame)
{
Debug.Assert(!IsVirtualThread);
((ICorDebugChain)this.GetLastCorDebugThread().Chain).GetActiveFrame(out ppFrame);
return COM_HResults.S_OK;
}
int ICorDebugThread.GetActiveChain(out ICorDebugChain ppChain)
{
Debug.Assert(!IsVirtualThread);
ppChain = this.GetLastCorDebugThread().Chain;
return COM_HResults.S_OK;
}
int ICorDebugThread.ClearCurrentException()
{
Debug.Assert(!IsVirtualThread);
Debug.Assert(false, "API for unmanaged code only?");
return COM_HResults.S_OK;
}
int ICorDebugThread.GetID(out uint pdwThreadId)
{
Debug.Assert(!IsVirtualThread);
pdwThreadId = ID;
return COM_HResults.S_OK;
}
int ICorDebugThread.CreateStepper(out ICorDebugStepper ppStepper)
{
Debug.Assert(!IsVirtualThread);
ICorDebugFrame frame;
((ICorDebugThread)this).GetActiveFrame(out frame);
ppStepper = new CorDebugStepper((CorDebugFrame)frame);
return COM_HResults.S_OK;
}
int ICorDebugThread.GetCurrentException(out ICorDebugValue ppExceptionObject)
{
ppExceptionObject = this.GetLastCorDebugThread()._currentException;
return COM_HResults.BOOL_TO_HRESULT_FALSE( ppExceptionObject != null );
}
int ICorDebugThread.GetAppDomain(out ICorDebugAppDomain ppAppDomain)
{
ppAppDomain = ((CorDebugThread)this).AppDomain;
return COM_HResults.S_OK;
}
#endregion
#region ICorDebugThread2 Members
int ICorDebugThread2.GetActiveFunctions(uint cFunctions, out uint pcFunctions, COR_ACTIVE_FUNCTION[] pFunctions)
{
pcFunctions = 0;
return COM_HResults.E_NOTIMPL;
}
int ICorDebugThread2.GetConnectionID( out uint pdwConnectionId )
{
pdwConnectionId = 0;
return COM_HResults.E_NOTIMPL;
}
int ICorDebugThread2.GetTaskID( out ulong pTaskId )
{
pTaskId = 0;
return COM_HResults.E_NOTIMPL;
}
int ICorDebugThread2.GetVolatileOSThreadID( out uint pdwTid )
{
pdwTid = ID;
return COM_HResults.S_OK;
}
int ICorDebugThread2.InterceptCurrentException( ICorDebugFrame pFrame )
{
CorDebugFrame frame = (CorDebugFrame)pFrame;
this.Engine.UnwindThread(this.ID, frame.DepthnanoCLR);
return COM_HResults.S_OK;
}
#endregion
}
}
| |
//
// CryptoConvert.cs - Crypto Convertion Routines
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 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.Security.Cryptography;
#if !(SILVERLIGHT || READ_ONLY)
namespace Zenject.ReflectionBaking.Mono.Security.Cryptography {
static class CryptoConvert {
static private int ToInt32LE (byte [] bytes, int offset)
{
return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
}
static private uint ToUInt32LE (byte [] bytes, int offset)
{
return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
}
static private byte[] Trim (byte[] array)
{
for (int i=0; i < array.Length; i++) {
if (array [i] != 0x00) {
byte[] result = new byte [array.Length - i];
Buffer.BlockCopy (array, i, result, 0, result.Length);
return result;
}
}
return null;
}
static RSA FromCapiPrivateKeyBlob (byte[] blob, int offset)
{
RSAParameters rsap = new RSAParameters ();
try {
if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07)
(blob [offset+1] != 0x02) || // Version (0x02)
(blob [offset+2] != 0x00) || // Reserved (word)
(blob [offset+3] != 0x00) ||
(ToUInt32LE (blob, offset+8) != 0x32415352)) // DWORD magic = RSA2
throw new CryptographicException ("Invalid blob header");
// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
// int algId = ToInt32LE (blob, offset+4);
// DWORD bitlen
int bitLen = ToInt32LE (blob, offset+12);
// DWORD public exponent
byte[] exp = new byte [4];
Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
Array.Reverse (exp);
rsap.Exponent = Trim (exp);
int pos = offset+20;
// BYTE modulus[rsapubkey.bitlen/8];
int byteLen = (bitLen >> 3);
rsap.Modulus = new byte [byteLen];
Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
Array.Reverse (rsap.Modulus);
pos += byteLen;
// BYTE prime1[rsapubkey.bitlen/16];
int byteHalfLen = (byteLen >> 1);
rsap.P = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
Array.Reverse (rsap.P);
pos += byteHalfLen;
// BYTE prime2[rsapubkey.bitlen/16];
rsap.Q = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
Array.Reverse (rsap.Q);
pos += byteHalfLen;
// BYTE exponent1[rsapubkey.bitlen/16];
rsap.DP = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
Array.Reverse (rsap.DP);
pos += byteHalfLen;
// BYTE exponent2[rsapubkey.bitlen/16];
rsap.DQ = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
Array.Reverse (rsap.DQ);
pos += byteHalfLen;
// BYTE coefficient[rsapubkey.bitlen/16];
rsap.InverseQ = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
Array.Reverse (rsap.InverseQ);
pos += byteHalfLen;
// ok, this is hackish but CryptoAPI support it so...
// note: only works because CRT is used by default
// http://bugzilla.ximian.com/show_bug.cgi?id=57941
rsap.D = new byte [byteLen]; // must be allocated
if (pos + byteLen + offset <= blob.Length) {
// BYTE privateExponent[rsapubkey.bitlen/8];
Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
Array.Reverse (rsap.D);
}
}
catch (Exception e) {
throw new CryptographicException ("Invalid blob.", e);
}
RSA rsa = null;
try {
rsa = RSA.Create ();
rsa.ImportParameters (rsap);
}
catch (CryptographicException) {
// this may cause problem when this code is run under
// the SYSTEM identity on Windows (e.g. ASP.NET). See
// http://bugzilla.ximian.com/show_bug.cgi?id=77559
bool throws = false;
try {
CspParameters csp = new CspParameters ();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider (csp);
rsa.ImportParameters (rsap);
}
catch {
throws = true;
}
if (throws) {
// rethrow original, not the latter, exception if this fails
throw;
}
}
return rsa;
}
static RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
{
try {
if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06)
(blob [offset+1] != 0x02) || // Version (0x02)
(blob [offset+2] != 0x00) || // Reserved (word)
(blob [offset+3] != 0x00) ||
(ToUInt32LE (blob, offset+8) != 0x31415352)) // DWORD magic = RSA1
throw new CryptographicException ("Invalid blob header");
// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
// int algId = ToInt32LE (blob, offset+4);
// DWORD bitlen
int bitLen = ToInt32LE (blob, offset+12);
// DWORD public exponent
RSAParameters rsap = new RSAParameters ();
rsap.Exponent = new byte [3];
rsap.Exponent [0] = blob [offset+18];
rsap.Exponent [1] = blob [offset+17];
rsap.Exponent [2] = blob [offset+16];
int pos = offset+20;
// BYTE modulus[rsapubkey.bitlen/8];
int byteLen = (bitLen >> 3);
rsap.Modulus = new byte [byteLen];
Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
Array.Reverse (rsap.Modulus);
RSA rsa = null;
try {
rsa = RSA.Create ();
rsa.ImportParameters (rsap);
}
catch (CryptographicException) {
// this may cause problem when this code is run under
// the SYSTEM identity on Windows (e.g. ASP.NET). See
// http://bugzilla.ximian.com/show_bug.cgi?id=77559
CspParameters csp = new CspParameters ();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider (csp);
rsa.ImportParameters (rsap);
}
return rsa;
}
catch (Exception e) {
throw new CryptographicException ("Invalid blob.", e);
}
}
// PRIVATEKEYBLOB
// PUBLICKEYBLOB
static public RSA FromCapiKeyBlob (byte[] blob)
{
return FromCapiKeyBlob (blob, 0);
}
static public RSA FromCapiKeyBlob (byte[] blob, int offset)
{
if (blob == null)
throw new ArgumentNullException ("blob");
if (offset >= blob.Length)
throw new ArgumentException ("blob is too small.");
switch (blob [offset]) {
case 0x00:
// this could be a public key inside an header
// like "sn -e" would produce
if (blob [offset + 12] == 0x06) {
return FromCapiPublicKeyBlob (blob, offset + 12);
}
break;
case 0x06:
return FromCapiPublicKeyBlob (blob, offset);
case 0x07:
return FromCapiPrivateKeyBlob (blob, offset);
}
throw new CryptographicException ("Unknown blob format.");
}
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Osu.Difficulty
{
public class OsuPerformanceCalculator : PerformanceCalculator
{
public new OsuDifficultyAttributes Attributes => (OsuDifficultyAttributes)base.Attributes;
private Mod[] mods;
private double accuracy;
private int scoreMaxCombo;
private int countGreat;
private int countOk;
private int countMeh;
private int countMiss;
public OsuPerformanceCalculator(Ruleset ruleset, DifficultyAttributes attributes, ScoreInfo score)
: base(ruleset, attributes, score)
{
}
public override double Calculate(Dictionary<string, double> categoryRatings = null)
{
mods = Score.Mods;
accuracy = Score.Accuracy;
scoreMaxCombo = Score.MaxCombo;
countGreat = Score.Statistics.GetValueOrDefault(HitResult.Great);
countOk = Score.Statistics.GetValueOrDefault(HitResult.Ok);
countMeh = Score.Statistics.GetValueOrDefault(HitResult.Meh);
countMiss = Score.Statistics.GetValueOrDefault(HitResult.Miss);
// Custom multipliers for NoFail and SpunOut.
double multiplier = 1.12; // This is being adjusted to keep the final pp value scaled around what it used to be when changing things
if (mods.Any(m => m is OsuModNoFail))
multiplier *= Math.Max(0.90, 1.0 - 0.02 * countMiss);
if (mods.Any(m => m is OsuModSpunOut))
multiplier *= 1.0 - Math.Pow((double)Attributes.SpinnerCount / totalHits, 0.85);
double aimValue = computeAimValue();
double speedValue = computeSpeedValue();
double accuracyValue = computeAccuracyValue();
double totalValue =
Math.Pow(
Math.Pow(aimValue, 1.1) +
Math.Pow(speedValue, 1.1) +
Math.Pow(accuracyValue, 1.1), 1.0 / 1.1
) * multiplier;
if (categoryRatings != null)
{
categoryRatings.Add("Aim", aimValue);
categoryRatings.Add("Speed", speedValue);
categoryRatings.Add("Accuracy", accuracyValue);
categoryRatings.Add("OD", Attributes.OverallDifficulty);
categoryRatings.Add("AR", Attributes.ApproachRate);
categoryRatings.Add("Max Combo", Attributes.MaxCombo);
}
return totalValue;
}
private double computeAimValue()
{
double rawAim = Attributes.AimStrain;
if (mods.Any(m => m is OsuModTouchDevice))
rawAim = Math.Pow(rawAim, 0.8);
double aimValue = Math.Pow(5.0 * Math.Max(1.0, rawAim / 0.0675) - 4.0, 3.0) / 100000.0;
// Longer maps are worth more
double lengthBonus = 0.95 + 0.4 * Math.Min(1.0, totalHits / 2000.0) +
(totalHits > 2000 ? Math.Log10(totalHits / 2000.0) * 0.5 : 0.0);
aimValue *= lengthBonus;
// Penalize misses by assessing # of misses relative to the total # of objects. Default a 3% reduction for any # of misses.
if (countMiss > 0)
aimValue *= 0.97 * Math.Pow(1 - Math.Pow((double)countMiss / totalHits, 0.775), countMiss);
// Combo scaling
if (Attributes.MaxCombo > 0)
aimValue *= Math.Min(Math.Pow(scoreMaxCombo, 0.8) / Math.Pow(Attributes.MaxCombo, 0.8), 1.0);
double approachRateFactor = 0.0;
if (Attributes.ApproachRate > 10.33)
approachRateFactor = Attributes.ApproachRate - 10.33;
else if (Attributes.ApproachRate < 8.0)
approachRateFactor = 0.025 * (8.0 - Attributes.ApproachRate);
double approachRateTotalHitsFactor = 1.0 / (1.0 + Math.Exp(-(0.007 * (totalHits - 400))));
double approachRateBonus = 1.0 + (0.03 + 0.37 * approachRateTotalHitsFactor) * approachRateFactor;
// We want to give more reward for lower AR when it comes to aim and HD. This nerfs high AR and buffs lower AR.
if (mods.Any(h => h is OsuModHidden))
aimValue *= 1.0 + 0.04 * (12.0 - Attributes.ApproachRate);
double flashlightBonus = 1.0;
if (mods.Any(h => h is OsuModFlashlight))
{
// Apply object-based bonus for flashlight.
flashlightBonus = 1.0 + 0.35 * Math.Min(1.0, totalHits / 200.0) +
(totalHits > 200
? 0.3 * Math.Min(1.0, (totalHits - 200) / 300.0) +
(totalHits > 500 ? (totalHits - 500) / 1200.0 : 0.0)
: 0.0);
}
aimValue *= Math.Max(flashlightBonus, approachRateBonus);
// Scale the aim value with accuracy _slightly_
aimValue *= 0.5 + accuracy / 2.0;
// It is important to also consider accuracy difficulty when doing that
aimValue *= 0.98 + Math.Pow(Attributes.OverallDifficulty, 2) / 2500;
return aimValue;
}
private double computeSpeedValue()
{
double speedValue = Math.Pow(5.0 * Math.Max(1.0, Attributes.SpeedStrain / 0.0675) - 4.0, 3.0) / 100000.0;
// Longer maps are worth more
double lengthBonus = 0.95 + 0.4 * Math.Min(1.0, totalHits / 2000.0) +
(totalHits > 2000 ? Math.Log10(totalHits / 2000.0) * 0.5 : 0.0);
speedValue *= lengthBonus;
// Penalize misses by assessing # of misses relative to the total # of objects. Default a 3% reduction for any # of misses.
if (countMiss > 0)
speedValue *= 0.97 * Math.Pow(1 - Math.Pow((double)countMiss / totalHits, 0.775), Math.Pow(countMiss, .875));
// Combo scaling
if (Attributes.MaxCombo > 0)
speedValue *= Math.Min(Math.Pow(scoreMaxCombo, 0.8) / Math.Pow(Attributes.MaxCombo, 0.8), 1.0);
double approachRateFactor = 0.0;
if (Attributes.ApproachRate > 10.33)
approachRateFactor = Attributes.ApproachRate - 10.33;
double approachRateTotalHitsFactor = 1.0 / (1.0 + Math.Exp(-(0.007 * (totalHits - 400))));
speedValue *= 1.0 + (0.03 + 0.37 * approachRateTotalHitsFactor) * approachRateFactor;
if (mods.Any(m => m is OsuModHidden))
speedValue *= 1.0 + 0.04 * (12.0 - Attributes.ApproachRate);
// Scale the speed value with accuracy and OD
speedValue *= (0.95 + Math.Pow(Attributes.OverallDifficulty, 2) / 750) * Math.Pow(accuracy, (14.5 - Math.Max(Attributes.OverallDifficulty, 8)) / 2);
// Scale the speed value with # of 50s to punish doubletapping.
speedValue *= Math.Pow(0.98, countMeh < totalHits / 500.0 ? 0 : countMeh - totalHits / 500.0);
return speedValue;
}
private double computeAccuracyValue()
{
// This percentage only considers HitCircles of any value - in this part of the calculation we focus on hitting the timing hit window
double betterAccuracyPercentage;
int amountHitObjectsWithAccuracy = Attributes.HitCircleCount;
if (amountHitObjectsWithAccuracy > 0)
betterAccuracyPercentage = ((countGreat - (totalHits - amountHitObjectsWithAccuracy)) * 6 + countOk * 2 + countMeh) / (double)(amountHitObjectsWithAccuracy * 6);
else
betterAccuracyPercentage = 0;
// It is possible to reach a negative accuracy with this formula. Cap it at zero - zero points
if (betterAccuracyPercentage < 0)
betterAccuracyPercentage = 0;
// Lots of arbitrary values from testing.
// Considering to use derivation from perfect accuracy in a probabilistic manner - assume normal distribution
double accuracyValue = Math.Pow(1.52163, Attributes.OverallDifficulty) * Math.Pow(betterAccuracyPercentage, 24) * 2.83;
// Bonus for many hitcircles - it's harder to keep good accuracy up for longer
accuracyValue *= Math.Min(1.15, Math.Pow(amountHitObjectsWithAccuracy / 1000.0, 0.3));
if (mods.Any(m => m is OsuModHidden))
accuracyValue *= 1.08;
if (mods.Any(m => m is OsuModFlashlight))
accuracyValue *= 1.02;
return accuracyValue;
}
private int totalHits => countGreat + countOk + countMeh + countMiss;
private int totalSuccessfulHits => countGreat + countOk + countMeh;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agent.Plugins.PipelineArtifact;
using Agent.Plugins.PipelineCache.Telemetry;
using Agent.Sdk;
using Microsoft.VisualStudio.Services.Agent.Blob;
using BuildXL.Cache.ContentStore.Hashing;
using Microsoft.VisualStudio.Services.BlobStore.Common.Telemetry;
using Microsoft.VisualStudio.Services.BlobStore.WebApi;
using Microsoft.VisualStudio.Services.Content.Common;
using Microsoft.VisualStudio.Services.Content.Common.Tracing;
using Microsoft.VisualStudio.Services.PipelineCache.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using JsonSerializer = Microsoft.VisualStudio.Services.Content.Common.JsonSerializer;
namespace Agent.Plugins.PipelineCache
{
public class PipelineCacheServer
{
private readonly IAppTraceSource tracer;
public PipelineCacheServer(AgentTaskPluginExecutionContext context)
{
this.tracer = context.CreateArtifactsTracer();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1068: CancellationToken parameters must come last")]
internal async Task UploadAsync(
AgentTaskPluginExecutionContext context,
Fingerprint fingerprint,
string path,
CancellationToken cancellationToken,
ContentFormat contentFormat)
{
VssConnection connection = context.VssConnection;
var (dedupManifestClient, clientTelemetry) = await DedupManifestArtifactClientFactory.Instance
.CreateDedupManifestClientAsync(context.IsSystemDebugTrue(), (str) => context.Output(str), connection, cancellationToken);
PipelineCacheClient pipelineCacheClient = this.CreateClient(clientTelemetry, context, connection);
using (clientTelemetry)
{
// Check if the key exists.
PipelineCacheActionRecord cacheRecordGet = clientTelemetry.CreateRecord<PipelineCacheActionRecord>((level, uri, type) =>
new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.RestoreCache, context));
PipelineCacheArtifact getResult = await pipelineCacheClient.GetPipelineCacheArtifactAsync(new [] {fingerprint}, cancellationToken, cacheRecordGet);
// Send results to CustomerIntelligence
context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecordGet);
//If cache exists, return.
if (getResult != null)
{
context.Output($"Cache with fingerprint `{getResult.Fingerprint}` already exists.");
return;
}
string uploadPath = await this.GetUploadPathAsync(contentFormat, context, path, cancellationToken);
//Upload the pipeline artifact.
PipelineCacheActionRecord uploadRecord = clientTelemetry.CreateRecord<PipelineCacheActionRecord>((level, uri, type) =>
new PipelineCacheActionRecord(level, uri, type, nameof(dedupManifestClient.PublishAsync), context));
PublishResult result = await clientTelemetry.MeasureActionAsync(
record: uploadRecord,
actionAsync: async () =>
await AsyncHttpRetryHelper.InvokeAsync(
async () =>
{
return await dedupManifestClient.PublishAsync(uploadPath, cancellationToken);
},
maxRetries: 3,
tracer: tracer,
canRetryDelegate: e => true, // this isn't great, but failing on upload stinks, so just try a couple of times
cancellationToken: cancellationToken,
continueOnCapturedContext: false)
);
CreatePipelineCacheArtifactContract options = new CreatePipelineCacheArtifactContract
{
Fingerprint = fingerprint,
RootId = result.RootId,
ManifestId = result.ManifestId,
ProofNodes = result.ProofNodes.ToArray(),
ContentFormat = contentFormat.ToString(),
};
// delete archive file if it's tar.
if (contentFormat == ContentFormat.SingleTar)
{
try
{
if (File.Exists(uploadPath))
{
File.Delete(uploadPath);
}
}
catch { }
}
// Cache the artifact
PipelineCacheActionRecord cacheRecord = clientTelemetry.CreateRecord<PipelineCacheActionRecord>((level, uri, type) =>
new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.SaveCache, context));
CreateStatus status = await pipelineCacheClient.CreatePipelineCacheArtifactAsync(options, cancellationToken, cacheRecord);
// Send results to CustomerIntelligence
context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: uploadRecord);
context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecord);
context.Output("Saved item.");
}
}
internal async Task DownloadAsync(
AgentTaskPluginExecutionContext context,
Fingerprint[] fingerprints,
string path,
string cacheHitVariable,
CancellationToken cancellationToken)
{
VssConnection connection = context.VssConnection;
var (dedupManifestClient, clientTelemetry) = await DedupManifestArtifactClientFactory.Instance
.CreateDedupManifestClientAsync(context.IsSystemDebugTrue(), (str) => context.Output(str), connection, cancellationToken);
PipelineCacheClient pipelineCacheClient = this.CreateClient(clientTelemetry, context, connection);
using (clientTelemetry)
{
PipelineCacheActionRecord cacheRecord = clientTelemetry.CreateRecord<PipelineCacheActionRecord>((level, uri, type) =>
new PipelineCacheActionRecord(level, uri, type, PipelineArtifactConstants.RestoreCache, context));
PipelineCacheArtifact result = await pipelineCacheClient.GetPipelineCacheArtifactAsync(fingerprints, cancellationToken, cacheRecord);
// Send results to CustomerIntelligence
context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: cacheRecord);
if (result != null)
{
context.Output($"Entry found at fingerprint: `{result.Fingerprint.ToString()}`");
context.Verbose($"Manifest ID is: {result.ManifestId.ValueString}");
PipelineCacheActionRecord downloadRecord = clientTelemetry.CreateRecord<PipelineCacheActionRecord>((level, uri, type) =>
new PipelineCacheActionRecord(level, uri, type, nameof(DownloadAsync), context));
await clientTelemetry.MeasureActionAsync(
record: downloadRecord,
actionAsync: async () =>
{
await this.DownloadPipelineCacheAsync(context, dedupManifestClient, result.ManifestId, path, Enum.Parse<ContentFormat>(result.ContentFormat), cancellationToken);
});
// Send results to CustomerIntelligence
context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.PipelineCache, record: downloadRecord);
context.Output("Cache restored.");
}
if (!string.IsNullOrEmpty(cacheHitVariable))
{
if (result == null)
{
context.SetVariable(cacheHitVariable, "false");
}
else
{
context.Verbose($"Exact fingerprint: `{result.Fingerprint.ToString()}`");
bool foundExact = false;
foreach(var fingerprint in fingerprints)
{
context.Verbose($"This fingerprint: `{fingerprint.ToString()}`");
if (fingerprint == result.Fingerprint
|| result.Fingerprint.Segments.Length == 1 && result.Fingerprint.Segments.Single() == fingerprint.SummarizeForV1())
{
foundExact = true;
break;
}
}
context.SetVariable(cacheHitVariable, foundExact ? "true" : "inexact");
}
}
}
}
private PipelineCacheClient CreateClient(
BlobStoreClientTelemetry blobStoreClientTelemetry,
AgentTaskPluginExecutionContext context,
VssConnection connection)
{
var tracer = context.CreateArtifactsTracer();
IClock clock = UtcClock.Instance;
var pipelineCacheHttpClient = connection.GetClient<PipelineCacheHttpClient>();
var pipelineCacheClient = new PipelineCacheClient(blobStoreClientTelemetry, pipelineCacheHttpClient, clock, tracer);
return pipelineCacheClient;
}
private async Task<string> GetUploadPathAsync(ContentFormat contentFormat, AgentTaskPluginExecutionContext context, string path, CancellationToken cancellationToken)
{
string uploadPath = path;
if(contentFormat == ContentFormat.SingleTar)
{
uploadPath = await TarUtils.ArchiveFilesToTarAsync(context, path, cancellationToken);
}
return uploadPath;
}
private async Task DownloadPipelineCacheAsync(
AgentTaskPluginExecutionContext context,
DedupManifestArtifactClient dedupManifestClient,
DedupIdentifier manifestId,
string targetDirectory,
ContentFormat contentFormat,
CancellationToken cancellationToken)
{
if (contentFormat == ContentFormat.SingleTar)
{
string manifestPath = Path.Combine(Path.GetTempPath(), $"{nameof(DedupManifestArtifactClient)}.{Path.GetRandomFileName()}.manifest");
await AsyncHttpRetryHelper.InvokeVoidAsync(
async () =>
{
await dedupManifestClient.DownloadFileToPathAsync(manifestId, manifestPath, proxyUri: null, cancellationToken: cancellationToken);
},
maxRetries: 3,
tracer: tracer,
canRetryDelegate: e => true,
context: nameof(DownloadPipelineCacheAsync),
cancellationToken: cancellationToken,
continueOnCapturedContext: false);
Manifest manifest = JsonSerializer.Deserialize<Manifest>(File.ReadAllText(manifestPath));
await TarUtils.DownloadAndExtractTarAsync (context, manifest, dedupManifestClient, targetDirectory, cancellationToken);
try
{
if(File.Exists(manifestPath))
{
File.Delete(manifestPath);
}
}
catch {}
}
else
{
DownloadDedupManifestArtifactOptions options = DownloadDedupManifestArtifactOptions.CreateWithManifestId(
manifestId,
targetDirectory,
proxyUri: null,
minimatchPatterns: null);
await AsyncHttpRetryHelper.InvokeVoidAsync(
async () =>
{
await dedupManifestClient.DownloadAsync(options, cancellationToken);
},
maxRetries: 3,
tracer: tracer,
canRetryDelegate: e => true,
context: nameof(DownloadPipelineCacheAsync),
cancellationToken: cancellationToken,
continueOnCapturedContext: false);
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Xml;
using System.Globalization;
using System.ServiceModel;
#if USE_REFEMIT
public class JsonWriterDelegator : XmlWriterDelegator
#else
internal class JsonWriterDelegator : XmlWriterDelegator
#endif
{
DateTimeFormat dateTimeFormat;
public JsonWriterDelegator(XmlWriter writer)
: base(writer)
{
}
public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat)
: this(writer)
{
this.dateTimeFormat = dateTimeFormat;
}
internal override void WriteChar(char value)
{
WriteString(XmlConvert.ToString(value));
}
internal override void WriteBase64(byte[] bytes)
{
if (bytes == null)
{
return;
}
ByteArrayHelperWithString.Instance.WriteArray(Writer, bytes, 0, bytes.Length);
}
internal override void WriteQName(XmlQualifiedName value)
{
if (value != XmlQualifiedName.Empty)
{
writer.WriteString(value.Name);
writer.WriteString(JsonGlobals.NameValueSeparatorString);
writer.WriteString(value.Namespace);
}
}
internal override void WriteUnsignedLong(ulong value)
{
WriteDecimal((decimal)value);
}
internal override void WriteDecimal(decimal value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteDecimal(value);
}
internal override void WriteDouble(double value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteDouble(value);
}
internal override void WriteFloat(float value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteFloat(value);
}
internal override void WriteLong(long value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteLong(value);
}
internal override void WriteSignedByte(sbyte value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteSignedByte(value);
}
internal override void WriteUnsignedInt(uint value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteUnsignedInt(value);
}
internal override void WriteUnsignedShort(ushort value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteUnsignedShort(value);
}
internal override void WriteUnsignedByte(byte value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteUnsignedByte(value);
}
internal override void WriteShort(short value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteShort(value);
}
internal override void WriteBoolean(bool value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.booleanString);
base.WriteBoolean(value);
}
internal override void WriteInt(int value)
{
writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString);
base.WriteInt(value);
}
#if USE_REFEMIT
public void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteBoolean(value[i], itemName, itemNamespace);
}
}
#if USE_REFEMIT
public void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteDateTime(value[i], itemName, itemNamespace);
}
}
#if USE_REFEMIT
public void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteDecimal(value[i], itemName, itemNamespace);
}
}
#if USE_REFEMIT
public void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteInt(value[i], itemName, itemNamespace);
}
}
#if USE_REFEMIT
public void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteLong(value[i], itemName, itemNamespace);
}
}
internal override void WriteDateTime(DateTime value)
{
if (this.dateTimeFormat == null)
{
WriteDateTimeInDefaultFormat(value);
}
else
{
writer.WriteString(value.ToString(this.dateTimeFormat.FormatString, this.dateTimeFormat.FormatProvider));
}
}
void WriteDateTimeInDefaultFormat(DateTime value)
{
// ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing
// This will break round-tripping of these dates (see bug 9690 in CSD Developer Framework)
if (value.Kind != DateTimeKind.Utc)
{
long tickCount = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks;
if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.JsonDateTimeOutOfRange), new ArgumentOutOfRangeException("value")));
}
}
writer.WriteString(JsonGlobals.DateTimeStartGuardReader);
writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000);
switch (value.Kind)
{
case DateTimeKind.Unspecified:
case DateTimeKind.Local:
// +"zzzz";
TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
if (ts.Ticks < 0)
{
writer.WriteString("-");
}
else
{
writer.WriteString("+");
}
int hours = Math.Abs(ts.Hours);
writer.WriteString((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture));
int minutes = Math.Abs(ts.Minutes);
writer.WriteString((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture));
break;
case DateTimeKind.Utc:
break;
}
writer.WriteString(JsonGlobals.DateTimeEndGuardReader);
}
#if USE_REFEMIT
public void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteFloat(value[i], itemName, itemNamespace);
}
}
#if USE_REFEMIT
public void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
for (int i = 0; i < value.Length; i++)
{
WriteDouble(value[i], itemName, itemNamespace);
}
}
internal override void WriteStartElement(string prefix, string localName, string ns)
{
if (localName != null && localName.Length == 0)
{
base.WriteStartElement(JsonGlobals.itemString, JsonGlobals.itemString);
base.WriteAttributeString(null, JsonGlobals.itemString, null, localName);
}
else
{
base.WriteStartElement(prefix, localName, ns);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleIQFeed.SampleIQFeedPublic
File: SecuritiesWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleIQFeed
{
using System;
using System.Collections.Generic;
using System.Windows;
using Ecng.Collections;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
using StockSharp.Xaml;
public partial class SecuritiesWindow
{
private readonly SynchronizedDictionary<Security, QuotesWindow> _quotesWindows = new SynchronizedDictionary<Security, QuotesWindow>();
private readonly SynchronizedDictionary<Security, Level1Window> _level1Windows = new SynchronizedDictionary<Security, Level1Window>();
private readonly SynchronizedDictionary<Security, HistoryLevel1Window> _historyLevel1Windows = new SynchronizedDictionary<Security, HistoryLevel1Window>();
private readonly SynchronizedDictionary<Security, HistoryCandlesWindow> _historyCandlesWindows = new SynchronizedDictionary<Security, HistoryCandlesWindow>();
private bool _initialized;
public SecuritiesWindow()
{
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
var trader = MainWindow.Instance.Trader;
if (trader != null)
{
if (_initialized)
{
trader.ValuesChanged -= TraderOnValuesChanged;
trader.MarketDepthsChanged -= TraderOnMarketDepthsChanged;
}
_quotesWindows.ForEach(pair =>
{
trader.UnRegisterMarketDepth(pair.Key);
DeleteHideableAndClose(pair.Value);
});
_level1Windows.ForEach(pair =>
{
trader.UnRegisterSecurity(pair.Key);
DeleteHideableAndClose(pair.Value);
});
_historyLevel1Windows.ForEach(pair => DeleteHideableAndClose(pair.Value));
_historyCandlesWindows.ForEach(pair => DeleteHideableAndClose(pair.Value));
}
base.OnClosed(e);
}
private static void DeleteHideableAndClose(Window window)
{
window.DeleteHideable();
window.Close();
}
public Security SelectedSecurity => SecurityPicker.SelectedSecurity;
private void SecurityPicker_OnSecuritySelected(Security security)
{
HistoryLevel1.IsEnabled = HistoryCandles.IsEnabled = Level1.IsEnabled = Depth.IsEnabled = security != null;
}
private void DepthClick(object sender, RoutedEventArgs e)
{
var trader = MainWindow.Instance.Trader;
var window = _quotesWindows.SafeAdd(SelectedSecurity, security =>
{
// subscribe on order book flow
trader.RegisterMarketDepth(security);
// create order book window
var wnd = new QuotesWindow { Title = security.Id + " " + LocalizedStrings.MarketDepth };
wnd.MakeHideable();
return wnd;
});
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
TryInitialize();
}
private void Level1Click(object sender, RoutedEventArgs e)
{
TryInitialize();
var window = _level1Windows.SafeAdd(SelectedSecurity, security =>
{
// create level1 window
var wnd = new Level1Window { Title = security.Code + " level1" };
// subscribe on level1
MainWindow.Instance.Trader.RegisterSecurity(security);
wnd.MakeHideable();
return wnd;
});
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
private void TryInitialize()
{
if (!_initialized)
{
_initialized = true;
var trader = MainWindow.Instance.Trader;
trader.ValuesChanged += TraderOnValuesChanged;
trader.MarketDepthsChanged += TraderOnMarketDepthsChanged;
TraderOnMarketDepthsChanged(new[] { trader.GetMarketDepth(SecurityPicker.SelectedSecurity) });
}
}
private void TraderOnValuesChanged(Security security, IEnumerable<KeyValuePair<Level1Fields, object>> changes, DateTimeOffset serverTime, DateTimeOffset localTime)
{
var wnd = _level1Windows.TryGetValue(security);
if (wnd == null)
return;
var msg = new Level1ChangeMessage
{
SecurityId = security.ToSecurityId(),
ServerTime = serverTime,
LocalTime = localTime
};
msg.Changes.AddRange(changes);
wnd.Level1Grid.Messages.Add(msg);
}
private void TraderOnMarketDepthsChanged(IEnumerable<MarketDepth> depths)
{
foreach (var depth in depths)
{
var wnd = _quotesWindows.TryGetValue(depth.Security);
if (wnd != null)
wnd.DepthCtrl.UpdateDepth(depth);
}
}
private void HistoryLevel1Click(object sender, RoutedEventArgs e)
{
var window = _historyLevel1Windows.SafeAdd(SelectedSecurity, security =>
{
// create historical level1 window
var wnd = new HistoryLevel1Window(SelectedSecurity);
wnd.MakeHideable();
return wnd;
});
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
private void HistoryCandlesClick(object sender, RoutedEventArgs e)
{
var window = _historyCandlesWindows.SafeAdd(SelectedSecurity, security =>
{
// create historical candles window
var wnd = new HistoryCandlesWindow(SelectedSecurity);
wnd.MakeHideable();
return wnd;
});
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
private void FindClick(object sender, RoutedEventArgs e)
{
var wnd = new SecurityLookupWindow { Criteria = new Security { Code = "AAPL" } };
if (!wnd.ShowModal(this))
return;
MainWindow.Instance.Trader.LookupSecurities(wnd.Criteria);
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Wgl
{
/// <summary>
/// [WGL] Value of WGL_ACCESS_READ_ONLY_NV symbol.
/// </summary>
[RequiredByFeature("WGL_NV_DX_interop")]
[Log(BitmaskName = "WGLDXInteropMaskNV")]
public const int ACCESS_READ_ONLY_NV = 0x00000000;
/// <summary>
/// [WGL] Value of WGL_ACCESS_READ_WRITE_NV symbol.
/// </summary>
[RequiredByFeature("WGL_NV_DX_interop")]
[Log(BitmaskName = "WGLDXInteropMaskNV")]
public const int ACCESS_READ_WRITE_NV = 0x00000001;
/// <summary>
/// [WGL] Value of WGL_ACCESS_WRITE_DISCARD_NV symbol.
/// </summary>
[RequiredByFeature("WGL_NV_DX_interop")]
[Log(BitmaskName = "WGLDXInteropMaskNV")]
public const int ACCESS_WRITE_DISCARD_NV = 0x00000002;
/// <summary>
/// [WGL] wglDXSetResourceShareHandleNV: Binding for wglDXSetResourceShareHandleNV.
/// </summary>
/// <param name="dxObject">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="shareHandle">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXSetResourceShareHandleNV(IntPtr dxObject, IntPtr shareHandle)
{
bool retValue;
Debug.Assert(Delegates.pwglDXSetResourceShareHandleNV != null, "pwglDXSetResourceShareHandleNV not implemented");
retValue = Delegates.pwglDXSetResourceShareHandleNV(dxObject, shareHandle);
LogCommand("wglDXSetResourceShareHandleNV", retValue, dxObject, shareHandle );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXOpenDeviceNV: Binding for wglDXOpenDeviceNV.
/// </summary>
/// <param name="dxDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static IntPtr DXOpenDeviceNV(IntPtr dxDevice)
{
IntPtr retValue;
Debug.Assert(Delegates.pwglDXOpenDeviceNV != null, "pwglDXOpenDeviceNV not implemented");
retValue = Delegates.pwglDXOpenDeviceNV(dxDevice);
LogCommand("wglDXOpenDeviceNV", retValue, dxDevice );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXCloseDeviceNV: Binding for wglDXCloseDeviceNV.
/// </summary>
/// <param name="hDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXCloseDeviceNV(IntPtr hDevice)
{
bool retValue;
Debug.Assert(Delegates.pwglDXCloseDeviceNV != null, "pwglDXCloseDeviceNV not implemented");
retValue = Delegates.pwglDXCloseDeviceNV(hDevice);
LogCommand("wglDXCloseDeviceNV", retValue, hDevice );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXRegisterObjectNV: Binding for wglDXRegisterObjectNV.
/// </summary>
/// <param name="hDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="dxObject">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="name">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="access">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static IntPtr DXRegisterObjectNV(IntPtr hDevice, IntPtr dxObject, uint name, int type, int access)
{
IntPtr retValue;
Debug.Assert(Delegates.pwglDXRegisterObjectNV != null, "pwglDXRegisterObjectNV not implemented");
retValue = Delegates.pwglDXRegisterObjectNV(hDevice, dxObject, name, type, access);
LogCommand("wglDXRegisterObjectNV", retValue, hDevice, dxObject, name, type, access );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXUnregisterObjectNV: Binding for wglDXUnregisterObjectNV.
/// </summary>
/// <param name="hDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="hObject">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXUnregisterObjectNV(IntPtr hDevice, IntPtr hObject)
{
bool retValue;
Debug.Assert(Delegates.pwglDXUnregisterObjectNV != null, "pwglDXUnregisterObjectNV not implemented");
retValue = Delegates.pwglDXUnregisterObjectNV(hDevice, hObject);
LogCommand("wglDXUnregisterObjectNV", retValue, hDevice, hObject );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXObjectAccessNV: Binding for wglDXObjectAccessNV.
/// </summary>
/// <param name="hObject">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="access">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXObjectNV(IntPtr hObject, int access)
{
bool retValue;
Debug.Assert(Delegates.pwglDXObjectAccessNV != null, "pwglDXObjectAccessNV not implemented");
retValue = Delegates.pwglDXObjectAccessNV(hObject, access);
LogCommand("wglDXObjectAccessNV", retValue, hObject, access );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXLockObjectsNV: Binding for wglDXLockObjectsNV.
/// </summary>
/// <param name="hDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="count">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="hObjects">
/// A <see cref="T:IntPtr[]"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXLockObjectNV(IntPtr hDevice, int count, IntPtr[] hObjects)
{
bool retValue;
unsafe {
fixed (IntPtr* p_hObjects = hObjects)
{
Debug.Assert(Delegates.pwglDXLockObjectsNV != null, "pwglDXLockObjectsNV not implemented");
retValue = Delegates.pwglDXLockObjectsNV(hDevice, count, p_hObjects);
LogCommand("wglDXLockObjectsNV", retValue, hDevice, count, hObjects );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [WGL] wglDXUnlockObjectsNV: Binding for wglDXUnlockObjectsNV.
/// </summary>
/// <param name="hDevice">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="count">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="hObjects">
/// A <see cref="T:IntPtr[]"/>.
/// </param>
[RequiredByFeature("WGL_NV_DX_interop")]
public static bool DXUnlockObjectsNV(IntPtr hDevice, int count, IntPtr[] hObjects)
{
bool retValue;
unsafe {
fixed (IntPtr* p_hObjects = hObjects)
{
Debug.Assert(Delegates.pwglDXUnlockObjectsNV != null, "pwglDXUnlockObjectsNV not implemented");
retValue = Delegates.pwglDXUnlockObjectsNV(hDevice, count, p_hObjects);
LogCommand("wglDXUnlockObjectsNV", retValue, hDevice, count, hObjects );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXSetResourceShareHandleNV(IntPtr dxObject, IntPtr shareHandle);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXSetResourceShareHandleNV pwglDXSetResourceShareHandleNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate IntPtr wglDXOpenDeviceNV(IntPtr dxDevice);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXOpenDeviceNV pwglDXOpenDeviceNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXCloseDeviceNV(IntPtr hDevice);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXCloseDeviceNV pwglDXCloseDeviceNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate IntPtr wglDXRegisterObjectNV(IntPtr hDevice, IntPtr dxObject, uint name, int type, int access);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXRegisterObjectNV pwglDXRegisterObjectNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXUnregisterObjectNV(IntPtr hDevice, IntPtr hObject);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXUnregisterObjectNV pwglDXUnregisterObjectNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXObjectAccessNV(IntPtr hObject, int access);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXObjectAccessNV pwglDXObjectAccessNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXLockObjectsNV(IntPtr hDevice, int count, IntPtr* hObjects);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXLockObjectsNV pwglDXLockObjectsNV;
[RequiredByFeature("WGL_NV_DX_interop")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool wglDXUnlockObjectsNV(IntPtr hDevice, int count, IntPtr* hObjects);
[RequiredByFeature("WGL_NV_DX_interop")]
internal static wglDXUnlockObjectsNV pwglDXUnlockObjectsNV;
}
}
}
| |
/*
* Copyright 2010 ZXing authors
*
* 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 ZXing.Common;
using ZXing.Common.Detector;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
/// is rotated or skewed, or partially obscured.
/// </summary>
/// <author>David Olivier</author>
public sealed class Detector
{
private readonly BitMatrix image;
private bool compact;
private int nbLayers;
private int nbDataBlocks;
private int nbCenterLayers;
private int shift;
/// <summary>
/// Initializes a new instance of the <see cref="Detector"/> class.
/// </summary>
/// <param name="image">The image.</param>
public Detector(BitMatrix image)
{
this.image = image;
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
public AztecDetectorResult detect()
{
return detect(false);
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
/// <param name="isMirror">if true, image is a mirror-image of original.</param>
/// <returns>
/// encapsulating results of detecting an Aztec Code
/// </returns>
public AztecDetectorResult detect(bool isMirror)
{
// 1. Get the center of the aztec matrix
var pCenter = getMatrixCenter();
if (pCenter == null)
return null;
// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
var bullsEyeCorners = getBullsEyeCorners(pCenter);
if (bullsEyeCorners == null)
{
return null;
}
if (isMirror)
{
ResultPoint temp = bullsEyeCorners[0];
bullsEyeCorners[0] = bullsEyeCorners[2];
bullsEyeCorners[2] = temp;
}
// 3. Get the size of the matrix and other parameters from the bull's eye
if (!extractParameters(bullsEyeCorners))
{
return null;
}
// 4. Sample the grid
var bits = sampleGrid(image,
bullsEyeCorners[shift%4],
bullsEyeCorners[(shift + 1)%4],
bullsEyeCorners[(shift + 2)%4],
bullsEyeCorners[(shift + 3)%4]);
if (bits == null)
{
return null;
}
// 5. Get the corners of the matrix.
var corners = getMatrixCornerPoints(bullsEyeCorners);
if (corners == null)
{
return null;
}
return new AztecDetectorResult(bits, corners, compact, nbDataBlocks, nbLayers);
}
/// <summary>
/// Extracts the number of data layers and data blocks from the layer around the bull's eye
/// </summary>
/// <param name="bullsEyeCorners">bullEyeCornerPoints the array of bull's eye corners</param>
/// <returns></returns>
private bool extractParameters(ResultPoint[] bullsEyeCorners)
{
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3]))
{
return false;
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides =
{
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
if (shift < 0)
return false;
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++)
{
int side = sides[(shift + i) % 4];
if (compact)
{
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
}
else
{
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (correctedData < 0)
return false;
if (compact)
{
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
}
else
{
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
return true;
}
private static readonly int[] EXPECTED_CORNER_BITS =
{
0xee0, // 07340 XXX .XX X.. ...
0x1dc, // 00734 ... XXX .XX X..
0x83b, // 04073 X.. ... XXX .XX
0x707, // 03407 .XX X.. ... XXX
};
private static int getRotation(int[] sides, int length)
{
// In a normal pattern, we expect to See
// ** .* D A
// * *
//
// . *
// .. .. C B
//
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A
int cornerBits = 0;
foreach (int side in sides)
{
// XX......X where X's are orientation marks
int t = ((side >> (length - 2)) << 1) + (side & 1);
cornerBits = (cornerBits << 3) + t;
}
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
// together. cornerBits is now:
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
// The result shift indicates which element of BullsEyeCorners[] goes into the top-left
// corner. Since the four rotation values have a Hamming distance of 8, we
// can easily tolerate two errors.
for (int shift = 0; shift < 4; shift++)
{
if (SupportClass.bitCount(cornerBits ^ EXPECTED_CORNER_BITS[shift]) <= 2)
{
return shift;
}
}
return -1;
}
/// <summary>
/// Corrects the parameter bits using Reed-Solomon algorithm
/// </summary>
/// <param name="parameterData">paremeter bits</param>
/// <param name="compact">compact true if this is a compact Aztec code</param>
/// <returns></returns>
private static int getCorrectedParameterData(long parameterData, bool compact)
{
int numCodewords;
int numDataCodewords;
if (compact)
{
numCodewords = 7;
numDataCodewords = 2;
}
else
{
numCodewords = 10;
numDataCodewords = 4;
}
int numECCodewords = numCodewords - numDataCodewords;
int[] parameterWords = new int[numCodewords];
for (int i = numCodewords - 1; i >= 0; --i)
{
parameterWords[i] = (int)parameterData & 0xF;
parameterData >>= 4;
}
var rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
if (!rsDecoder.decode(parameterWords, numECCodewords))
return -1;
// Toss the error correction. Just return the data as an integer
int result = 0;
for (int i = 0; i < numDataCodewords; i++)
{
result = (result << 4) + parameterWords[i];
}
return result;
}
/// <summary>
/// Finds the corners of a bull-eye centered on the passed point
/// This returns the centers of the diagonal points just outside the bull's eye
/// Returns [topRight, bottomRight, bottomLeft, topLeft]
/// </summary>
/// <param name="pCenter">Center point</param>
/// <returns>The corners of the bull-eye</returns>
private ResultPoint[] getBullsEyeCorners(Point pCenter)
{
Point pina = pCenter;
Point pinb = pCenter;
Point pinc = pCenter;
Point pind = pCenter;
bool color = true;
for (nbCenterLayers = 1; nbCenterLayers < 9; nbCenterLayers++)
{
Point pouta = getFirstDifferent(pina, color, 1, -1);
Point poutb = getFirstDifferent(pinb, color, 1, 1);
Point poutc = getFirstDifferent(pinc, color, -1, 1);
Point poutd = getFirstDifferent(pind, color, -1, -1);
//d a
//
//c b
if (nbCenterLayers > 2)
{
var corr = (int)(distance(pina, pouta) / 2);
float q = distance(poutd, pouta)*nbCenterLayers/(distance(pind, pina)*(nbCenterLayers + 2));
if (q < 0.75 || q > 1.25 || !isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd, corr))
{
break;
}
}
pina = pouta;
pinb = poutb;
pinc = poutc;
pind = poutd;
color = !color;
}
if (nbCenterLayers != 5 && nbCenterLayers != 7)
{
return null;
}
compact = nbCenterLayers == 5;
// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
var pinax = new ResultPoint(pina.X + 0.5f, pina.Y - 0.5f);
var pinbx = new ResultPoint(pinb.X + 0.5f, pinb.Y + 0.5f);
var pincx = new ResultPoint(pinc.X - 0.5f, pinc.Y + 0.5f);
var pindx = new ResultPoint(pind.X - 0.5f, pind.Y - 0.5f);
// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return expandSquare(new[] {pinax, pinbx, pincx, pindx},
2*nbCenterLayers - 3,
2*nbCenterLayers);
}
/// <summary>
/// Finds a candidate center point of an Aztec code from an image
/// </summary>
/// <returns>the center point</returns>
private Point getMatrixCenter()
{
ResultPoint pointA;
ResultPoint pointB;
ResultPoint pointC;
ResultPoint pointD;
int cx;
int cy;
//Get a white rectangle that can be the border of the matrix in center bull's eye or
var whiteDetector = WhiteRectangleDetector.Create(image);
if (whiteDetector == null)
return null;
ResultPoint[] cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
cx = image.Width/2;
cy = image.Height/2;
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
//Compute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
whiteDetector = WhiteRectangleDetector.Create(image, 15, cx, cy);
if (whiteDetector == null)
return null;
cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Recompute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
return new Point(cx, cy);
}
/// <summary>
/// Gets the Aztec code corners from the bull's eye corners and the parameters.
/// </summary>
/// <param name="bullsEyeCorners">the array of bull's eye corners</param>
/// <returns>the array of aztec code corners</returns>
private ResultPoint[] getMatrixCornerPoints(ResultPoint[] bullsEyeCorners)
{
return expandSquare(bullsEyeCorners, 2 * nbCenterLayers, getDimension());
}
/// <summary>
/// Creates a BitMatrix by sampling the provided image.
/// topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
/// diagonal just outside the bull's eye.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="topLeft">The top left.</param>
/// <param name="bottomLeft">The bottom left.</param>
/// <param name="bottomRight">The bottom right.</param>
/// <param name="topRight">The top right.</param>
/// <returns></returns>
private BitMatrix sampleGrid(BitMatrix image,
ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomRight,
ResultPoint bottomLeft)
{
GridSampler sampler = GridSampler.Instance;
int dimension = getDimension();
float low = dimension/2.0f - nbCenterLayers;
float high = dimension/2.0f + nbCenterLayers;
return sampler.sampleGrid(image,
dimension,
dimension,
low, low, // topleft
high, low, // topright
high, high, // bottomright
low, high, // bottomleft
topLeft.X, topLeft.Y,
topRight.X, topRight.Y,
bottomRight.X, bottomRight.Y,
bottomLeft.X, bottomLeft.Y);
}
/// <summary>
/// Samples a line
/// </summary>
/// <param name="p1">start point (inclusive)</param>
/// <param name="p2">end point (exclusive)</param>
/// <param name="size">number of bits</param>
/// <returns> the array of bits as an int (first bit is high-order bit of result)</returns>
private int sampleLine(ResultPoint p1, ResultPoint p2, int size)
{
int result = 0;
float d = distance(p1, p2);
float moduleSize = d / size;
float px = p1.X;
float py = p1.Y;
float dx = moduleSize * (p2.X - p1.X) / d;
float dy = moduleSize * (p2.Y - p1.Y) / d;
for (int i = 0; i < size; i++)
{
if (image[MathUtils.round(px + i * dx), MathUtils.round(py + i * dy)])
{
result |= 1 << (size - i - 1);
}
}
return result;
}
/// <summary>
/// Determines whether [is white or black rectangle] [the specified p1].
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <param name="p3">The p3.</param>
/// <param name="p4">The p4.</param>
/// <param name="corr">The correction to check color in the middle.</param>
/// <returns>true if the border of the rectangle passed in parameter is compound of white points only
/// or black points only</returns>
private bool isWhiteOrBlackRectangle(Point p1, Point p2, Point p3, Point p4, int corr)
{
p1 = new Point(p1.X - corr, p1.Y + corr);
p2 = new Point(p2.X - corr, p2.Y - corr);
p3 = new Point(p3.X + corr, p3.Y - corr);
p4 = new Point(p4.X + corr, p4.Y + corr);
int cInit = getColor(p4, p1);
if (cInit == 0)
{
return false;
}
int c = getColor(p1, p2);
if (c != cInit)
{
return false;
}
c = getColor(p2, p3);
if (c != cInit)
{
return false;
}
c = getColor(p3, p4);
return c == cInit;
}
/// <summary>
/// Gets the color of a segment
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <returns>1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else</returns>
private int getColor(Point p1, Point p2)
{
float d = distance(p1, p2);
float dx = (p2.X - p1.X) / d;
float dy = (p2.Y - p1.Y) / d;
int error = 0;
float px = p1.X;
float py = p1.Y;
bool colorModel = image[p1.X, p1.Y];
int iMax = (int) Math.Ceiling(d);
for (int i = 0; i < iMax; i++)
{
px += dx;
py += dy;
if (image[MathUtils.round(px), MathUtils.round(py)] != colorModel)
{
error++;
}
}
float errRatio = error / d;
if (errRatio > 0.1f && errRatio < 0.9f)
{
return 0;
}
return (errRatio <= 0.1f) == colorModel ? 1 : -1;
}
/// <summary>
/// Gets the coordinate of the first point with a different color in the given direction
/// </summary>
/// <param name="init">The init.</param>
/// <param name="color">if set to <c>true</c> [color].</param>
/// <param name="dx">The dx.</param>
/// <param name="dy">The dy.</param>
/// <returns></returns>
private Point getFirstDifferent(Point init, bool color, int dx, int dy)
{
int x = init.X + dx;
int y = init.Y + dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
y += dy;
}
x -= dx;
y -= dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
}
x -= dx;
while (isValid(x, y) && image[x, y] == color)
{
y += dy;
}
y -= dy;
return new Point(x, y);
}
/// <summary>
/// Expand the square represented by the corner points by pushing out equally in all directions
/// </summary>
/// <param name="cornerPoints">the corners of the square, which has the bull's eye at its center</param>
/// <param name="oldSide">the original length of the side of the square in the target bit matrix</param>
/// <param name="newSide">the new length of the size of the square in the target bit matrix</param>
/// <returns>the corners of the expanded square</returns>
private static ResultPoint[] expandSquare(ResultPoint[] cornerPoints, float oldSide, float newSide)
{
float ratio = newSide/(2*oldSide);
float dx = cornerPoints[0].X - cornerPoints[2].X;
float dy = cornerPoints[0].Y - cornerPoints[2].Y;
float centerx = (cornerPoints[0].X + cornerPoints[2].X)/2.0f;
float centery = (cornerPoints[0].Y + cornerPoints[2].Y)/2.0f;
var result0 = new ResultPoint(centerx + ratio*dx, centery + ratio*dy);
var result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
dx = cornerPoints[1].X - cornerPoints[3].X;
dy = cornerPoints[1].Y - cornerPoints[3].Y;
centerx = (cornerPoints[1].X + cornerPoints[3].X)/2.0f;
centery = (cornerPoints[1].Y + cornerPoints[3].Y)/2.0f;
var result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
var result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
return new ResultPoint[] {result0, result1, result2, result3};
}
private bool isValid(int x, int y)
{
return x >= 0 && x < image.Width && y > 0 && y < image.Height;
}
private bool isValid(ResultPoint point)
{
int x = MathUtils.round(point.X);
int y = MathUtils.round(point.Y);
return isValid(x, y);
}
// L2 distance
private static float distance(Point a, Point b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private static float distance(ResultPoint a, ResultPoint b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private int getDimension()
{
if (compact)
{
return 4 * nbLayers + 11;
}
if (nbLayers <= 4)
{
return 4 * nbLayers + 15;
}
return 4 * nbLayers + 2 * ((nbLayers - 4) / 8 + 1) + 15;
}
internal sealed class Point
{
public int X { get; private set; }
public int Y { get; private set; }
public ResultPoint toResultPoint()
{
return new ResultPoint(X, Y);
}
internal Point(int x, int y)
{
X = x;
Y = y;
}
public override String ToString()
{
return "<" + X + ' ' + Y + '>';
}
}
}
}
| |
// 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.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Transactions;
namespace System.Data.SqlClient
{
internal sealed partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
{
private static int _objectTypeCount;
private readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions
internal int ObjectID
{
get
{
return _objectID;
}
}
// WARNING!!! Multithreaded object!
// Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then
// validate this object's active state. Locked activities should ONLY include Sql-transaction state altering activities
// or notifications of same. Updates to the connection's association with the transaction or to the connection pool
// may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy.
private SqlInternalConnection _connection; // the internal connection that is the root of the transaction
private readonly IsolationLevel _isolationLevel; // the IsolationLevel of the transaction we delegated to the server
private SqlInternalTransaction _internalTransaction; // the SQL Server transaction we're delegating to
private readonly Transaction _atomicTransaction;
private bool _active; // Is the transaction active?
internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx)
{
Debug.Assert(null != connection, "null connection?");
_connection = connection;
_atomicTransaction = tx;
_active = false;
Transactions.IsolationLevel systxIsolationLevel = (Transactions.IsolationLevel)tx.IsolationLevel;
// We need to map the System.Transactions IsolationLevel to the one
// that System.Data uses and communicates to SqlServer. We could
// arguably do that in Initialize when the transaction is delegated,
// however it is better to do this before we actually begin the process
// of delegation, in case System.Transactions adds another isolation
// level we don't know about -- we can throw the exception at a better
// place.
_isolationLevel = systxIsolationLevel switch
{
Transactions.IsolationLevel.ReadCommitted => IsolationLevel.ReadCommitted,
Transactions.IsolationLevel.ReadUncommitted => IsolationLevel.ReadUncommitted,
Transactions.IsolationLevel.RepeatableRead => IsolationLevel.RepeatableRead,
Transactions.IsolationLevel.Serializable => IsolationLevel.Serializable,
Transactions.IsolationLevel.Snapshot => IsolationLevel.Snapshot,
_ => throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel),
};
}
internal Transaction Transaction
{
get { return _atomicTransaction; }
}
public void Initialize()
{
// if we get here, then we know for certain that we're the delegated
// transaction.
SqlInternalConnection connection = _connection;
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (connection.IsEnlistedInTransaction)
{ // defect first
connection.EnlistNull();
}
_internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true);
// Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw.
if (null == connection.CurrentTransaction)
{
connection.DoomThisConnection();
throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure);
}
_active = true;
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
internal bool IsActive
{
get
{
return _active;
}
}
public byte[] Promote()
{
// Operations that might be affected by multi-threaded use MUST be done inside the lock.
// Don't read values off of the connection outside the lock unless it doesn't really matter
// from an operational standpoint (i.e. logging connection's ObjectID should be fine,
// but the PromotedDTCToken can change over calls. so that must be protected).
SqlInternalConnection connection = GetValidConnection();
Exception promoteException;
byte[] returnValue = null;
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
returnValue = _connection.PromotedDTCToken;
// For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
if (_connection.IsGlobalTransaction)
{
if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
{
throw SQL.UnsupportedSysTxForGlobalTransactions();
}
if (!_connection.IsGlobalTransactionsEnabledForServer)
{
throw SQL.GlobalTransactionsNotEnabled();
}
SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
}
promoteException = null;
}
catch (SqlException e)
{
promoteException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
promoteException = e;
connection.DoomThisConnection();
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
if (promoteException != null)
{
throw SQL.PromotionFailed(promoteException);
}
return returnValue;
}
// Called by transaction to initiate abort sequence
public void Rollback(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
// If we haven't already rolled back (or aborted) then tell the SQL Server to roll back
if (!_internalTransaction.IsAborted)
{
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, IsolationLevel.Unspecified, _internalTransaction, true);
}
}
catch (SqlException)
{
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
// Unlike SinglePhaseCommit, a rollback is a rollback, regardless
// of how it happens, so SysTx won't throw an exception, and we
// don't want to throw an exception either, because SysTx isn't
// handling it and it may create a fail fast scenario. In the end,
// there is no way for us to communicate to the consumer that this
// failed for more serious reasons than usual.
//
// This is a bit like "should you throw if Close fails", however,
// it only matters when you really need to know. In that case,
// we have the tracing that we're doing to fallback on for the
// investigation.
}
catch (InvalidOperationException)
{
connection.DoomThisConnection();
}
}
// it doesn't matter whether the rollback succeeded or not, we presume
// that the transaction is aborted, because it will be eventually.
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
enlistment.Aborted();
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
// Called by the transaction to initiate commit sequence
public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
// If the connection is dooomed, we can be certain that the
// transaction will eventually be rolled back, and we shouldn't
// attempt to commit it.
if (connection.IsConnectionDoomed)
{
lock (connection)
{
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null;
}
enlistment.Aborted(SQL.ConnectionDoomed());
}
else
{
Exception commitException;
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
commitException = null;
}
catch (SqlException e)
{
commitException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
commitException = e;
connection.DoomThisConnection();
}
}
if (commitException != null)
{
// connection.ExecuteTransaction failed with exception
if (_internalTransaction.IsCommitted)
{
// Even though we got an exception, the transaction
// was committed by the server.
enlistment.Committed();
}
else if (_internalTransaction.IsAborted)
{
// The transaction was aborted, report that to
// SysTx.
enlistment.Aborted(commitException);
}
else
{
// The transaction is still active, we cannot
// know the state of the transaction.
enlistment.InDoubt(commitException);
}
// We eat the exception. This is called on the SysTx
// thread, not the applications thread. If we don't
// eat the exception an UnhandledException will occur,
// causing the process to FailFast.
}
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
if (commitException == null)
{
// connection.ExecuteTransaction succeeded
enlistment.Committed();
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
// Event notification that transaction ended. This comes from the subscription to the Transaction's
// ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call,
// it indicates the transaction was ended externally (generally that one of the DTC participants aborted
// the transaction).
internal void TransactionEnded(Transaction transaction)
{
SqlInternalConnection connection = _connection;
if (connection != null)
{
lock (connection)
{
if (_atomicTransaction.Equals(transaction))
{
// No need to validate active on connection, this operation can be called on completed transactions
_active = false;
_connection = null;
}
}
}
}
// Check for connection validity
private SqlInternalConnection GetValidConnection()
{
SqlInternalConnection connection = _connection;
if (null == connection)
{
throw ADP.ObjectDisposed(this);
}
return connection;
}
// Dooms connection and throws and error if not a valid, active, delegated transaction for the given
// connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return
// may not be trusted.
private void ValidateActiveOnConnection(SqlInternalConnection connection)
{
bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this);
if (!valid)
{
// Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance)
// Doom anything remotely involved.
if (null != connection)
{
connection.DoomThisConnection();
}
if (connection != _connection && null != _connection)
{
_connection.DoomThisConnection();
}
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); //TODO: Create a new code
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// 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 LiveConnectDesktopSample;
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Microsoft.Live.Desktop.Samples.ApiExplorer
{
public partial class MainForm : Form, IRefreshTokenHandler
{
// Update the ClientID with your app client Id that you created from https://account.live.com/developers/applications.
private const string ClientID = "0000000048122D4E";
private LiveAuthForm authForm;
private LiveAuthClient liveAuthClient;
private LiveConnectClient liveConnectClient;
private RefreshTokenInfo refreshTokenInfo;
public MainForm()
{
if (ClientID.Contains('%'))
{
throw new ArgumentException("Update the ClientID with your app client Id that you created from https://account.live.com/developers/applications.");
}
InitializeComponent();
}
private LiveAuthClient AuthClient
{
get
{
if (this.liveAuthClient == null)
{
this.AuthClient = new LiveAuthClient(ClientID, this);
}
return this.liveAuthClient;
}
set
{
if (this.liveAuthClient != null)
{
this.liveAuthClient.PropertyChanged -= this.liveAuthClient_PropertyChanged;
}
this.liveAuthClient = value;
if (this.liveAuthClient != null)
{
this.liveAuthClient.PropertyChanged += this.liveAuthClient_PropertyChanged;
}
this.liveConnectClient = null;
}
}
private LiveConnectSession AuthSession
{
get
{
return this.AuthClient.Session;
}
}
private void liveAuthClient_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Session")
{
this.UpdateUIElements();
}
}
private void UpdateUIElements()
{
LiveConnectSession session = this.AuthSession;
bool isSignedIn = session != null;
this.signOutButton.Enabled = isSignedIn;
this.connectGroupBox.Enabled = isSignedIn;
this.currentScopeTextBox.Text = isSignedIn ? string.Join(" ", session.Scopes) : string.Empty;
if (!isSignedIn)
{
this.meNameLabel.Text = string.Empty;
this.mePictureBox.Image = null;
}
}
private void SigninButton_Click(object sender, EventArgs e)
{
if (this.authForm == null)
{
string startUrl = this.AuthClient.GetLoginUrl(this.GetAuthScopes());
string endUrl = "https://login.live.com/oauth20_desktop.srf";
this.authForm = new LiveAuthForm(
startUrl,
endUrl,
this.OnAuthCompleted);
this.authForm.FormClosed += AuthForm_FormClosed;
this.authForm.ShowDialog(this);
}
}
private string[] GetAuthScopes()
{
string[] scopes = new string[this.scopeListBox.SelectedItems.Count];
this.scopeListBox.SelectedItems.CopyTo(scopes, 0);
return scopes;
}
void AuthForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.CleanupAuthForm();
}
private void CleanupAuthForm()
{
if (this.authForm != null)
{
this.authForm.Dispose();
this.authForm = null;
}
}
private void LogOutput(string text)
{
this.outputTextBox.Text += text + Environment.NewLine;
}
private async void OnAuthCompleted(AuthResult result)
{
this.CleanupAuthForm();
if (result.AuthorizeCode != null)
{
try
{
LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode);
this.liveConnectClient = new LiveConnectClient(session);
LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
dynamic meData = meRs.Result;
this.meNameLabel.Text = meData.name;
LiveDownloadOperationResult meImgResult = await this.liveConnectClient.DownloadAsync("me/picture");
this.mePictureBox.Image = Image.FromStream(meImgResult.Stream);
}
catch (LiveAuthException aex)
{
this.LogOutput("Failed to retrieve access token. Error: " + aex.Message);
}
catch (LiveConnectException cex)
{
this.LogOutput("Failed to retrieve the user's data. Error: " + cex.Message);
}
}
else
{
this.LogOutput(string.Format("Error received. Error: {0} Detail: {1}", result.ErrorCode, result.ErrorDescription));
}
}
private void SignOutButton_Click(object sender, EventArgs e)
{
this.signOutWebBrowser.Navigate(this.AuthClient.GetLogoutUrl());
this.AuthClient = null;
this.UpdateUIElements();
}
private void ClearOutputButton_Click(object sender, EventArgs e)
{
this.outputTextBox.Text = string.Empty;
}
private void ScopeListBox_SelectedIndexChanged(object sender, EventArgs e)
{
this.signinButton.Enabled = this.scopeListBox.SelectedItems.Count > 0;
}
private async void ExecuteButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(this.pathTextBox.Text))
{
this.LogOutput("Path cannot be empty.");
return;
}
try
{
LiveOperationResult result = null;
switch (this.methodComboBox.Text)
{
case "GET":
result = await this.liveConnectClient.GetAsync(this.pathTextBox.Text);
break;
case "PUT":
result = await this.liveConnectClient.PutAsync(this.pathTextBox.Text, this.requestBodyTextBox.Text);
break;
case "POST":
result = await this.liveConnectClient.PostAsync(this.pathTextBox.Text, this.requestBodyTextBox.Text);
break;
case "DELETE":
result = await this.liveConnectClient.DeleteAsync(this.pathTextBox.Text);
break;
case "MOVE":
result = await this.liveConnectClient.MoveAsync(this.pathTextBox.Text, this.destPathTextBox.Text);
break;
case "COPY":
result = await this.liveConnectClient.CopyAsync(this.pathTextBox.Text, this.destPathTextBox.Text);
break;
case "UPLOAD":
result = await this.UploadFile(this.pathTextBox.Text);
break;
case "DOWNLOAD":
await this.DownloadFile(this.pathTextBox.Text);
this.LogOutput("The download operation is completed.");
break;
}
if (result != null)
{
this.LogOutput(this.methodComboBox.Text + "\t" + this.pathTextBox.Text);
this.LogOutput(JsonHelper.FormatJson(result.RawResult));
this.LogOutput(string.Empty);
}
}
catch (Exception ex)
{
this.LogOutput("Received an error. " + ex.Message);
}
}
private async Task<LiveOperationResult> UploadFile(string path)
{
OpenFileDialog dialog = new OpenFileDialog();
Stream stream = null;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() != DialogResult.OK)
{
throw new InvalidOperationException("No file is picked to upload.");
}
try
{
if ((stream = dialog.OpenFile()) == null)
{
throw new Exception("Unable to open the file selected to upload.");
}
using (stream)
{
return await this.liveConnectClient.UploadAsync(path, dialog.SafeFileName, stream, OverwriteOption.DoNotOverwrite);
}
}
catch (Exception ex)
{
throw ex;
}
}
private async Task DownloadFile(string path)
{
SaveFileDialog dialog = new SaveFileDialog();
Stream stream = null;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() != DialogResult.OK)
{
throw new InvalidOperationException("No file is picked to upload.");
}
try
{
if ((stream = dialog.OpenFile()) == null)
{
throw new Exception("Unable to open the file selected to upload.");
}
using (stream)
{
LiveDownloadOperationResult result = await this.liveConnectClient.DownloadAsync(path);
if (result.Stream != null)
{
using (result.Stream)
{
await result.Stream.CopyToAsync(stream);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private async void MainForm_Load(object sender, EventArgs e)
{
this.methodComboBox.SelectedIndex = 0;
this.scopeListBox.SelectedIndex = 0;
try
{
LiveLoginResult loginResult = await this.AuthClient.InitializeAsync();
if (loginResult.Session != null)
{
this.liveConnectClient = new LiveConnectClient(loginResult.Session);
}
}
catch (Exception ex)
{
this.LogOutput("Received an error during initializing. " + ex.Message);
}
}
private void MainForm_ClientSizeChange(object sender, EventArgs e)
{
this.connectGroupBox.SetBounds(
this.connectGroupBox.Bounds.X,
this.connectGroupBox.Bounds.Y,
Width - 43 > 0 ? Width - 43 : 658,
Height - 200 > 0 ? Height - 200 : 394);
this.outputTextBox.SetBounds(
this.outputTextBox.Bounds.X,
this.outputTextBox.Bounds.Y,
Width - 131 > 0 ? Width - 131 : 570,
Height - 388 > 0 ? Height - 388 : 209);
}
Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
{
// Note:
// 1) In order to receive refresh token, wl.offline_access scope is needed.
// 2) Alternatively, we can persist the refresh token.
return Task.Factory.StartNew(() =>
{
this.refreshTokenInfo = tokenInfo;
});
}
Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync()
{
return Task.Factory.StartNew<RefreshTokenInfo>(() =>
{
return this.refreshTokenInfo;
});
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* LinePlot.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT 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.Drawing;
namespace NPlot
{
/// <summary>
/// Encapsulates functionality for plotting data as a line chart.
/// </summary>
public class LinePlot : BaseSequencePlot, IPlot, ISequencePlot
{
private Pen pen_ = new Pen(Color.Black);
private Color shadowColor_ = Color.FromArgb(100, 100, 100);
private Point shadowOffset_ = new Point(1, 1);
private bool shadow_;
/// <summary>
/// Default constructor
/// </summary>
public LinePlot()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="dataSource">The data source to associate with this plot</param>
public LinePlot(object dataSource)
{
DataSource = dataSource;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ordinateData">the ordinate data to associate with this plot.</param>
/// <param name="abscissaData">the abscissa data to associate with this plot.</param>
public LinePlot(object ordinateData, object abscissaData)
{
OrdinateData = ordinateData;
AbscissaData = abscissaData;
}
/// <summary>
/// If true, draw a shadow under the line.
/// </summary>
public bool Shadow
{
get { return shadow_; }
set { shadow_ = value; }
}
/// <summary>
/// Color of line shadow if drawn. Use Shadow method to turn shadow on and off.
/// </summary>
public Color ShadowColor
{
get { return shadowColor_; }
set { shadowColor_ = value; }
}
/// <summary>
/// Offset of shadow line from primary line.
/// </summary>
public Point ShadowOffset
{
get { return shadowOffset_; }
set { shadowOffset_ = value; }
}
/// <summary>
/// The pen used to draw the plot
/// </summary>
public Pen Pen
{
get { return pen_; }
set { pen_ = value; }
}
/// <summary>
/// The color of the pen used to draw lines in this plot.
/// </summary>
public Color Color
{
set
{
if (pen_ != null)
{
pen_.Color = value;
}
else
{
pen_ = new Pen(value);
}
}
get { return pen_.Color; }
}
/// <summary>
/// Draws the line plot on a GDI+ surface against the provided x and y axes.
/// </summary>
/// <param name="g">The GDI+ surface on which to draw.</param>
/// <param name="xAxis">The X-Axis to draw against.</param>
/// <param name="yAxis">The Y-Axis to draw against.</param>
public void Draw(Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis)
{
if (shadow_)
{
DrawLineOrShadow(g, xAxis, yAxis, true);
}
DrawLineOrShadow(g, xAxis, yAxis, false);
}
/// <summary>
/// Returns an x-axis that is suitable for drawing this plot.
/// </summary>
/// <returns>A suitable x-axis.</returns>
public Axis SuggestXAxis()
{
SequenceAdapter data_ =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
return data_.SuggestXAxis();
}
/// <summary>
/// Returns a y-axis that is suitable for drawing this plot.
/// </summary>
/// <returns>A suitable y-axis.</returns>
public Axis SuggestYAxis()
{
SequenceAdapter data_ =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
return data_.SuggestYAxis();
}
/// <summary>
/// Draws a representation of this plot in the legend.
/// </summary>
/// <param name="g">The graphics surface on which to draw.</param>
/// <param name="startEnd">A rectangle specifying the bounds of the area in the legend set aside for drawing.</param>
public virtual void DrawInLegend(Graphics g, Rectangle startEnd)
{
g.DrawLine(pen_, startEnd.Left, (startEnd.Top + startEnd.Bottom)/2,
startEnd.Right, (startEnd.Top + startEnd.Bottom)/2);
}
/// <summary>
/// Draws the line plot on a GDI+ surface against the provided x and y axes.
/// </summary>
/// <param name="g">The GDI+ surface on which to draw.</param>
/// <param name="xAxis">The X-Axis to draw against.</param>
/// <param name="yAxis">The Y-Axis to draw against.</param>
/// <param name="drawShadow">If true draw the shadow for the line. If false, draw line.</param>
public void DrawLineOrShadow(Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis, bool drawShadow)
{
Pen shadowPen = null;
if (drawShadow)
{
shadowPen = (Pen) Pen.Clone();
shadowPen.Color = ShadowColor;
}
SequenceAdapter data =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
ITransform2D t = Transform2D.GetTransformer(xAxis, yAxis);
int numberPoints = data.Count;
if (data.Count == 0)
{
return;
}
// clipping is now handled assigning a clip region in the
// graphic object before this call
if (numberPoints == 1)
{
PointF physical = t.Transform(data[0]);
if (drawShadow)
{
g.DrawLine(shadowPen,
physical.X - 0.5f + ShadowOffset.X,
physical.Y + ShadowOffset.Y,
physical.X + 0.5f + ShadowOffset.X,
physical.Y + ShadowOffset.Y);
}
else
{
g.DrawLine(Pen, physical.X - 0.5f, physical.Y, physical.X + 0.5f, physical.Y);
}
}
else
{
// prepare for clipping
double leftCutoff = xAxis.PhysicalToWorld(xAxis.PhysicalMin, false);
double rightCutoff = xAxis.PhysicalToWorld(xAxis.PhysicalMax, false);
if (leftCutoff > rightCutoff)
{
Utils.Swap(ref leftCutoff, ref rightCutoff);
}
if (drawShadow)
{
// correct cut-offs
double shadowCorrection =
xAxis.PhysicalToWorld(ShadowOffset, false) - xAxis.PhysicalToWorld(new Point(0, 0), false);
leftCutoff -= shadowCorrection;
rightCutoff -= shadowCorrection;
}
for (int i = 1; i < numberPoints; ++i)
{
// check to see if any values null. If so, then continue.
double dx1 = data[i - 1].X;
double dx2 = data[i].X;
double dy1 = data[i - 1].Y;
double dy2 = data[i].Y;
if (Double.IsNaN(dx1) || Double.IsNaN(dy1) ||
Double.IsNaN(dx2) || Double.IsNaN(dy2))
{
continue;
}
// do horizontal clipping here, to speed up
if ((dx1 < leftCutoff || rightCutoff < dx1) &&
(dx2 < leftCutoff || rightCutoff < dx2))
{
continue;
}
// else draw line.
PointF p1 = t.Transform(data[i - 1]);
PointF p2 = t.Transform(data[i]);
// when very far zoomed in, points can fall ontop of each other,
// and g.DrawLine throws an overflow exception
if (p1.Equals(p2))
continue;
if (drawShadow)
{
g.DrawLine(shadowPen,
p1.X + ShadowOffset.X,
p1.Y + ShadowOffset.Y,
p2.X + ShadowOffset.X,
p2.Y + ShadowOffset.Y);
}
else
{
g.DrawLine(Pen, p1.X, p1.Y, p2.X, p2.Y);
}
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullableAddTests
{
#region Test methods
[Fact]
public static void CheckNullableByteAddTest()
{
byte?[] array = new byte?[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteAdd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSByteAddTest()
{
sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteAdd(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortAddTest(bool useInterpreter)
{
ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortAddTest(bool useInterpreter)
{
short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntAddTest(bool useInterpreter)
{
uint?[] array = new uint?[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntAddTest(bool useInterpreter)
{
int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongAddTest(bool useInterpreter)
{
ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongAddTest(bool useInterpreter)
{
long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatAddTest(bool useInterpreter)
{
float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleAddTest(bool useInterpreter)
{
double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalAddTest(bool useInterpreter)
{
decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalAdd(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckNullableCharAddTest()
{
char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharAdd(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteAdd(byte? a, byte? b)
{
Expression aExp = Expression.Constant(a, typeof(byte?));
Expression bExp = Expression.Constant(b, typeof(byte?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifyNullableSByteAdd(sbyte? a, sbyte? b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte?));
Expression bExp = Expression.Constant(b, typeof(sbyte?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifyNullableUShortAdd(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Add(
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 VerifyNullableShortAdd(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Add(
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 VerifyNullableUIntAdd(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Add(
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 VerifyNullableIntAdd(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Add(
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 VerifyNullableULongAdd(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Add(
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 VerifyNullableLongAdd(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Add(
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 VerifyNullableFloatAdd(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Add(
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 VerifyNullableDoubleAdd(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Add(
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 VerifyNullableDecimalAdd(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Add(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected = 0;
try
{
expected = a + b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableCharAdd(char? a, char? b)
{
Expression aExp = Expression.Constant(a, typeof(char?));
Expression bExp = Expression.Constant(b, typeof(char?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using bv.common;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.db.Core;
using bv.common.Enums;
using bv.common.Resources;
using bv.model.Model.Core;
using bv.winclient.Core;
using DevExpress.Data.Filtering;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraPivotGrid;
using EIDSS;
using eidss.avr.BaseComponents;
using eidss.avr.BaseComponents.Views;
using eidss.avr.db.Common;
using eidss.avr.db.DBService;
using eidss.avr.db.DBService.DataSource;
using eidss.avr.PivotComponents;
using eidss.avr.Tools;
using eidss.model.Avr.Chart;
using eidss.model.Avr.Commands;
using eidss.model.Avr.Commands.Layout;
using eidss.model.Avr.Pivot;
using eidss.model.Enums;
using eidss.model.Reports.OperationContext;
using eidss.model.Resources;
using BaseReferenceType = bv.common.db.BaseReferenceType;
using Localizer = bv.common.Core.Localizer;
namespace eidss.avr.PivotForm
{
public sealed class PivotDetailPresenter : RelatedObjectPresenter
{
private readonly IPivotDetailView m_PivotView;
private readonly BaseAvrDbService m_PivotFormService;
private readonly LayoutMediator m_LayoutMediator;
static PivotDetailPresenter()
{
InitGisTypes();
}
public PivotDetailPresenter(SharedPresenter sharedPresenter, IPivotDetailView view)
: base(sharedPresenter, view)
{
m_PivotFormService = new BaseAvrDbService();
m_PivotView = view;
m_PivotView.DBService = PivotFormService;
m_LayoutMediator = new LayoutMediator(this);
}
public bool Changed { get; set; }
public static Dictionary<string, GisCaseType> GisTypeDictionary { get; private set; }
public BaseAvrDbService PivotFormService
{
get { return m_PivotFormService; }
}
public string CorrectedLayoutName
{
get
{
return (Utils.IsEmpty(LayoutName))
? EidssMessages.Get("msgNoReportHeader", "[Untitled]")
: LayoutName;
}
}
public string LayoutName
{
get
{
return (ModelUserContext.CurrentLanguage == Localizer.lngEn)
? m_LayoutMediator.LayoutRow.strDefaultLayoutName
: m_LayoutMediator.LayoutRow.strLayoutName;
}
}
public long LayoutId
{
get { return m_LayoutMediator.LayoutRow.idflLayout; }
}
public bool ApplyFilter
{
get { return m_LayoutMediator.LayoutRow.blnApplyPivotGridFilter; }
}
public PivotGridXmlVersion PivotGridXmlVersion
{
get { return (PivotGridXmlVersion) m_LayoutMediator.LayoutRow.intPivotGridXmlVersion; }
}
public LayoutDetailDataSet.LayoutSearchFieldDataTable LayoutSearchFieldTable
{
get { return m_LayoutMediator.LayoutDataSet.LayoutSearchField; }
}
public string SettingsXml
{
get
{
string basicXml = m_LayoutMediator.LayoutRow.IsstrPivotGridSettingsNull()
? String.Empty
: m_LayoutMediator.LayoutRow.strPivotGridSettings;
return basicXml;
}
set { m_LayoutMediator.LayoutRow.strPivotGridSettings = value; }
}
public bool ReadOnly
{
get { return m_LayoutMediator.LayoutRow.blnReadOnly; }
}
public bool FreezeRowHeaders
{
get { return m_LayoutMediator.LayoutRow.blnFreezeRowHeaders; }
}
public bool ShowMissedValues
{
get { return m_LayoutMediator.LayoutRow.blnShowMissedValuesInPivotGrid; }
}
public bool CopyPivotName { get; set; }
public bool CopyMapName { get; set; }
public bool CopyChartName { get; set; }
#region Binding
public void BindFreezeRowHeaders(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnFreezeRowHeadersColumn.ColumnName);
}
public void BindShareLayout(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShareLayoutColumn.ColumnName);
}
public void BindApplyFilter(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnApplyPivotGridFilterColumn.ColumnName);
}
public void BindShowMissedValues(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShowMissedValuesInPivotGridColumn.ColumnName);
}
public void BindDefaultLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDefaultLayoutNameColumn.ColumnName);
}
public void BindLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strLayoutNameColumn.ColumnName);
}
public void BindDescription(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDescriptionColumn.ColumnName);
}
internal void BindGroupInterval(LookUpEdit comboBox)
{
BindingHelper.BindCombobox(comboBox,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.idfsDefaultGroupDateColumn.ColumnName,
BaseReferenceType.rftGroupInterval,
(long) DBGroupInterval.gitDateYear);
}
public void BindShowTotalCols(CheckedComboBoxEdit edit)
{
edit.Properties.Items[0].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColsTotals);
edit.Properties.Items[1].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowsTotals);
edit.Properties.Items[2].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColGrandTotals);
edit.Properties.Items[3].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowGrandTotals);
edit.Properties.Items[4].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowForSingleTotals);
edit.RefreshEditValue();
edit.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
if (Utils.IsEmpty(edit.EditValue))
{
edit.EditValue = DBNull.Value;
}
}
public void BindBackShowTotalCols(CheckedComboBoxEdit edit, PivotGridOptionsView optionsView, bool isCompact)
{
if (isCompact)
{
optionsView.ShowRowTotals = true;
optionsView.ShowTotalsForSingleValues = true;
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Tree;
}
else
{
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Far;
m_LayoutMediator.LayoutRow.blnShowColsTotals = IsChecked(edit, 0);
m_LayoutMediator.LayoutRow.blnShowRowsTotals = IsChecked(edit, 1);
m_LayoutMediator.LayoutRow.blnShowColGrandTotals = IsChecked(edit, 2);
m_LayoutMediator.LayoutRow.blnShowRowGrandTotals = IsChecked(edit, 3);
m_LayoutMediator.LayoutRow.blnShowForSingleTotals = IsChecked(edit, 4);
optionsView.ShowColumnTotals = m_LayoutMediator.LayoutRow.blnShowColsTotals;
optionsView.ShowRowTotals = m_LayoutMediator.LayoutRow.blnShowRowsTotals;
optionsView.ShowColumnGrandTotals = m_LayoutMediator.LayoutRow.blnShowColGrandTotals;
optionsView.ShowRowGrandTotals = m_LayoutMediator.LayoutRow.blnShowRowGrandTotals;
optionsView.ShowTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
optionsView.ShowGrandTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
}
}
private static CheckState GetCheckState(bool flag)
{
return flag
? CheckState.Checked
: CheckState.Unchecked;
}
private static bool IsChecked(CheckedComboBoxEdit edit, int index)
{
if (index >= edit.Properties.Items.Count || index < 0)
{
throw new ArgumentException("Index out of range");
}
return edit.Properties.Items[index].CheckState == CheckState.Checked;
}
#endregion
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strLayoutName = layoutName;
}
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetDefaultLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strDefaultLayoutName = layoutName;
}
public void InitAdmUnit(LookUpEdit cbAdministrativeUnit, IAvrPivotGridField selectedField)
{
using (SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.InitAdmUnit))
{
DataView dataView = AvrPivotGridHelper.GetAdministrativeUnitView(m_SharedPresenter.SharedModel.SelectedQueryId,
m_PivotView.AvrFields.ToList());
string fieldAlias = SharedPresenter.GetSelectedAdministrativeFieldAlias(dataView, selectedField);
SharedPresenter.BindComboBox(cbAdministrativeUnit, dataView, fieldAlias);
}
}
public void InitStatDate(LookUpEdit cbStatDate, IAvrPivotGridField selectedField)
{
DataView dataView = AvrPivotGridHelper.GetStatisticDateView(m_PivotView.AvrFields);
string fieldAlias = selectedField == null
? null
: selectedField.GetSelectedDateFieldAlias();
SharedPresenter.BindComboBox(cbStatDate, dataView, fieldAlias);
}
public override void Process(Command cmd)
{
try
{
var fieldCommand = cmd as PivotFieldCommand;
if (fieldCommand != null)
{
switch (fieldCommand.FieldOperation)
{
case PivotFieldOperation.Rename:
ProcessRenameFieldCaption(fieldCommand);
break;
case PivotFieldOperation.Copy:
ProcessCopyField(fieldCommand);
break;
case PivotFieldOperation.DeleteCopy:
ProcessDeleteField(fieldCommand);
break;
case PivotFieldOperation.AddMissedValues:
ProcessAddMissedValues(fieldCommand);
break;
case PivotFieldOperation.DeleteMissedValues:
ProcessDeleteMissedValues(fieldCommand);
break;
}
}
var fieldGroupDateCommand = cmd as PivotFieldGroupIntervalCommand;
if (fieldGroupDateCommand != null)
{
ProcessGroupInterval(fieldGroupDateCommand);
}
}
catch (Exception ex)
{
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
ErrorForm.ShowError(ex);
}
}
private void ProcessRenameFieldCaption(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
LayoutDetailDataSet.LayoutSearchFieldRow row = GetLayoutSearchFieldRowByField(command.Field);
using (var form = new RenameFieldDialog(row.strOriginalFieldENCaption, row.strOriginalFieldCaption,
row.strNewFieldENCaption, row.strNewFieldCaption))
{
if (form.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
row.strNewFieldENCaption = form.NewEnglishCaption;
row.strNewFieldCaption = ModelUserContext.CurrentLanguage == Localizer.lngEn
? form.NewEnglishCaption
: form.NewNationalCaption;
command.Field.Caption = row.strNewFieldCaption;
m_PivotView.InitFilterControlHelperAndRefreshFilter();
}
}
command.State = CommandState.Processed;
}
private void ProcessCopyField(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
using (m_PivotView.PivotGridView.BeginTransaction())
{
CreateFieldCopy<WinPivotGridField>(command.Field);
m_PivotView.PivotGridView.ClearCacheDataRowColumnAreaFields();
}
m_PivotView.ClickOnFocusedCell(true);
command.State = CommandState.Processed;
}
private void ProcessDeleteField(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
using (m_PivotView.PivotGridView.BeginTransaction())
{
DeleteFieldCopy(command.Field);
m_PivotView.PivotGridView.ClearCacheDataRowColumnAreaFields();
}
m_PivotView.ClickOnFocusedCell(true);
//AjustCreateDeleteFieldsEnable();
command.State = CommandState.Processed;
}
private void ProcessAddMissedValues(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
IAvrPivotGridField field = command.Field;
bool needToChange = !field.IsDateTimeField;
if (field.IsDateTimeField)
{
using (var form = new DateDiapasonDialog(field.DiapasonStartDate, field.DiapasonEndDate))
{
if (form.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
field.DiapasonStartDate = form.DateFrom;
field.DiapasonEndDate = form.DateTo;
needToChange = true;
}
}
}
if (needToChange)
{
foreach (IAvrPivotGridField change in GetFieldCopiesExceptHidden(command))
{
change.AddMissedValues = true;
change.UpdateImageIndex();
}
Changed = true;
m_PivotView.RejectChangesAddMissingValues();
}
command.State = CommandState.Processed;
}
private void ProcessDeleteMissedValues(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
foreach (IAvrPivotGridField change in GetFieldCopiesExceptHidden(command))
{
change.DiapasonStartDate = null;
change.DiapasonEndDate = null;
change.AddMissedValues = false;
change.UpdateImageIndex();
}
Changed = true;
m_PivotView.RejectChangesAddMissingValues(m_PivotView.ShowData);
command.State = CommandState.Processed;
}
private IEnumerable<IAvrPivotGridField> GetFieldCopiesExceptHidden(PivotFieldCommand command)
{
IEnumerable<IAvrPivotGridField> fieldsToChange = command.Field.IsDateTimeField
? new List<IAvrPivotGridField> {command.Field}
: m_PivotView.AvrFields.Where(f => !f.IsHiddenFilterField && f.GetOriginalName() == command.Field.GetOriginalName());
return fieldsToChange;
}
private void ProcessGroupInterval(PivotFieldGroupIntervalCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
IAvrPivotGridField field = command.Field;
field.PrivateGroupInterval = command.GroupInterval;
m_PivotView.RejectChangesAddMissingValues();
command.State = CommandState.Processed;
}
#region Prepare Data Source For Pivot Grid
public DataTable GetPreparedDataSource()
{
if (m_SharedPresenter.IsQueryResultNull)
{
return null;
}
DataTable newDataSource = m_SharedPresenter.GetQueryResultCopy();
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
bool isNewObject = IsNewObject || LayoutSearchFieldTable.Count == 0;
return AvrPivotGridHelper.GetPreparedDataSource(LayoutSearchFieldTable, queryId, LayoutId, newDataSource, isNewObject);
}
#endregion
#region Load Pivot Grid
public void LoadPivotFromDB()
{
List<IAvrPivotGridField> avrFields = m_PivotView.AvrFields.ToList();
if (!IsNewObject)
{
if (PivotGridXmlVersion == PivotGridXmlVersion.Version6)
{
long intervalId = m_LayoutMediator.LayoutRow.idfsDefaultGroupDate;
AvrPivotGridHelper.LoadSearchFieldsVersionSixFromDB(avrFields, LayoutSearchFieldTable, intervalId);
LoadPivotFilterVersionSixFromDB();
}
else
{
LoadPivotVersionFiveFromDB();
}
}
AvrPivotGridHelper.LoadExstraSearchFieldsProperties(avrFields, LayoutSearchFieldTable);
}
private void LoadPivotFilterVersionSixFromDB()
{
try
{
m_PivotView.PivotGridView.Criteria = CriteriaOperator.Parse(SettingsXml);
}
catch (Exception ex)
{
m_PivotView.PivotGridView.Criteria = null;
Trace.WriteLine(ex);
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
string msg = EidssMessages.Get("errCannotRestoreAvrFilterFromDb", "Pivot Grid filter can't be restored from Database");
ErrorForm.ShowErrorDirect(msg, ex);
}
}
private void LoadPivotVersionFiveFromDB()
{
if (!string.IsNullOrEmpty(SettingsXml))
{
using (var stream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.Write(SettingsXml);
streamWriter.Flush();
stream.Position = 0;
m_PivotView.PivotGridView.RestoreLayoutFromStream(stream);
}
}
}
else
{
m_PivotView.PivotGridView.CriteriaString = string.Empty;
}
}
#endregion
#region Save Pivot Grid
public void SavePivotFilterToDB(CriteriaOperator filter)
{
Changed = false;
SettingsXml = (ReferenceEquals(filter, null)) ? null : filter.ToString();
}
#endregion
#region Create and delete Field Copy
public Dictionary<IAvrPivotGridField, IAvrPivotGridField> GetFieldsAndCopies()
{
var fieldsAndCopies = new Dictionary<IAvrPivotGridField, IAvrPivotGridField>();
foreach (IAvrPivotGridField field in m_PivotView.AvrFields.Where(f => !f.IsHiddenFilterField))
{
IAvrPivotGridField fieldCopy =
m_PivotView.AvrFields.FirstOrDefault(f => f.IsHiddenFilterField && f.GetOriginalName() == field.GetOriginalName());
if (fieldCopy != null)
{
fieldsAndCopies.Add(field, fieldCopy);
}
}
return fieldsAndCopies;
}
public void CreateFieldCopy<T>(IAvrPivotGridField sourceField) where T : IAvrPivotGridField, new()
{
var copy = AvrPivotGridHelper.CreateFieldCopy<T>(sourceField,
m_LayoutMediator.LayoutDataSet,
m_PivotView.DataSource,
m_SharedPresenter.SharedModel.SelectedQueryId,
LayoutId);
m_PivotView.AddField(copy);
m_PivotView.DataSource.AcceptChanges();
m_PivotView.RefreshPivotData();
}
private LayoutDetailDataSet.LayoutSearchFieldRow GetLayoutSearchFieldRowByField(IAvrPivotGridField sourceField)
{
return AvrPivotGridHelper.GetLayoutSearchFieldRowByField(sourceField, m_LayoutMediator.LayoutDataSet);
}
public void DeleteFieldCopy(IAvrPivotGridField sourceField)
{
string message =String.Format(BvMessages.Get("msgDeleteAVRFieldPrompt", "{0} field will be deleted. Delete field?"),
sourceField.Caption);
DialogResult dialogResult = MessageForm.Show(message, BvMessages.Get("Confirmation"),
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult != DialogResult.Yes)
{
return;
}
AvrPivotGridHelper.DeleteFieldCopy(sourceField, m_LayoutMediator.LayoutDataSet, m_PivotView.DataSource);
m_PivotView.RemoveField(sourceField);
m_PivotView.DataSource.AcceptChanges();
m_PivotView.RefreshPivotData();
}
#endregion
#region Helper Methods
private static void InitGisTypes()
{
GisTypeDictionary = new Dictionary<string, GisCaseType>();
DataView lookupGisTypes = LookupCache.Get(LookupTables.CaseType.ToString());
if (lookupGisTypes == null)
{
return;
}
foreach (DataRowView row in lookupGisTypes)
{
string key = row["name"].ToString();
if (!GisTypeDictionary.ContainsKey(key))
{
var id = (long) row["idfsReference"];
switch (id)
{
case (long) CaseTypeEnum.Human:
GisTypeDictionary.Add(key, GisCaseType.Human);
break;
case (long) CaseTypeEnum.Livestock:
GisTypeDictionary.Add(key, GisCaseType.Livestock);
break;
case (long) CaseTypeEnum.Avian:
GisTypeDictionary.Add(key, GisCaseType.Avian);
break;
case (long) CaseTypeEnum.Veterinary:
GisTypeDictionary.Add(key, GisCaseType.Vet);
break;
case (long) CaseTypeEnum.Vector:
GisTypeDictionary.Add(key, GisCaseType.Vector);
break;
default:
GisTypeDictionary.Add(key, GisCaseType.Unkown);
break;
}
}
}
}
public static bool AskQuestion(string text, string caption)
{
return MessageForm.Show(text, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes;
}
public static string AppendLanguageNameTo(string text)
{
if (!Utils.IsEmpty(text))
{
int bracketInd = text.IndexOf("(", StringComparison.Ordinal);
if (bracketInd >= 0)
{
text = text.Substring(0, bracketInd).Trim();
}
string languageName = Localizer.GetLanguageName(ModelUserContext.CurrentLanguage);
text = String.Format("{0} ({1})", text, languageName);
}
return text;
}
#endregion
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.NodejsTools.Debugger.DebugEngine {
#region Event base classes
class AD7AsynchronousEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7StoppingEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2 {
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 m_engine;
AD7EngineCreateEvent(AD7Engine engine) {
m_engine = engine;
}
public static void Send(AD7Engine engine) {
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine) {
engine = m_engine;
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2 {
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine) {
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ExpressionEvaluationCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2 {
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
private readonly IDebugExpression2 _expression;
private readonly IDebugProperty2 _property;
public AD7ExpressionEvaluationCompleteEvent(IDebugExpression2 expression, IDebugProperty2 property) {
this._expression = expression;
this._property = property;
}
#region IDebugExpressionEvaluationCompleteEvent2 Members
public int GetExpression(out IDebugExpression2 ppExpr) {
ppExpr = _expression;
return VSConstants.S_OK;
}
public int GetResult(out IDebugProperty2 ppResult) {
ppResult = _property;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2 {
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
readonly AD7Module m_module;
readonly bool m_fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad) {
m_module = module;
m_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad) {
module = m_module;
if (m_fLoad) {
debugMessage = null; //String.Concat("Loaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 1;
} else {
debugMessage = null; // String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 0;
}
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2 {
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
readonly uint m_exitCode;
public AD7ProgramDestroyEvent(uint exitCode) {
m_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode) {
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2 {
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2 {
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
readonly uint m_exitCode;
public AD7ThreadDestroyEvent(uint exitCode) {
m_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode) {
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2 {
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent() {
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but running.
sealed class AD7LoadCompleteRunningEvent : AD7AsynchronousEvent, IDebugLoadCompleteEvent2 {
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteRunningEvent() {
}
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2 {
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7SteppingCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2 {
public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D";
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2 {
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint m_pendingBreakpoint;
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint) {
m_pendingBreakpoint = pendingBreakpoint;
m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) {
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = m_boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return VSConstants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP) {
ppPendingBP = m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when a bound breakpoint has been unbound in the debuggee.
sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2 {
public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c";
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointUnboundEvent(AD7BoundBreakpoint boundBreakpoint) {
m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointUnboundEvent2 Members
int IDebugBreakpointUnboundEvent2.GetBreakpoint(out IDebugBoundBreakpoint2 ppBP)
{
ppBP = m_boundBreakpoint;
return VSConstants.S_OK;
}
int IDebugBreakpointUnboundEvent2.GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason)
{
pdwUnboundReason[0] = enum_BP_UNBOUND_REASON.BPUR_BREAKPOINT_REBIND;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2, IDebugErrorBreakpoint2, IDebugErrorBreakpointResolution2 {
public const string IID = "abb0ca42-f82b-4622-84e4-6903ae90f210";
private AD7Engine m_engine;
private AD7PendingBreakpoint m_pendingBreakpoint;
public AD7BreakpointErrorEvent(AD7PendingBreakpoint pendingBreakpoint, AD7Engine engine) {
m_engine = engine;
m_pendingBreakpoint = pendingBreakpoint;
}
#region IDebugBreakpointErrorEvent2 Members
int IDebugBreakpointErrorEvent2.GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP) {
ppErrorBP = this;
return VSConstants.S_OK;
}
#endregion
#region IDebugErrorBreakpoint2 Members
int IDebugErrorBreakpoint2.GetBreakpointResolution(out IDebugErrorBreakpointResolution2 ppErrorResolution) {
ppErrorResolution = this;
return VSConstants.S_OK;
}
int IDebugErrorBreakpoint2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBreakpoint) {
ppPendingBreakpoint = m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
#region IDebugErrorBreakpoint2 Members
int IDebugErrorBreakpointResolution2.GetBreakpointType(enum_BP_TYPE[] pBPType) {
pBPType[0] = enum_BP_TYPE.BPT_CODE;
return VSConstants.S_OK;
}
int IDebugErrorBreakpointResolution2.GetResolutionInfo(enum_BPERESI_FIELDS dwFields, BP_ERROR_RESOLUTION_INFO[] pErrorResolutionInfo) {
pErrorResolutionInfo[0].dwFields = dwFields;
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_PROGRAM) != 0) {
pErrorResolutionInfo[0].pProgram = (IDebugProgram2)m_engine;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_THREAD) != 0) {
pErrorResolutionInfo[0].pThread = (IDebugThread2)m_engine.MainThread;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_TYPE) != 0) {
pErrorResolutionInfo[0].dwType = enum_BP_ERROR_TYPE.BPET_GENERAL_WARNING;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_BPRESLOCATION) != 0) {
pErrorResolutionInfo[0].bpResLocation = new BP_RESOLUTION_LOCATION();
pErrorResolutionInfo[0].bpResLocation.bpType = (uint)enum_BP_TYPE.BPT_CODE;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_MESSAGE) != 0) {
pErrorResolutionInfo[0].bstrMessage = "No code has been loaded for this code location.";
}
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when the entry point has been hit.
sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2 {
public const string IID = "e8414a3e-1642-48ec-829e-5f4040e16da9";
}
// This Event is sent when a breakpoint is hit in the debuggee
sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2 {
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
IEnumDebugBoundBreakpoints2 m_boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints) {
m_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) {
ppEnum = m_boundBreakpoints;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7DebugExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2 {
public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0";
private readonly string _exception, _description;
private readonly bool _isUnhandled;
private AD7Engine _engine;
public AD7DebugExceptionEvent(string typeName, string description, bool isUnhandled, AD7Engine engine) {
_exception = typeName;
_description = description;
_isUnhandled = isUnhandled;
_engine = engine;
}
#region IDebugExceptionEvent2 Members
public int CanPassToDebuggee() {
return VSConstants.S_FALSE;
}
public int GetException(EXCEPTION_INFO[] pExceptionInfo) {
pExceptionInfo[0].pProgram = _engine;
pExceptionInfo[0].guidType = AD7Engine.DebugEngineGuid;
pExceptionInfo[0].bstrExceptionName = _exception;
if (_isUnhandled) {
pExceptionInfo[0].dwState = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
} else {
pExceptionInfo[0].dwState = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE;
}
return VSConstants.S_OK;
}
public int GetExceptionDescription(out string pbstrDescription) {
pbstrDescription = _description;
return VSConstants.S_OK;
}
public int PassToDebuggee(int fPass) {
if (fPass != 0) {
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
#endregion
}
sealed class AD7DebugOutputStringEvent2 : AD7AsynchronousEvent, IDebugOutputStringEvent2 {
public const string IID = "569C4BB1-7B82-46FC-AE28-4536DDAD753E";
private readonly string _output;
public AD7DebugOutputStringEvent2(string output) {
_output = output;
}
#region IDebugOutputStringEvent2 Members
public int GetString(out string pbstrString) {
pbstrString = _output;
return VSConstants.S_OK;
}
#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.
*/
/*
* Created on May 30, 2005
*
*/
namespace NPOI.SS.Formula.Functions
{
using NPOI.Util;
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
* Library for common statistics functions
*/
public class StatsLib
{
private StatsLib() { }
/**
* returns the mean of deviations from mean.
* @param v
*/
public static double avedev(double[] v)
{
double r = 0;
double m = 0;
double s = 0;
for (int i = 0, iSize = v.Length; i < iSize; i++)
{
s += v[i];
}
m = s / v.Length;
s = 0;
for (int i = 0, iSize = v.Length; i < iSize; i++)
{
s += Math.Abs(v[i] - m);
}
r = s / v.Length;
return r;
}
public static double stdev(double[] v)
{
double r = double.NaN;
if (v != null && v.Length > 1)
{
r = Math.Sqrt(devsq(v) / (v.Length - 1));
}
return r;
}
public static double var(double[] v)
{
double r = Double.NaN;
if (v != null && v.Length > 1)
{
r = devsq(v) / (v.Length - 1);
}
return r;
}
public static double varp(double[] v)
{
double r = Double.NaN;
if (v != null && v.Length > 1)
{
r = devsq(v) / v.Length;
}
return r;
}
/**
* if v Is zero Length or Contains no duplicates, return value
* Is double.NaN. Else returns the value that occurs most times
* and if there Is a tie, returns the first such value.
* @param v
*/
public static double mode(double[] v)
{
double r = double.NaN;
// very naive impl, may need to be optimized
if (v != null && v.Length > 1)
{
int[] Counts = new int[v.Length];
Arrays.Fill(Counts, 1);
for (int i = 0, iSize = v.Length; i < iSize; i++)
{
for (int j = i + 1, jSize = v.Length; j < jSize; j++)
{
if (v[i] == v[j]) Counts[i]++;
}
}
double maxv = 0;
int maxc = 0;
for (int i = 0, iSize = Counts.Length; i < iSize; i++)
{
if (Counts[i] > maxc)
{
maxv = v[i];
maxc = Counts[i];
}
}
r = (maxc > 1) ? maxv : double.NaN; // "no-dups" Check
}
return r;
}
public static double median(double[] v)
{
double r = double.NaN;
if (v != null && v.Length >= 1)
{
int n = v.Length;
Array.Sort(v);
r = (n % 2 == 0)
? (v[n / 2] + v[n / 2 - 1]) / 2
: v[n / 2];
}
return r;
}
public static double devsq(double[] v)
{
double r = double.NaN;
if (v != null && v.Length >= 1)
{
double m = 0;
double s = 0;
int n = v.Length;
for (int i = 0; i < n; i++)
{
s += v[i];
}
m = s / n;
s = 0;
for (int i = 0; i < n; i++)
{
s += (v[i] - m) * (v[i] - m);
}
r = (n == 1)
? 0
: s;
}
return r;
}
/*
* returns the kth largest element in the array. Duplicates
* are considered as distinct values. Hence, eg.
* for array {1,2,4,3,3} & k=2, returned value Is 3.
* <br/>
* k <= 0 & k >= v.Length and null or empty arrays
* will result in return value double.NaN
* @param v
* @param k
*/
public static double kthLargest(double[] v, int k)
{
double r = double.NaN;
k--; // since arrays are 0-based
if (v != null && v.Length > k && k >= 0)
{
Array.Sort(v);
r = v[v.Length - k - 1];
}
return r;
}
/*
* returns the kth smallest element in the array. Duplicates
* are considered as distinct values. Hence, eg.
* for array {1,1,2,4,3,3} & k=2, returned value Is 1.
* <br/>
* k <= 0 & k >= v.Length or null array or empty array
* will result in return value double.NaN
* @param v
* @param k
*/
public static double kthSmallest(double[] v, int k)
{
double r = double.NaN;
k--; // since arrays are 0-based
if (v != null && v.Length > k && k >= 0)
{
Array.Sort(v);
r = v[k];
}
return r;
}
}
}
| |
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using static @float;
using static stdlib;
using static stdio;
using static math;
using static _time;
using static wchar;
namespace xpInterop.msvcrt.Test
{
[TestClass]
public class FloatingPointSupportTest
{
private readonly Func<double, double, double> createRandomRealNumber =
(min, max) => min + ((double)rand() / RAND_MAX) * (max - min);
[TestMethod]
public void absTest()
{
int len;
int ix = -4, iy;
long lx = -41567L, ly;
double dx = -3.141593, dy;
iy = abs(ix);
len = printf("The absolute value of %d is %d\n", ix, iy);
Assert.IsTrue(len > (-1));
ly = labs(lx);
len = printf("The absolute value of %ld is %ld\n", lx, ly);
Assert.IsTrue(len > (-1));
dy = fabs(dx);
len = printf("The absolute value of %f is %f\n", dx, dy);
Assert.IsTrue(len > (-1));
}
[TestMethod]
public void acosTest()
{
int len;
double x, y;
len = printf("Enter a real number between -1 and 1: ");
Assert.IsTrue(len > (-1));
//len = scanf("%lf", out x);
//Assert.IsTrue(len > (-1));
x = createRandomRealNumber(-1d, 1d);
y = asin(x);
len = printf("Arcsine of %f = %f\n", x, y);
Assert.IsTrue(len > (-1));
y = acos(x);
len = printf("Arccosine of %f = %f\n", x, y);
Assert.IsTrue(len > (-1));
}
[TestMethod]
public void atanTest()
{
int len;
double x1, x2, y;
len = printf("Enter a real number: ");
Assert.IsTrue(len > (-1));
//scanf("%lf", &x1);
x1 = this.createRandomRealNumber(-1d, 1d);
y = atan(x1);
len = printf("Arctangent of %f: %f\n", x1, y);
Assert.IsTrue(len > (-1));
len = printf("Enter a second real number: ");
Assert.IsTrue(len > (-1));
//scanf("%lf", &x2);
x2 = this.createRandomRealNumber(-1d, 1d);
y = atan2(x1, x2);
len = printf("Arctangent of %f / %f: %f\n", x1, x2, y);
Assert.IsTrue(len > (-1));
}
[TestMethod]
public void atoiTest()
{
int len;
string s; double x; int i, l;
s = " -2309.12E-15"; /* Test of atof */
x = atof(s);
len = printf("atof test: ASCII string: %s\tfloat: %e\n", s, x);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-2.309120e-012d, x);
s = "7.8912654773d210"; /* Test of atof */
x = atof(s);
len = printf("atof test: ASCII string: %s\tfloat: %e\n", s, x);
Assert.IsTrue(len > (-1));
Assert.AreEqual(7.8912654773e+210d, x);
s = " -9885 pigs"; /* Test of atoi */
i = atoi(s);
len = printf("atoi test: ASCII string: %s\t\tinteger: %d\n", s, i);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-9885, i);
s = "98854 dollars"; /* Test of atol */
l = atol(s);
len = printf("atol test: ASCII string: %s\t\tlong: %ld\n", s, l);
Assert.IsTrue(len > (-1));
Assert.AreEqual(98854, l);
}
[TestMethod]
public void besselFunctionTest()
{
int len;
double x = 2.387, y;
int c;
len = printf("Bessel functions for x = %f:\n", x);
Assert.IsTrue(len > (-1));
len = printf(" Kind\t\tOrder\tFunction\tResult\n\n");
Assert.IsTrue(len > (-1));
len = printf(" First\t\t0\t_j0( x )\t%f\n", y = _j0(x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.0092880"));
len = printf(" First\t\t1\t_j1( x )\t%f\n", y = _j1(x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.522941"));
c = 2;
len = printf(" First\t\t%d\t_jn( n, x )\t%f\n", c, y = _jn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.428869"));
c = 3;
len = printf(" First\t\t%d\t_jn( n, x )\t%f\n", c, y = _jn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.195734"));
c = 4;
len = printf(" First\t\t%d\t_jn( n, x )\t%f\n", c, y = _jn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.063131"));
len = printf(" Second\t0\t_y0( x )\t%f\n", y = _y0(x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.511681"));
len = printf(" Second\t1\t_y1( x )\t%f\n", y = _y1(x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.094374"));
c = 2;
len = printf(" Second\t%d\t_yn( n, x )\t%f\n", c, y = _yn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("-0.432607"));
c = 3;
len = printf(" Second\t%d\t_yn( n, x )\t%f\n", c, y = _yn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("-0.819314"));
c = 4;
len = printf(" Second\t%d\t_yn( n, x )\t%f\n", c, y = _yn(c, x));
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("-1.626832"));
}
[TestMethod]
public void _cabsTest()
{
int len;
_complex number = new _complex { x = 3.0d, y = 4.0d };
double d;
d = _cabs(number);
len = printf("The absolute value of %f + %fi is %f\n", number.x, number.y, d);
Assert.IsTrue(len > (-1));
Assert.AreEqual(5.0d, d);
}
[TestMethod]
public void ceilTest()
{
int len;
double y;
y = floor(2.8);
len = printf("The floor of 2.8 is %f\n", y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(2d, y);
y = floor(-2.8);
len = printf("The floor of -2.8 is %f\n", y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-3d, y);
y = ceil(2.8);
len = printf("The ceil of 2.8 is %f\n", y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(3d, y);
y = ceil(-2.8);
len = printf("The ceil of -2.8 is %f\n", y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-2d, y);
}
[TestMethod]
public void _chgsignTest()
{
double x = (-1.34d);
double y = _chgsign(x);
Assert.AreEqual(1.34d, y);
}
[TestMethod]
public void sincosTest()
{
int len;
double pi = 3.1415926535d;
double x, y;
x = pi / 2;
y = sin(x);
len = printf("sin( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(1d, y);
y = sinh(x);
len = printf("sinh( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("2.301298"));
x = pi;
y = cos(x);
len = printf("cos( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-1d, y);
y = cosh(x);
len = printf("cosh( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("11.59195"));
}
[TestMethod]
public void difftimeTest()
{
time_t start, finish;
long loop;
int len;
double result = 0d, elapsed_time;
len = printf("Multiplying 2 floating point numbers 10 million times...\n");
Assert.IsTrue(len > (-1));
time(out start);
for (loop = 0; loop < 1000000000; loop++)
result = 3.63 * 5.27;
time(out finish);
elapsed_time = difftime(finish, start);
len = printf("\nProgram takes %6.0f seconds.\n", elapsed_time);
Assert.IsTrue(len > (-1));
Assert.IsTrue(elapsed_time > 0d);
Assert.AreEqual(3.63 * 5.27, result);
}
[TestMethod]
public void divTest()
{
int x, y, len;
div_t div_result;
x = atoi("876");
y = atoi("13");
len = printf("x is %d, y is %d\n", x, y);
Assert.IsTrue(len > (-1));
div_result = div(x, y);
Assert.AreEqual(67, div_result.quot);
Assert.AreEqual(5, div_result.rem);
len = printf("The quotient is %d, and the remainder is %d\n",
div_result.quot, div_result.rem);
Assert.IsTrue(len > (-1));
}
[TestMethod]
public void _ecvtTest()
{
int @decimal, sign, len;
IntPtr buffer;
int precision = 10;
double source = 3.1415926535;
buffer = _ecvt(source, precision, out @decimal, out sign);
len = printf("source: %2.10f buffer: '%s' decimal: %d sign: %d\n",
source, buffer, @decimal, sign);
Assert.IsTrue(len > (-1));
Assert.AreEqual("3141592654", buffer.ToStringAnsi());
Assert.AreEqual(1, @decimal);
Assert.AreEqual(0, sign);
}
[TestMethod]
public void expTest()
{
int len;
double x = 2.302585093, y;
y = exp(x);
len = printf("exp( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("10.000000"));
}
[TestMethod]
public void _fcvtTest()
{
int @decimal, sign, len;
IntPtr buffer;
double source = 3.1415926535;
buffer = _fcvt(source, 7, out @decimal, out sign);
len = printf("source: %2.10f buffer: '%s' decimal: %d sign: %d\n",
source, buffer, @decimal, sign);
Assert.IsTrue(len > (-1));
Assert.AreEqual("31415927", buffer.ToStringAnsi());
Assert.AreEqual(1, @decimal);
Assert.AreEqual(0, sign);
}
[TestMethod]
public void fmodTest()
{
int len;
double w = -10.0d, x = 3.0d, y = 0.0d, z;
z = fmod(x, y);
len = printf("The remainder of %.2f / %.2f is %f\n", w, x, z);
Assert.IsTrue(len > (-1));
Assert.AreEqual(Double.NaN, z);
z = fmod(w, x);
len = printf("The remainder of %.2f / %.2f is %f\n", x, y, z);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-1d, z);
}
[TestMethod]
public void frexpTest()
{
double x, y;
int n, len;
x = 16.4;
y = frexp(x, out n);
len = printf("frexp( %f, &n ) = %f, n = %d\n", x, y, n);
Assert.IsTrue(len > (-1));
Assert.AreEqual(y, 0.512500d);
Assert.AreEqual(n, 5);
}
[TestMethod]
public void _gcvtTest()
{
var buffer = new StringBuilder(50);
double source = -3.1415e5;
int len;
_gcvt(source, 7, buffer);
len = printf("source: %f buffer: '%s'\n", source, buffer.ToString());
Assert.IsTrue(len > (-1));
Assert.AreEqual(buffer.ToString(), "-314150.");
_gcvt(source, 7, buffer);
len = printf("source: %e buffer: '%s'\n", source, buffer.ToString());
Assert.IsTrue(len > (-1));
Assert.AreEqual(buffer.ToString(), "-314150.");
}
[TestMethod]
public void _hypotTest()
{
double x = 3d, y = 4d, z;
int len;
len = printf("If a right triangle has sides %2.1f and %2.1f, " +
"its hypotenuse is %2.1f\n", x, y, z = _hypot(x, y));
Assert.IsTrue(len > (-1));
Assert.AreEqual(5d, z);
}
[TestMethod]
public void _isnanTest()
{
Assert.AreNotEqual(0, _isnan(0d / 0d));
}
[TestMethod]
public void ldexpTest()
{
double x = 4d, y;
int p = 3, len;
y = ldexp(x, p);
len = printf("%2.1f times two to the power of %d is %2.1f\n", x, p, y);
Assert.IsTrue(len > (-1));
Assert.AreEqual(y, 32d);
}
[TestMethod]
public void ldivTest()
{
int x = 5149627, y = 234879, len;
ldiv_t div_result;
div_result = ldiv(x, y);
len = printf("For %ld / %ld, the quotient is ", x, y);
Assert.IsTrue(len > (-1));
len = printf("%ld, and the remainder is %ld\n",
div_result.quot, div_result.rem);
Assert.IsTrue(len > (-1));
Assert.AreEqual(21, div_result.quot);
Assert.AreEqual(217168, div_result.rem);
}
[TestMethod]
public void logTest()
{
double x = 9000.0;
double y;
int len;
y = log(x);
len = printf("log( %.2f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("9.1049"));
y = log10(x);
len = printf("log10( %.2f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("3.9542"));
}
[TestMethod]
public void _lrotlrTest()
{
uint val = 0x0fac35791u, y;
int len;
len = printf("0x%8.8lx rotated left eight times is 0x%8.8lx\n",
val, y = _lrotl(val, 8));
Assert.IsTrue(len > (-1));
Assert.AreEqual(y, 0xc35791fau);
len = printf("0x%8.8lx rotated right four times is 0x%8.8lx\n",
val, y = _lrotr(val, 4));
Assert.IsTrue(len > (-1));
Assert.AreEqual(y, 0x1fac3579u);
}
[TestMethod]
public void __maxminTest()
{
int a = 10;
int b = 21;
int y, len;
len = printf("The larger of %d and %d is %d\n", a, b, y = __max(a, b));
Assert.IsTrue(len > (-1));
Assert.AreEqual(b, y);
len = printf("The smaller of %d and %d is %d\n", a, b, y = __min(a, b));
Assert.IsTrue(len > (-1));
Assert.AreEqual(a, y);
}
[TestMethod]
public void modfTest()
{
int len;
double x, y, n;
x = -14.87654321; /* Divide x into its fractional */
y = modf(x, out n); /* and integer parts */
len = printf("For %f, the fraction is %f and the integer is %.f\n",
x, y, n);
Assert.IsTrue(len > (-1));
Assert.AreEqual(-14d, n);
}
[TestMethod]
public void powTest()
{
double x = 2.0, y = 3.0, z;
int len;
z = pow(x, y);
len = printf("%.1f to the power of %.1f is %.1f\n", x, y, z);
Assert.IsTrue(len > (-1));
Assert.AreEqual(8d, z);
}
[TestMethod]
public unsafe void printfTest()
{
var @string = "computer".ToAnsiHeapPtr();
var wstring = "Unicode".ToUniHeapPtr();
try
{
char ch = 'h';
int count = -9234;
double fp = 251.7366;
char wch = 'w';
int len;
/* Display integers. */
len = printf("Integer formats:\n" +
"\tDecimal: %d Justified: %.6d Unsigned: %u\n",
count, count, count, count);
Assert.IsTrue(len > (-1));
len = printf("Decimal %d as:\n\tHex: %Xh C hex: 0x%x Octal: %o\n",
count, count, count, count);
Assert.IsTrue(len > (-1));
/* Display in different radixes. */
len = printf("Digits 10 equal:\n\tHex: %i Octal: %i Decimal: %i\n",
0x10, 010, 10);
Assert.IsTrue(len > (-1));
/* Display characters. */
len = printf("Characters in field (1):\n%10c%5hc%5C%5lc\n", ch, ch, wch, wch);
Assert.IsTrue(len > (-1));
len = wprintf("Characters in field (2):\n%10C%5hc%5c%5lc\n", ch, ch, wch, wch);
Assert.IsTrue(len > (-1));
/* Display strings. */
len = printf("Strings in field (1):\n%25s\n%25.4hs\n\t%S%25.3ls\n",
@string, @string, wstring, wstring);
Assert.IsTrue(len > (-1));
len = wprintf("Strings in field (2):\n%25S\n%25.4hs\n\t%s%25.3ls\n",
@string, @string, wstring, wstring);
Assert.IsTrue(len > (-1));
/* Display real numbers. */
len = printf("Real numbers:\n\t%f %.2f %e %E\n", fp, fp, fp, fp);
Assert.IsTrue(len > (-1));
/* Display pointer. */
len = printf("\nAddress as:\t%p\n", new IntPtr(&count));
Assert.IsTrue(len > (-1));
/* Count characters printed. */
len = printf("\nDisplay to here:\n");
Assert.IsTrue(len > (-1));
len = printf("1234567890123456%d78901234567890\n", new IntPtr(&count));
Assert.IsTrue(len > (-1));
len = printf("\tNumber displayed: %d\n\n", count);
Assert.IsTrue(len > (-1));
}
finally
{
@string.Dispose();
wstring.Dispose();
}
}
[TestMethod]
public void randTest()
{
int len;
int i;
/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand((uint)time(NULL));
/* Display 10 numbers. */
for (i = 0; i < 10; i++)
{
len = printf(" %6d\n", rand());
Assert.IsTrue(len > (-1));
}
}
[TestMethod]
public void _rotlrTest()
{
uint val = 0x0fd93, y;
int len;
len = printf("0x%4.4x rotated left three times is 0x%4.4x\n",
val, y = _rotl(val, 3));
Assert.IsTrue(len > (-1));
Assert.AreEqual(0x7ec98u, y);
len = printf("0x%4.4x rotated right four times is 0x%4.4x\n",
val, y = _rotr(val, 4));
Assert.IsTrue(len > (-1));
Assert.AreEqual(0x30000fd9u, y);
}
[Ignore]
public void scanfTest()
{
// TODO
}
[TestMethod]
public void sqrtTest()
{
int len;
double question = 45.35, answer;
answer = sqrt(question);
if (question < 0)
len = printf("Error: sqrt returns %.2f\n, answer");
else
len = printf("The square root of %.2f is %.2f\n", question, answer);
Assert.IsTrue(len > (-1));
Assert.IsTrue(answer.ToString().StartsWith("6.73424"));
}
[TestMethod]
public void strtodTest()
{
HeapPtr @string;
IntPtr stopstring;
double x;
long l;
int @base;
uint ul;
int len;
@string = "3.1415926This stopped it".ToAnsiHeapPtr();
x = strtod( @string, out stopstring );
len = printf( "string = %s\n", @string );
Assert.IsTrue(len > (-1));
len = printf(" strtod = %f\n", x );
Assert.IsTrue(len > (-1));
Assert.AreEqual(3.1415926d, x);
len = printf(" Stopped scan at: %s\n\n", stopstring );
Assert.IsTrue(len > (-1));
Assert.AreEqual("This stopped it", stopstring.ToStringAnsi());
@string.Dispose();
@string = "-10110134932This stopped it".ToAnsiHeapPtr();
l = strtol( @string, out stopstring, 10 );
len = printf( "string = %s", @string );
Assert.IsTrue(len > (-1));
len = printf(" strtol = %ld", l );
Assert.IsTrue(len > (-1));
Assert.AreEqual(-2147483648, l);
len = printf(" Stopped scan at: %s", stopstring );
Assert.IsTrue(len > (-1));
Assert.AreEqual("This stopped it", stopstring.ToStringAnsi());
@string.Dispose();
@string = "10110134932".ToAnsiHeapPtr();
len = printf( "string = %s\n", @string );
Assert.IsTrue(len > (-1));
// Convert string using base 2, 4, and 8:
for (@base = 2; @base <= 10; @base *= 2)
{
// Convert the string:
ul = strtoul(@string, out stopstring, @base);
len = printf(" strtol = %ld (base %d)\n", ul, @base);
Assert.IsTrue(len > (-1));
if (@base == 2) Assert.AreEqual(45u, ul);
if (@base == 4) Assert.AreEqual(4423u, ul);
if (@base == 8) Assert.AreEqual(2134108u, ul);
if (@base == 10) Assert.AreEqual(10110134932u, ul);
len = printf(" Stopped scan at: %s\n", stopstring);
Assert.IsTrue(len > (-1));
if (@base == 2) Assert.AreEqual("34932", stopstring.ToStringAnsi());
if (@base == 4) Assert.AreEqual("4932", stopstring.ToStringAnsi());
if (@base == 8) Assert.AreEqual("932", stopstring.ToStringAnsi());
if (@base == 10) Assert.AreEqual(String.Empty, stopstring.ToStringAnsi());
}
@string.Dispose();
}
[TestMethod]
public void tanTest()
{
double pi = 3.1415926535;
double x, y;
int len;
x = tan(pi / 4);
y = tanh(x);
len = printf("tan( %f ) = %f\n", pi / 4, x);
Assert.IsTrue(len > (-1));
Assert.IsTrue(x.ToString().StartsWith("0.9999"));
len = printf("tanh( %f ) = %f\n", x, y);
Assert.IsTrue(len > (-1));
Assert.IsTrue(y.ToString().StartsWith("0.76159"));
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
#region Constructors
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given User.
/// </summary>
public override void UpdateFrom(User record)
{
uuid = record.uuid;
short_name = record.short_name;
fullname = record.fullname;
other_config = record.other_config;
}
internal void UpdateFrom(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
short_name = proxy.short_name == null ? null : proxy.short_name;
fullname = proxy.fullname == null ? null : proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this User
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("short_name"))
short_name = Marshalling.ParseString(table, "short_name");
if (table.ContainsKey("fullname"))
fullname = Marshalling.ParseString(table, "fullname");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = uuid ?? "";
result_.short_name = short_name ?? "";
result_.fullname = fullname ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static User get_record(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_record(session.opaque_ref, _user);
else
return new User(session.XmlRpcProxy.user_get_record(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<User>.Create(session.XmlRpcProxy.user_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> create(Session session, User _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_create(session.opaque_ref, _record);
else
return XenRef<User>.Create(session.XmlRpcProxy.user_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_create(Session session, User _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_user_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_user_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static void destroy(Session session, string _user)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_destroy(session.opaque_ref, _user);
else
session.XmlRpcProxy.user_destroy(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_destroy(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_user_destroy(session.opaque_ref, _user);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_user_destroy(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_uuid(session.opaque_ref, _user);
else
return session.XmlRpcProxy.user_get_uuid(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_short_name(session.opaque_ref, _user);
else
return session.XmlRpcProxy.user_get_short_name(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_fullname(session.opaque_ref, _user);
else
return session.XmlRpcProxy.user_get_fullname(session.opaque_ref, _user ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.user_get_other_config(session.opaque_ref, _user);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.user_get_other_config(session.opaque_ref, _user ?? "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_set_fullname(session.opaque_ref, _user, _fullname);
else
session.XmlRpcProxy.user_set_fullname(session.opaque_ref, _user ?? "", _fullname ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_set_other_config(session.opaque_ref, _user, _other_config);
else
session.XmlRpcProxy.user_set_other_config(session.opaque_ref, _user ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_add_to_other_config(session.opaque_ref, _user, _key, _value);
else
session.XmlRpcProxy.user_add_to_other_config(session.opaque_ref, _user ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.user_remove_from_other_config(session.opaque_ref, _user, _key);
else
session.XmlRpcProxy.user_remove_from_other_config(session.opaque_ref, _user ?? "", _key ?? "").parse();
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name = "";
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname = "";
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Octokit.Tests.Integration;
using Octokit.Tests.Integration.Helpers;
using Xunit;
public class PullRequestReviewRequestsClientTests
{
private static readonly string[] _collaboratorLogins = {
"octokitnet-test1",
"octokitnet-test2"
};
public class PullRequestReviewRequestClientTestsBase : IDisposable
{
internal readonly IGitHubClient _github;
internal readonly IPullRequestReviewRequestsClient _client;
internal readonly RepositoryContext _context;
public PullRequestReviewRequestClientTestsBase()
{
_github = Helper.GetAuthenticatedClient();
_client = _github.PullRequest.ReviewRequest;
_context = _github.CreateRepositoryContext("test-repo").Result;
Task.WaitAll(_collaboratorLogins.Select(AddCollaborator).ToArray());
}
private Task AddCollaborator(string collaborator) => _github.Repository.Collaborator.Add(_context.RepositoryOwner, _context.RepositoryName, collaborator);
public void Dispose()
{
_context.Dispose();
}
}
public class TheGetAllMethod : PullRequestReviewRequestClientTestsBase
{
[IntegrationTest]
public async Task GetsNoRequestsWhenNoneExist()
{
var pullRequestId = await CreateTheWorld(_github, _context, createReviewRequests: false);
var reviewRequests = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId);
Assert.NotNull(reviewRequests);
Assert.Empty(reviewRequests);
}
[IntegrationTest]
public async Task GetsNoRequestsWhenNoneExistWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context, createReviewRequests: false);
var reviewRequests = await _client.GetAll(_context.RepositoryId, pullRequestId);
Assert.NotNull(reviewRequests);
Assert.Empty(reviewRequests);
}
[IntegrationTest]
public async Task GetsRequests()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var reviewRequests = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId);
Assert.Equal(_collaboratorLogins, reviewRequests.Select(rr => rr.Login));
}
[IntegrationTest]
public async Task GetsRequestsWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var reviewRequests = await _client.GetAll(_context.RepositoryId, pullRequestId);
Assert.Equal(_collaboratorLogins, reviewRequests.Select(rr => rr.Login));
}
[IntegrationTest]
public async Task ReturnsCorrectCountOfReviewRequestsWithStart()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var options = new ApiOptions
{
PageSize = 1,
PageCount = 1,
StartPage = 2
};
var reviewRequests = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId, options);
Assert.Equal(1, reviewRequests.Count);
}
[IntegrationTest]
public async Task ReturnsCorrectCountOfReviewRequestsWithStartWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var options = new ApiOptions
{
PageSize = 1,
PageCount = 2,
StartPage = 2
};
var reviewRequests = await _client.GetAll(_context.RepositoryId, pullRequestId, options);
Assert.Equal(1, reviewRequests.Count);
}
[IntegrationTest]
public async Task ReturnsDistinctResultsBasedOnStartPage()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var startOptions = new ApiOptions
{
PageSize = 1,
PageCount = 1
};
var firstPage = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId, startOptions);
var skipStartOptions = new ApiOptions
{
PageSize = 1,
PageCount = 1,
StartPage = 2
};
var secondPage = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId, skipStartOptions);
Assert.Equal(1, firstPage.Count);
Assert.Equal(1, secondPage.Count);
Assert.NotEqual(firstPage[0].Id, secondPage[0].Id);
}
[IntegrationTest]
public async Task ReturnsDistinctResultsBasedOnStartPageWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var startOptions = new ApiOptions
{
PageSize = 1,
PageCount = 1
};
var firstPage = await _client.GetAll(_context.RepositoryId, pullRequestId, startOptions);
var skipStartOptions = new ApiOptions
{
PageSize = 1,
PageCount = 1,
StartPage = 2
};
var secondPage = await _client.GetAll(_context.RepositoryId, pullRequestId, skipStartOptions);
Assert.Equal(1, firstPage.Count);
Assert.Equal(1, secondPage.Count);
Assert.NotEqual(firstPage[0].Id, secondPage[0].Id);
}
}
public class TheDeleteMethod : PullRequestReviewRequestClientTestsBase
{
[IntegrationTest]
public async Task DeletesRequests()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var reviewRequestsBeforeDelete = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId);
var reviewRequestToCreate = new PullRequestReviewRequest(_collaboratorLogins);
await _client.Delete(_context.RepositoryOwner, _context.RepositoryName, pullRequestId, reviewRequestToCreate);
var reviewRequestsAfterDelete = await _client.GetAll(_context.RepositoryOwner, _context.RepositoryName, pullRequestId);
Assert.NotEmpty(reviewRequestsBeforeDelete);
Assert.Empty(reviewRequestsAfterDelete);
}
[IntegrationTest]
public async Task DeletesRequestsWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context);
var reviewRequestsBeforeDelete = await _client.GetAll(_context.RepositoryId, pullRequestId);
var reviewRequestToCreate = new PullRequestReviewRequest(_collaboratorLogins);
await _client.Delete(_context.RepositoryId, pullRequestId, reviewRequestToCreate);
var reviewRequestsAfterDelete = await _client.GetAll(_context.RepositoryId, pullRequestId);
Assert.NotEmpty(reviewRequestsBeforeDelete);
Assert.Empty(reviewRequestsAfterDelete);
}
}
public class TheCreateMethod : PullRequestReviewRequestClientTestsBase, IDisposable
{
[IntegrationTest]
public async Task CreatesRequests()
{
var pullRequestId = await CreateTheWorld(_github, _context, createReviewRequests: false);
var reviewRequestToCreate = new PullRequestReviewRequest(_collaboratorLogins);
var pr = await _client.Create(_context.RepositoryOwner, _context.RepositoryName, pullRequestId, reviewRequestToCreate);
Assert.Equal(_collaboratorLogins.ToList(), pr.RequestedReviewers.Select(rr => rr.Login));
}
[IntegrationTest]
public async Task CreatesRequestsWithRepositoryId()
{
var pullRequestId = await CreateTheWorld(_github, _context, createReviewRequests: false);
var reviewRequestToCreate = new PullRequestReviewRequest(_collaboratorLogins);
var pr = await _client.Create(_context.RepositoryId, pullRequestId, reviewRequestToCreate);
Assert.Equal(_collaboratorLogins.ToList(), pr.RequestedReviewers.Select(rr => rr.Login));
}
}
static async Task<int> CreateTheWorld(IGitHubClient github, RepositoryContext context, bool createReviewRequests = true)
{
var master = await github.Git.Reference.Get(context.RepositoryOwner, context.RepositoryName, "heads/master");
// create new commit for master branch
var newMasterTree = await CreateTree(github, context, new Dictionary<string, string> { { "README.md", "Hello World!" } });
var newMaster = await CreateCommit(github, context, "baseline for pull request", newMasterTree.Sha, master.Object.Sha);
// update master
await github.Git.Reference.Update(context.RepositoryOwner, context.RepositoryName, "heads/master", new ReferenceUpdate(newMaster.Sha));
// create new commit for feature branch
var featureBranchTree = await CreateTree(github, context, new Dictionary<string, string> { { "README.md", "I am overwriting this blob with something new" } });
var featureBranchCommit = await CreateCommit(github, context, "this is the commit to merge into the pull request", featureBranchTree.Sha, newMaster.Sha);
var featureBranchTree2 = await CreateTree(github, context, new Dictionary<string, string> { { "README.md", "I am overwriting this blob with something new a 2nd time" } });
var featureBranchCommit2 = await CreateCommit(github, context, "this is a 2nd commit to merge into the pull request", featureBranchTree2.Sha, featureBranchCommit.Sha);
// create branch
await github.Git.Reference.Create(context.RepositoryOwner, context.RepositoryName, new NewReference("refs/heads/my-branch", featureBranchCommit2.Sha));
// create a pull request
var pullRequest = new NewPullRequest("Nice title for the pull request", "my-branch", "master");
var createdPullRequest = await github.PullRequest.Create(context.RepositoryOwner, context.RepositoryName, pullRequest);
// Create review requests (optional)
if (createReviewRequests)
{
var reviewRequest = new PullRequestReviewRequest(_collaboratorLogins);
await github.PullRequest.ReviewRequest.Create(context.RepositoryOwner, context.RepositoryName, createdPullRequest.Number, reviewRequest);
}
return createdPullRequest.Number;
}
static async Task<TreeResponse> CreateTree(IGitHubClient github, RepositoryContext context, IEnumerable<KeyValuePair<string, string>> treeContents)
{
var collection = new List<NewTreeItem>();
foreach (var c in treeContents)
{
var baselineBlob = new NewBlob
{
Content = c.Value,
Encoding = EncodingType.Utf8
};
var baselineBlobResult = await github.Git.Blob.Create(context.RepositoryOwner, context.RepositoryName, baselineBlob);
collection.Add(new NewTreeItem
{
Type = TreeType.Blob,
Mode = FileMode.File,
Path = c.Key,
Sha = baselineBlobResult.Sha
});
}
var newTree = new NewTree();
foreach (var item in collection)
{
newTree.Tree.Add(item);
}
return await github.Git.Tree.Create(context.RepositoryOwner, context.RepositoryName, newTree);
}
static async Task<Commit> CreateCommit(IGitHubClient github, RepositoryContext context, string message, string sha, string parent)
{
var newCommit = new NewCommit(message, sha, parent);
return await github.Git.Commit.Create(context.RepositoryOwner, context.RepositoryName, newCommit);
}
}
| |
/*
* @(#)ParserImpl.java 1.11 2000/08/16
*
*/
using System;
namespace Comzept.Genesis.Tidy
{
/// <summary>
/// HTML Parser implementation</summary>
/// <remarks>
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.java for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
/// </remarks>
///
/// <author> Dave Raggett dsr@w3.org
/// </author>
/// <author> Andy Quick ac.quick@sympatico.ca (translation to Java)
/// </author>
/// <version> 1.0, 1999/05/22
/// </version>
/// <version> 1.0.1, 1999/05/29
/// </version>
/// <version> 1.1, 1999/06/18 Java Bean
/// </version>
/// <version> 1.2, 1999/07/10 Tidy Release 7 Jul 1999
/// </version>
/// <version> 1.3, 1999/07/30 Tidy Release 26 Jul 1999
/// </version>
/// <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>
public class ParserImpl
{
//private static int SeenBodyEndTag; /* AQ: moved into lexer structure */
internal static void parseTag(Lexer lexer, Node node, short mode)
{
// Local fix by GLP 2000-12-21. Need to reset insertspace if this
// is both a non-inline and empty tag (base, link, meta, isindex, hr, area).
// Remove this code once the fix is made in Tidy.
/****** (Original code follows)
if ((node.tag.model & Dict.CM_EMPTY) != 0)
{
lexer.waswhite = false;
return;
}
else if (!((node.tag.model & Dict.CM_INLINE) != 0))
lexer.insertspace = false;
*******/
if (!((node.tag.model & Dict.CM_INLINE) != 0))
lexer.insertspace = false;
if ((node.tag.model & Dict.CM_EMPTY) != 0)
{
lexer.waswhite = false;
return ;
}
if (node.tag.parser == null || node.type == Node.StartEndTag)
return ;
node.tag.parser.Parse(lexer, node, mode);
}
internal static void moveToHead(Lexer lexer, Node element, Node node)
{
Node head;
TagTable tt = lexer.configuration.tt;
if (node.type == Node.StartTag || node.type == Node.StartEndTag)
{
Report.Warning(lexer, element, node, Report.TAG_NOT_ALLOWED_IN);
while (element.tag != tt.tagHtml)
element = element.parent;
for (head = element.content; head != null; head = head.next)
{
if (head.tag == tt.tagHead)
{
Node.insertNodeAtEnd(head, node);
break;
}
}
if (node.tag.parser != null)
parseTag(lexer, node, Lexer.IgnoreWhitespace);
}
else
{
Report.Warning(lexer, element, node, Report.DISCARDING_UNEXPECTED);
}
}
public static Parser getParseHTML()
{
return _parseHTML;
}
public static Parser getParseHead()
{
return _parseHead;
}
public static Parser getParseTitle()
{
return _parseTitle;
}
public static Parser getParseScript()
{
return _parseScript;
}
public static Parser getParseBody()
{
return _parseBody;
}
public static Parser getParseFrameSet()
{
return _parseFrameSet;
}
public static Parser getParseInline()
{
return _parseInline;
}
public static Parser ParseList
{
get { return _parseList; }
}
public static Parser ParseDefList
{
get { return _parseDefList; }
}
public static Parser ParsePre
{
get { return _parsePre; }
}
public static Parser getParseBlock()
{
return _parseBlock;
}
public static Parser getParseTableTag()
{
return _parseTableTag;
}
public static Parser getParseColGroup()
{
return _parseColGroup;
}
public static Parser getParseRowGroup()
{
return _parseRowGroup;
}
public static Parser getParseRow()
{
return _parseRow;
}
public static Parser getParseNoFrames()
{
return _parseNoFrames;
}
public static Parser getParseSelect()
{
return _parseSelect;
}
public static Parser getParseText()
{
return _parseText;
}
public static Parser ParseOptGroup
{
get { return _parseOptGroup; }
}
private static Parser _parseHTML = new ParseHTML();
private static Parser _parseHead = new ParseHead();
private static Parser _parseTitle = new ParseTitle();
private static Parser _parseScript = new ParseScript();
private static Parser _parseBody = new ParseBody();
private static Parser _parseFrameSet = new ParseFrameSet();
private static Parser _parseInline = new ParseInline();
private static Parser _parseList = new ParseList();
private static Parser _parseDefList = new ParseDefList();
private static Parser _parsePre = new ParsePre();
private static Parser _parseBlock = new ParseBlock();
private static Parser _parseTableTag = new ParseTableTag();
private static Parser _parseColGroup = new ParseColGroup();
private static Parser _parseRowGroup = new ParseRowGroup();
private static Parser _parseRow = new ParseRow();
private static Parser _parseNoFrames = new ParseNoFrames();
private static Parser _parseSelect = new ParseSelect();
private static Parser _parseText = new ParseText();
private static Parser _parseOptGroup = new ParseOptGroup();
/*
HTML is the top level element
*/
public static Node parseDocument(Lexer lexer)
{
Node node, document, html;
Node doctype = null;
TagTable tt = lexer.configuration.tt;
document = lexer.newNode();
document.type = Node.RootNode;
while (true)
{
node = lexer.GetToken(Lexer.IgnoreWhitespace);
if (node == null)
break;
/* deal with comments etc. */
if (Node.insertMisc(document, node))
continue;
if (node.type == Node.DocTypeTag)
{
if (doctype == null)
{
Node.insertNodeAtEnd(document, node);
doctype = node;
}
else
Report.Warning(lexer, document, node, Report.DISCARDING_UNEXPECTED);
continue;
}
if (node.type == Node.EndTag)
{
Report.Warning(lexer, document, node, Report.DISCARDING_UNEXPECTED); //TODO?
continue;
}
if (node.type != Node.StartTag || node.tag != tt.tagHtml)
{
lexer.ungetToken();
html = lexer.inferredTag("html");
}
else
html = node;
Node.insertNodeAtEnd(document, html);
getParseHTML().Parse(lexer, html, (short) 0); // TODO?
break;
}
return document;
}
/// <summary> Indicates whether or not whitespace should be preserved for this element.
/// If an <code>xml:space</code> attribute is found, then if the attribute value is
/// <code>preserve</code>, returns <code>true</code>. For any other value, returns
/// <code>false</code>. If an <code>xml:space</code> attribute was <em>not</em>
/// found, then the following element names result in a return value of <code>true:
/// pre, script, style,</code> and <code>xsl:text</code>. Finally, if a
/// <code>TagTable</code> was passed in and the element appears as the "pre" element
/// in the <code>TagTable</code>, then <code>true</code> will be returned.
/// Otherwise, <code>false</code> is returned.
/// </summary>
/// <param name="element">The <code>Node</code> to test to see if whitespace should be
/// preserved.
/// </param>
/// <param name="tt">The <code>TagTable</code> to test for the <code>getNodePre()</code>
/// function. This may be <code>null</code>, in which case this test
/// is bypassed.
/// </param>
/// <returns> <code>true</code> or <code>false</code>, as explained above.
/// </returns>
public static bool XMLPreserveWhiteSpace(Node element, TagTable tt)
{
AttVal attribute;
/* search attributes for xml:space */
for (attribute = element.attributes; attribute != null; attribute = attribute.next)
{
if (attribute.attribute.Equals("xml:space"))
{
if (attribute.value_Renamed.Equals("preserve"))
return true;
return false;
}
}
/* kludge for html docs without explicit xml:space attribute */
if (Lexer.wstrcasecmp(element.element, "pre") == 0 || Lexer.wstrcasecmp(element.element, "script") == 0 || Lexer.wstrcasecmp(element.element, "style") == 0)
return true;
if ((tt != null) && (tt.findParser(element) == ParsePre))
return true;
/* kludge for XSL docs */
if (Lexer.wstrcasecmp(element.element, "xsl:text") == 0)
return true;
return false;
}
/*
XML documents
*/
public static void ParseXMLElement(Lexer lexer, Node element, short mode)
{
Node node;
/* Jeff Young's kludge for XSL docs */
if (Lexer.wstrcasecmp(element.element, "xsl:text") == 0)
return ;
/* if node is pre or has xml:space="preserve" then do so */
if (XMLPreserveWhiteSpace(element, lexer.configuration.tt))
mode = Lexer.Preformatted;
while (true)
{
node = lexer.GetToken(mode);
if (node == null)
break;
if (node.type == Node.EndTag && node.element.Equals(element.element))
{
element.closed = true;
break;
}
/* discard unexpected end tags */
if (node.type == Node.EndTag)
{
Report.error(lexer, element, node, Report.UNEXPECTED_ENDTAG);
continue;
}
/* parse content on seeing start tag */
if (node.type == Node.StartTag)
ParseXMLElement(lexer, node, mode);
Node.insertNodeAtEnd(element, node);
}
/*
if first child is text then trim initial space and
delete text node if it is empty.
*/
node = element.content;
if (node != null && node.type == Node.TextNode && mode != Lexer.Preformatted)
{
if (node.textarray[node.start] == (sbyte) ' ')
{
node.start++;
if (node.start >= node.end)
Node.discardElement(node);
}
}
/*
if last child is text then trim final space and
delete the text node if it is empty
*/
node = element.last;
if (node != null && node.type == Node.TextNode && mode != Lexer.Preformatted)
{
if (node.textarray[node.end - 1] == (sbyte) ' ')
{
node.end--;
if (node.start >= node.end)
Node.discardElement(node);
}
}
}
public static Node ParseXMLDocument(Lexer lexer)
{
Node node, document, doctype;
document = lexer.newNode();
document.type = Node.RootNode;
doctype = null;
lexer.configuration.XmlTags = true;
while (true)
{
node = lexer.GetToken(Lexer.IgnoreWhitespace);
if (node == null)
break;
/* discard unexpected end tags */
if (node.type == Node.EndTag)
{
Report.Warning(lexer, null, node, Report.UNEXPECTED_ENDTAG);
continue;
}
/* deal with comments etc. */
if (Node.insertMisc(document, node))
continue;
if (node.type == Node.DocTypeTag)
{
if (doctype == null)
{
Node.insertNodeAtEnd(document, node);
doctype = node;
}
else
Report.Warning(lexer, document, node, Report.DISCARDING_UNEXPECTED); // TODO
continue;
}
/* if start tag then parse element's content */
if (node.type == Node.StartTag)
{
Node.insertNodeAtEnd(document, node);
ParseXMLElement(lexer, node, Lexer.IgnoreWhitespace);
}
}
if (false)
{
//#if 0
/* discard the document type */
node = document.findDocType();
if (node != null)
Node.discardElement(node);
} // #endif
if (doctype != null && !lexer.checkDocTypeKeyWords(doctype))
Report.Warning(lexer, doctype, null, Report.DTYPE_NOT_UPPER_CASE);
/* ensure presence of initial <?XML version="1.0"?> */
if (lexer.configuration.XmlPi)
lexer.fixXMLPI(document);
return document;
}
public static bool IsJavaScript(Node node)
{
bool result = false;
AttVal attr;
if (node.attributes == null)
return true;
for (attr = node.attributes; attr != null; attr = attr.next)
{
if ((Lexer.wstrcasecmp(attr.attribute, "language") == 0 || Lexer.wstrcasecmp(attr.attribute, "type") == 0) && Lexer.wsubstr(attr.value_Renamed, "javascript"))
result = true;
}
return result;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
This library 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.1 of the License, or (at your option) any later version.
This library 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 this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
#region Using Statements
using System;
using System.Collections;
using System.Data;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Media;
#endregion;
#region Versioning Information
/// File Revision
/// ===============================================
/// OgrePagingLandScapeOptions.h 1.13
/// OgrePagingLandScapeOptions.cpp 1.16
///
#endregion
namespace Axiom.SceneManagers.PagingLandscape
{
/// <summary>
/// Summary description for IPLOptions.
/// </summary>
public sealed class Options : IDisposable
{
#region Singleton Implementation
/// <summary>
/// Constructor
/// </summary>
private Options()
{
this.Data2DFormat = "HeightField";
this.TextureFormat = "Image";
this.Landscape_Filename = "";
this.Landscape_Extension = "";
this.MatColor = new ColorEx[4];
for (int i = 0; i < 4; i++)
{
this.MatColor[i] = new ColorEx();
}
this.MatHeight = new float[2];
this.MatHeight[0] = 0f;
this.MatHeight[1] = 0f;
this.MaxValue = 5000;
this.MinValue = 0;
this.PageSize = 257;
this.TileSize = 64;
this.World_Width = 0;
this.World_Height = 0;
this.Change_Factor = 1;
this.Max_Adjacent_Pages = 1;
this.Max_Preload_Pages = 2;
this.Renderable_Factor = 10;
this.Scale = new Vector3( 1, 1, 1 );
this.DistanceLOD = 4;
this.LOD_Factor = 10;
this.Num_Renderables = 1000;
this.Num_Renderables_Increment = 16;
this.Num_Tiles = 1000;
this.Num_Tiles_Increment = 16;
this.CameraThreshold = 5;
this.VisibilityAngle = 50;
this.Num_Renderables_Loading = 10;
this.Lit = false;
this.Colored = false;
this.Coverage_Vertex_Color = false;
this.Base_Vertex_Color = false;
this.Vertex_Shadowed = false;
this.Vertex_Instant_Colored = false;
}
private static Options instance = null;
public static Options Instance
{
get
{
if ( instance == null ) instance = new Options();
return instance;
}
}
#endregion Singleton Implementation
#region IDisposable Implementation
public void Dispose()
{
if (instance == this)
{
instance = null;
}
}
#endregion IDisposable Implementation
#region Fields
/// <summary>
/// Contain option data loaded during the Load method
/// </summary>
private DataSet optionData;
private DataTable table;
private DataRow row;
#endregion Fields
#region Properties
public string Data2DFormat;
public string TextureFormat;
public string Landscape_Filename;
public string Landscape_Extension;
public string Image_Filename;
public bool ImageNameLoad;
#region Map Tool Options
// MAP TOOL OPTIONS
public string Splat_Filename_0;
public string Splat_Filename_1;
public string Splat_Filename_2;
public string Splat_Filename_3;
public String OutDirectory;
public bool Paged;
public bool PVSMap;
public bool BaseMap;
public bool RGBMaps;
public bool ColorMapSplit;
public bool ColorMapGenerate;
public bool LightMap;
public bool NormalMap;
public bool HeightMap;
public bool AlphaMaps;
public bool ShadowMap;
public bool HorizonMap;
public bool LitBaseMap;
public bool LitColorMapSplit;
public bool LitColorMapGenerate;
public bool InfiniteMap;
public bool CoverageMap;
public bool ElevationMap;
public bool HeightNormalMap;
public bool AlphaSplatRGBAMaps;
public bool AlphaSplatLightMaps;
public float HeightMapBlurFactor;
public string ColorMapName;
public Vector3 Sun;
public float Amb;
public float Diff;
public int Blur;
// end of MAP TOOL OPTIONS
#endregion Map Tool Options
public long MaxValue; //Compression range for the TC height field
public long MinValue;
public long TileSize;
public long PageSize; //size of the page.
public long World_Height; //world page height, from 0 to height
public long World_Width; //world page width, from 0 to width
public float Change_Factor; //Determines the value of the change factor for loading/unloading LandScape Pages
public long Max_Adjacent_Pages;
public long Max_Preload_Pages;
public float Visible_Renderables; //Numbers of visible renderables surrounding the camera
public float Renderable_Factor; //Determines the distance of loading and unloading of renderables in renderable numbers
public Vector3 Scale;
public float DistanceLOD; //Distance for the LOD change
public float LOD_Factor;
public long Num_Renderables; //Max number of renderables to use.
public long Num_Renderables_Increment; //Number of renderables to add in case we run out of renderables
public long Num_Tiles; //Max number of tiles to use.
public long Num_Tiles_Increment; //Number of renderables to add in case we run out of renderables
public float CameraThreshold; //If the last camera position is >= the the scene is transverse again.
public float VisibilityAngle; //Angle to discard renderables
public long Num_Renderables_Loading; //Max number of renderable to load in a single Frame.
public long MaxRenderLevel;
public ColorEx[] MatColor; //4
public float[] MatHeight; //2
public bool Lit;
public bool Colored;
public bool Coverage_Vertex_Color;
public bool Base_Vertex_Color;
public bool Vertex_Shadowed;
public bool Vertex_Instant_Colored;
#endregion // Properties
public void Load( string filename )
{
/* Set up the options */
//ConfigFile this;
string val;
//config.load( filename );
optionData = new DataSet();
optionData.ReadXml(filename);
table = optionData.Tables[0];
row = table.Rows[0];
this.Data2DFormat = this.getSetting( "Data2DFormat" );
this.TextureFormat = this.getSetting( "TextureFormat" );
val = this.getSetting( "ScaleX" );
if ( val != string.Empty ) this.Scale.x = float.Parse( val );
val = this.getSetting( "ScaleY" );
if ( val != string.Empty ) this.Scale.y = float.Parse( val );
val = this.getSetting( "ScaleZ" );
if ( val != string.Empty ) this.Scale.z = float.Parse( val );
if ( Data2DFormat.StartsWith("HeightFieldTC") )
{
this.MaxValue = long.Parse( this.getSetting( "MaxValue" )) * (long)this.Scale.y ;
this.MinValue = long.Parse( this.getSetting( "MinValue" )) * (long)this.Scale.y;
}
else
{
this.MaxValue = (long)(255 * this.Scale.y);
this.MinValue = (long)(0 * this.Scale.y);
}
this.Landscape_Filename = this.getSetting( "LandScapeFileName" );
this.Landscape_Extension = this.getSetting( "LandScapeExtension" );
this.Image_Filename = this.getSetting( "ImageFilename" );
this.ImageNameLoad = (this.Image_Filename != string.Empty);
this.Colored = ( this.getSetting( "VertexColors" ) == "yes" );
this.Coverage_Vertex_Color = (this.getSetting( "CoverageVertexColor" ) == "yes" );
this.Base_Vertex_Color = (this.getSetting( "BaseVertexColor" ) == "yes" );
this.Vertex_Shadowed = (this.getSetting( "BaseVertexShadow" ) == "yes" );
this.Vertex_Instant_Colored = (this.getSetting( "BaseVertexInstantColor" ) == "yes" );
// Make sure If we are Shadowed then We are Instant Colored
if (this.Vertex_Shadowed) this.Vertex_Instant_Colored = true;
if (this.Coverage_Vertex_Color || this.Base_Vertex_Color ||
this.Vertex_Shadowed || this.Vertex_Instant_Colored)
this.Colored = true;
this.Lit = ( this.getSetting( "VertexNormals" ) == "yes" );
this.Splat_Filename_0 = this.getSetting( "SplatFilename0" );
this.Splat_Filename_1 = this.getSetting( "SplatFilename1" );
this.Splat_Filename_2 = this.getSetting( "SplatFilename2" );
this.Splat_Filename_3 = this.getSetting( "SplatFilename3" );
// TODO: Why is this commented out??? If those filenames are not present then these should be skipped (unless they are no longer needed)
// this.MatColor[0] = getAvgColor( this.Splat_Filename_0 );
// this.MatColor[1] = getAvgColor( this.Splat_Filename_1 );
// this.MatColor[2] = getAvgColor( this.Splat_Filename_2 );
// this.MatColor[3] = getAvgColor( this.Splat_Filename_3 );
float divider = ( MaxValue - MinValue ) / 255.0f;
// FH 06/17/2005: Got an exception when not supplying these...
if ((val = this.getSetting( "MaterialHeight1" )) != string.Empty)
this.MatHeight[0] = float.Parse( val );
this.MatHeight[0] = this.MatHeight[0] * divider;
if ((val = this.getSetting( "MaterialHeight2" )) != string.Empty)
this.MatHeight[1] = float.Parse( val );
this.MatHeight[1] = this.MatHeight[1] * divider;
val = this.getSetting( "MaxNumRenderables" );
if (val != string.Empty ) this.Num_Renderables = long.Parse( val );
val = this.getSetting( "IncrementRenderables" );
if (val != string.Empty ) this.Num_Renderables_Increment = long.Parse( val );
val = this.getSetting( "MaxNumTiles" );
if (val != string.Empty ) this.Num_Tiles = long.Parse( val );
val = this.getSetting( "IncrementTiles" );
if (val != string.Empty ) this.Num_Tiles_Increment = long.Parse( val );
val = this.getSetting( "CameraThreshold" );
if ( val != string.Empty ) this.CameraThreshold = float.Parse( val );
// To avoid the use of a square root.
this.CameraThreshold *= this.CameraThreshold;
val = this.getSetting( "VisibilityAngle" );
if (val != string.Empty ) this.VisibilityAngle = float.Parse( val );
val = this.getSetting( "NumRenderablesLoading" );
if ( val != string.Empty ) this.Num_Renderables_Loading = long.Parse( val );
val = this.getSetting( "MaxAdjacentPages" );
if ( val != string.Empty ) this.Max_Adjacent_Pages = long.Parse( val );
val = this.getSetting( "MaxPreloadedPages" );
if ( val != string.Empty ) this.Max_Preload_Pages = long.Parse( val );
val = this.getSetting( "Height" );
if ( val != string.Empty ) this.World_Height = long.Parse( val );
val = this.getSetting( "Width" );
if ( val != string.Empty ) this.World_Width = long.Parse( val );
val = this.getSetting( "PageSize" );
if ( val != string.Empty ) this.PageSize = long.Parse( val );
val = this.getSetting( "TileSize" );
if ( val != string.Empty ) this.TileSize = long.Parse( val );
val = this.getSetting( "MaxRenderLevel" );
if (val != string.Empty ) this.MaxRenderLevel = long.Parse( val );
if (this.MaxRenderLevel == 0)
{
while ((long)(1 << (int)this.MaxRenderLevel) < this.TileSize)
this.MaxRenderLevel++;
}
val = this.getSetting( "ChangeFactor" );
if (val != string.Empty ) this.Change_Factor = float.Parse( val ) * ( this.PageSize / 9 );
val = this.getSetting( "VisibleRenderables" );
if (val != string.Empty ) this.Visible_Renderables = float.Parse( val );
// compute the actual distance as a square
this.Renderable_Factor = this.Visible_Renderables * ( this.TileSize * this.Scale.x + this.TileSize * this.Scale.z );
this.Renderable_Factor *= this.Renderable_Factor;
val = this.getSetting( "DistanceLOD" );
if (val != string.Empty ) this.DistanceLOD = float.Parse( val );
// Compute the actual distance as a square
this.LOD_Factor = this.DistanceLOD * ( this.TileSize * this.Scale.x + this.TileSize * this.Scale.z );
this.LOD_Factor *= this.LOD_Factor;
// MAP TOOL OPTIONS
this.Paged = (this.getSetting( "Paged" ) == "yes" );
this.OutDirectory = this.getSetting( "OutDirectory" );
if ( OutDirectory.StartsWith( "LandScapeFileName") == true )
this.OutDirectory = this.Landscape_Filename;
this.PVSMap = (this.getSetting( "PVSMap" ) == "yes" );
this.BaseMap = (this.getSetting( "BaseMap" ) == "yes" );
this.RGBMaps = (this.getSetting( "RGBMaps" ) == "yes" );
this.ColorMapGenerate = (this.getSetting( "ColorMapGenerate" ) == "yes" );
this.ColorMapSplit = (this.getSetting( "ColorMapSplit" ) == "yes" );
this.LightMap = (this.getSetting( "LightMap" ) == "yes" );
this.NormalMap = (this.getSetting( "NormalMap" ) == "yes" );
this.HeightMap = (this.getSetting( "HeightMap" ) == "yes" );
this.AlphaMaps = (this.getSetting( "AlphaMaps" ) == "yes" );
this.ShadowMap = (this.getSetting( "ShadowMap" ) == "yes" );
this.HorizonMap = (this.getSetting( "HorizonMap" ) == "yes" );
this.LitBaseMap = (this.getSetting( "LitBaseMap" ) == "yes" );
this.InfiniteMap = (this.getSetting( "InfiniteMap" ) == "yes" );
this.CoverageMap = (this.getSetting( "CoverageMap" ) == "yes" );
this.LitColorMapGenerate = (this.getSetting( "LitColorMapGenerate" ) == "yes" );
this.LitColorMapSplit = (this.getSetting( "LitColorMapSplit" ) == "yes" );
this.ElevationMap= (this.getSetting( "ElevationMap" ) == "yes" );
this.HeightNormalMap = (this.getSetting( "HeightNormalMap" ) == "yes" );
this.AlphaSplatRGBAMaps = (this.getSetting( "AlphaSplatRGBAMaps" ) == "yes" );
this.AlphaSplatLightMaps = (this.getSetting( "AlphaSplatLightMaps" ) == "yes" );
this.ColorMapName = this.getSetting( "ColorMapName" );
val = this.getSetting( "HeightMapBlurFactor" );
if (val != string.Empty ) HeightMapBlurFactor = float.Parse( val );
Sun = new Vector3();
val =this.getSetting( "SunX" );
if (val != string.Empty ) Sun.x = float.Parse( val );
val =this.getSetting( "SunY" );
if (val != string.Empty ) Sun.y = float.Parse( val );
val =this.getSetting( "SunZ" );
if (val != string.Empty ) Sun.z = float.Parse( val );
val =this.getSetting( "Ambient" );
if (val != string.Empty ) Amb = float.Parse( val );
val =this.getSetting( "Diffuse" );
if (val != string.Empty ) Diff = float.Parse( val );
val =this.getSetting( "Blur" );
if (val != string.Empty ) Blur = int.Parse( val );
}
public bool setOption( string strKey, object pValue )
{
if ( strKey == "VisibleRenderables" )
{
Visible_Renderables = (int) pValue ;
// compute the actual distance as a square
Renderable_Factor = Visible_Renderables * ( TileSize * Scale.x + TileSize * Scale.z );
Renderable_Factor *= Renderable_Factor;
return true;
}
if ( strKey == "DistanceLOD" )
{
DistanceLOD = (float) ( pValue );
// Compute the actual distance as a square
LOD_Factor = DistanceLOD * ( TileSize * Scale.x + TileSize * Scale.z );
LOD_Factor *= LOD_Factor;
return true;
}
return false;
}
public bool getOption( string strKey, object pDestValue )
{
if ( strKey == "VisibleRenderables" )
{
pDestValue = Visible_Renderables;
return true;
}
if ( strKey == "DistanceLOD" )
{
pDestValue = DistanceLOD;
return true;
}
if ( strKey == "VisibleDistance" )
{
// we need to return the square root of the distance
pDestValue = Math.Sqrt (Renderable_Factor);
}
if ( strKey == "VisibleLOD" )
{
// we need to return the square root of the distance
pDestValue = Math.Sqrt (LOD_Factor);
}
// Some options proposed by Praetor
if ( strKey == "Width" )
{
pDestValue = World_Width;
return true;
}
if ( strKey == "Height" )
{
pDestValue = World_Height;
return true;
}
if ( strKey == "PageSize" )
{
pDestValue = PageSize;
return true;
}
if ( strKey == "ScaleX" )
{
pDestValue = Scale.x;
return true;
}
if ( strKey == "ScaleY" )
{
pDestValue = Scale.y;
return true;
}
if ( strKey == "ScaleZ" )
{
pDestValue = Scale.z;
return true;
}
return false;
}
public bool hasOption( string strKey )
{
if ( strKey == "VisibleRenderables" )
{
return true;
}
if ( strKey == "DistanceLOD" )
{
return true;
}
if ( strKey == "VisibleDistance" )
{
return true;
}
if ( strKey == "VisibleLOD" )
{
return true;
}
// Some options proposed by Praetor
if ( strKey == "Width" )
{
return true;
}
if ( strKey == "Height" )
{
return true;
}
if ( strKey == "PageSize" )
{
return true;
}
if ( strKey == "ScaleX" )
{
return true;
}
if ( strKey == "ScaleY" )
{
return true;
}
if ( strKey == "ScaleZ" )
{
return true;
}
return false;
}
public bool getOptionValues( string strKey, ArrayList refValueList )
{
if ( strKey == "VisibleRenderables" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "DistanceLOD" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "VisibleDistance" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "VisibleLOD" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "Width" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "Height" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "PageSize" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "ScaleX" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "ScaleY" )
{
refValueList.Add(new object());
return true;
}
if ( strKey == "ScaleZ" )
{
refValueList.Add(new object());
return true;
}
return false;
}
public bool getOptionKeys( ArrayList refKeys )
{
refKeys.Add( "VisibleRenderables" );
refKeys.Add( "DistanceLOD" );
refKeys.Add( "VisibleDistance" );
refKeys.Add( "VisibleLOD" );
// Some options from Praetor
refKeys.Add( "Width" );
refKeys.Add( "Height" );
refKeys.Add( "PageSize" );
refKeys.Add( "ScaleX" );
refKeys.Add( "ScaleY" );
refKeys.Add( "ScaleZ" );
return true;
}
private string getSetting( string setting )
{
if(table.Columns[setting] != null)
{
return (string)row[setting];
}
return "";
}
private ColorEx getAvgColor(string tex)
{
Image img = Image.FromFile(tex);
int bpp = Image.GetNumElemBytes( img.Format );
byte[] data = img.Data;
int cr = 0, cg = 0, cb = 0, s = 0;
for (int i = 0; i < img.Size; i += bpp)
{
cr += data[i];
cg += data[i+1];
cb += data[i+2];
s++;
}
cr /= s;
cg /= s;
cb /= s;
return new ColorEx(cr / 255.0F, cg / 255.0F, cb / 255.0F, 1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.ContentTypes.Services;
using OrchardCore.ContentTypes.ViewModels;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Environment.Shell;
using OrchardCore.Mvc.Utilities;
using YesSql;
using System.Reflection;
using OrchardCore.Mvc.ActionConstraints;
namespace OrchardCore.ContentTypes.Controllers
{
public class AdminController : Controller, IUpdateModel
{
private readonly IContentDefinitionService _contentDefinitionService;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ShellSettings _settings;
private readonly IAuthorizationService _authorizationService;
private readonly ISession _session;
private readonly IContentDefinitionDisplayManager _contentDefinitionDisplayManager;
private readonly INotifier _notifier;
public AdminController(
IContentDefinitionDisplayManager contentDefinitionDisplayManager,
IContentDefinitionService contentDefinitionService,
IContentDefinitionManager contentDefinitionManager,
ShellSettings settings,
IAuthorizationService authorizationService,
ISession session,
ILogger<AdminController> logger,
IHtmlLocalizer<AdminMenu> htmlLocalizer,
IStringLocalizer<AdminMenu> stringLocalizer,
INotifier notifier
)
{
_notifier = notifier;
_contentDefinitionDisplayManager = contentDefinitionDisplayManager;
_session = session;
_authorizationService = authorizationService;
_contentDefinitionService = contentDefinitionService;
_contentDefinitionManager = contentDefinitionManager;
_settings = settings;
Logger = logger;
T = htmlLocalizer;
S = stringLocalizer;
}
public IHtmlLocalizer T { get; set; }
public IStringLocalizer S { get; set; }
public ILogger Logger { get; set; }
public Task<ActionResult> Index() { return List(); }
#region Types
public async Task<ActionResult> List()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContentTypes))
return Unauthorized();
return View("List", new ListContentTypesViewModel
{
Types = _contentDefinitionService.GetTypes()
});
}
public async Task<ActionResult> Create(string suggestion)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
return View(new CreateTypeViewModel { DisplayName = suggestion, Name = suggestion.ToSafeName() });
}
[HttpPost, ActionName("Create")]
public async Task<ActionResult> CreatePOST(CreateTypeViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
viewModel.DisplayName = viewModel.DisplayName ?? String.Empty;
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Content Type Id can't be empty."]);
}
if (_contentDefinitionService.GetTypes().Any(t => String.Equals(t.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A type with the same Id already exists."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The technical name must start with a letter."]);
}
if (_contentDefinitionService.GetTypes().Any(t => String.Equals(t.DisplayName.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A type with the same Display Name already exists."]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
var contentTypeDefinition = _contentDefinitionService.AddType(viewModel.Name, viewModel.DisplayName);
var typeViewModel = new EditTypeViewModel(contentTypeDefinition);
_notifier.Success(T["The \"{0}\" content type has been created.", typeViewModel.DisplayName]);
return RedirectToAction("AddPartsTo", new { id = typeViewModel.Name });
}
public async Task<ActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
{
return NotFound();
}
typeViewModel.Editor = await _contentDefinitionDisplayManager.BuildTypeEditorAsync(typeViewModel.TypeDefinition, this);
return View(typeViewModel);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditPOST(string id, EditTypeViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(id);
if (contentTypeDefinition == null)
{
return NotFound();
}
viewModel.Settings = contentTypeDefinition.Settings;
viewModel.TypeDefinition = contentTypeDefinition;
viewModel.DisplayName = contentTypeDefinition.DisplayName;
viewModel.Editor = await _contentDefinitionDisplayManager.UpdateTypeEditorAsync(contentTypeDefinition, this);
if (!ModelState.IsValid)
{
_session.Cancel();
HackModelState(nameof(EditTypeViewModel.OrderedFieldNames));
HackModelState(nameof(EditTypeViewModel.OrderedPartNames));
return View(viewModel);
}
else
{
var ownedPartDefinition = _contentDefinitionManager.GetPartDefinition(contentTypeDefinition.Name);
if (ownedPartDefinition != null && viewModel.OrderedFieldNames != null)
{
_contentDefinitionService.AlterPartFieldsOrder(ownedPartDefinition, viewModel.OrderedFieldNames);
}
_contentDefinitionService.AlterTypePartsOrder(contentTypeDefinition, viewModel.OrderedPartNames);
_notifier.Success(T["\"{0}\" settings have been saved.", contentTypeDefinition.Name]);
}
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Delete")]
public async Task<ActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
return NotFound();
_contentDefinitionService.RemoveType(id, true);
_notifier.Success(T["\"{0}\" has been removed.", typeViewModel.DisplayName]);
return RedirectToAction("List");
}
public async Task<ActionResult> AddPartsTo(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Unauthorized();
}
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
return NotFound();
var typePartNames = new HashSet<string>(typeViewModel.TypeDefinition.Parts.Select(p => p.PartDefinition.Name));
var viewModel = new AddPartsViewModel
{
Type = typeViewModel,
PartSelections = _contentDefinitionService.GetParts(metadataPartsOnly: false)
.Where(cpd => !typePartNames.Contains(cpd.Name) && cpd.Settings.ToObject<ContentPartSettings>().Attachable)
.Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description })
.ToList()
};
return View(viewModel);
}
public async Task<ActionResult> AddReusablePartTo(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
{
return Unauthorized();
}
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
return NotFound();
var reusableParts = _contentDefinitionService.GetParts(metadataPartsOnly: false)
.Where(cpd =>
cpd.Settings.ToObject<ContentPartSettings>().Attachable &&
cpd.Settings.ToObject<ContentPartSettings>().Reusable);
var viewModel = new AddReusablePartViewModel
{
Type = typeViewModel,
PartSelections = reusableParts
.Select(cpd => new PartSelectionViewModel { PartName = cpd.Name, PartDisplayName = cpd.DisplayName, PartDescription = cpd.Description })
.ToList(),
SelectedPartName = reusableParts.FirstOrDefault()?.Name
};
return View(viewModel);
}
[HttpPost, ActionName("AddPartsTo")]
public async Task<ActionResult> AddPartsToPOST(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
return NotFound();
var viewModel = new AddPartsViewModel();
if (!await TryUpdateModelAsync(viewModel))
{
return await AddPartsTo(id);
}
var partsToAdd = viewModel.PartSelections.Where(ps => ps.IsSelected).Select(ps => ps.PartName);
foreach (var partToAdd in partsToAdd)
{
_contentDefinitionService.AddPartToType(partToAdd, typeViewModel.Name);
_notifier.Success(T["The \"{0}\" part has been added.", partToAdd]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return await AddPartsTo(id);
}
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("AddReusablePartTo")]
public async Task<ActionResult> AddReusablePartToPOST(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null)
return NotFound();
var viewModel = new AddReusablePartViewModel();
if (!await TryUpdateModelAsync(viewModel))
{
return await AddReusablePartTo(id);
}
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name can't be empty."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Content Type Id can't be empty."]);
}
var partToAdd = viewModel.SelectedPartName;
_contentDefinitionService.AddReusablePartToType(viewModel.Name, viewModel.DisplayName, viewModel.Description, partToAdd, typeViewModel.Name);
_notifier.Success(T["The \"{0}\" part has been added.", partToAdd]);
if (!ModelState.IsValid)
{
_session.Cancel();
return await AddReusablePartTo(id);
}
return RedirectToAction("Edit", new { id });
}
[HttpPost, ActionName("RemovePart")]
public async Task<ActionResult> RemovePartPOST(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel == null
|| !typeViewModel.TypeDefinition.Parts.Any(p => p.Name == name))
return NotFound();
_contentDefinitionService.RemovePartFromType(name, id);
_notifier.Success(T["The \"{0}\" part has been removed.", name]);
return RedirectToAction("Edit", new { id });
}
#endregion
#region Parts
public async Task<ActionResult> ListParts()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContentTypes))
return Unauthorized();
return View(new ListContentPartsViewModel
{
// only user-defined parts (not code as they are not configurable)
Parts = _contentDefinitionService.GetParts(true/*metadataPartsOnly*/)
});
}
public async Task<ActionResult> CreatePart(string suggestion)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
return View(new CreatePartViewModel { Name = suggestion.ToSafeName() });
}
[HttpPost, ActionName("CreatePart")]
public async Task<ActionResult> CreatePartPOST(CreatePartViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
if (_contentDefinitionManager.GetPartDefinition(viewModel.Name) != null)
ModelState.AddModelError("Name", S["Cannot add part named '{0}'. It already exists.", viewModel.Name]);
if (!ModelState.IsValid)
return View(viewModel);
var partViewModel = _contentDefinitionService.AddPart(viewModel);
if (partViewModel == null)
{
_notifier.Information(T["The content part could not be created."]);
return View(viewModel);
}
_notifier.Success(T["The \"{0}\" content part has been created.", partViewModel.Name]);
return RedirectToAction("EditPart", new { id = partViewModel.Name });
}
public async Task<ActionResult> EditPart(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var contentPartDefinition = _contentDefinitionManager.GetPartDefinition(id);
if (contentPartDefinition == null)
{
return NotFound();
}
var viewModel = new EditPartViewModel(contentPartDefinition);
viewModel.Editor = await _contentDefinitionDisplayManager.BuildPartEditorAsync(contentPartDefinition, this);
return View(viewModel);
}
[HttpPost, ActionName("EditPart")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditPartPOST(string id, string[] orderedFieldNames)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var contentPartDefinition = _contentDefinitionManager.GetPartDefinition(id);
if (contentPartDefinition == null)
{
return NotFound();
}
var viewModel = new EditPartViewModel(contentPartDefinition);
viewModel.Editor = await _contentDefinitionDisplayManager.UpdatePartEditorAsync(contentPartDefinition, this);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
_contentDefinitionService.AlterPartFieldsOrder(contentPartDefinition, orderedFieldNames);
_notifier.Success(T["The settings of \"{0}\" have been saved.", contentPartDefinition.Name]);
}
return RedirectToAction("EditPart", new { id });
}
[HttpPost, ActionName("EditPart")]
[FormValueRequired("submit.Delete")]
public async Task<ActionResult> DeletePart(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
return NotFound();
_contentDefinitionService.RemovePart(id);
_notifier.Information(T["\"{0}\" has been removed.", partViewModel.DisplayName]);
return RedirectToAction("ListParts");
}
public async Task<ActionResult> AddFieldTo(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var viewModel = new AddFieldViewModel
{
Part = partViewModel.PartDefinition,
Fields = _contentDefinitionService.GetFields().Select(x => x.Name).OrderBy(x => x).ToList()
};
return View(viewModel);
}
[HttpPost, ActionName("AddFieldTo")]
public async Task<ActionResult> AddFieldToPOST(AddFieldViewModel viewModel, string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var partDefinition = partViewModel.PartDefinition;
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
viewModel.Name = viewModel.Name ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name name can't be empty."]);
}
if (String.IsNullOrWhiteSpace(viewModel.Name))
{
ModelState.AddModelError("Name", S["The Technical Name can't be empty."]);
}
if (partDefinition.Fields.Any(t => String.Equals(t.Name.Trim(), viewModel.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("Name", S["A field with the same name already exists."]);
}
if (!String.IsNullOrWhiteSpace(viewModel.Name) && !viewModel.Name[0].IsLetter())
{
ModelState.AddModelError("Name", S["The technical name must start with a letter."]);
}
if (!String.Equals(viewModel.Name, viewModel.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("Name", S["The technical name contains invalid characters."]);
}
if (partDefinition.Fields.Any(t => String.Equals(t.DisplayName().Trim(), Convert.ToString(viewModel.DisplayName).Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A field with the same Display Name already exists."]);
}
if (!ModelState.IsValid)
{
viewModel.Part = partDefinition;
viewModel.Fields = _contentDefinitionService.GetFields().Select(x => x.Name).OrderBy(x => x).ToList();
_session.Cancel();
return View(viewModel);
}
_contentDefinitionService.AddFieldToPart(viewModel.Name, viewModel.DisplayName, viewModel.FieldTypeName, partDefinition.Name);
_notifier.Success(T["The field \"{0}\" has been added.", viewModel.DisplayName]);
return RedirectToAction("EditField", new { id, viewModel.Name });
}
public async Task<ActionResult> EditField(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var partFieldDefinition = partViewModel.PartDefinition.Fields.FirstOrDefault(x => x.Name == name);
if (partFieldDefinition == null)
{
return NotFound();
}
var viewModel = new EditFieldViewModel
{
Name = partFieldDefinition.Name,
DisplayName = partFieldDefinition.DisplayName(),
PartFieldDefinition = partFieldDefinition,
Editor = await _contentDefinitionDisplayManager.BuildPartFieldEditorAsync(partFieldDefinition, this)
};
return View(viewModel);
}
[HttpPost, ActionName("EditField")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditFieldPOST(string id, EditFieldViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
if (viewModel == null)
return NotFound();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var field = _contentDefinitionManager.GetPartDefinition(id).Fields.FirstOrDefault(x => x.Name == viewModel.Name);
if (field == null)
{
return NotFound();
}
if (field.DisplayName() != viewModel.DisplayName)
{
// prevent null reference exception in validation
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The Display Name name can't be empty."]);
}
if (_contentDefinitionService.GetPart(partViewModel.Name).PartDefinition.Fields.Any(t => t.Name != viewModel.Name && String.Equals(t.DisplayName().Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A field with the same Display Name already exists."]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
_contentDefinitionService.AlterField(partViewModel, viewModel);
_notifier.Information(T["Display name changed to {0}.", viewModel.DisplayName]);
}
viewModel.Editor = await _contentDefinitionDisplayManager.UpdatePartFieldEditorAsync(field, this);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
_notifier.Success(T["The \"{0}\" field settings have been saved.", field.DisplayName()]);
}
// Redirect to the type editor if a type exists with this name
var typeViewModel = _contentDefinitionService.GetType(id);
if (typeViewModel != null)
{
return RedirectToAction("Edit", new { id });
}
return RedirectToAction("EditPart", new { id });
}
[HttpPost, ActionName("RemoveFieldFrom")]
public async Task<ActionResult> RemoveFieldFromPOST(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var partViewModel = _contentDefinitionService.GetPart(id);
if (partViewModel == null)
{
return NotFound();
}
var field = partViewModel.PartDefinition.Fields.FirstOrDefault(x => x.Name == name);
if (field == null)
{
return NotFound();
}
_contentDefinitionService.RemoveFieldFromPart(name, partViewModel.Name);
_notifier.Success(T["The \"{0}\" field has been removed.", field.DisplayName()]);
if (_contentDefinitionService.GetType(id) != null)
{
return RedirectToAction("Edit", new { id });
}
return RedirectToAction("EditPart", new { id });
}
#endregion
#region Type Parts
public async Task<ActionResult> EditTypePart(string id, string name)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(id);
if (typeDefinition == null)
{
return NotFound();
}
var typePartDefinition = typeDefinition.Parts.FirstOrDefault(x => x.Name == name);
if (typePartDefinition == null)
{
return NotFound();
}
var typePartViewModel = new EditTypePartViewModel
{
Name = typePartDefinition.Name,
DisplayName = typePartDefinition.DisplayName(),
Description = typePartDefinition.Description(),
TypePartDefinition = typePartDefinition,
Editor = await _contentDefinitionDisplayManager.BuildTypePartEditorAsync(typePartDefinition, this)
};
return View(typePartViewModel);
}
[HttpPost, ActionName("EditTypePart")]
[FormValueRequired("submit.Save")]
public async Task<ActionResult> EditTypePartPOST(string id, EditTypePartViewModel viewModel)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContentTypes))
return Unauthorized();
if (viewModel == null)
{
return NotFound();
}
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(id);
if (typeDefinition == null)
{
return NotFound();
}
var part = typeDefinition.Parts.FirstOrDefault(x => x.Name == viewModel.Name);
if (part == null)
{
return NotFound();
}
viewModel.TypePartDefinition = part;
if (part.PartDefinition.IsReusable())
{
if (part.DisplayName() != viewModel.DisplayName)
{
// Prevent null reference exception in validation
viewModel.DisplayName = viewModel.DisplayName?.Trim() ?? String.Empty;
if (String.IsNullOrWhiteSpace(viewModel.DisplayName))
{
ModelState.AddModelError("DisplayName", S["The display name can't be empty."]);
}
if (typeDefinition.Parts.Any(t => t.Name != viewModel.Name && String.Equals(t.DisplayName()?.Trim(), viewModel.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
ModelState.AddModelError("DisplayName", S["A part with the same display name already exists."]);
}
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
}
_contentDefinitionService.AlterTypePart(viewModel);
}
viewModel.Editor = await _contentDefinitionDisplayManager.UpdateTypePartEditorAsync(part, this);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(viewModel);
}
else
{
_notifier.Success(T["The \"{0}\" part settings have been saved.", part.DisplayName()]);
}
return RedirectToAction("Edit", new { id });
}
#endregion
private void HackModelState(string key)
{
// TODO: Remove this once https://github.com/aspnet/Mvc/issues/4989 has shipped
var modelStateEntry = ModelState[key];
var nodeType = modelStateEntry.GetType();
nodeType.GetMethod("GetNode").Invoke(modelStateEntry, new object[] { new Microsoft.Extensions.Primitives.StringSegment("--!!f-a-k-e"), true });
((System.Collections.IList)nodeType.GetProperty("ChildNodes").GetValue(modelStateEntry)).Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.TestHooks;
using Orleans.TestingHost.Utils;
namespace Orleans.TestingHost
{
/// <summary>Configuration builder for starting a <see cref="TestCluster"/>.</summary>
public class TestClusterBuilder
{
private readonly List<Action<IConfigurationBuilder>> configureHostConfigActions = new List<Action<IConfigurationBuilder>>();
private readonly List<Action> configureBuilderActions = new List<Action>();
/// <summary>
/// Initializes a new instance of <see cref="TestClusterBuilder"/> using the default options.
/// </summary>
public TestClusterBuilder()
: this(2)
{
}
/// <summary>
/// Initializes a new instance of <see cref="TestClusterBuilder"/> overriding the initial silos count.
/// </summary>
/// <param name="initialSilosCount">The number of initial silos to deploy.</param>
public TestClusterBuilder(short initialSilosCount)
{
this.Options = new TestClusterOptions
{
InitialSilosCount = initialSilosCount,
ClusterId = CreateClusterId(),
ServiceId = Guid.NewGuid().ToString("N"),
UseTestClusterMembership = true,
InitializeClientOnDeploy = true,
ConfigureFileLogging = true,
AssumeHomogenousSilosForTesting = true
};
this.AddClientBuilderConfigurator<AddTestHooksApplicationParts>();
this.AddSiloBuilderConfigurator<AddTestHooksApplicationParts>();
this.AddSiloBuilderConfigurator<ConfigureStaticClusterDeploymentOptions>();
this.ConfigureBuilder(ConfigureDefaultPorts);
}
/// <summary>
/// Configuration values which will be provided to the silos and clients created by this builder.
/// </summary>
public Dictionary<string, string> Properties { get; } = new Dictionary<string, string>();
public TestClusterOptions Options { get; }
/// <summary>
/// Delegate used to create and start an individual silo.
/// </summary>
public Func<string, IList<IConfigurationSource>, Task<SiloHandle>> CreateSiloAsync { private get; set; }
public TestClusterBuilder ConfigureBuilder(Action configureDelegate)
{
this.configureBuilderActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
return this;
}
/// <summary>
/// Set up the configuration for the builder itself. This will be used as a base to initialize each silo host
/// for use later in the build process. This can be called multiple times and the results will be additive.
/// </summary>
/// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder"/> that will be used
/// to construct the <see cref="IConfiguration"/> for the host.</param>
/// <returns>The same instance of the host builder for chaining.</returns>
public TestClusterBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate)
{
this.configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
return this;
}
public void AddSiloBuilderConfigurator<TSiloBuilderConfigurator>() where TSiloBuilderConfigurator : ISiloBuilderConfigurator, new()
{
this.Options.SiloBuilderConfiguratorTypes.Add(typeof(TSiloBuilderConfigurator).AssemblyQualifiedName);
}
public void AddClientBuilderConfigurator<TClientBuilderConfigurator>() where TClientBuilderConfigurator : IClientBuilderConfigurator, new()
{
this.Options.ClientBuilderConfiguratorTypes.Add(typeof(TClientBuilderConfigurator).AssemblyQualifiedName);
}
public TestCluster Build()
{
var configBuilder = new ConfigurationBuilder();
foreach (var action in configureBuilderActions)
{
action();
}
configBuilder.AddInMemoryCollection(this.Properties);
configBuilder.AddInMemoryCollection(this.Options.ToDictionary());
foreach (var buildAction in this.configureHostConfigActions)
{
buildAction(configBuilder);
}
var configuration = configBuilder.Build();
var finalOptions = new TestClusterOptions();
configuration.Bind(finalOptions);
var configSources = new ReadOnlyCollection<IConfigurationSource>(configBuilder.Sources);
var testCluster = new TestCluster(finalOptions, configSources);
if (this.CreateSiloAsync != null) testCluster.CreateSiloAsync = this.CreateSiloAsync;
return testCluster;
}
public static string CreateClusterId()
{
string prefix = "testcluster-";
int randomSuffix = ThreadSafeRandom.Next(1000);
DateTime now = DateTime.UtcNow;
string DateTimeFormat = @"yyyy-MM-dd\tHH-mm-ss";
return $"{prefix}{now.ToString(DateTimeFormat, CultureInfo.InvariantCulture)}-{randomSuffix}";
}
private void ConfigureDefaultPorts()
{
// Set base ports if none are currently set.
(int baseSiloPort, int baseGatewayPort) = GetAvailableConsecutiveServerPortsPair(this.Options.InitialSilosCount + 3);
if (this.Options.BaseSiloPort == 0) this.Options.BaseSiloPort = baseSiloPort;
if (this.Options.BaseGatewayPort == 0) this.Options.BaseGatewayPort = baseGatewayPort;
}
// Returns a pairs of ports which have the specified number of consecutive ports available for use.
internal static ValueTuple<int, int> GetAvailableConsecutiveServerPortsPair(int consecutivePortsToCheck = 5)
{
// Evaluate current system tcp connections
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
// each returned port in the pair will have to have at least this amount of available ports following it
return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, consecutivePortsToCheck),
GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, consecutivePortsToCheck));
}
private static int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck)
{
const int MaxAttempts = 10;
for (int attempts = 0; attempts < MaxAttempts; attempts++)
{
int basePort = ThreadSafeRandom.Next(portStartRange, portEndRange);
// get ports in buckets, so we don't interfere with parallel runs of this same function
basePort = basePort - (basePort % consecutivePortsToCheck);
int endPort = basePort + consecutivePortsToCheck;
// make sure none of the ports in the sub range are in use
if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort))
return basePort;
}
throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster");
}
internal class AddTestHooksApplicationParts : IClientBuilderConfigurator, ISiloBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.ConfigureApplicationParts(parts => parts.AddFrameworkPart(typeof(ITestHooksSystemTarget).Assembly));
}
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.ConfigureApplicationParts(parts => parts.AddFrameworkPart(typeof(ITestHooksSystemTarget).Assembly));
}
}
internal class ConfigureStaticClusterDeploymentOptions : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices((context, services) =>
{
var initialSilos = int.Parse(context.Configuration[nameof(TestClusterOptions.InitialSilosCount)]);
var siloNames = Enumerable.Range(0, initialSilos).Select(GetSiloName).ToList();
services.Configure<StaticClusterDeploymentOptions>(options => options.SiloNames = siloNames);
});
}
private static string GetSiloName(int instanceNumber)
{
return instanceNumber == 0 ? Silo.PrimarySiloName : $"Secondary_{instanceNumber}";
}
}
}
}
| |
// 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.Reflection.Metadata.Ecma335;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class HandleTests
{
[Fact]
public void HandleKindsMatchSpecAndDoNotChange()
{
// These are chosen to match their encoding in metadata tokens as specified by the CLI spec
Assert.Equal(0x00, (int)HandleKind.ModuleDefinition);
Assert.Equal(0x01, (int)HandleKind.TypeReference);
Assert.Equal(0x02, (int)HandleKind.TypeDefinition);
Assert.Equal(0x04, (int)HandleKind.FieldDefinition);
Assert.Equal(0x06, (int)HandleKind.MethodDefinition);
Assert.Equal(0x08, (int)HandleKind.Parameter);
Assert.Equal(0x09, (int)HandleKind.InterfaceImplementation);
Assert.Equal(0x0A, (int)HandleKind.MemberReference);
Assert.Equal(0x0B, (int)HandleKind.Constant);
Assert.Equal(0x0C, (int)HandleKind.CustomAttribute);
Assert.Equal(0x0E, (int)HandleKind.DeclarativeSecurityAttribute);
Assert.Equal(0x11, (int)HandleKind.StandaloneSignature);
Assert.Equal(0x14, (int)HandleKind.EventDefinition);
Assert.Equal(0x17, (int)HandleKind.PropertyDefinition);
Assert.Equal(0x19, (int)HandleKind.MethodImplementation);
Assert.Equal(0x1A, (int)HandleKind.ModuleReference);
Assert.Equal(0x1B, (int)HandleKind.TypeSpecification);
Assert.Equal(0x20, (int)HandleKind.AssemblyDefinition);
Assert.Equal(0x26, (int)HandleKind.AssemblyFile);
Assert.Equal(0x23, (int)HandleKind.AssemblyReference);
Assert.Equal(0x27, (int)HandleKind.ExportedType);
Assert.Equal(0x2A, (int)HandleKind.GenericParameter);
Assert.Equal(0x2B, (int)HandleKind.MethodSpecification);
Assert.Equal(0x2C, (int)HandleKind.GenericParameterConstraint);
Assert.Equal(0x28, (int)HandleKind.ManifestResource);
Assert.Equal(0x70, (int)HandleKind.UserString);
// These values were chosen arbitrarily, but must still never change
Assert.Equal(0x71, (int)HandleKind.Blob);
Assert.Equal(0x72, (int)HandleKind.Guid);
Assert.Equal(0x78, (int)HandleKind.String);
Assert.Equal(0x7c, (int)HandleKind.NamespaceDefinition);
}
[Fact]
public void HandleConversionGivesCorrectKind()
{
var expectedKinds = new SortedSet<HandleKind>((HandleKind[])Enum.GetValues(typeof(HandleKind)));
Action<Handle, HandleKind> assert = (handle, expectedKind) =>
{
Assert.False(expectedKinds.Count == 0, "Repeat handle in tests below.");
Assert.Equal(expectedKind, handle.Kind);
expectedKinds.Remove(expectedKind);
};
assert(default(ModuleDefinitionHandle), HandleKind.ModuleDefinition);
assert(default(AssemblyDefinitionHandle), HandleKind.AssemblyDefinition);
assert(default(InterfaceImplementationHandle), HandleKind.InterfaceImplementation);
assert(default(MethodDefinitionHandle), HandleKind.MethodDefinition);
assert(default(MethodSpecificationHandle), HandleKind.MethodSpecification);
assert(default(TypeDefinitionHandle), HandleKind.TypeDefinition);
assert(default(ExportedTypeHandle), HandleKind.ExportedType);
assert(default(TypeReferenceHandle), HandleKind.TypeReference);
assert(default(TypeSpecificationHandle), HandleKind.TypeSpecification);
assert(default(MemberReferenceHandle), HandleKind.MemberReference);
assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition);
assert(default(EventDefinitionHandle), HandleKind.EventDefinition);
assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition);
assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature);
assert(default(MemberReferenceHandle), HandleKind.MemberReference);
assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition);
assert(default(EventDefinitionHandle), HandleKind.EventDefinition);
assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition);
assert(default(ParameterHandle), HandleKind.Parameter);
assert(default(GenericParameterHandle), HandleKind.GenericParameter);
assert(default(GenericParameterConstraintHandle), HandleKind.GenericParameterConstraint);
assert(default(ModuleReferenceHandle), HandleKind.ModuleReference);
assert(default(CustomAttributeHandle), HandleKind.CustomAttribute);
assert(default(DeclarativeSecurityAttributeHandle), HandleKind.DeclarativeSecurityAttribute);
assert(default(ManifestResourceHandle), HandleKind.ManifestResource);
assert(default(ConstantHandle), HandleKind.Constant);
assert(default(ManifestResourceHandle), HandleKind.ManifestResource);
assert(default(MethodImplementationHandle), HandleKind.MethodImplementation);
assert(default(AssemblyFileHandle), HandleKind.AssemblyFile);
assert(default(StringHandle), HandleKind.String);
assert(default(AssemblyReferenceHandle), HandleKind.AssemblyReference);
assert(default(UserStringHandle), HandleKind.UserString);
assert(default(GuidHandle), HandleKind.Guid);
assert(default(BlobHandle), HandleKind.Blob);
assert(default(NamespaceDefinitionHandle), HandleKind.NamespaceDefinition);
assert(default(DocumentHandle), HandleKind.Document);
assert(default(MethodDebugInformationHandle), HandleKind.MethodDebugInformation);
assert(default(LocalScopeHandle), HandleKind.LocalScope);
assert(default(LocalConstantHandle), HandleKind.LocalConstant);
assert(default(LocalVariableHandle), HandleKind.LocalVariable);
assert(default(ImportScopeHandle), HandleKind.ImportScope);
assert(default(CustomDebugInformationHandle), HandleKind.CustomDebugInformation);
Assert.True(expectedKinds.Count == 0, "Some handles are missing from this test: " + string.Join("," + Environment.NewLine, expectedKinds));
}
[Fact]
public void Conversions_Handles()
{
Assert.Equal(1, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 1)).RowId);
Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 0x00ffffff)).RowId);
Assert.Equal(1, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 1)).RowId);
Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 0x00ffffff)).RowId);
Assert.Equal(1, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 1)).RowId);
Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 0x00ffffff)).RowId);
Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId);
Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId);
Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId);
Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId);
Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId);
Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId);
Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId);
Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId);
Assert.Equal(1, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 1)).RowId);
Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 0x00ffffff)).RowId);
Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId);
Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId);
Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId);
Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId);
Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId);
Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId);
Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId);
Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId);
Assert.Equal(1, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 1)).RowId);
Assert.Equal(0x00ffffff, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 0x00ffffff)).RowId);
Assert.Equal(1, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 1)).RowId);
Assert.Equal(0x00ffffff, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 0x00ffffff)).RowId);
Assert.Equal(1, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 1)).RowId);
Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 0x00ffffff)).RowId);
Assert.Equal(1, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 1)).RowId);
Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 0x00ffffff)).RowId);
Assert.Equal(1, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 1)).RowId);
Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 0x00ffffff)).RowId);
Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 1)).RowId);
Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 0x00ffffff)).RowId);
Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId);
Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId);
Assert.Equal(1, ((ConstantHandle)new Handle((byte)HandleType.Constant, 1)).RowId);
Assert.Equal(0x00ffffff, ((ConstantHandle)new Handle((byte)HandleType.Constant, 0x00ffffff)).RowId);
Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId);
Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 0x00ffffff)).RowId);
Assert.Equal(1, ((UserStringHandle)new Handle((byte)HandleType.UserString, 1)).GetHeapOffset());
Assert.Equal(0x00ffffff, ((UserStringHandle)new Handle((byte)HandleType.UserString, 0x00ffffff)).GetHeapOffset());
Assert.Equal(1, ((GuidHandle)new Handle((byte)HandleType.Guid, 1)).Index);
Assert.Equal(0x1fffffff, ((GuidHandle)new Handle((byte)HandleType.Guid, 0x1fffffff)).Index);
Assert.Equal(1, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 1)).GetHeapOffset());
Assert.Equal(0x1fffffff, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 0x1fffffff)).GetHeapOffset());
Assert.Equal(1, ((StringHandle)new Handle((byte)HandleType.String, 1)).GetHeapOffset());
Assert.Equal(0x1fffffff, ((StringHandle)new Handle((byte)HandleType.String, 0x1fffffff)).GetHeapOffset());
Assert.Equal(1, ((BlobHandle)new Handle((byte)HandleType.Blob, 1)).GetHeapOffset());
Assert.Equal(0x1fffffff, ((BlobHandle)new Handle((byte)HandleType.Blob, 0x1fffffff)).GetHeapOffset());
}
[Fact]
public void Conversions_EntityHandles()
{
Assert.Equal(1, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 1)).RowId);
Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 0x00ffffff)).RowId);
Assert.Equal(1, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 1)).RowId);
Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 0x00ffffff)).RowId);
Assert.Equal(1, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 1)).RowId);
Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 0x00ffffff)).RowId);
Assert.Equal(1, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 1)).RowId);
Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 0x00ffffff)).RowId);
Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId);
Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId);
Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId);
Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId);
Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId);
Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId);
Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId);
Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId);
Assert.Equal(1, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 1)).RowId);
Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 0x00ffffff)).RowId);
Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId);
Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId);
Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId);
Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId);
Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId);
Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId);
Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId);
Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId);
Assert.Equal(1, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 1)).RowId);
Assert.Equal(0x00ffffff, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 0x00ffffff)).RowId);
Assert.Equal(1, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 1)).RowId);
Assert.Equal(0x00ffffff, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 0x00ffffff)).RowId);
Assert.Equal(1, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 1)).RowId);
Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 0x00ffffff)).RowId);
Assert.Equal(1, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 1)).RowId);
Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 0x00ffffff)).RowId);
Assert.Equal(1, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 1)).RowId);
Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 0x00ffffff)).RowId);
Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 1)).RowId);
Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 0x00ffffff)).RowId);
Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId);
Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId);
Assert.Equal(1, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 1)).RowId);
Assert.Equal(0x00ffffff, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 0x00ffffff)).RowId);
Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId);
Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 0x00ffffff)).RowId);
Assert.Equal(1, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 1)).RowId);
Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 0x00ffffff)).RowId);
Assert.Equal(1, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 1)).RowId);
Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 0x00ffffff)).RowId);
}
[Fact]
public void Conversions_VirtualHandles()
{
Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Module ), 1));
Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Assembly ), 1));
Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.InterfaceImpl), 1));
Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodDef ), 1));
Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodSpec), 1));
Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeDef ), 1));
Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ExportedType), 1));
Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeRef), 1));
Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeSpec), 1));
Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1));
Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1));
Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1));
Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1));
Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Signature), 1));
Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1));
Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1));
Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1));
Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1));
Assert.Throws<InvalidCastException>(() => (ParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ParamDef), 1));
Assert.Throws<InvalidCastException>(() => (GenericParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParam), 1));
Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParamConstraint), 1));
Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ModuleRef), 1));
Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.CustomAttribute), 1));
Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.DeclSecurity), 1));
Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1));
Assert.Throws<InvalidCastException>(() => (ConstantHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Constant), 1));
Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1));
Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.File), 1));
Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodImpl), 1));
Assert.Throws<InvalidCastException>(() => (UserStringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.UserString), 1));
Assert.Throws<InvalidCastException>(() => (GuidHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Guid), 1));
var x1 = (AssemblyReferenceHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.AssemblyRef), 1);
var x2 = (StringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.String), 1);
var x3 = (BlobHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Blob), 1);
var x4 = (NamespaceDefinitionHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Namespace), 1);
}
[Fact]
public void Conversions_VirtualEntityHandles()
{
Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Module | 1));
Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Assembly | 1));
Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.InterfaceImpl | 1));
Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodDef | 1));
Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodSpec | 1));
Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeDef | 1));
Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ExportedType | 1));
Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeRef | 1));
Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeSpec | 1));
Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1));
Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1));
Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1));
Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1));
Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Signature | 1));
Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1));
Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1));
Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1));
Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1));
Assert.Throws<InvalidCastException>(() => (ParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ParamDef | 1));
Assert.Throws<InvalidCastException>(() => (GenericParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParam | 1));
Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParamConstraint | 1));
Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ModuleRef | 1));
Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.CustomAttribute | 1));
Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.DeclSecurity | 1));
Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1));
Assert.Throws<InvalidCastException>(() => (ConstantHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Constant | 1));
Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1));
Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.File | 1));
Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodImpl | 1));
var x1 = (AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.AssemblyRef | 1);
}
[Fact]
public void IsNil()
{
Assert.False(ModuleDefinitionHandle.FromRowId(1).IsNil);
Assert.False(AssemblyDefinitionHandle.FromRowId(1).IsNil);
Assert.False(InterfaceImplementationHandle.FromRowId(1).IsNil);
Assert.False(MethodDefinitionHandle.FromRowId(1).IsNil);
Assert.False(MethodSpecificationHandle.FromRowId(1).IsNil);
Assert.False(TypeDefinitionHandle.FromRowId(1).IsNil);
Assert.False(ExportedTypeHandle.FromRowId(1).IsNil);
Assert.False(TypeReferenceHandle.FromRowId(1).IsNil);
Assert.False(TypeSpecificationHandle.FromRowId(1).IsNil);
Assert.False(MemberReferenceHandle.FromRowId(1).IsNil);
Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil);
Assert.False(EventDefinitionHandle.FromRowId(1).IsNil);
Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil);
Assert.False(StandaloneSignatureHandle.FromRowId(1).IsNil);
Assert.False(MemberReferenceHandle.FromRowId(1).IsNil);
Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil);
Assert.False(EventDefinitionHandle.FromRowId(1).IsNil);
Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil);
Assert.False(ParameterHandle.FromRowId(1).IsNil);
Assert.False(GenericParameterHandle.FromRowId(1).IsNil);
Assert.False(GenericParameterConstraintHandle.FromRowId(1).IsNil);
Assert.False(ModuleReferenceHandle.FromRowId(1).IsNil);
Assert.False(CustomAttributeHandle.FromRowId(1).IsNil);
Assert.False(DeclarativeSecurityAttributeHandle.FromRowId(1).IsNil);
Assert.False(ManifestResourceHandle.FromRowId(1).IsNil);
Assert.False(ConstantHandle.FromRowId(1).IsNil);
Assert.False(ManifestResourceHandle.FromRowId(1).IsNil);
Assert.False(AssemblyFileHandle.FromRowId(1).IsNil);
Assert.False(MethodImplementationHandle.FromRowId(1).IsNil);
Assert.False(AssemblyReferenceHandle.FromRowId(1).IsNil);
Assert.False(((EntityHandle)ModuleDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)AssemblyDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)InterfaceImplementationHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)MethodDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)MethodSpecificationHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)TypeDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ExportedTypeHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)TypeReferenceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)TypeSpecificationHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)StandaloneSignatureHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ParameterHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)GenericParameterHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)GenericParameterConstraintHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ModuleReferenceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)CustomAttributeHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ConstantHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)AssemblyFileHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)MethodImplementationHandle.FromRowId(1)).IsNil);
Assert.False(((EntityHandle)AssemblyReferenceHandle.FromRowId(1)).IsNil);
Assert.False(StringHandle.FromOffset(1).IsNil);
Assert.False(BlobHandle.FromOffset(1).IsNil);
Assert.False(UserStringHandle.FromOffset(1).IsNil);
Assert.False(GuidHandle.FromIndex(1).IsNil);
Assert.False(DocumentNameBlobHandle.FromOffset(1).IsNil);
Assert.False(((Handle)StringHandle.FromOffset(1)).IsNil);
Assert.False(((Handle)BlobHandle.FromOffset(1)).IsNil);
Assert.False(((Handle)UserStringHandle.FromOffset(1)).IsNil);
Assert.False(((Handle)GuidHandle.FromIndex(1)).IsNil);
Assert.False(((BlobHandle)DocumentNameBlobHandle.FromOffset(1)).IsNil);
Assert.True(ModuleDefinitionHandle.FromRowId(0).IsNil);
Assert.True(AssemblyDefinitionHandle.FromRowId(0).IsNil);
Assert.True(InterfaceImplementationHandle.FromRowId(0).IsNil);
Assert.True(MethodDefinitionHandle.FromRowId(0).IsNil);
Assert.True(MethodSpecificationHandle.FromRowId(0).IsNil);
Assert.True(TypeDefinitionHandle.FromRowId(0).IsNil);
Assert.True(ExportedTypeHandle.FromRowId(0).IsNil);
Assert.True(TypeReferenceHandle.FromRowId(0).IsNil);
Assert.True(TypeSpecificationHandle.FromRowId(0).IsNil);
Assert.True(MemberReferenceHandle.FromRowId(0).IsNil);
Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil);
Assert.True(EventDefinitionHandle.FromRowId(0).IsNil);
Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil);
Assert.True(StandaloneSignatureHandle.FromRowId(0).IsNil);
Assert.True(MemberReferenceHandle.FromRowId(0).IsNil);
Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil);
Assert.True(EventDefinitionHandle.FromRowId(0).IsNil);
Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil);
Assert.True(ParameterHandle.FromRowId(0).IsNil);
Assert.True(GenericParameterHandle.FromRowId(0).IsNil);
Assert.True(GenericParameterConstraintHandle.FromRowId(0).IsNil);
Assert.True(ModuleReferenceHandle.FromRowId(0).IsNil);
Assert.True(CustomAttributeHandle.FromRowId(0).IsNil);
Assert.True(DeclarativeSecurityAttributeHandle.FromRowId(0).IsNil);
Assert.True(ManifestResourceHandle.FromRowId(0).IsNil);
Assert.True(ConstantHandle.FromRowId(0).IsNil);
Assert.True(ManifestResourceHandle.FromRowId(0).IsNil);
Assert.True(AssemblyFileHandle.FromRowId(0).IsNil);
Assert.True(MethodImplementationHandle.FromRowId(0).IsNil);
Assert.True(AssemblyReferenceHandle.FromRowId(0).IsNil);
Assert.True(((EntityHandle)ModuleDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)AssemblyDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)InterfaceImplementationHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)MethodDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)MethodSpecificationHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)TypeDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ExportedTypeHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)TypeReferenceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)TypeSpecificationHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)StandaloneSignatureHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ParameterHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)GenericParameterHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)GenericParameterConstraintHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ModuleReferenceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)CustomAttributeHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ConstantHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)AssemblyFileHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)MethodImplementationHandle.FromRowId(0)).IsNil);
Assert.True(((EntityHandle)AssemblyReferenceHandle.FromRowId(0)).IsNil);
// heaps:
Assert.True(StringHandle.FromOffset(0).IsNil);
Assert.True(BlobHandle.FromOffset(0).IsNil);
Assert.True(UserStringHandle.FromOffset(0).IsNil);
Assert.True(GuidHandle.FromIndex(0).IsNil);
Assert.True(DocumentNameBlobHandle.FromOffset(0).IsNil);
Assert.True(((Handle)StringHandle.FromOffset(0)).IsNil);
Assert.True(((Handle)BlobHandle.FromOffset(0)).IsNil);
Assert.True(((Handle)UserStringHandle.FromOffset(0)).IsNil);
Assert.True(((Handle)GuidHandle.FromIndex(0)).IsNil);
Assert.True(((BlobHandle)DocumentNameBlobHandle.FromOffset(0)).IsNil);
// virtual:
Assert.False(AssemblyReferenceHandle.FromVirtualIndex(0).IsNil);
Assert.False(StringHandle.FromVirtualIndex(0).IsNil);
Assert.False(BlobHandle.FromVirtualIndex(0, 0).IsNil);
Assert.False(((Handle)AssemblyReferenceHandle.FromVirtualIndex(0)).IsNil);
Assert.False(((Handle)StringHandle.FromVirtualIndex(0)).IsNil);
Assert.False(((Handle)BlobHandle.FromVirtualIndex(0, 0)).IsNil);
}
[Fact]
public void IsVirtual()
{
Assert.False(AssemblyReferenceHandle.FromRowId(1).IsVirtual);
Assert.False(StringHandle.FromOffset(1).IsVirtual);
Assert.False(BlobHandle.FromOffset(1).IsVirtual);
Assert.True(AssemblyReferenceHandle.FromVirtualIndex(0).IsVirtual);
Assert.True(StringHandle.FromVirtualIndex(0).IsVirtual);
Assert.True(BlobHandle.FromVirtualIndex(0, 0).IsVirtual);
}
[Fact]
public void StringKinds()
{
var str = StringHandle.FromOffset(123);
Assert.Equal(StringKind.Plain, str.StringKind);
Assert.False(str.IsVirtual);
Assert.Equal(123, str.GetHeapOffset());
var vstr = StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.AttributeTargets);
Assert.Equal(StringKind.Virtual, vstr.StringKind);
Assert.True(vstr.IsVirtual);
Assert.Equal(StringHandle.VirtualIndex.AttributeTargets, vstr.GetVirtualIndex());
var dot = StringHandle.FromOffset(123).WithDotTermination();
Assert.Equal(StringKind.DotTerminated, dot.StringKind);
Assert.False(dot.IsVirtual);
Assert.Equal(123, dot.GetHeapOffset());
var winrtPrefix = StringHandle.FromOffset(123).WithWinRTPrefix();
Assert.Equal(StringKind.WinRTPrefixed, winrtPrefix.StringKind);
Assert.True(winrtPrefix.IsVirtual);
Assert.Equal(123, winrtPrefix.GetHeapOffset());
}
[Fact]
public void NamespaceKinds()
{
var full = NamespaceDefinitionHandle.FromFullNameOffset(123);
Assert.False(full.IsVirtual);
Assert.Equal(123, full.GetHeapOffset());
var virtual1 = NamespaceDefinitionHandle.FromVirtualIndex(123);
Assert.True(virtual1.IsVirtual);
var virtual2 = NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3));
Assert.True(virtual2.IsVirtual);
Assert.Throws<BadImageFormatException>(() => NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3) + 1));
}
[Fact]
public void HandleKindHidesSpecialStringAndNamespaces()
{
foreach (int virtualBit in new[] { 0, (int)HandleType.VirtualBit })
{
for (int i = 0; i <= sbyte.MaxValue; i++)
{
Handle handle = new Handle((byte)(virtualBit | i), 0);
Assert.True(handle.IsNil ^ handle.IsVirtual);
Assert.Equal(virtualBit != 0, handle.IsVirtual);
Assert.Equal(handle.EntityHandleType, (uint)i << TokenTypeIds.RowIdBitCount);
switch (i)
{
// String has two extra bits to represent its kind that are hidden from the handle type
case (int)HandleKind.String:
case (int)HandleKind.String + 1:
case (int)HandleKind.String + 2:
case (int)HandleKind.String + 3:
Assert.Equal(HandleKind.String, handle.Kind);
break;
// all other types surface token type directly.
default:
Assert.Equal((int)handle.Kind, i);
break;
}
}
}
}
[Fact]
public void MethodDefToDebugInfo()
{
Assert.Equal(
MethodDefinitionHandle.FromRowId(123).ToDebugInformationHandle(),
MethodDebugInformationHandle.FromRowId(123));
Assert.Equal(
MethodDebugInformationHandle.FromRowId(123).ToDefinitionHandle(),
MethodDefinitionHandle.FromRowId(123));
}
}
}
| |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
namespace Skewworks.NETMF.Controls
{
/// <summary>
/// Default top-level container for controls
/// </summary>
/// <remarks>
/// This is the container that should be used by default to represent a Screen/Window/Form.
/// </remarks>
/// <example>
/// Form frm = new Form("frm");
/// frm.AddChild(new Label("lbl1", "This is a label", Fonts.Droid11, 4, 4));
/// Core.ActiveContainer = frm;
/// </example>
[Serializable]
public class Form : Container
{
#region Variables
// Background
private Color _bkg;
private Bitmap _img;
private ScaleMode _scale;
// Auto Scroll
private bool _autoScroll;
private int _maxX;
private int _maxY;
#pragma warning disable 649
private int _minX;
private int _minY;
#pragma warning restore 649
private bool _moving;
// Size
private readonly int _w;
private readonly int _h;
#endregion
#region Constructors
/// <summary>
/// Creates a new Form
/// </summary>
/// <param name="name">Name of the Form</param>
public Form(string name)
{
Name = name;
_bkg = Core.SystemColors.ContainerBackground;
_w = Core.ScreenWidth;
_h = Core.ScreenHeight;
}
/// <summary>
/// Creates a new Form
/// </summary>
/// <param name="name">Name of the Form</param>
/// <param name="backColor">Background color</param>
public Form(string name, Color backColor)
{
Name = name;
_bkg = backColor;
_w = Core.ScreenWidth;
_h = Core.ScreenHeight;
}
#endregion
#region Properties
/// <summary>
/// Form will automatically display scrollbars as needed when true
/// </summary>
public bool AutoScroll
{
get { return _autoScroll; }
set
{
if (_autoScroll == value)
return;
_autoScroll = value;
//if (value)
// CheckAutoScroll();
Render(true);
}
}
/// <summary>
/// Gets/Sets background color
/// </summary>
public Color BackColor
{
get { return _bkg; }
set
{
if (value == _bkg)
return;
_bkg = value;
Render(true);
}
}
/// <summary>
/// Gets/Sets background image
/// </summary>
public Bitmap BackgroundImage
{
get { return _img; }
set
{
if (_img == value)
return;
_img = value;
Render(true);
}
}
/// <summary>
/// Gets/Sets scale mode for background image
/// </summary>
public ScaleMode BackgroundImageScaleMode
{
get { return _scale; }
set
{
if (_scale == value)
return;
_scale = value;
if (_img != null)
Render(true);
}
}
/// <summary>
/// Forms do not have parents, attempting to set one will throw an exception
/// </summary>
public override IContainer Parent
{
get { return null; }
set { throw new InvalidOperationException("Forms cannot have parents"); }
}
/// <summary>
/// Height cannot be set on a Form; attempting to do so will throw an exception
/// </summary>
public override int Height
{
get { return _h; }
set { throw new InvalidOperationException("Forms must always be the size of the screen"); }
}
public override IContainer TopLevelContainer
{
get { return this; }
}
/// <summary>
/// Forms are not allowed to be invisible; attempting to change setting will throw exception
/// </summary>
public override bool Visible
{
get { return true; }
set { throw new InvalidOperationException("Forms must always be visible"); }
}
/// <summary>
/// Width cannot be set on a Form; attempting to do so will throw an exception
/// </summary>
public override int Width
{
get { return _w; }
set { throw new InvalidOperationException("Forms must always be the size of the screen"); }
}
/// <summary>
/// X must always be 0; attempting to change setting will throw exception
/// </summary>
public override int X
{
get { return 0; }
set { throw new InvalidOperationException("Forms must always have X of 0"); }
}
/// <summary>
/// Y must always be 0; attempting to change setting will throw exception
/// </summary>
public override int Y
{
get { return 0; }
set { throw new InvalidOperationException("Forms must always have Y of 0"); }
}
#endregion
#region Button Methods
/// <summary>
/// Override this message to handle button pressed events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under <see cref="Core.MousePosition"/>
/// </remarks>
protected override void ButtonPressedMessage(int buttonId, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (Children != null)
{
if (ActiveChild != null)
{
ActiveChild.SendButtonEvent(buttonId, true);
}
else
{
for (var i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, true);
break;
}
}
}
}
base.ButtonPressedMessage(buttonId, ref handled);
}
/// <summary>
/// Override this message to handle button released events internally.
/// </summary>
/// <param name="buttonId">Integer ID corresponding to the affected button</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under <see cref="Core.MousePosition"/>
/// </remarks>
protected override void ButtonReleasedMessage(int buttonId, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (Children != null)
{
if (ActiveChild != null)
{
ActiveChild.SendButtonEvent(buttonId, false);
}
else
{
for (var i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, false);
break;
}
}
}
}
base.ButtonReleasedMessage(buttonId, ref handled);
}
#endregion
#region Keyboard Methods
/// <summary>
/// Override this message to handle alt key events internally.
/// </summary>
/// <param name="key">Integer value of the Alt key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void KeyboardAltKeyMessage(int key, bool pressed, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
ActiveChild.SendKeyboardAltKeyEvent(key, pressed);
}
base.KeyboardAltKeyMessage(key, pressed, ref handled);
}
/// <summary>
/// Override this message to handle key events internally.
/// </summary>
/// <param name="key">Integer value of the key affected</param>
/// <param name="pressed">True if the key is currently being pressed; false if released</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void KeyboardKeyMessage(char key, bool pressed, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
ActiveChild.SendKeyboardKeyEvent(key, pressed);
}
base.KeyboardKeyMessage(key, pressed, ref handled);
}
#endregion
#region Touch Methods
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to the top most child under the point.
/// The hit child is made the active child.
/// </remarks>
protected override void TouchDownMessage(object sender, point point, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
// Check Controls
if (Children != null)
{
lock (Children)
{
for (var i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Visible && Children[i].HitTest(point))
{
ActiveChild = Children[i];
Children[i].SendTouchDown(this, point);
handled = true;
return;
}
}
}
}
if (ActiveChild != null)
{
ActiveChild.Blur();
Render(ActiveChild.ScreenBounds, true);
ActiveChild = null;
}
//TODO: check if _touch shouldn't be set to true here
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="type">Type of touch gesture</param>
/// <param name="force">Force associated with gesture (0.0 to 1.0)</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Forwards the message to <see cref="Container.ActiveChild"/>
/// </remarks>
protected override void TouchGestureMessage(object sender, TouchType type, float force, ref bool handled)
{
//TODO: check if this code shouldn't go to Container
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendTouchGesture(sender, type, force);
}
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Moves the form if touch down was on the form.
/// If no then forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under point
/// </remarks>
protected override void TouchMoveMessage(object sender, point point, ref bool handled)
{
if (Touching)
{
var bUpdated = false;
var diffY = 0;
var diffX = 0;
// Scroll Y
if (_maxY > _h)
{
diffY = point.Y - LastTouch.Y;
if (diffY > 0 && _minY < Top)
{
diffY = System.Math.Min(diffY, _minY + Top);
bUpdated = true;
}
else if (diffY < 0 && _maxY > _h)
{
diffY = System.Math.Min(-diffY, _maxY - _minY - _h);
bUpdated = true;
}
else
{
diffY = 0;
}
_moving = true;
//handled = true; //TODO: check why not handled
}
// Scroll X
if (_maxX > _w)
{
diffX = point.X - LastTouch.X;
if (diffX > 0 && _minX < Left)
{
diffX = System.Math.Min(diffX, _minX + Left);
bUpdated = true;
}
else if (diffX < 0 && _maxX > _w)
{
diffX = System.Math.Min(-diffX, _maxX - _minX - _w);
bUpdated = true;
}
else
{
diffX = 0;
}
_moving = true;
handled = true;
}
LastTouch = point;
if (bUpdated)
{
var ptOff = new point(diffX, diffY);
for (var i = 0; i < Children.Length; i++)
{
Children[i].UpdateOffsets(ptOff);
}
Render(true);
handled = true;
}
else if (_moving)
{
Render(true);
}
}
else
{
//TODO: check if this code shouldn't go to Container (or may be even the whole method?)
// Check Controls
if (ActiveChild != null && ActiveChild.Touching)
{
ActiveChild.SendTouchMove(this, point);
handled = true;
return;
}
if (Children != null)
{
for (var i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Touching || Children[i].HitTest(point))
{
Children[i].SendTouchMove(this, point);
}
}
}
}
}
/// <summary>
/// Override this message to handle touch events internally.
/// </summary>
/// <param name="sender">Object sending the event</param>
/// <param name="point">Point on screen touch event is occurring</param>
/// <param name="handled">true if the event is handled. Set to true if handled.</param>
/// <remarks>
/// Finishes the from moving if touch down was on the form.
/// If not then it forwards the message to <see cref="Container.ActiveChild"/> or if null, to the child under point
/// </remarks>
protected override void TouchUpMessage(object sender, point point, ref bool handled)
{
if (_moving)
{
_moving = false;
Render(true);
return;
}
//TODO: check if this code shouldn't go to Container
// Check Controls
if (Children != null)
{
for (var i = Children.Length - 1; i >= 0; i--)
{
try
{
if (Children[i].HitTest(point) && !handled)
{
handled = true;
Children[i].SendTouchUp(this, point);
}
else if (Children[i].Touching)
{
Children[i].SendTouchUp(this, point);
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch // This can happen if the user clears the Form during a tap
{ }
}
}
}
#endregion
#region GUI
/// <summary>
/// Renders the control contents
/// </summary>
/// <param name="x">X position in screen coordinates</param>
/// <param name="y">Y position in screen coordinates</param>
/// <param name="width">Width in pixel</param>
/// <param name="height">Height in pixel</param>
/// <remarks>
/// Renders the form and all its childes.
/// </remarks>
protected override void OnRender(int x, int y, int width, int height)
{
var area = new rect(x, y, width, height);
DrawBackground();
_maxX = _w;
_maxY = _h;
//TODO: check if this code shouldn't go to Container
// Render controls
if (Children != null)
{
for (var i = 0; i < Children.Length; i++)
{
if (Children[i] != null)
{
if (Children[i].ScreenBounds.Intersects(area))
{
Children[i].Render();
}
//if (Children[i].Y < _minY)
// _minY = Children[i].Y;
//else if (Children[i].Y + Children[i].Height > _maxY)
// _maxY = Children[i].Y + Children[i].Height;
//if (Children[i].X < _minX)
// _minX = Children[i].X;
//else if (Children[i].X + Children[i].Width > _maxX)
// _maxX = Children[i].X + Children[i].Width;
}
}
}
}
#endregion
#region Private Methods
private void DrawBackground()
{
Core.Screen.DrawRectangle(_bkg, 0, 0, 0, _w, _h, 0, 0, _bkg, 0, 0, _bkg, 0, 0, 256);
if (_img != null)
{
switch (_scale)
{
case ScaleMode.Center:
Core.Screen.DrawImage(Core.ScreenWidth / 2 - _img.Width / 2, Core.ScreenHeight / 2 - _img.Height / 2, _img, 0, 0, _img.Width, _img.Height);
break;
case ScaleMode.Normal:
Core.Screen.DrawImage(0, 0, _img, 0, 0, _img.Width, _img.Height);
break;
case ScaleMode.Scale:
float multiplier;
if (_img.Height > _img.Width)
{
// Portrait
if (_h > _w)
{
multiplier = _w/(float) _img.Width;
}
else
{
multiplier = _h / (float)_img.Height;
}
}
else
{
// Landscape
if (_h > _w)
{
multiplier = _w/(float) _img.Width;
}
else
{
multiplier = _h / (float)_img.Height;
}
}
var dsW = (int)(_img.Width * multiplier);
var dsH = (int)(_img.Height * multiplier);
var dX = (int)(_w / 2.0f - dsW / 2.0f);
var dY = (int)(_h / 2.0f - dsH / 2.0f);
Core.Screen.StretchImage(dX, dY, _img, dsW, dsH, 256);
break;
case ScaleMode.Stretch:
Core.Screen.StretchImage(0, 0, _img, Core.ScreenWidth, Core.ScreenHeight, 256);
break;
case ScaleMode.Tile:
Core.Screen.TileImage(0, 0, _img, Core.ScreenWidth, Core.ScreenHeight, 256);
break;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Shouldly;
using Wyam.Common.Documents;
using Wyam.Common.Execution;
using Wyam.Common.Meta;
using Wyam.Common.Shortcodes;
using Wyam.Core.Modules.Contents;
using Wyam.Testing;
using Wyam.Testing.Documents;
using Wyam.Testing.Execution;
namespace Wyam.Core.Tests.Modules.Contents
{
[TestFixture]
[NonParallelizable]
public class ShortcodesFixture : BaseFixture
{
public class ExecuteTests : ShortcodesFixture
{
[Test]
public void ProcessesShortcode()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<TestShortcode>("Bar");
IDocument document = new TestDocument("123<?# Bar /?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123Foo456");
}
[Test]
public void ProcessesNestedShortcodeInResult()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<TestShortcode>("Nested");
context.Shortcodes.Add<NestedShortcode>("Bar");
IDocument document = new TestDocument("123<?# Bar /?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123ABCFooXYZ456");
}
[Test]
public void ProcessesNestedShortcode()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<RawShortcode>("Foo");
context.Shortcodes.Add<TestShortcode>("Bar");
IDocument document = new TestDocument("123<?# Foo ?>ABC<?# Bar /?>XYZ<?#/ Foo ?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123ABCFooXYZ456");
}
[Test]
public void DoesNotProcessNestedRawShortcode()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<RawShortcode>("Raw");
context.Shortcodes.Add<TestShortcode>("Bar");
IDocument document = new TestDocument("123<?# Raw ?>ABC<?# Bar /?>XYZ<?#/ Raw ?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123ABC<?# Bar /?>XYZ456");
}
[Test]
public void DoesNotProcessDirectlyNestedRawShortcode()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<RawShortcode>("Raw");
context.Shortcodes.Add<TestShortcode>("Bar");
IDocument document = new TestDocument("123<?# Raw ?><?# Bar /?><?#/ Raw ?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123<?# Bar /?>456");
}
[Test]
public void ShortcodeSupportsNullStreamResult()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<NullStreamShortcode>("Bar");
IDocument document = new TestDocument("123<?# Bar /?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123456");
}
[Test]
public void ShortcodeSupportsNullResult()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<TestShortcode>("S1");
context.Shortcodes.Add<NullResultShortcode>("S2");
IDocument document = new TestDocument("123<?# S1 /?>456<?# S2 /?>789<?# S1 /?>");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123Foo456789Foo");
}
[Test]
public void DisposesShortcode()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<DisposableShortcode>("Bar");
IDocument document = new TestDocument("123<?# Bar /?>456");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
DisposableShortcode.Disposed.ShouldBeTrue();
}
[Test]
public void ShortcodesCanAddMetadata()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<AddsMetadataShortcode>("S1");
context.Shortcodes.Add<AddsMetadataShortcode2>("S2");
IDocument document = new TestDocument("123<?# S1 /?>456<?# S2 /?>789");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123456789");
results.Single()["A"].ShouldBe("3");
results.Single()["B"].ShouldBe("2");
results.Single()["C"].ShouldBe("4");
}
[Test]
public void ShortcodesCanReadMetadata()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<ReadsMetadataShortcode>("S1");
context.Shortcodes.Add<ReadsMetadataShortcode>("S2");
IDocument document = new TestDocument("123<?# S1 /?>456<?# S2 /?>789<?# S1 /?>", new MetadataItems
{
{ "Foo", 10 }
});
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123456789");
results.Single()["Foo"].ShouldBe(13);
}
[Test]
public void ShortcodesPersistState()
{
// Given
TestExecutionContext context = new TestExecutionContext();
context.Shortcodes.Add<IncrementingShortcode>("S");
IDocument document = new TestDocument("123<?# S /?>456<?# S /?>789<?# S /?>");
Core.Modules.Contents.Shortcodes module = new Core.Modules.Contents.Shortcodes();
// When
List<IDocument> results = module.Execute(new[] { document }, context).ToList();
// Then
results.Single().Content.ShouldBe("123456789");
results.Single()["Foo"].ShouldBe(22);
}
}
public class TestShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult(context.GetContentStream("Foo"));
}
public class NestedShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult(context.GetContentStream("ABC<?# Nested /?>XYZ"));
}
public class RawShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult(context.GetContentStream(content));
}
public class NullStreamShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult((Stream)null);
}
public class NullResultShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) => null;
}
public class DisposableShortcode : IShortcode, IDisposable
{
public static bool Disposed { get; set; }
public DisposableShortcode()
{
// Make sure it resets
Disposed = false;
}
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult(context.GetContentStream("Foo"));
public void Dispose() =>
Disposed = true;
}
public class AddsMetadataShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult((Stream)null, new MetadataItems
{
{ "A", "1" },
{ "B", "2" }
});
}
public class AddsMetadataShortcode2 : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult((Stream)null, new MetadataItems
{
{ "A", "3" },
{ "C", "4" }
});
}
public class ReadsMetadataShortcode : IShortcode
{
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult((Stream)null, new MetadataItems
{
{ $"Foo", document.Get<int>("Foo") + 1 }
});
}
public class IncrementingShortcode : IShortcode
{
private int _value = 20;
public IShortcodeResult Execute(KeyValuePair<string, string>[] args, string content, IDocument document, IExecutionContext context) =>
context.GetShortcodeResult((Stream)null, new MetadataItems
{
{ $"Foo", _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.
using System.Collections.Generic;
using System.Net.Sockets;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static class IPAddressTest
{
private const long MinAddress = 0;
private const long MaxAddress = 0xFFFFFFFF;
private const long MinScopeId = 0;
private const long MaxScopeId = 0xFFFFFFFF;
private static byte[] ipV6AddressBytes1 = new byte[] { 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
private static byte[] ipV6AddressBytes2 = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
private static IPAddress IPV4Address()
{
return IPAddress.Parse("192.168.0.9");
}
private static IPAddress IPV6Address1()
{
return new IPAddress(ipV6AddressBytes1);
}
private static IPAddress IPV6Address2()
{
return new IPAddress(ipV6AddressBytes2);
}
[Theory]
[InlineData(MinAddress, new byte[] { 0, 0, 0, 0 })]
[InlineData(MaxAddress, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF })]
[InlineData(0x2414188f, new byte[] { 0x8f, 0x18, 0x14, 0x24 })]
[InlineData(0xFF, new byte[] { 0xFF, 0, 0, 0 })]
[InlineData(0xFF00FF, new byte[] { 0xFF, 0, 0xFF, 0 })]
[InlineData(0xFF00FF00, new byte[] { 0, 0xFF, 0, 0xFF })]
public static void Ctor_Long_Success(long address, byte[] expectedBytes)
{
IPAddress ip = new IPAddress(address);
Assert.Equal(expectedBytes, ip.GetAddressBytes());
Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily);
}
[Theory]
[InlineData(MinAddress - 1)]
[InlineData(MaxAddress + 1)]
public static void Ctor_Long_Invalid(long address)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("newAddress", () => new IPAddress(address));
}
[Theory]
[MemberData(nameof(AddressBytesAndFamilies))]
public static void Ctor_Bytes_Success(byte[] address, AddressFamily expectedFamily)
{
IPAddress ip = new IPAddress(address);
Assert.Equal(address, ip.GetAddressBytes());
Assert.Equal(expectedFamily, ip.AddressFamily);
}
public static object[][] AddressBytesAndFamilies =
{
new object[] { new byte[] { 0x8f, 0x18, 0x14, 0x24 }, AddressFamily.InterNetwork },
new object[] { ipV6AddressBytes1, AddressFamily.InterNetworkV6 },
new object[] { ipV6AddressBytes2, AddressFamily.InterNetworkV6 }
};
[Fact]
public static void Ctor_Bytes_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("address", () => new IPAddress(null));
AssertExtensions.Throws<ArgumentException>("address", () => new IPAddress(new byte[] { 0x01, 0x01, 0x02 }));
}
[Theory]
[MemberData(nameof(IPv6AddressBytesAndScopeIds))]
public static void Ctor_BytesScopeId_Success(byte[] address, long scopeId)
{
IPAddress ip = new IPAddress(address, scopeId);
Assert.Equal(address, ip.GetAddressBytes());
Assert.Equal(scopeId, ip.ScopeId);
Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
}
public static IEnumerable<object[]> IPv6AddressBytesAndScopeIds
{
get
{
foreach (long scopeId in new long[] { MinScopeId, MaxScopeId, 500 })
{
yield return new object[] { ipV6AddressBytes1, scopeId };
yield return new object[] { ipV6AddressBytes2, scopeId };
}
}
}
[Fact]
public static void Ctor_BytesScopeId_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("address", () => new IPAddress(null, 500));
AssertExtensions.Throws<ArgumentException>("address", () => new IPAddress(new byte[] { 0x01, 0x01, 0x02 }, 500));
AssertExtensions.Throws<ArgumentOutOfRangeException>("scopeid", () => new IPAddress(ipV6AddressBytes1, MinScopeId - 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("scopeid", () => new IPAddress(ipV6AddressBytes1, MaxScopeId + 1));
}
[Fact]
public static void ScopeId_GetSet_Success()
{
IPAddress ip = IPV6Address1();
Assert.Equal(0, ip.ScopeId);
ip.ScopeId = 700;
Assert.Equal(ip.ScopeId, 700);
ip.ScopeId = 700;
}
[Fact]
public static void ScopeId_Set_Invalid()
{
IPAddress ip = IPV4Address(); //IpV4
Assert.ThrowsAny<Exception>(() => ip.ScopeId = 500);
Assert.ThrowsAny<Exception>(() => ip.ScopeId);
ip = IPV6Address1(); //IpV6
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ip.ScopeId = MinScopeId - 1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ip.ScopeId = MaxScopeId + 1);
}
[Fact]
public static void HostToNetworkOrder_Compare_Equal()
{
long l1 = (long)0x1350;
long l2 = (long)0x5013000000000000;
int i1 = (int)0x1350;
int i2 = (int)0x50130000;
short s1 = (short)0x1350;
short s2 = (short)0x5013;
Assert.Equal(l2, IPAddress.HostToNetworkOrder(l1));
Assert.Equal(i2, IPAddress.HostToNetworkOrder(i1));
Assert.Equal(s2, IPAddress.HostToNetworkOrder(s1));
Assert.Equal(l1, IPAddress.NetworkToHostOrder(l2));
Assert.Equal(i1, IPAddress.NetworkToHostOrder(i2));
Assert.Equal(s1, IPAddress.NetworkToHostOrder(s2));
}
[Fact]
public static void IsLoopback_Get_Success()
{
IPAddress ip = IPV4Address(); //IpV4
Assert.False(IPAddress.IsLoopback(ip));
ip = new IPAddress(IPAddress.Loopback.GetAddressBytes()); //IpV4 loopback
Assert.True(IPAddress.IsLoopback(ip));
ip = IPV6Address1(); //IpV6
Assert.False(IPAddress.IsLoopback(ip));
ip = new IPAddress(IPAddress.IPv6Loopback.GetAddressBytes()); //IpV6 loopback
Assert.True(IPAddress.IsLoopback(ip));
}
[Fact]
public static void IsLooback_Get_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("address", () => IPAddress.IsLoopback(null));
}
[Fact]
public static void IsIPV6Multicast_Get_Success()
{
Assert.True(IPAddress.Parse("ff02::1").IsIPv6Multicast);
Assert.False(IPAddress.Parse("Fe08::1").IsIPv6Multicast);
Assert.False(IPV4Address().IsIPv6Multicast);
}
[Fact]
public static void IsIPV6LinkLocal_Get_Success()
{
Assert.True(IPAddress.Parse("fe80::1").IsIPv6LinkLocal);
Assert.False(IPAddress.Parse("Fe08::1").IsIPv6LinkLocal);
Assert.False(IPV4Address().IsIPv6LinkLocal);
}
[Fact]
public static void IsIPV6SiteLocal_Get_Success()
{
Assert.True(IPAddress.Parse("FEC0::1").IsIPv6SiteLocal);
Assert.False(IPAddress.Parse("Fe08::1").IsIPv6SiteLocal);
Assert.False(IPV4Address().IsIPv6SiteLocal);
}
[Fact]
public static void IsIPV6Teredo_Get_Success()
{
Assert.True(IPAddress.Parse("2001::1").IsIPv6Teredo);
Assert.False(IPAddress.Parse("Fe08::1").IsIPv6Teredo);
Assert.False(IPV4Address().IsIPv6Teredo);
}
[Fact]
public static void Equals_Compare_Success()
{
IPAddress ip1 = IPAddress.Parse("192.168.0.9"); //IpV4
IPAddress ip2 = IPAddress.Parse("192.168.0.9"); //IpV4
IPAddress ip3 = IPAddress.Parse("169.192.1.10"); //IpV4
IPAddress ip4 = new IPAddress(ipV6AddressBytes1); //IpV6
IPAddress ip5 = new IPAddress(ipV6AddressBytes1); //IpV6
IPAddress ip6 = new IPAddress(ipV6AddressBytes2); //IpV6
Assert.True(ip1.Equals(ip2));
Assert.True(ip2.Equals(ip1));
Assert.True(ip1.GetHashCode().Equals(ip2.GetHashCode()));
Assert.False(ip1.GetHashCode().Equals(ip3.GetHashCode()));
Assert.False(ip1.Equals(ip3));
Assert.False(ip1.Equals(ip4)); //IpV4 /= IpV6
Assert.False(ip1.Equals(null));
Assert.False(ip1.Equals(""));
Assert.True(ip4.Equals(ip5));
Assert.False(ip4.Equals(ip6));
Assert.True(ip4.GetHashCode().Equals(ip5.GetHashCode()));
Assert.False(ip4.GetHashCode().Equals(ip6.GetHashCode()));
}
#pragma warning disable 618
[Fact]
public static void Address_Property_Failure()
{
IPAddress ip1 = IPAddress.Parse("fe80::200:f8ff:fe21:67cf");
Assert.Throws<SocketException>(() => ip1.Address);
}
[Fact]
public static void Address_Property_Success()
{
IPAddress ip1 = IPAddress.Parse("192.168.0.9");
//192.168.0.10
long newIp4Address = 192 << 24 | 168 << 16 | 0 << 8 | 10;
ip1.Address = newIp4Address;
Assert.Equal("10.0.168.192" , ip1.ToString());
}
#pragma warning restore 618
}
}
| |
/*
* Copyright 2012 ZXing authors
*
* 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.Text;
namespace ZXing.PDF417.Internal.EC
{
/// <summary>
/// <see cref="ZXing.Common.ReedSolomon.GenericGFPoly"/>
/// </summary>
/// <author>Sean Owen</author>
internal sealed class ModulusPoly
{
private readonly ModulusGF field;
private readonly int[] coefficients;
public ModulusPoly(ModulusGF field, int[] coefficients)
{
if (coefficients.Length == 0)
{
throw new ArgumentException();
}
this.field = field;
int coefficientsLength = coefficients.Length;
if (coefficientsLength > 1 && coefficients[0] == 0)
{
// Leading term must be non-zero for anything except the constant polynomial "0"
int firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0)
{
firstNonZero++;
}
if (firstNonZero == coefficientsLength)
{
this.coefficients = new int[]{0};
}
else
{
this.coefficients = new int[coefficientsLength - firstNonZero];
Array.Copy(coefficients,
firstNonZero,
this.coefficients,
0,
this.coefficients.Length);
}
}
else
{
this.coefficients = coefficients;
}
}
/// <summary>
/// Gets the coefficients.
/// </summary>
/// <value>The coefficients.</value>
internal int[] Coefficients
{
get { return coefficients; }
}
/// <summary>
/// degree of this polynomial
/// </summary>
internal int Degree
{
get
{
return coefficients.Length - 1;
}
}
/// <summary>
/// Gets a value indicating whether this instance is zero.
/// </summary>
/// <value>true if this polynomial is the monomial "0"
/// </value>
internal bool isZero
{
get { return coefficients[0] == 0; }
}
/// <summary>
/// coefficient of x^degree term in this polynomial
/// </summary>
/// <param name="degree">The degree.</param>
/// <returns>coefficient of x^degree term in this polynomial</returns>
internal int getCoefficient(int degree)
{
return coefficients[coefficients.Length - 1 - degree];
}
/// <summary>
/// evaluation of this polynomial at a given point
/// </summary>
/// <param name="a">A.</param>
/// <returns>evaluation of this polynomial at a given point</returns>
internal int evaluateAt(int a)
{
if (a == 0)
{
// Just return the x^0 coefficient
return getCoefficient(0);
}
int result = 0;
if (a == 1)
{
// Just the sum of the coefficients
foreach (var coefficient in coefficients)
{
result = field.add(result, coefficient);
}
return result;
}
result = coefficients[0];
int size = coefficients.Length;
for (int i = 1; i < size; i++)
{
result = field.add(field.multiply(a, result), coefficients[i]);
}
return result;
}
/// <summary>
/// Adds another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly add(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero)
{
return other;
}
if (other.isZero)
{
return this;
}
int[] smallerCoefficients = this.coefficients;
int[] largerCoefficients = other.coefficients;
if (smallerCoefficients.Length > largerCoefficients.Length)
{
int[] temp = smallerCoefficients;
smallerCoefficients = largerCoefficients;
largerCoefficients = temp;
}
int[] sumDiff = new int[largerCoefficients.Length];
int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length;
// Copy high-order terms only found in higher-degree polynomial's coefficients
Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
for (int i = lengthDiff; i < largerCoefficients.Length; i++)
{
sumDiff[i] = field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new ModulusPoly(field, sumDiff);
}
/// <summary>
/// Subtract another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly subtract(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
return this;
}
return add(other.getNegative());
}
/// <summary>
/// Multiply by another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly multiply(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero || other.isZero)
{
return field.Zero;
}
int[] aCoefficients = this.coefficients;
int aLength = aCoefficients.Length;
int[] bCoefficients = other.coefficients;
int bLength = bCoefficients.Length;
int[] product = new int[aLength + bLength - 1];
for (int i = 0; i < aLength; i++)
{
int aCoeff = aCoefficients[i];
for (int j = 0; j < bLength; j++)
{
product[i + j] = field.add(product[i + j], field.multiply(aCoeff, bCoefficients[j]));
}
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Returns a Negative version of this instance
/// </summary>
internal ModulusPoly getNegative()
{
int size = coefficients.Length;
int[] negativeCoefficients = new int[size];
for (int i = 0; i < size; i++)
{
negativeCoefficients[i] = field.subtract(0, coefficients[i]);
}
return new ModulusPoly(field, negativeCoefficients);
}
/// <summary>
/// Multiply by a Scalar.
/// </summary>
/// <param name="scalar">Scalar.</param>
internal ModulusPoly multiply(int scalar)
{
if (scalar == 0)
{
return field.Zero;
}
if (scalar == 1)
{
return this;
}
int size = coefficients.Length;
int[] product = new int[size];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], scalar);
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Multiplies by a Monomial
/// </summary>
/// <returns>The by monomial.</returns>
/// <param name="degree">Degree.</param>
/// <param name="coefficient">Coefficient.</param>
internal ModulusPoly multiplyByMonomial(int degree, int coefficient)
{
if (degree < 0)
{
throw new ArgumentException();
}
if (coefficient == 0)
{
return field.Zero;
}
int size = coefficients.Length;
int[] product = new int[size + degree];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], coefficient);
}
return new ModulusPoly(field, product);
}
/*
/// <summary>
/// Divide by another modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly[] divide(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
throw new DivideByZeroException();
}
ModulusPoly quotient = field.Zero;
ModulusPoly remainder = this;
int denominatorLeadingTerm = other.getCoefficient(other.Degree);
int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm);
while (remainder.Degree >= other.Degree && !remainder.isZero)
{
int degreeDifference = remainder.Degree - other.Degree;
int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm);
ModulusPoly term = other.multiplyByMonomial(degreeDifference, scale);
ModulusPoly iterationQuotient = field.buildMonomial(degreeDifference, scale);
quotient = quotient.add(iterationQuotient);
remainder = remainder.subtract(term);
}
return new ModulusPoly[] { quotient, remainder };
}
*/
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.</returns>
public override String ToString()
{
var result = new StringBuilder(8 * Degree);
for (int degree = Degree; degree >= 0; degree--)
{
int coefficient = getCoefficient(degree);
if (coefficient != 0)
{
if (coefficient < 0)
{
result.Append(" - ");
coefficient = -coefficient;
}
else
{
if (result.Length > 0)
{
result.Append(" + ");
}
}
if (degree == 0 || coefficient != 1)
{
result.Append(coefficient);
}
if (degree != 0)
{
if (degree == 1)
{
result.Append('x');
}
else
{
result.Append("x^");
result.Append(degree);
}
}
}
}
return result.ToString();
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here
* xxxx-xx-xx, author, fix bug about xxx
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using rDSN.Tron.Contract;
using rDSN.Tron.LanguageProvider;
using rDSN.Tron.Utility;
namespace rDSN.Tron.Compiler
{
//
// build compilable query
// all external values must be converted into constant
// all external functions and types must be referenced with full namespace
//
//
public class CodeGenerator
{
private CodeBuilder _builder = new CodeBuilder();
private QueryContext[] _contexts;
private string _appClassName;
private Dictionary<Type, string> _rewrittenTypes = new Dictionary<Type, string>();
public ulong AppId { get; } = RandomGenerator.Random64();
public string BuildRdsn(Type service, QueryContext[] contexts)
{
//_stages = stages;
_contexts = contexts;
_appClassName = service.Name;
//BuildInputOutputValueTypes();
BuildHeaderRdsn(service.Namespace);
BuildRewrittenTypes();
_builder.AppendLine("public class " + _appClassName + "Server_impl :" + _appClassName + "Server");
_builder.BeginBlock();
BuildServiceClientsRdsn();
//thrift or protobuf
BuildServiceCallsRdsn(_appClassName);
foreach (var c in contexts)
//never change
BuildQueryRdsn(c);
//always thrift
BuildServer(_appClassName, ServiceContract.GetServiceCalls(service));
_builder.EndBlock();
BuildMain();
BuildFooter();
return _builder.ToString();
}
public void BuildMain()
{
_builder.AppendLine("class Program");
_builder.BeginBlock();
_builder.AppendLine("static void Main(string[] args)");
_builder.BeginBlock();
_builder.AppendLine(_appClassName + "Helper.InitCodes();");
foreach (var s in _contexts.SelectMany(c => c.Services).DistinctBy(s => s.Key.Member.Name))
{
_builder.AppendLine(s.Value.Spec.MainSpecFile.Split('.')[0] + "Helper.InitCodes();");
}
_builder.AppendLine("ServiceApp.RegisterApp<" + _appClassName + "ServerApp>(\"server\");");
_builder.AppendLine("ServiceApp.RegisterApp<" + _appClassName + "ClientApp>(\"client\");");
_builder.AppendLine("string[] args2 = (new string[] { \"" + _appClassName + "\" }).Union(args).ToArray();");
_builder.AppendLine("Native.dsn_run(args2.Length, args2, true);");
_builder.EndBlock();
_builder.EndBlock();
}
public string Build(string className, QueryContext[] contexts)
{
//_stages = stages;
_contexts = contexts;
_appClassName = className;
//BuildInputOutputValueTypes();
BuildRewrittenTypes();
BuildHeader();
_builder.AppendLine("public class " + _appClassName + " : ServiceMesh");
_builder.BeginBlock();
//BuildConstructor();
BuildServiceClients();
BuildServiceCalls();
foreach (var c in contexts)
BuildQuery(c);
_builder.EndBlock();
BuildFooter();
return _builder.ToString();
}
private void BuildConstructor()
{
_builder.AppendLine("public " + _appClassName + "()");
_builder.BeginBlock();
_builder.EndBlock();
_builder.AppendLine();
}
//private void BuildInputOutputValueTypes()
//{
// if (_primaryContext.OutputType.IsSymbols())
// {
// throw new Exception("we are not support ISymbolCollection<> output right now, you can use an Gather method to merge it into a single ISymbol<>");
// }
// Trace.Assert(_primaryContext.InputType.IsSymbol() && _primaryContext.InputType.IsGenericType);
// Trace.Assert(_primaryContext.OutputType.IsSymbol() && _primaryContext.OutputType.IsGenericType);
// _inputValueType = _primaryContext.InputType.GetGenericArguments()[0];
// _outputValueType = _primaryContext.OutputType.GetGenericArguments()[0];
//}
private void BuildServiceClientsRdsn()
{
foreach (var s in _contexts.SelectMany(c => c.Services).DistinctBy(s => s.Key.Member.Name))
{
_builder.AppendLine("private " + s.Value.TypeName() + "Client " + s.Key.Member.Name + " = new " + s.Value.TypeName() + "Client(new RpcAddress(\"" + s.Value.URL + "\"));");
_builder.AppendLine();
}
}
private void BuildServiceClients()
{
}
private void BuildServiceCallsRdsn(string serviceName)
{
var calls = new HashSet<string>();
foreach (var s in _contexts.SelectMany(c => c.ServiceCalls))
{
Trace.Assert(s.Key.Object != null && s.Key.Object.NodeType == ExpressionType.MemberAccess);
var callName = s.Key.Method.Name;
var respTypeName = s.Key.Type.GetCompilableTypeName(_rewrittenTypes);
var reqTypeName = s.Key.Arguments[0].Type.GetCompilableTypeName(_rewrittenTypes);
var call = "Call_" + s.Value.PlainTypeName() + "_" + callName;
if (!calls.Add(call + ":" + reqTypeName))
continue;
_builder.AppendLine("private " + respTypeName + " " + call + "( " + reqTypeName + " req)");
_builder.BeginBlock();
var provider = SpecProviderManager.Instance().GetProvider(s.Value.Spec.SType);
provider.GenerateClientCall(_builder, s.Key, s.Value, _rewrittenTypes);
_builder.EndBlock();
_builder.AppendLine();
}
}
private void BuildServiceCalls()
{
}
private void BuildQueryRdsn(QueryContext c)
{
_builder.AppendLine("public " + c.OutputType.GetGenericArguments()[0].FullName.GetCompilableTypeName()
+ " " + c.Name + "(" + c.InputType.GetCompilableTypeName(_rewrittenTypes) + " request)");
_builder.AppendLine("{");
_builder++;
_builder.AppendLine("Console.Write(\".\");");
// local vars
foreach (var s in c.TempSymbolsByAlias)
{
_builder.AppendLine(s.Value.Type.GetCompilableTypeName(_rewrittenTypes) + " " + s.Key + ";");
}
if (c.TempSymbolsByAlias.Count > 0)
_builder.AppendLine();
// final query
var codeBuilder = new ExpressionToCode(c.RootExpression, c);
var code = codeBuilder.GenCode(_builder.Indent);
_builder.AppendLine(code + ";");
_builder--;
_builder.AppendLine("}");
_builder.AppendLine();
}
private void BuildServer(string serviceName, IEnumerable<MethodInfo> methods)
{
foreach (var m in methods)
{
var respType = m.ReturnType.GetGenericArguments()[0].FullName.GetCompilableTypeName();
_builder.AppendLine("protected override void On" + m.Name + "(" + m.GetParameters()[0].ParameterType.GetGenericArguments()[0].FullName.GetCompilableTypeName() + " request, RpcReplier<" + respType + "> replier)");
_builder.BeginBlock();
_builder.AppendLine("replier.Reply(" + m.Name + "(new IValue<" + m.GetParameters()[0].ParameterType.GetGenericArguments()[0].FullName.GetCompilableTypeName() + ">(request)));");
_builder.EndBlock();
_builder.AppendLine();
}
}
private void BuildQuery(QueryContext c)
{
_builder.AppendLine("public " + c.OutputType.GetCompilableTypeName(_rewrittenTypes)
+ " " + c.Name + "(" + c.InputType.GetCompilableTypeName(_rewrittenTypes) + " request)");
_builder.AppendLine("{");
_builder++;
_builder.AppendLine("Console.Write(\".\");");
// local vars
foreach (var s in c.TempSymbolsByAlias)
{
_builder.AppendLine(s.Value.Type.GetCompilableTypeName(_rewrittenTypes) + " " + s.Key + ";");
}
if (c.TempSymbolsByAlias.Count > 0)
_builder.AppendLine();
// final query
var codeBuilder = new ExpressionToCode(c.RootExpression, c);
var code = codeBuilder.GenCode(_builder.Indent);
_builder.AppendLine(code + ";");
_builder--;
_builder.AppendLine("}");
_builder.AppendLine();
}
private string VerboseStringArray(string[] parameters)
{
var ps = parameters.Aggregate("", (current, s) => current + ("@\"" + s + "\","));
if (ps.Length > 0)
{
ps = ps.Substring(0, ps.Length - 1);
}
return ps;
}
private void BuildRewrittenTypes()
{
foreach (var t in _contexts.SelectMany(c => c.RewrittenTypes.Where(t => !_rewrittenTypes.ContainsKey(t.Key))))
{
_rewrittenTypes.Add(t.Key, t.Value);
}
foreach (var c in _contexts)
{
c.RewrittenTypes = _rewrittenTypes;
}
foreach (var typeMap in _rewrittenTypes)
{
_builder.AppendLine("class " + typeMap.Value);
_builder.AppendLine("{");
_builder++;
foreach (var property in typeMap.Key.GetProperties())
{
_builder.AppendLine("public " + property.PropertyType.GetCompilableTypeName(_rewrittenTypes) + " " + property.Name + " { get; set; }");
}
_builder.AppendLine("public " + typeMap.Value + " () {}");
_builder--;
_builder.AppendLine("}");
_builder.AppendLine();
}
}
private void BuildHeaderRdsn(string serviceNamespce)
{
_builder.AppendLine("/* AUTO GENERATED BY Tron AT " + DateTime.Now.ToLocalTime() + " */");
var namespaces = new HashSet<string>
{
"System",
"System.IO",
"dsn.dev.csharp",
serviceNamespce,
"System.Linq",
"System.Text",
"System.Linq.Expressions",
"System.Reflection",
"System.Diagnostics",
"System.Net",
"System.Threading",
"rDSN.Tron.Contract",
"rDSN.Tron.Runtime",
"rDSN.Tron.App"
};
//namespaces.Add("rDSN.Tron.Utility");
//namespaces.Add("rDSN.Tron.Compiler");
foreach (var nm in _contexts.SelectMany(c => c.Methods).Select(mi => mi.DeclaringType.Namespace).Distinct().Except(namespaces))
{
namespaces.Add(nm);
}
foreach (var np in namespaces)
{
_builder.AppendLine("using " + np + ";");
}
_builder.AppendLine();
_builder.AppendLine("namespace rDSN.Tron.App");
_builder.AppendLine("{");
_builder++;
}
private void BuildHeader()
{
_builder.AppendLine("/* AUTO GENERATED BY Tron AT " + DateTime.Now.ToLocalTime() + " */");
var namespaces = new HashSet<string>
{
"System",
"System.IO",
"System.Collections.Generic",
"System.Linq",
"System.Text",
"System.Linq.Expressions",
"System.Reflection",
"System.Diagnostics",
"System.Net",
"System.Threading",
"rDSN.Tron.Utility",
"rDSN.Tron.Contract",
"rDSN.Tron.Runtime"
};
//namespaces.Add("rDSN.Tron.Compiler");
foreach (var nm in _contexts.SelectMany(c => c.Methods).Select(mi => mi.DeclaringType.Namespace).Distinct().Except(namespaces))
{
namespaces.Add(nm);
}
foreach (var np in namespaces)
{
_builder.AppendLine("using " + np + ";");
}
_builder.AppendLine();
_builder.AppendLine("namespace rDSN.Tron.App");
_builder.AppendLine("{");
_builder++;
}
private void BuildFooter()
{
_builder--;
_builder.AppendLine("} // end namespace");
_builder.AppendLine();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.OpenXml4Net.OPC.Compliance
{
using System;
using NPOI.OpenXml4Net.OPC;
using NPOI.OpenXml4Net.Exceptions;
using NUnit.Framework;
using System.IO;
using NPOI.Util;
/**
* Test core properties Open Packaging Convention compliance.
*
* M4.1: The format designer shall specify and the format producer shall create
* at most one core properties relationship for a package. A format consumer
* shall consider more than one core properties relationship for a package to be
* an error. If present, the relationship shall target the Core Properties part.
* (POI relaxes this on reading, as Office sometimes breaks this)
*
* M4.2: The format designer shall not specify and the format producer shall not
* create Core Properties that use the Markup Compatibility namespace as defined
* in Annex F, "Standard Namespaces and Content Types". A format consumer shall
* consider the use of the Markup Compatibility namespace to be an error.
*
* M4.3: Producers shall not create a document element that contains refinements
* to the Dublin Core elements, except for the two specified in the schema:
* <dcterms:created> and <dcterms:modified> Consumers shall consider a document
* element that violates this constraint to be an error.
*
* M4.4: Producers shall not create a document element that contains the
* xml:lang attribute. Consumers shall consider a document element that violates
* this constraint to be an error.
*
* M4.5: Producers shall not create a document element that contains the
* xsi:type attribute, except for a <dcterms:created> or <dcterms:modified>
* element where the xsi:type attribute shall be present and shall hold the
* value dcterms:W3CDTF, where dcterms is the namespace prefix of the Dublin
* Core namespace. Consumers shall consider a document element that violates
* this constraint to be an error.
*
* @author Julien Chable
*/
[TestFixture]
public class TestOPCComplianceCoreProperties
{
[Test]
public void TestCorePropertiesPart()
{
OPCPackage pkg;
string path = OpenXml4NetTestDataSamples.GetSampleFileName("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
pkg = OPCPackage.Open(path);
pkg.Revert();
}
private static String ExtractInvalidFormatMessage(String sampleNameSuffix)
{
Stream is1 = OpenXml4NetTestDataSamples.OpenComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
OPCPackage pkg;
try
{
pkg = OPCPackage.Open(is1);
}
catch (InvalidFormatException e)
{
// no longer required for successful test
return e.Message;
}
pkg.Revert();
throw new AssertionException("expected OPC compliance exception was not thrown");
}
/**
* Test M4.1 rule.
*/
[Test]
public void TestOnlyOneCorePropertiesPart()
{
// We have relaxed this check, so we can read the file anyway
try
{
ExtractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx");
Assert.Fail("M4.1 should be being relaxed");
}
catch (AssertionException e) { }
// We will use the first core properties, and ignore the others
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("MultipleCoreProperties.docx");
OPCPackage pkg = OPCPackage.Open(is1);
// We can see 2 by type
Assert.AreEqual(2, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
// But only the first one by relationship
Assert.AreEqual(1, pkg.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).Count);
// It should be core.xml not the older core1.xml
Assert.AreEqual(
"/docProps/core.xml",
pkg.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES)[0].PartName.ToString()
);
}
private static Uri CreateURI(String text)
{
return new Uri(text,UriKind.RelativeOrAbsolute);
}
/**
* Test M4.1 rule.
*/
[Test]
public void TestOnlyOneCorePropertiesPart_AddRelationship()
{
Stream is1 = OpenXml4NetTestDataSamples.OpenComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
OPCPackage pkg;
pkg = OPCPackage.Open(is1);
Uri partUri = CreateURI("/docProps/core2.xml");
try
{
pkg.AddRelationship(PackagingUriHelper.CreatePartName(partUri), TargetMode.Internal,
PackageRelationshipTypes.CORE_PROPERTIES);
// no longer fail on compliance error
//fail("expected OPC compliance exception was not thrown");
}
catch (InvalidFormatException e)
{
throw;
}
catch (InvalidOperationException e)
{
// expected during successful test
Assert.AreEqual("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.Message);
}
pkg.Revert();
}
/**
* Test M4.1 rule.
*/
[Test]
public void TestOnlyOneCorePropertiesPart_AddPart()
{
String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
OPCPackage pkg = null;
pkg = OPCPackage.Open(POIDataSamples.GetOpenXML4JInstance().GetFile(sampleFileName));
Uri partUri = CreateURI("/docProps/core2.xml");
try
{
pkg.CreatePart(PackagingUriHelper.CreatePartName(partUri),
ContentTypes.CORE_PROPERTIES_PART);
// no longer fail on compliance error
//fail("expected OPC compliance exception was not thrown");
}
catch (InvalidOperationException e)
{
// expected during successful test
Assert.AreEqual("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.Message);
}
pkg.Revert();
}
/**
* Test M4.2 rule.
*/
[Test]
public void TestDoNotUseCompatibilityMarkup()
{
String msg = ExtractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx");
Assert.AreEqual("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg);
}
/**
* Test M4.3 rule.
*/
[Test]
public void TestDCTermsNamespaceLimitedUse()
{
String msg = ExtractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx");
Assert.AreEqual("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
/**
* Test M4.4 rule.
*/
[Test]
public void TestUnauthorizedXMLLangAttribute()
{
String msg = ExtractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx");
Assert.AreEqual("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg);
}
/**
* Test M4.5 rule.
*/
[Test]
public void TestLimitedXSITypeAttribute_NotPresent()
{
String msg = ExtractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx");
Assert.AreEqual("The element 'created' must have the 'xsi:type' attribute present !", msg);
}
/**
* Test M4.5 rule.
*/
[Test]
public void TestLimitedXSITypeAttribute_PresentWithUnauthorizedValue()
{
String msg = ExtractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx");
Assert.AreEqual("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg);
}
/**
* Document with no core properties - testing at the OPC level,
* saving into a new stream
*/
[Test]
public void TestNoCoreProperties_saveNew()
{
String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
OPCPackage pkg = OPCPackage.Open(POIDataSamples.GetOpenXML4JInstance().GetFileInfo(sampleFileName).FullName);
// Verify it has empty properties
Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
// Save and re-load
MemoryStream baos = new MemoryStream();
pkg.Save(baos);
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg.Revert();
pkg = OPCPackage.Open(bais);
// An Empty Properties part has been Added in the save/load
Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
pkg.Close();
// Open a new copy of it
pkg = OPCPackage.Open(POIDataSamples.GetOpenXML4JInstance().GetFileInfo(sampleFileName).FullName);
// Save and re-load, without having touched the properties yet
baos = new MemoryStream();
pkg.Save(baos);
pkg.Revert();
bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
// Check that this too Added empty properties without error
Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
}
/**
* Document with no core properties - testing at the OPC level,
* from a temp-file, saving in-place
*/
[Test, RunSerialyAndSweepTmpFiles]
public void TestNoCoreProperties_saveInPlace()
{
String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
// Copy this into a temp file, so we can play with it
FileInfo tmp = TempFile.CreateTempFile("poi-test", ".opc");
FileStream out1 = new FileStream(tmp.FullName, FileMode.Create, FileAccess.ReadWrite);
Stream in1 = POIDataSamples.GetOpenXML4JInstance().OpenResourceAsStream(sampleFileName);
IOUtils.Copy(
in1,
out1);
out1.Close();
in1.Close();
// Open it from that temp file
OPCPackage pkg = OPCPackage.Open(tmp);
// Empty properties
Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
// Save and close
pkg.Close();
// Re-open and check
pkg = OPCPackage.Open(tmp);
// An Empty Properties part has been Added in the save/load
Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
// Finish and tidy
pkg.Revert();
tmp.Delete();
Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files.");
}
}
}
| |
// ***********************************************************************
// Copyright (c) 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.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Execution;
#if !SILVERLIGHT && !NETCF && !PORTABLE
using System.Runtime.Remoting.Messaging;
using System.Security.Principal;
using NUnit.Framework.Compatibility;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Helper class used to save and restore certain static or
/// singleton settings in the environment that affect tests
/// or which might be changed by the user tests.
///
/// An internal class is used to hold settings and a stack
/// of these objects is pushed and popped as Save and Restore
/// are called.
/// </summary>
public class TestExecutionContext
#if !SILVERLIGHT && !NETCF && !PORTABLE
: LongLivedMarshalByRefObject, ILogicalThreadAffinative
#endif
{
// NOTE: Be very careful when modifying this class. It uses
// conditional compilation extensively and you must give
// thought to whether any new features will be supported
// on each platform. In particular, instance fields,
// properties, initialization and restoration must all
// use the same conditions for each feature.
#region Instance Fields
/// <summary>
/// Link to a prior saved context
/// </summary>
private TestExecutionContext _priorContext;
/// <summary>
/// Indicates that a stop has been requested
/// </summary>
private TestExecutionStatus _executionStatus;
/// <summary>
/// The event listener currently receiving notifications
/// </summary>
private ITestListener _listener = TestListener.NULL;
/// <summary>
/// The number of assertions for the current test
/// </summary>
private int _assertCount;
private Randomizer _randomGenerator;
private IWorkItemDispatcher _dispatcher;
/// <summary>
/// The current culture
/// </summary>
private CultureInfo _currentCulture;
/// <summary>
/// The current UI culture
/// </summary>
private CultureInfo _currentUICulture;
/// <summary>
/// The current test result
/// </summary>
private TestResult _currentResult;
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// The current Principal.
/// </summary>
private IPrincipal _currentPrincipal;
#endif
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
public TestExecutionContext()
{
_priorContext = null;
TestCaseTimeout = 0;
UpstreamActions = new List<ITestAction>();
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val);
}
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
/// <param name="other">An existing instance of TestExecutionContext.</param>
public TestExecutionContext(TestExecutionContext other)
{
_priorContext = other;
CurrentTest = other.CurrentTest;
CurrentResult = other.CurrentResult;
TestObject = other.TestObject;
WorkDirectory = other.WorkDirectory;
_listener = other._listener;
StopOnError = other.StopOnError;
TestCaseTimeout = other.TestCaseTimeout;
UpstreamActions = new List<ITestAction>(other.UpstreamActions);
_currentCulture = other.CurrentCulture;
_currentUICulture = other.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = other.CurrentPrincipal;
#endif
CurrentValueFormatter = other.CurrentValueFormatter;
Dispatcher = other.Dispatcher;
ParallelScope = other.ParallelScope;
}
#endregion
#region Static Singleton Instance
/// <summary>
/// The current context, head of the list of saved contexts.
/// </summary>
#if SILVERLIGHT || PORTABLE
[ThreadStatic]
private static TestExecutionContext current;
#elif NETCF
private static LocalDataStoreSlot slotContext = Thread.AllocateDataSlot();
#else
private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext";
#endif
/// <summary>
/// Gets the current context.
/// </summary>
/// <value>The current context.</value>
public static TestExecutionContext CurrentContext
{
get
{
// If a user creates a thread then the current context
// will be null. This also happens when the compiler
// automatically creates threads for async methods.
// We create a new context, which is automatically
// populated with _values taken from the current thread.
#if SILVERLIGHT || PORTABLE
if (current == null)
current = new TestExecutionContext();
return current;
#elif NETCF
var current = (TestExecutionContext)Thread.GetData(slotContext);
if (current == null)
{
current = new TestExecutionContext();
Thread.SetData(slotContext, current);
}
return current;
#else
var context = GetTestExecutionContext();
if (context == null) // This can happen on Mono
{
context = new TestExecutionContext();
CallContext.SetData(CONTEXT_KEY, context);
}
return context;
#endif
}
private set
{
#if SILVERLIGHT || PORTABLE
current = value;
#elif NETCF
Thread.SetData(slotContext, value);
#else
if (value == null)
CallContext.FreeNamedDataSlot(CONTEXT_KEY);
else
CallContext.SetData(CONTEXT_KEY, value);
#endif
}
}
#if !SILVERLIGHT && !NETCF && !PORTABLE
/// <summary>
/// Get the current context or return null if none is found.
/// </summary>
public static TestExecutionContext GetTestExecutionContext()
{
return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;
}
#endif
/// <summary>
/// Clear the current context. This is provided to
/// prevent "leakage" of the CallContext containing
/// the current context back to any runners.
/// </summary>
public static void ClearCurrentContext()
{
CurrentContext = null;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current test
/// </summary>
public Test CurrentTest { get; set; }
/// <summary>
/// The time the current test started execution
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// The time the current test started in Ticks
/// </summary>
public long StartTicks { get; set; }
/// <summary>
/// Gets or sets the current test result
/// </summary>
public TestResult CurrentResult
{
get { return _currentResult; }
set
{
_currentResult = value;
if (value != null)
OutWriter = value.OutWriter;
}
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public TextWriter OutWriter { get; private set; }
/// <summary>
/// The current test object - that is the user fixture
/// object on which tests are being executed.
/// </summary>
public object TestObject { get; set; }
/// <summary>
/// Get or set the working directory
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Get or set indicator that run should stop on the first error
/// </summary>
public bool StopOnError { get; set; }
/// <summary>
/// Gets an enum indicating whether a stop has been requested.
/// </summary>
public TestExecutionStatus ExecutionStatus
{
get
{
// ExecutionStatus may have been set to StopRequested or AbortRequested
// in a prior context. If so, reflect the same setting in this context.
if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)
_executionStatus = _priorContext.ExecutionStatus;
return _executionStatus;
}
set
{
_executionStatus = value;
// Push the same setting up to all prior contexts
if (_priorContext != null)
_priorContext.ExecutionStatus = value;
}
}
/// <summary>
/// The current test event listener
/// </summary>
internal ITestListener Listener
{
get { return _listener; }
set { _listener = value; }
}
/// <summary>
/// The current WorkItemDispatcher
/// </summary>
internal IWorkItemDispatcher Dispatcher
{
get
{
if (_dispatcher == null)
_dispatcher = new SimpleWorkItemDispatcher();
return _dispatcher;
}
set { _dispatcher = value; }
}
/// <summary>
/// The ParallelScope to be used by tests running in this context.
/// For builds with out the parallel feature, it has no effect.
/// </summary>
public ParallelScope ParallelScope { get; set; }
/// <summary>
/// Gets the RandomGenerator specific to this Test
/// </summary>
public Randomizer RandomGenerator
{
get
{
if (_randomGenerator == null)
_randomGenerator = new Randomizer(CurrentTest.Seed);
return _randomGenerator;
}
}
/// <summary>
/// Gets the assert count.
/// </summary>
/// <value>The assert count.</value>
internal int AssertCount
{
get { return _assertCount; }
}
/// <summary>
/// Gets or sets the test case timeout value
/// </summary>
public int TestCaseTimeout { get; set; }
/// <summary>
/// Gets a list of ITestActions set by upstream tests
/// </summary>
public List<ITestAction> UpstreamActions { get; private set; }
// TODO: Put in checks on all of these settings
// with side effects so we only change them
// if the value is different
/// <summary>
/// Saves or restores the CurrentCulture
/// </summary>
public CultureInfo CurrentCulture
{
get { return _currentCulture; }
set
{
_currentCulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
#endif
}
}
/// <summary>
/// Saves or restores the CurrentUICulture
/// </summary>
public CultureInfo CurrentUICulture
{
get { return _currentUICulture; }
set
{
_currentUICulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
}
}
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
/// </summary>
public IPrincipal CurrentPrincipal
{
get { return _currentPrincipal; }
set
{
_currentPrincipal = value;
Thread.CurrentPrincipal = _currentPrincipal;
}
}
#endif
/// <summary>
/// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter
/// </summary>
public ValueFormatter CurrentValueFormatter { get; private set; }
#endregion
#region Instance Methods
/// <summary>
/// Record any changes in the environment made by
/// the test code in the execution context so it
/// will be passed on to lower level tests.
/// </summary>
public void UpdateContextFromEnvironment()
{
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
}
/// <summary>
/// Set up the execution environment to match a context.
/// Note that we may be running on the same thread where the
/// context was initially created or on a different thread.
/// </summary>
public void EstablishExecutionEnvironment()
{
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
#if !NETCF && !SILVERLIGHT && !PORTABLE
Thread.CurrentPrincipal = _currentPrincipal;
#endif
CurrentContext = this;
}
/// <summary>
/// Increments the assert count by one.
/// </summary>
public void IncrementAssertCount()
{
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Increments the assert count by a specified amount.
/// </summary>
public void IncrementAssertCount(int count)
{
// TODO: Temporary implementation
while (count-- > 0)
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Adds a new ValueFormatterFactory to the chain of formatters
/// </summary>
/// <param name="formatterFactory">The new factory</param>
public void AddFormatter(ValueFormatterFactory formatterFactory)
{
CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
}
#endregion
#region InitializeLifetimeService
#if !SILVERLIGHT && !NETCF && !PORTABLE
/// <summary>
/// Obtain lifetime service object
/// </summary>
/// <returns></returns>
public override object InitializeLifetimeService()
{
return null;
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class LastTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Last(), q.Last());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Last(), q.Last());
}
public void TestEmptyIList<T>()
{
T[] source = { };
Assert.NotNull(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.Last());
}
[Fact]
public void EmptyIListT()
{
TestEmptyIList<int>();
TestEmptyIList<string>();
TestEmptyIList<DateTime>();
TestEmptyIList<LastTests>();
}
[Fact]
public void IListTOneElement()
{
int[] source = { 5 };
int expected = 5;
Assert.NotNull(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null };
int? expected = null;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsNotDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null, 19 };
int? expected = 19;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
private static IEnumerable<T> EmptySource<T>()
{
yield break;
}
private static void TestEmptyNotIList<T>()
{
var source = EmptySource<T>();
Assert.Null(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.Last());
}
[Fact]
public void EmptyNotIListT()
{
TestEmptyNotIList<int>();
TestEmptyNotIList<string>();
TestEmptyNotIList<DateTime>();
TestEmptyNotIList<LastTests>();
}
[Fact]
public void OneElementNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1);
int expected = -5;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void ManyElementsNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10);
int expected = 12;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListEmptySourcePredicate()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementIListTruePredicate()
{
int[] source = { 4 };
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsIListPredicateFalseForAll()
{
int[] source = { 9, 5, 1, 3, 17, 21 };
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void IListPredicateTrueOnlyForLast()
{
int[] source = { 9, 5, 1, 3, 17, 21, 50 };
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void IListPredicateTrueForSome()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListIListEmptySourcePredicate()
{
IEnumerable<int> source = Enumerable.Range(1, 0);
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementNotIListTruePredicate()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(4, 1);
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsNotIListPredicateFalseForAll()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21 });
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueOnlyForLast()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21, 50 });
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueForSome()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NullSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last());
}
[Fact]
public void NullSourcePredicateUsed()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last(i => i != 2));
}
[Fact]
public void NullPredicate()
{
Func<int, bool> predicate = null;
Assert.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).Last(predicate));
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using mshtml;
namespace OpenLiveWriter.Mshtml
{
public class MarkupHelpers
{
public static bool AdjustMarkupRange(MarkupRange range, int offset, int length)
{
IHTMLTxtRange stagingTextRange = range.ToTextRange();
return AdjustMarkupRange(ref stagingTextRange, range, offset, length);
}
/// <summary>
/// Adjust the start and end of the range to match the offset/length, in characters.
/// if the offset/length adjustment fails to produce the expected value,
/// then the adjustment is cancelled and false is returned.
/// </summary>
public static bool AdjustMarkupRange(ref IHTMLTxtRange stagingTextRange, MarkupRange range, int offset, int length)
{
string currentText = GetRangeTextFast(range) ?? "";
if (offset == 0 && length == currentText.Length)
return true;
string expectedText;
try
{
expectedText = currentText.Substring(offset, length);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
MarkupRange testRange = range.Clone();
AdjustMarkupRangeCore(testRange, offset, length, currentText);
if (GetRangeTextFast(testRange) != expectedText)
return false;
range.MoveToRange(testRange);
return true;
}
private static void AdjustMarkupRangeCore(MarkupRange range, int offset, int length, string currentText)
{
MarkupPointer start = range.Start;
MarkupPointer end = range.End;
if (offset > 0)
start.MoveToMarkupPosition(start.Container, start.MarkupPosition + offset);
if (length < (offset + currentText.Length))
end.MoveToMarkupPosition(start.Container, start.MarkupPosition + length);
}
public static MarkupRange GetEditableRange(IHTMLElement e, MshtmlMarkupServices markupServices)
{
IHTMLElement3 editableElement = null;
while (e != null)
{
if (((IHTMLElement3)e).isContentEditable)
{
editableElement = (IHTMLElement3)e;
if (ElementFilters.IsBlockElement(e))
break;
}
else
break;
e = e.parentElement;
}
if (editableElement != null)
{
return markupServices.CreateMarkupRange((IHTMLElement)editableElement, false);
}
else
return null;
}
public static void SplitBlockForInsertionOrBreakout(MshtmlMarkupServices markupServices, MarkupRange bounds, MarkupPointer insertAt)
{
IHTMLElement currentBlock = insertAt.GetParentElement(ElementFilters.BLOCK_OR_TABLE_CELL_ELEMENTS);
if (currentBlock == null)
return;
if (ElementFilters.IsBlockQuoteElement(currentBlock) || ElementFilters.IsTableCellElement(currentBlock))
return;
MarkupPointer blockStart = markupServices.CreateMarkupPointer(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
MarkupPointer blockEnd = markupServices.CreateMarkupPointer(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (bounds != null && (blockStart.IsLeftOf(bounds.Start) || blockEnd.IsRightOf(bounds.End)))
return;
// Don't split if at the beginning or end of the visible content in the block.
// Instead just move the insertion point outside the block.
MarkupRange testRange = markupServices.CreateMarkupRange();
testRange.Start.MoveToPointer(insertAt);
testRange.End.MoveAdjacentToElement(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd);
if (testRange.IsEmptyOfContent())
{
insertAt.MoveAdjacentToElement(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
return;
}
testRange.Start.MoveAdjacentToElement(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
testRange.End.MoveToPointer(insertAt);
if (testRange.IsEmptyOfContent())
{
insertAt.MoveAdjacentToElement(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
return;
}
MarkupPointer moveTarget = markupServices.CreateMarkupPointer(blockEnd);
markupServices.Move(insertAt, blockEnd, moveTarget);
insertAt.MoveAdjacentToElement(currentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
}
public delegate TResult TextRangeFunc<TResult>(IHTMLTxtRange rng);
/// <summary>
/// Text ranges are extremely expensive to create, and readily reusable. UseStagingTextRange
/// is a higher order function that makes it slightly easier to reuse text ranges, which can
/// give much better performance if the lifetime of your stagingTextRange reference spans
/// lots of calls.
/// </summary>
/// <typeparam name="TResult">The type of the result from the function we'll execute.</typeparam>
/// <param name="stagingTextRange">A reference to a stagingTextRange that we can use, it can be null at first and we'll create on demand if necessary.</param>
/// <param name="range">The markup range to move the stagingTextRange to.</param>
/// <param name="func">The function to pass the stagingTextRange to after it's been created/positioned.</param>
/// <returns>The value returned from func.</returns>
public static TResult UseStagingTextRange<TResult>(ref IHTMLTxtRange stagingTextRange, MarkupRange range, TextRangeFunc<TResult> func)
{
Debug.Assert(range != null, "Range must not be null!");
Debug.Assert(range.Positioned, "Range must be positioned!");
Debug.Assert(range.Start.IsLeftOfOrEqualTo(range.End), "Range start must be left of or equal to range end!");
if (stagingTextRange == null)
stagingTextRange = range.MarkupServices.CreateTextRange(range.Start, range.End);
else
range.MarkupServices.MoveRangeToPointers(range.Start, range.End, stagingTextRange);
return func(stagingTextRange);
}
public static string GetRangeTextFast(MarkupRange range)
{
IHTMLTxtRange stagingTextRange = IHTMLTxtRangePool.AquireTxtRange(range);
string returnValue = UseStagingTextRange(ref stagingTextRange, range, rng => rng.text);
IHTMLTxtRangePool.RelinquishTxtRange(stagingTextRange, range);
return returnValue;
}
public static string GetRangeHtmlFast(MarkupRange range)
{
IHTMLTxtRange stagingTextRange = IHTMLTxtRangePool.AquireTxtRange(range);
string returnValue = UseStagingTextRange(ref stagingTextRange, range, rng => rng.htmlText);
IHTMLTxtRangePool.RelinquishTxtRange(stagingTextRange, range);
return returnValue;
}
}
internal static class IHTMLTxtRangePool
{
private static Hashtable cache = null;
static IHTMLTxtRangePool()
{
cache = Hashtable.Synchronized(new Hashtable());
}
public static IHTMLTxtRange AquireTxtRange(MarkupRange range)
{
try
{
if (cache != null)
{
int documentId = GetDocumentKey(range.MarkupServices.MarkupServicesRaw);
Queue queue = null;
IHTMLTxtRange returnRange = null;
lock (cache.SyncRoot)
{
queue = (Queue)cache[documentId];
if (queue == null)
{
queue = Queue.Synchronized(new Queue());
cache.Add(documentId, queue);
}
if (queue.Count > 0)
{
lock (queue.SyncRoot)
{
returnRange = (IHTMLTxtRange)queue.Dequeue();
}
}
else
{
returnRange = range.ToTextRange();
}
}
return returnRange;
}
}
catch (Exception ex)
{
Debug.WriteLine("Failure in IHTMLTxtRangePool: " + ex);
cache = null;
}
try
{
return range.ToTextRange();
}
catch (Exception ex)
{
Debug.WriteLine("Failure in IHTMLTxtRangePool: " + ex);
return null;
}
}
public static void RelinquishTxtRange(IHTMLTxtRange txtRange, MarkupRange range)
{
if (cache == null)
return;
try
{
lock (cache.SyncRoot)
{
Queue queue = (Queue)cache[GetDocumentKey(range.MarkupServices.MarkupServicesRaw)];
if (queue != null)
{
lock (queue.SyncRoot)
{
queue.Enqueue(txtRange);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Failure in IHTMLTxtRangePool: " + ex);
cache = null;
}
}
internal static void Clear(IMarkupServicesRaw markupServices)
{
if (cache == null)
return;
try
{
lock (cache.SyncRoot)
{
cache.Remove(GetDocumentKey(markupServices));
}
}
catch (Exception)
{
cache = null;
}
}
private static int GetDocumentKey(IMarkupServicesRaw markupServices)
{
return markupServices.GetHashCode();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Net.Cache;
namespace XmlNotepad
{
/// <summary>
/// XmlCache wraps an XmlDocument and provides the stuff necessary for an "editor" in terms
/// of watching for changes on disk, notification when the file has been reloaded, and keeping
/// track of the current file name and dirty state.
/// </summary>
public class XmlCache : IDisposable
{
string filename;
string xsltFilename;
bool dirty;
DomLoader loader;
XmlDocument doc;
FileSystemWatcher watcher;
int retries;
Timer timer = new Timer();
ISynchronizeInvoke sync;
//string namespaceUri = string.Empty;
SchemaCache schemaCache;
Dictionary<XmlNode, XmlSchemaInfo> typeInfo;
int batch;
DateTime lastModified;
Checker checker;
IServiceProvider site;
public event EventHandler FileChanged;
public event EventHandler<ModelChangedEventArgs> ModelChanged;
public XmlCache(IServiceProvider site, ISynchronizeInvoke sync)
{
this.loader = new DomLoader(site);
this.schemaCache = new SchemaCache(site);
this.site = site;
this.sync = sync;
this.Document = new XmlDocument();
this.timer.Tick += new EventHandler(Reload);
this.timer.Interval = 1000;
this.timer.Enabled = false;
}
~XmlCache() {
Dispose(false);
}
public Uri Location {
get { return new Uri(this.filename); }
}
public string FileName {
get { return this.filename; }
}
public bool IsFile {
get {
if (!string.IsNullOrEmpty(this.filename)) {
return this.Location.IsFile;
}
return false;
}
}
/// <summary>
/// File path to (optionally user-specified) xslt file.
/// </summary>
public string XsltFileName
{
get {
return this.xsltFilename;
}
set { this.xsltFilename = value; }
}
public bool Dirty
{
get { return this.dirty; }
}
public XmlResolver SchemaResolver {
get {
return this.schemaCache.Resolver;
}
}
public XPathNavigator Navigator
{
get
{
XPathDocument xdoc = new XPathDocument(this.filename);
XPathNavigator nav = xdoc.CreateNavigator();
return nav;
}
}
public void ValidateModel(TaskHandler handler) {
this.checker = new Checker(handler);
checker.Validate(this);
}
public XmlDocument Document
{
get { return this.doc; }
set
{
if (this.doc != null)
{
this.doc.NodeChanged -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeInserted -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeRemoved -= new XmlNodeChangedEventHandler(OnDocumentChanged);
}
this.doc = value;
if (this.doc != null)
{
this.doc.NodeChanged += new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeInserted += new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeRemoved += new XmlNodeChangedEventHandler(OnDocumentChanged);
}
}
}
public Dictionary<XmlNode, XmlSchemaInfo> TypeInfoMap {
get { return this.typeInfo; }
set { this.typeInfo = value; }
}
public XmlSchemaInfo GetTypeInfo(XmlNode node) {
if (this.typeInfo == null) return null;
if (this.typeInfo.ContainsKey(node)) {
return this.typeInfo[node];
}
return null;
}
public XmlSchemaElement GetElementType(XmlQualifiedName xmlQualifiedName)
{
if (this.schemaCache != null)
{
return this.schemaCache.GetElementType(xmlQualifiedName);
}
return null;
}
public XmlSchemaAttribute GetAttributeType(XmlQualifiedName xmlQualifiedName)
{
if (this.schemaCache != null)
{
return this.schemaCache.GetAttributeType(xmlQualifiedName);
}
return null;
}
/// <summary>
/// Provides schemas used for validation.
/// </summary>
public SchemaCache SchemaCache
{
get { return this.schemaCache; }
set { this.schemaCache = value; }
}
/// <summary>
/// Loads an instance of xml.
/// Load updated to handle validation when instance doc refers to schema.
/// </summary>
/// <param name="file">Xml instance document</param>
/// <returns></returns>
public void Load(string file)
{
this.Clear();
loader = new DomLoader(this.site);
StopFileWatch();
Uri uri = new Uri(file, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri) {
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
file = resolved.LocalPath;
uri = resolved;
}
this.filename = file;
this.lastModified = this.LastModTime;
this.dirty = false;
StartFileWatch();
XmlReaderSettings settings = GetReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
using (XmlReader reader = XmlReader.Create(file, settings)) {
this.Document = loader.Load(reader);
}
this.xsltFilename = this.loader.XsltFileName;
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
public void Load(XmlReader reader, string fileName)
{
this.Clear();
loader = new DomLoader(this.site);
StopFileWatch();
Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
{
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
fileName = resolved.LocalPath;
uri = resolved;
}
this.filename = fileName;
this.lastModified = this.LastModTime;
this.dirty = false;
StartFileWatch();
this.Document = loader.Load(reader);
this.xsltFilename = this.loader.XsltFileName;
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
internal XmlReaderSettings GetReaderSettings() {
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.CheckCharacters = false;
settings.XmlResolver = new XmlProxyResolver(this.site);
return settings;
}
public void ExpandIncludes() {
if (this.Document != null) {
this.dirty = true;
XmlReaderSettings s = new XmlReaderSettings();
s.ProhibitDtd = false;
s.XmlResolver = new XmlProxyResolver(this.site);
using (XmlReader r = XmlIncludeReader.CreateIncludeReader(this.Document, s, this.FileName)) {
this.Document = loader.Load(r);
}
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
}
public void BeginUpdate() {
if (batch == 0)
FireModelChanged(ModelChangeType.BeginBatchUpdate, this.doc);
batch++;
}
public void EndUpdate() {
batch--;
if (batch == 0)
FireModelChanged(ModelChangeType.EndBatchUpdate, this.doc);
}
public LineInfo GetLineInfo(XmlNode node) {
return loader.GetLineInfo(node);
}
void OnValidationEvent(object sender, ValidationEventArgs e)
{
// todo: log errors in error list window.
}
public void Reload()
{
string filename = this.filename;
Clear();
Load(filename);
}
public void Clear()
{
this.Document = new XmlDocument();
StopFileWatch();
this.filename = null;
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
public void Save()
{
Save(this.filename);
}
public Encoding GetEncoding() {
XmlDeclaration xmldecl = doc.FirstChild as XmlDeclaration;
Encoding result = null;
if (xmldecl != null)
{
try
{
string e = xmldecl.Encoding;
if (!string.IsNullOrEmpty(e))
{
result = Encoding.GetEncoding(e);
}
}
catch (Exception)
{
}
}
if (result == null)
{
// default is UTF-8.
result = Encoding.UTF8;
}
return result;
}
internal static Encoding SniffByteOrderMark(byte[] bytes, int len)
{
if (len >= 3 && bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf )
{
return Encoding.UTF8;
}
else if (len >= 4 && ((bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0xfe && bytes[3] == 0xff) || (bytes[0] == 0xfe && bytes[1] == 0xff && bytes[2] == 0xfe && bytes[3] == 0xff)))
{
return Encoding.GetEncoding(12001); // big endian UTF-32.
}
else if (len >= 4 && ((bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0x00 && bytes[3] == 0x00) || (bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0xff && bytes[3] == 0xfe) ))
{
return Encoding.UTF32; // skip UTF-32 little endian BOM
}
else if (len >= 2 && bytes[0] == 0xff && bytes[1] == 0xfe )
{
return Encoding.Unicode; // skip UTF-16 little endian BOM
}
else if (len >= 2 && bytes[0] == 0xf2 && bytes[1] == 0xff )
{
return Encoding.BigEndianUnicode; // skip UTF-16 big endian BOM
}
return null;
}
public void AddXmlDeclarationWithEncoding()
{
XmlDeclaration xmldecl = doc.FirstChild as XmlDeclaration;
if (xmldecl == null)
{
doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "utf-8", null), doc.FirstChild);
}
else
{
string e = xmldecl.Encoding;
if (string.IsNullOrEmpty(e))
{
xmldecl.Encoding = "utf-8";
}
}
}
public void Save(string name)
{
try
{
StopFileWatch();
XmlWriterSettings s = new XmlWriterSettings();
Utilities.InitializeWriterSettings(s, this.site);
var encoding = GetEncoding();
s.Encoding = encoding;
bool noBom = false;
if (this.site != null)
{
Settings settings = (Settings)this.site.GetService(typeof(Settings));
if (settings != null)
{
noBom = (bool)settings["NoByteOrderMark"];
if (noBom)
{
// then we must have an XML declaration with an encoding attribute.
AddXmlDeclarationWithEncoding();
}
}
}
if (noBom)
{
MemoryStream ms = new MemoryStream();
using (XmlWriter w = XmlWriter.Create(ms, s))
{
doc.Save(w);
}
ms.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] bytes = new byte[16000];
int len = ms.Read(bytes, 0, bytes.Length);
int start = 0;
Encoding sniff = SniffByteOrderMark(bytes, len);
if (sniff != null)
{
if (sniff == Encoding.UTF8)
{
start = 3;
}
else if (sniff == Encoding.GetEncoding(12001) || sniff == Encoding.UTF32) // UTF-32.
{
start = 4;
}
else if (sniff == Encoding.Unicode || sniff == Encoding.BigEndianUnicode) // UTF-16.
{
start = 2;
}
}
while (len > 0)
{
fs.Write(bytes, start, len - start);
len = ms.Read(bytes, 0, bytes.Length);
start = 0;
}
}
}
else
{
using (XmlWriter w = XmlWriter.Create(name, s))
{
doc.Save(w);
}
}
this.dirty = false;
this.filename = name;
this.lastModified = this.LastModTime;
FireModelChanged(ModelChangeType.Saved, this.doc);
}
finally
{
StartFileWatch();
}
}
public bool IsReadOnly(string filename) {
return File.Exists(filename) &&
(File.GetAttributes(filename) & FileAttributes.ReadOnly) != 0;
}
public void MakeReadWrite(string filename) {
if (!File.Exists(filename))
return;
StopFileWatch();
try {
FileAttributes attrsMinusReadOnly = File.GetAttributes(this.filename) & ~FileAttributes.ReadOnly;
File.SetAttributes(filename, attrsMinusReadOnly);
} finally {
StartFileWatch();
}
}
void StopFileWatch()
{
if (this.watcher != null)
{
this.watcher.Dispose();
this.watcher = null;
}
}
private void StartFileWatch()
{
if (this.filename != null && Location.IsFile && File.Exists(this.filename))
{
string dir = Path.GetDirectoryName(this.filename) + "\\";
this.watcher = new FileSystemWatcher(dir, "*.*");
this.watcher.Changed += new FileSystemEventHandler(watcher_Changed);
this.watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
this.watcher.EnableRaisingEvents = true;
}
else
{
StopFileWatch();
}
}
void StartReload(object sender, EventArgs e)
{
// Apart from retrying, the timer has the nice side effect of also
// collapsing multiple file system events into one timer event.
retries = 3;
timer.Enabled = true;
timer.Start();
}
DateTime LastModTime {
get {
if (Location.IsFile) return File.GetLastWriteTime(this.filename);
return DateTime.Now;
}
}
void Reload(object sender, EventArgs e)
{
try
{
// Only do the reload if the file on disk really is different from
// what we last loaded.
if (this.lastModified < LastModTime) {
// Test if we can open the file (it might still be locked).
using (FileStream fs = new FileStream(this.filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fs.Close();
}
timer.Enabled = false;
FireFileChanged();
}
}
finally
{
retries--;
if (retries == 0)
{
timer.Enabled = false;
}
}
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed &&
IsSamePath(this.filename, e.FullPath))
{
sync.BeginInvoke(new EventHandler(StartReload), new object[] { this, EventArgs.Empty });
}
}
private void watcher_Renamed(object sender, RenamedEventArgs e)
{
if (IsSamePath(this.filename, e.OldFullPath))
{
StopFileWatch();
this.filename = e.FullPath;
StartFileWatch();
sync.BeginInvoke(new EventHandler(StartReload), new object[] { this, EventArgs.Empty });
}
}
static bool IsSamePath(string a, string b)
{
return string.Compare(a, b, true) == 0;
}
void FireFileChanged()
{
if (this.FileChanged != null)
{
FileChanged(this, EventArgs.Empty);
}
}
void FireModelChanged(ModelChangeType t, XmlNode node)
{
if (this.ModelChanged != null)
this.ModelChanged(this, new ModelChangedEventArgs(t, node));
}
void OnPIChange(XmlNodeChangedEventArgs e) {
XmlProcessingInstruction pi = (XmlProcessingInstruction)e.Node;
if (pi.Name == "xml-stylesheet") {
if (e.Action == XmlNodeChangedAction.Remove) {
// see if there's another!
pi = (XmlProcessingInstruction)this.doc.SelectSingleNode("processing-instruction('xml-stylesheet')");
}
if (pi != null) {
this.xsltFilename = DomLoader.ParseXsltArgs(pi.Data);
}
}
}
private void OnDocumentChanged(object sender, XmlNodeChangedEventArgs e)
{
// initialize t
ModelChangeType t = ModelChangeType.NodeChanged;
if (e.Node is XmlProcessingInstruction) {
OnPIChange(e);
}
if (XmlHelpers.IsXmlnsNode(e.NewParent) || XmlHelpers.IsXmlnsNode(e.Node)) {
// we flag a namespace change whenever an xmlns attribute changes.
t = ModelChangeType.NamespaceChanged;
XmlNode node = e.Node;
if (e.Action == XmlNodeChangedAction.Remove) {
node = e.OldParent; // since node.OwnerElement link has been severed!
}
this.dirty = true;
FireModelChanged(t, node);
} else {
switch (e.Action) {
case XmlNodeChangedAction.Change:
t = ModelChangeType.NodeChanged;
break;
case XmlNodeChangedAction.Insert:
t = ModelChangeType.NodeInserted;
break;
case XmlNodeChangedAction.Remove:
t = ModelChangeType.NodeRemoved;
break;
}
this.dirty = true;
FireModelChanged(t, e.Node);
}
}
public void Dispose() {
Dispose(true);
}
protected virtual void Dispose(bool disposing) {
if (timer != null) {
timer.Dispose();
timer = null;
}
StopFileWatch();
GC.SuppressFinalize(this);
}
}
public enum ModelChangeType
{
Reloaded,
Saved,
NodeChanged,
NodeInserted,
NodeRemoved,
NamespaceChanged,
BeginBatchUpdate,
EndBatchUpdate,
}
public class ModelChangedEventArgs : EventArgs
{
ModelChangeType type;
XmlNode node;
public ModelChangedEventArgs(ModelChangeType t, XmlNode node)
{
this.type = t;
this.node = node;
}
public XmlNode Node {
get { return node; }
set { node = value; }
}
public ModelChangeType ModelChangeType
{
get { return this.type; }
set { this.type = value; }
}
}
public enum IndentChar {
Space,
Tab
}
}
| |
/* ====================================================================
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 NPOI.DDF
{
using System;
using System.Collections;
/// <summary>
/// Provides a list of all known escher properties including the description and
/// type.
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
public class EscherProperties
{
#region Property constants
public const short TRANSFORM__ROTATION = 4;
public const short PROTECTION__LOCKROTATION = 119;
public const short PROTECTION__LOCKASPECTRATIO = 120;
public const short PROTECTION__LOCKPOSITION = 121;
public const short PROTECTION__LOCKAGAINSTSELECT = 122;
public const short PROTECTION__LOCKCROPPING = 123;
public const short PROTECTION__LOCKVERTICES = 124;
public const short PROTECTION__LOCKTEXT = 125;
public const short PROTECTION__LOCKADJUSTHANDLES = 126;
public const short PROTECTION__LOCKAGAINSTGROUPING = 127;
public const short TEXT__TEXTID = 128;
public const short TEXT__TEXTLEFT = 129;
public const short TEXT__TEXTTOP = 130;
public const short TEXT__TEXTRIGHT = 131;
public const short TEXT__TEXTBOTTOM = 132;
public const short TEXT__WRAPTEXT = 133;
public const short TEXT__SCALETEXT = 134;
public const short TEXT__ANCHORTEXT = 135;
public const short TEXT__TEXTFLOW = 136;
public const short TEXT__FONTROTATION = 137;
public const short TEXT__IDOFNEXTSHAPE = 138;
public const short TEXT__BIDIR = 139;
public const short TEXT__SINGLECLICKSELECTS = 187;
public const short TEXT__USEHOSTMARGINS = 188;
public const short TEXT__ROTATETEXTWITHSHAPE = 189;
public const short TEXT__SIZESHAPETOFITTEXT = 190;
public const short TEXT__SIZE_TEXT_TO_FIT_SHAPE = 191;
public const short GEOTEXT__UNICODE = 192;
public const short GEOTEXT__RTFTEXT = 193;
public const short GEOTEXT__ALIGNMENTONCURVE = 194;
public const short GEOTEXT__DEFAULTPOINTSIZE = 195;
public const short GEOTEXT__TEXTSPACING = 196;
public const short GEOTEXT__FONTFAMILYNAME = 197;
public const short GEOTEXT__REVERSEROWORDER = 240;
public const short GEOTEXT__HASTEXTEFFECT = 241;
public const short GEOTEXT__ROTATECHARACTERS = 242;
public const short GEOTEXT__KERNCHARACTERS = 243;
public const short GEOTEXT__TIGHTORTRACK = 244;
public const short GEOTEXT__STRETCHTOFITSHAPE = 245;
public const short GEOTEXT__CHARBOUNDINGBOX = 246;
public const short GEOTEXT__SCALETEXTONPATH = 247;
public const short GEOTEXT__STRETCHCHARHEIGHT = 248;
public const short GEOTEXT__NOMEASUREALONGPATH = 249;
public const short GEOTEXT__BOLDFONT = 250;
public const short GEOTEXT__ITALICFONT = 251;
public const short GEOTEXT__UNDERLINEFONT = 252;
public const short GEOTEXT__SHADOWFONT = 253;
public const short GEOTEXT__SMALLCAPSFONT = 254;
public const short GEOTEXT__STRIKETHROUGHFONT = 255;
public const short BLIP__CROPFROMTOP = 256;
public const short BLIP__CROPFROMBOTTOM = 257;
public const short BLIP__CROPFROMLEFT = 258;
public const short BLIP__CROPFROMRIGHT = 259;
public const short BLIP__BLIPTODISPLAY = 260;
public const short BLIP__BLIPFILENAME = 261;
public const short BLIP__BLIPFLAGS = 262;
public const short BLIP__TRANSPARENTCOLOR = 263;
public const short BLIP__CONTRASTSetTING = 264;
public const short BLIP__BRIGHTNESSSetTING = 265;
public const short BLIP__GAMMA = 266;
public const short BLIP__PICTUREID = 267;
public const short BLIP__DOUBLEMOD = 268;
public const short BLIP__PICTUREFillMOD = 269;
public const short BLIP__PICTURELINE = 270;
public const short BLIP__PRINTBLIP = 271;
public const short BLIP__PRINTBLIPFILENAME = 272;
public const short BLIP__PRINTFLAGS = 273;
public const short BLIP__NOHITTESTPICTURE = 316;
public const short BLIP__PICTUREGRAY = 317;
public const short BLIP__PICTUREBILEVEL = 318;
public const short BLIP__PICTUREACTIVE = 319;
public const short GEOMETRY__LEFT = 320;
public const short GEOMETRY__TOP = 321;
public const short GEOMETRY__RIGHT = 322;
public const short GEOMETRY__BOTTOM = 323;
public const short GEOMETRY__SHAPEPATH = 324;
public const short GEOMETRY__VERTICES = 325;
public const short GEOMETRY__SEGMENTINFO = 326;
public const short GEOMETRY__ADJUSTVALUE = 327;
public const short GEOMETRY__ADJUST2VALUE = 328;
public const short GEOMETRY__ADJUST3VALUE = 329;
public const short GEOMETRY__ADJUST4VALUE = 330;
public const short GEOMETRY__ADJUST5VALUE = 331;
public const short GEOMETRY__ADJUST6VALUE = 332;
public const short GEOMETRY__ADJUST7VALUE = 333;
public const short GEOMETRY__ADJUST8VALUE = 334;
public const short GEOMETRY__ADJUST9VALUE = 335;
public const short GEOMETRY__ADJUST10VALUE = 336;
public const short GEOMETRY__SHADOWok = 378;
public const short GEOMETRY__3DOK = 379;
public const short GEOMETRY__LINEOK = 380;
public const short GEOMETRY__GEOTEXTOK = 381;
public const short GEOMETRY__FILLSHADESHAPEOK = 382;
public const short GEOMETRY__FILLOK = 383;
public const short FILL__FILLTYPE = 384;
public const short FILL__FILLCOLOR = 385;
public const short FILL__FILLOPACITY = 386;
public const short FILL__FILLBACKCOLOR = 387;
public const short FILL__BACKOPACITY = 388;
public const short FILL__CRMOD = 389;
public const short FILL__PATTERNTEXTURE = 390;
public const short FILL__BLIPFILENAME = 391;
public const short FILL__BLIPFLAGS = 392;
public const short FILL__WIDTH = 393;
public const short FILL__HEIGHT = 394;
public const short FILL__ANGLE = 395;
public const short FILL__FOCUS = 396;
public const short FILL__TOLEFT = 397;
public const short FILL__TOTOP = 398;
public const short FILL__TORIGHT = 399;
public const short FILL__TOBOTTOM = 400;
public const short FILL__RECTLEFT = 401;
public const short FILL__RECTTOP = 402;
public const short FILL__RECTRIGHT = 403;
public const short FILL__RECTBOTTOM = 404;
public const short FILL__DZTYPE = 405;
public const short FILL__SHADEPRESet = 406;
public const short FILL__SHADECOLORS = 407;
public const short FILL__ORIGINX = 408;
public const short FILL__ORIGINY = 409;
public const short FILL__SHAPEORIGINX = 410;
public const short FILL__SHAPEORIGINY = 411;
public const short FILL__SHADETYPE = 412;
public const short FILL__FILLED = 443;
public const short FILL__HITTESTFILL = 444;
public const short FILL__SHAPE = 445;
public const short FILL__USERECT = 446;
public const short FILL__NOFILLHITTEST = 447;
public const short LINESTYLE__COLOR = 448;
public const short LINESTYLE__OPACITY = 449;
public const short LINESTYLE__BACKCOLOR = 450;
public const short LINESTYLE__CRMOD = 451;
public const short LINESTYLE__LINETYPE = 452;
public const short LINESTYLE__FILLBLIP = 453;
public const short LINESTYLE__FILLBLIPNAME = 454;
public const short LINESTYLE__FILLBLIPFLAGS = 455;
public const short LINESTYLE__FILLWIDTH = 456;
public const short LINESTYLE__FILLHEIGHT = 457;
public const short LINESTYLE__FILLDZTYPE = 458;
public const short LINESTYLE__LINEWIDTH = 459;
public const short LINESTYLE__LINEMITERLIMIT = 460;
public const short LINESTYLE__LINESTYLE = 461;
public const short LINESTYLE__LINEDASHING = 462;
public const short LINESTYLE__LINEDASHSTYLE = 463;
public const short LINESTYLE__LINESTARTARROWHEAD = 464;
public const short LINESTYLE__LINEENDARROWHEAD = 465;
public const short LINESTYLE__LINESTARTARROWWIDTH = 466;
public const short LINESTYLE__LINEESTARTARROWLength = 467;
public const short LINESTYLE__LINEENDARROWWIDTH = 468;
public const short LINESTYLE__LINEENDARROWLength = 469;
public const short LINESTYLE__LINEJOINSTYLE = 470;
public const short LINESTYLE__LINEENDCAPSTYLE = 471;
public const short LINESTYLE__ARROWHEADSOK = 507;
public const short LINESTYLE__ANYLINE = 508;
public const short LINESTYLE__HITLINETEST = 509;
public const short LINESTYLE__LINEFILLSHAPE = 510;
public const short LINESTYLE__NOLINEDRAWDASH = 511;
public const short SHADOWSTYLE__TYPE = 512;
public const short SHADOWSTYLE__COLOR = 513;
public const short SHADOWSTYLE__HIGHLIGHT = 514;
public const short SHADOWSTYLE__CRMOD = 515;
public const short SHADOWSTYLE__OPACITY = 516;
public const short SHADOWSTYLE__OFFSetX = 517;
public const short SHADOWSTYLE__OFFSetY = 518;
public const short SHADOWSTYLE__SECONDOFFSetX = 519;
public const short SHADOWSTYLE__SECONDOFFSetY = 520;
public const short SHADOWSTYLE__SCALEXTOX = 521;
public const short SHADOWSTYLE__SCALEYTOX = 522;
public const short SHADOWSTYLE__SCALEXTOY = 523;
public const short SHADOWSTYLE__SCALEYTOY = 524;
public const short SHADOWSTYLE__PERSPECTIVEX = 525;
public const short SHADOWSTYLE__PERSPECTIVEY = 526;
public const short SHADOWSTYLE__WEIGHT = 527;
public const short SHADOWSTYLE__ORIGINX = 528;
public const short SHADOWSTYLE__ORIGINY = 529;
public const short SHADOWSTYLE__SHADOW = 574;
public const short SHADOWSTYLE__SHADOWOBSURED = 575;
public const short PERSPECTIVE__TYPE = 576;
public const short PERSPECTIVE__OFFSetX = 577;
public const short PERSPECTIVE__OFFSetY = 578;
public const short PERSPECTIVE__SCALEXTOX = 579;
public const short PERSPECTIVE__SCALEYTOX = 580;
public const short PERSPECTIVE__SCALEXTOY = 581;
public const short PERSPECTIVE__SCALEYTOY = 582;
public const short PERSPECTIVE__PERSPECTIVEX = 583;
public const short PERSPECTIVE__PERSPECTIVEY = 584;
public const short PERSPECTIVE__WEIGHT = 585;
public const short PERSPECTIVE__ORIGINX = 586;
public const short PERSPECTIVE__ORIGINY = 587;
public const short PERSPECTIVE__PERSPECTIVEON = 639;
public const short THREED__SPECULARAMOUNT = 640;
public const short THREED__DIFFUSEAMOUNT = 661;
public const short THREED__SHININESS = 662;
public const short THREED__EDGetHICKNESS = 663;
public const short THREED__EXTRUDEFORWARD = 664;
public const short THREED__EXTRUDEBACKWARD = 665;
public const short THREED__EXTRUDEPLANE = 666;
public const short THREED__EXTRUSIONCOLOR = 667;
public const short THREED__CRMOD = 648;
public const short THREED__3DEFFECT = 700;
public const short THREED__METALLIC = 701;
public const short THREED__USEEXTRUSIONCOLOR = 702;
public const short THREED__LIGHTFACE = 703;
public const short THREEDSTYLE__YROTATIONANGLE = 704;
public const short THREEDSTYLE__XROTATIONANGLE = 705;
public const short THREEDSTYLE__ROTATIONAXISX = 706;
public const short THREEDSTYLE__ROTATIONAXISY = 707;
public const short THREEDSTYLE__ROTATIONAXISZ = 708;
public const short THREEDSTYLE__ROTATIONANGLE = 709;
public const short THREEDSTYLE__ROTATIONCENTERX = 710;
public const short THREEDSTYLE__ROTATIONCENTERY = 711;
public const short THREEDSTYLE__ROTATIONCENTERZ = 712;
public const short THREEDSTYLE__RENDERMODE = 713;
public const short THREEDSTYLE__TOLERANCE = 714;
public const short THREEDSTYLE__XVIEWPOINT = 715;
public const short THREEDSTYLE__YVIEWPOINT = 716;
public const short THREEDSTYLE__ZVIEWPOINT = 717;
public const short THREEDSTYLE__ORIGINX = 718;
public const short THREEDSTYLE__ORIGINY = 719;
public const short THREEDSTYLE__SKEWANGLE = 720;
public const short THREEDSTYLE__SKEWAMOUNT = 721;
public const short THREEDSTYLE__AMBIENTINTENSITY = 722;
public const short THREEDSTYLE__KEYX = 723;
public const short THREEDSTYLE__KEYY = 724;
public const short THREEDSTYLE__KEYZ = 725;
public const short THREEDSTYLE__KEYINTENSITY = 726;
public const short THREEDSTYLE__FillX = 727;
public const short THREEDSTYLE__FillY = 728;
public const short THREEDSTYLE__FillZ = 729;
public const short THREEDSTYLE__FillINTENSITY = 730;
public const short THREEDSTYLE__CONSTRAINROTATION = 763;
public const short THREEDSTYLE__ROTATIONCENTERAUTO = 764;
public const short THREEDSTYLE__PARALLEL = 765;
public const short THREEDSTYLE__KEYHARSH = 766;
public const short THREEDSTYLE__FillHARSH = 767;
public const short SHAPE__MASTER = 769;
public const short SHAPE__CONNECTORSTYLE = 771;
public const short SHAPE__BLACKANDWHITESetTINGS = 772;
public const short SHAPE__WMODEPUREBW = 773;
public const short SHAPE__WMODEBW = 774;
public const short SHAPE__OLEICON = 826;
public const short SHAPE__PREFERRELATIVERESIZE = 827;
public const short SHAPE__LOCKSHAPETYPE = 828;
public const short SHAPE__DELETEATTACHEDOBJECT = 830;
public const short SHAPE__BACKGROUNDSHAPE = 831;
public const short CALLOUT__CALLOUTTYPE = 832;
public const short CALLOUT__XYCALLOUTGAP = 833;
public const short CALLOUT__CALLOUTANGLE = 834;
public const short CALLOUT__CALLOUTDROPTYPE = 835;
public const short CALLOUT__CALLOUTDROPSPECIFIED = 836;
public const short CALLOUT__CALLOUTLENGTHSPECIFIED = 837;
public const short CALLOUT__ISCALLOUT = 889;
public const short CALLOUT__CALLOUTACCENTBAR = 890;
public const short CALLOUT__CALLOUTTEXTBORDER = 891;
public const short CALLOUT__CALLOUTMINUSX = 892;
public const short CALLOUT__CALLOUTMINUSY = 893;
public const short CALLOUT__DROPAUTO = 894;
public const short CALLOUT__LENGTHSPECIFIED = 895;
public const short GROUPSHAPE__SHAPENAME = 0x0380;
public const short GROUPSHAPE__DESCRIPTION = 0x0381;
public const short GROUPSHAPE__HYPERLINK = 0x0382;
public const short GROUPSHAPE__WRAPPOLYGONVERTICES = 0x0383;
public const short GROUPSHAPE__WRAPDISTLEFT = 0x0384;
public const short GROUPSHAPE__WRAPDISTTOP = 0x0385;
public const short GROUPSHAPE__WRAPDISTRIGHT = 0x0386;
public const short GROUPSHAPE__WRAPDISTBOTTOM = 0x0387;
public const short GROUPSHAPE__REGROUPID = 0x0388;
public const short GROUPSHAPE__UNUSED906 = 0x038A;
public const short GROUPSHAPE__TOOLTIP = 0x038D;
public const short GROUPSHAPE__SCRIPT = 0x038E;
public const short GROUPSHAPE__POSH = 0x038F;
public const short GROUPSHAPE__POSRELH = 0x0390;
public const short GROUPSHAPE__POSV = 0x0391;
public const short GROUPSHAPE__POSRELV = 0x0392;
public const short GROUPSHAPE__HR_PCT = 0x0393;
public const short GROUPSHAPE__HR_ALIGN = 0x0394;
public const short GROUPSHAPE__HR_HEIGHT = 0x0395;
public const short GROUPSHAPE__HR_WIDTH = 0x0396;
public const short GROUPSHAPE__SCRIPTEXT = 0x0397;
public const short GROUPSHAPE__SCRIPTLANG = 0x0398;
public const short GROUPSHAPE__BORDERTOPCOLOR = 0x039B;
public const short GROUPSHAPE__BORDERLEFTCOLOR = 0x039C;
public const short GROUPSHAPE__BORDERBOTTOMCOLOR = 0x039D;
public const short GROUPSHAPE__BORDERRIGHTCOLOR = 0x039E;
public const short GROUPSHAPE__TABLEPROPERTIES = 0x039F;
public const short GROUPSHAPE__TABLEROWPROPERTIES = 0x03A0;
public const short GROUPSHAPE__WEBBOT = 0x03A5;
public const short GROUPSHAPE__METROBLOB = 0x03A9;
public const short GROUPSHAPE__ZORDER = 0x03AA;
public const short GROUPSHAPE__FLAGS = 0x03BF;
public const short GROUPSHAPE__EDITEDWRAP = 953;
public const short GROUPSHAPE__BEHINDDOCUMENT = 954;
public const short GROUPSHAPE__ONDBLCLICKNOTIFY = 955;
public const short GROUPSHAPE__ISBUTTON = 956;
public const short GROUPSHAPE__1DADJUSTMENT = 957;
public const short GROUPSHAPE__HIDDEN = 958;
public const short GROUPSHAPE__PRINT = 959;
#endregion
private static Hashtable properties;
/// <summary>
/// Inits the props.
/// </summary>
private static void InitProps()
{
if (properties == null)
{
properties = new Hashtable();
AddProp(TRANSFORM__ROTATION, GetData("transform.rotation"));
AddProp(PROTECTION__LOCKROTATION, GetData("protection.lockrotation"));
AddProp(PROTECTION__LOCKASPECTRATIO, GetData("protection.lockaspectratio"));
AddProp(PROTECTION__LOCKPOSITION, GetData("protection.lockposition"));
AddProp(PROTECTION__LOCKAGAINSTSELECT, GetData("protection.lockagainstselect"));
AddProp(PROTECTION__LOCKCROPPING, GetData("protection.lockcropping"));
AddProp(PROTECTION__LOCKVERTICES, GetData("protection.lockvertices"));
AddProp(PROTECTION__LOCKTEXT, GetData("protection.locktext"));
AddProp(PROTECTION__LOCKADJUSTHANDLES, GetData("protection.lockadjusthandles"));
AddProp(PROTECTION__LOCKAGAINSTGROUPING, GetData("protection.lockagainstgrouping", EscherPropertyMetaData.TYPE_bool));
AddProp(TEXT__TEXTID, GetData("text.textid"));
AddProp(TEXT__TEXTLEFT, GetData("text.textleft"));
AddProp(TEXT__TEXTTOP, GetData("text.texttop"));
AddProp(TEXT__TEXTRIGHT, GetData("text.textright"));
AddProp(TEXT__TEXTBOTTOM, GetData("text.textbottom"));
AddProp(TEXT__WRAPTEXT, GetData("text.wraptext"));
AddProp(TEXT__SCALETEXT, GetData("text.scaletext"));
AddProp(TEXT__ANCHORTEXT, GetData("text.anchortext"));
AddProp(TEXT__TEXTFLOW, GetData("text.textflow"));
AddProp(TEXT__FONTROTATION, GetData("text.fontrotation"));
AddProp(TEXT__IDOFNEXTSHAPE, GetData("text.idofnextshape"));
AddProp(TEXT__BIDIR, GetData("text.bidir"));
AddProp(TEXT__SINGLECLICKSELECTS, GetData("text.singleclickselects"));
AddProp(TEXT__USEHOSTMARGINS, GetData("text.usehostmargins"));
AddProp(TEXT__ROTATETEXTWITHSHAPE, GetData("text.rotatetextwithshape"));
AddProp(TEXT__SIZESHAPETOFITTEXT, GetData("text.sizeshapetofittext"));
AddProp(TEXT__SIZE_TEXT_TO_FIT_SHAPE, GetData("text.sizetexttofitshape", EscherPropertyMetaData.TYPE_bool));
AddProp(GEOTEXT__UNICODE, GetData("geotext.unicode"));
AddProp(GEOTEXT__RTFTEXT, GetData("geotext.rtftext"));
AddProp(GEOTEXT__ALIGNMENTONCURVE, GetData("geotext.alignmentoncurve"));
AddProp(GEOTEXT__DEFAULTPOINTSIZE, GetData("geotext.defaultpointsize"));
AddProp(GEOTEXT__TEXTSPACING, GetData("geotext.textspacing"));
AddProp(GEOTEXT__FONTFAMILYNAME, GetData("geotext.fontfamilyname"));
AddProp(GEOTEXT__REVERSEROWORDER, GetData("geotext.reverseroworder"));
AddProp(GEOTEXT__HASTEXTEFFECT, GetData("geotext.hastexteffect"));
AddProp(GEOTEXT__ROTATECHARACTERS, GetData("geotext.rotatecharacters"));
AddProp(GEOTEXT__KERNCHARACTERS, GetData("geotext.kerncharacters"));
AddProp(GEOTEXT__TIGHTORTRACK, GetData("geotext.tightortrack"));
AddProp(GEOTEXT__STRETCHTOFITSHAPE, GetData("geotext.stretchtofitshape"));
AddProp(GEOTEXT__CHARBOUNDINGBOX, GetData("geotext.charboundingbox"));
AddProp(GEOTEXT__SCALETEXTONPATH, GetData("geotext.scaletextonpath"));
AddProp(GEOTEXT__STRETCHCHARHEIGHT, GetData("geotext.stretchcharheight"));
AddProp(GEOTEXT__NOMEASUREALONGPATH, GetData("geotext.nomeasurealongpath"));
AddProp(GEOTEXT__BOLDFONT, GetData("geotext.boldfont"));
AddProp(GEOTEXT__ITALICFONT, GetData("geotext.italicfont"));
AddProp(GEOTEXT__UNDERLINEFONT, GetData("geotext.underlinefont"));
AddProp(GEOTEXT__SHADOWFONT, GetData("geotext.shadowfont"));
AddProp(GEOTEXT__SMALLCAPSFONT, GetData("geotext.smallcapsfont"));
AddProp(GEOTEXT__STRIKETHROUGHFONT, GetData("geotext.strikethroughfont"));
AddProp(BLIP__CROPFROMTOP, GetData("blip.cropfromtop"));
AddProp(BLIP__CROPFROMBOTTOM, GetData("blip.cropfrombottom"));
AddProp(BLIP__CROPFROMLEFT, GetData("blip.cropfromleft"));
AddProp(BLIP__CROPFROMRIGHT, GetData("blip.cropfromright"));
AddProp(BLIP__BLIPTODISPLAY, GetData("blip.bliptodisplay"));
AddProp(BLIP__BLIPFILENAME, GetData("blip.blipfilename"));
AddProp(BLIP__BLIPFLAGS, GetData("blip.blipflags"));
AddProp(BLIP__TRANSPARENTCOLOR, GetData("blip.transparentcolor"));
AddProp(BLIP__CONTRASTSetTING, GetData("blip.contrastSetting"));
AddProp(BLIP__BRIGHTNESSSetTING, GetData("blip.brightnessSetting"));
AddProp(BLIP__GAMMA, GetData("blip.gamma"));
AddProp(BLIP__PICTUREID, GetData("blip.pictureid"));
AddProp(BLIP__DOUBLEMOD, GetData("blip.doublemod"));
AddProp(BLIP__PICTUREFillMOD, GetData("blip.pictureFillmod"));
AddProp(BLIP__PICTURELINE, GetData("blip.pictureline"));
AddProp(BLIP__PRINTBLIP, GetData("blip.printblip"));
AddProp(BLIP__PRINTBLIPFILENAME, GetData("blip.printblipfilename"));
AddProp(BLIP__PRINTFLAGS, GetData("blip.printflags"));
AddProp(BLIP__NOHITTESTPICTURE, GetData("blip.nohittestpicture"));
AddProp(BLIP__PICTUREGRAY, GetData("blip.picturegray"));
AddProp(BLIP__PICTUREBILEVEL, GetData("blip.picturebilevel"));
AddProp(BLIP__PICTUREACTIVE, GetData("blip.pictureactive"));
AddProp(GEOMETRY__LEFT, GetData("geometry.left"));
AddProp(GEOMETRY__TOP, GetData("geometry.top"));
AddProp(GEOMETRY__RIGHT, GetData("geometry.right"));
AddProp(GEOMETRY__BOTTOM, GetData("geometry.bottom"));
AddProp(GEOMETRY__SHAPEPATH, GetData("geometry.shapepath", EscherPropertyMetaData.TYPE_SHAPEPATH));
AddProp(GEOMETRY__VERTICES, GetData("geometry.vertices", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GEOMETRY__SEGMENTINFO, GetData("geometry.segmentinfo", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GEOMETRY__ADJUSTVALUE, GetData("geometry.adjustvalue"));
AddProp(GEOMETRY__ADJUST2VALUE, GetData("geometry.adjust2value"));
AddProp(GEOMETRY__ADJUST3VALUE, GetData("geometry.adjust3value"));
AddProp(GEOMETRY__ADJUST4VALUE, GetData("geometry.adjust4value"));
AddProp(GEOMETRY__ADJUST5VALUE, GetData("geometry.adjust5value"));
AddProp(GEOMETRY__ADJUST6VALUE, GetData("geometry.adjust6value"));
AddProp(GEOMETRY__ADJUST7VALUE, GetData("geometry.adjust7value"));
AddProp(GEOMETRY__ADJUST8VALUE, GetData("geometry.adjust8value"));
AddProp(GEOMETRY__ADJUST9VALUE, GetData("geometry.adjust9value"));
AddProp(GEOMETRY__ADJUST10VALUE, GetData("geometry.adjust10value"));
AddProp(GEOMETRY__SHADOWok, GetData("geometry.shadowOK"));
AddProp(GEOMETRY__3DOK, GetData("geometry.3dok"));
AddProp(GEOMETRY__LINEOK, GetData("geometry.lineok"));
AddProp(GEOMETRY__GEOTEXTOK, GetData("geometry.geotextok"));
AddProp(GEOMETRY__FILLSHADESHAPEOK, GetData("geometry.fillshadeshapeok"));
AddProp(GEOMETRY__FILLOK, GetData("geometry.fillok", EscherPropertyMetaData.TYPE_bool));
AddProp(FILL__FILLTYPE, GetData("fill.filltype"));
AddProp(FILL__FILLCOLOR, GetData("fill.fillcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(FILL__FILLOPACITY, GetData("fill.fillopacity"));
AddProp(FILL__FILLBACKCOLOR, GetData("fill.fillbackcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(FILL__BACKOPACITY, GetData("fill.backopacity"));
AddProp(FILL__CRMOD, GetData("fill.crmod"));
AddProp(FILL__PATTERNTEXTURE, GetData("fill.patterntexture"));
AddProp(FILL__BLIPFILENAME, GetData("fill.blipfilename"));
AddProp(FILL__BLIPFLAGS, GetData("fill.blipflags"));
AddProp(FILL__WIDTH, GetData("fill.width"));
AddProp(FILL__HEIGHT, GetData("fill.height"));
AddProp(FILL__ANGLE, GetData("fill.angle"));
AddProp(FILL__FOCUS, GetData("fill.focus"));
AddProp(FILL__TOLEFT, GetData("fill.toleft"));
AddProp(FILL__TOTOP, GetData("fill.totop"));
AddProp(FILL__TORIGHT, GetData("fill.toright"));
AddProp(FILL__TOBOTTOM, GetData("fill.tobottom"));
AddProp(FILL__RECTLEFT, GetData("fill.rectleft"));
AddProp(FILL__RECTTOP, GetData("fill.recttop"));
AddProp(FILL__RECTRIGHT, GetData("fill.rectright"));
AddProp(FILL__RECTBOTTOM, GetData("fill.rectbottom"));
AddProp(FILL__DZTYPE, GetData("fill.dztype"));
AddProp(FILL__SHADEPRESet, GetData("fill.shadepReset"));
AddProp(FILL__SHADECOLORS, GetData("fill.shadecolors", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(FILL__ORIGINX, GetData("fill.originx"));
AddProp(FILL__ORIGINY, GetData("fill.originy"));
AddProp(FILL__SHAPEORIGINX, GetData("fill.shapeoriginx"));
AddProp(FILL__SHAPEORIGINY, GetData("fill.shapeoriginy"));
AddProp(FILL__SHADETYPE, GetData("fill.shadetype"));
AddProp(FILL__FILLED, GetData("fill.filled"));
AddProp(FILL__HITTESTFILL, GetData("fill.hittestfill"));
AddProp(FILL__SHAPE, GetData("fill.shape"));
AddProp(FILL__USERECT, GetData("fill.userect"));
AddProp(FILL__NOFILLHITTEST, GetData("fill.nofillhittest", EscherPropertyMetaData.TYPE_bool));
AddProp(LINESTYLE__COLOR, GetData("linestyle.color", EscherPropertyMetaData.TYPE_RGB));
AddProp(LINESTYLE__OPACITY, GetData("linestyle.opacity"));
AddProp(LINESTYLE__BACKCOLOR, GetData("linestyle.backcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(LINESTYLE__CRMOD, GetData("linestyle.crmod"));
AddProp(LINESTYLE__LINETYPE, GetData("linestyle.linetype"));
AddProp(LINESTYLE__FILLBLIP, GetData("linestyle.fillblip"));
AddProp(LINESTYLE__FILLBLIPNAME, GetData("linestyle.fillblipname"));
AddProp(LINESTYLE__FILLBLIPFLAGS, GetData("linestyle.fillblipflags"));
AddProp(LINESTYLE__FILLWIDTH, GetData("linestyle.fillwidth"));
AddProp(LINESTYLE__FILLHEIGHT, GetData("linestyle.fillheight"));
AddProp(LINESTYLE__FILLDZTYPE, GetData("linestyle.filldztype"));
AddProp(LINESTYLE__LINEWIDTH, GetData("linestyle.linewidth"));
AddProp(LINESTYLE__LINEMITERLIMIT, GetData("linestyle.linemiterlimit"));
AddProp(LINESTYLE__LINESTYLE, GetData("linestyle.linestyle"));
AddProp(LINESTYLE__LINEDASHING, GetData("linestyle.linedashing"));
AddProp(LINESTYLE__LINEDASHSTYLE, GetData("linestyle.linedashstyle", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(LINESTYLE__LINESTARTARROWHEAD, GetData("linestyle.linestartarrowhead"));
AddProp(LINESTYLE__LINEENDARROWHEAD, GetData("linestyle.lineendarrowhead"));
AddProp(LINESTYLE__LINESTARTARROWWIDTH, GetData("linestyle.linestartarrowwidth"));
AddProp(LINESTYLE__LINEESTARTARROWLength, GetData("linestyle.lineestartarrowlength"));
AddProp(LINESTYLE__LINEENDARROWWIDTH, GetData("linestyle.lineendarrowwidth"));
AddProp(LINESTYLE__LINEENDARROWLength, GetData("linestyle.lineendarrowlength"));
AddProp(LINESTYLE__LINEJOINSTYLE, GetData("linestyle.linejoinstyle"));
AddProp(LINESTYLE__LINEENDCAPSTYLE, GetData("linestyle.lineendcapstyle"));
AddProp(LINESTYLE__ARROWHEADSOK, GetData("linestyle.arrowheadsok"));
AddProp(LINESTYLE__ANYLINE, GetData("linestyle.anyline"));
AddProp(LINESTYLE__HITLINETEST, GetData("linestyle.hitlinetest"));
AddProp(LINESTYLE__LINEFILLSHAPE, GetData("linestyle.linefillshape"));
AddProp(LINESTYLE__NOLINEDRAWDASH, GetData("linestyle.nolinedrawdash", EscherPropertyMetaData.TYPE_bool));
AddProp(SHADOWSTYLE__TYPE, GetData("shadowstyle.type"));
AddProp(SHADOWSTYLE__COLOR, GetData("shadowstyle.color", EscherPropertyMetaData.TYPE_RGB));
AddProp(SHADOWSTYLE__HIGHLIGHT, GetData("shadowstyle.highlight"));
AddProp(SHADOWSTYLE__CRMOD, GetData("shadowstyle.crmod"));
AddProp(SHADOWSTYLE__OPACITY, GetData("shadowstyle.opacity"));
AddProp(SHADOWSTYLE__OFFSetX, GetData("shadowstyle.offsetx"));
AddProp(SHADOWSTYLE__OFFSetY, GetData("shadowstyle.offsety"));
AddProp(SHADOWSTYLE__SECONDOFFSetX, GetData("shadowstyle.secondoffsetx"));
AddProp(SHADOWSTYLE__SECONDOFFSetY, GetData("shadowstyle.secondoffsety"));
AddProp(SHADOWSTYLE__SCALEXTOX, GetData("shadowstyle.scalextox"));
AddProp(SHADOWSTYLE__SCALEYTOX, GetData("shadowstyle.scaleytox"));
AddProp(SHADOWSTYLE__SCALEXTOY, GetData("shadowstyle.scalextoy"));
AddProp(SHADOWSTYLE__SCALEYTOY, GetData("shadowstyle.scaleytoy"));
AddProp(SHADOWSTYLE__PERSPECTIVEX, GetData("shadowstyle.perspectivex"));
AddProp(SHADOWSTYLE__PERSPECTIVEY, GetData("shadowstyle.perspectivey"));
AddProp(SHADOWSTYLE__WEIGHT, GetData("shadowstyle.weight"));
AddProp(SHADOWSTYLE__ORIGINX, GetData("shadowstyle.originx"));
AddProp(SHADOWSTYLE__ORIGINY, GetData("shadowstyle.originy"));
AddProp(SHADOWSTYLE__SHADOW, GetData("shadowstyle.shadow"));
AddProp(SHADOWSTYLE__SHADOWOBSURED, GetData("shadowstyle.shadowobsured"));
AddProp(PERSPECTIVE__TYPE, GetData("perspective.type"));
AddProp(PERSPECTIVE__OFFSetX, GetData("perspective.offsetx"));
AddProp(PERSPECTIVE__OFFSetY, GetData("perspective.offsety"));
AddProp(PERSPECTIVE__SCALEXTOX, GetData("perspective.scalextox"));
AddProp(PERSPECTIVE__SCALEYTOX, GetData("perspective.scaleytox"));
AddProp(PERSPECTIVE__SCALEXTOY, GetData("perspective.scalextoy"));
AddProp(PERSPECTIVE__SCALEYTOY, GetData("perspective.scaleytoy"));
AddProp(PERSPECTIVE__PERSPECTIVEX, GetData("perspective.perspectivex"));
AddProp(PERSPECTIVE__PERSPECTIVEY, GetData("perspective.perspectivey"));
AddProp(PERSPECTIVE__WEIGHT, GetData("perspective.weight"));
AddProp(PERSPECTIVE__ORIGINX, GetData("perspective.originx"));
AddProp(PERSPECTIVE__ORIGINY, GetData("perspective.originy"));
AddProp(PERSPECTIVE__PERSPECTIVEON, GetData("perspective.perspectiveon"));
AddProp(THREED__SPECULARAMOUNT, GetData("3d.specularamount"));
AddProp(THREED__DIFFUSEAMOUNT, GetData("3d.diffuseamount"));
AddProp(THREED__SHININESS, GetData("3d.shininess"));
AddProp(THREED__EDGetHICKNESS, GetData("3d.edGethickness"));
AddProp(THREED__EXTRUDEFORWARD, GetData("3d.extrudeforward"));
AddProp(THREED__EXTRUDEBACKWARD, GetData("3d.extrudebackward"));
AddProp(THREED__EXTRUDEPLANE, GetData("3d.extrudeplane"));
AddProp(THREED__EXTRUSIONCOLOR, GetData("3d.extrusioncolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(THREED__CRMOD, GetData("3d.crmod"));
AddProp(THREED__3DEFFECT, GetData("3d.3deffect"));
AddProp(THREED__METALLIC, GetData("3d.metallic"));
AddProp(THREED__USEEXTRUSIONCOLOR, GetData("3d.useextrusioncolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(THREED__LIGHTFACE, GetData("3d.lightface"));
AddProp(THREEDSTYLE__YROTATIONANGLE, GetData("3dstyle.yrotationangle"));
AddProp(THREEDSTYLE__XROTATIONANGLE, GetData("3dstyle.xrotationangle"));
AddProp(THREEDSTYLE__ROTATIONAXISX, GetData("3dstyle.rotationaxisx"));
AddProp(THREEDSTYLE__ROTATIONAXISY, GetData("3dstyle.rotationaxisy"));
AddProp(THREEDSTYLE__ROTATIONAXISZ, GetData("3dstyle.rotationaxisz"));
AddProp(THREEDSTYLE__ROTATIONANGLE, GetData("3dstyle.rotationangle"));
AddProp(THREEDSTYLE__ROTATIONCENTERX, GetData("3dstyle.rotationcenterx"));
AddProp(THREEDSTYLE__ROTATIONCENTERY, GetData("3dstyle.rotationcentery"));
AddProp(THREEDSTYLE__ROTATIONCENTERZ, GetData("3dstyle.rotationcenterz"));
AddProp(THREEDSTYLE__RENDERMODE, GetData("3dstyle.rendermode"));
AddProp(THREEDSTYLE__TOLERANCE, GetData("3dstyle.tolerance"));
AddProp(THREEDSTYLE__XVIEWPOINT, GetData("3dstyle.xviewpoint"));
AddProp(THREEDSTYLE__YVIEWPOINT, GetData("3dstyle.yviewpoint"));
AddProp(THREEDSTYLE__ZVIEWPOINT, GetData("3dstyle.zviewpoint"));
AddProp(THREEDSTYLE__ORIGINX, GetData("3dstyle.originx"));
AddProp(THREEDSTYLE__ORIGINY, GetData("3dstyle.originy"));
AddProp(THREEDSTYLE__SKEWANGLE, GetData("3dstyle.skewangle"));
AddProp(THREEDSTYLE__SKEWAMOUNT, GetData("3dstyle.skewamount"));
AddProp(THREEDSTYLE__AMBIENTINTENSITY, GetData("3dstyle.ambientintensity"));
AddProp(THREEDSTYLE__KEYX, GetData("3dstyle.keyx"));
AddProp(THREEDSTYLE__KEYY, GetData("3dstyle.keyy"));
AddProp(THREEDSTYLE__KEYZ, GetData("3dstyle.keyz"));
AddProp(THREEDSTYLE__KEYINTENSITY, GetData("3dstyle.keyintensity"));
AddProp(THREEDSTYLE__FillX, GetData("3dstyle.fillx"));
AddProp(THREEDSTYLE__FillY, GetData("3dstyle.filly"));
AddProp(THREEDSTYLE__FillZ, GetData("3dstyle.fillz"));
AddProp(THREEDSTYLE__FillINTENSITY, GetData("3dstyle.fillintensity"));
AddProp(THREEDSTYLE__CONSTRAINROTATION, GetData("3dstyle.constrainrotation"));
AddProp(THREEDSTYLE__ROTATIONCENTERAUTO, GetData("3dstyle.rotationcenterauto"));
AddProp(THREEDSTYLE__PARALLEL, GetData("3dstyle.parallel"));
AddProp(THREEDSTYLE__KEYHARSH, GetData("3dstyle.keyharsh"));
AddProp(THREEDSTYLE__FillHARSH, GetData("3dstyle.fillharsh"));
AddProp(SHAPE__MASTER, GetData("shape.master"));
AddProp(SHAPE__CONNECTORSTYLE, GetData("shape.connectorstyle"));
AddProp(SHAPE__BLACKANDWHITESetTINGS, GetData("shape.blackandwhiteSettings"));
AddProp(SHAPE__WMODEPUREBW, GetData("shape.wmodepurebw"));
AddProp(SHAPE__WMODEBW, GetData("shape.wmodebw"));
AddProp(SHAPE__OLEICON, GetData("shape.oleicon"));
AddProp(SHAPE__PREFERRELATIVERESIZE, GetData("shape.preferrelativeresize"));
AddProp(SHAPE__LOCKSHAPETYPE, GetData("shape.lockshapetype"));
AddProp(SHAPE__DELETEATTACHEDOBJECT, GetData("shape.deleteattachedobject"));
AddProp(SHAPE__BACKGROUNDSHAPE, GetData("shape.backgroundshape"));
AddProp(CALLOUT__CALLOUTTYPE, GetData("callout.callouttype"));
AddProp(CALLOUT__XYCALLOUTGAP, GetData("callout.xycalloutgap"));
AddProp(CALLOUT__CALLOUTANGLE, GetData("callout.calloutangle"));
AddProp(CALLOUT__CALLOUTDROPTYPE, GetData("callout.calloutdroptype"));
AddProp(CALLOUT__CALLOUTDROPSPECIFIED, GetData("callout.calloutdropspecified"));
AddProp(CALLOUT__CALLOUTLENGTHSPECIFIED, GetData("callout.calloutlengthspecified"));
AddProp(CALLOUT__ISCALLOUT, GetData("callout.iscallout"));
AddProp(CALLOUT__CALLOUTACCENTBAR, GetData("callout.calloutaccentbar"));
AddProp(CALLOUT__CALLOUTTEXTBORDER, GetData("callout.callouttextborder"));
AddProp(CALLOUT__CALLOUTMINUSX, GetData("callout.calloutminusx"));
AddProp(CALLOUT__CALLOUTMINUSY, GetData("callout.calloutminusy"));
AddProp(CALLOUT__DROPAUTO, GetData("callout.dropauto"));
AddProp(CALLOUT__LENGTHSPECIFIED, GetData("callout.lengthspecified"));
AddProp(GROUPSHAPE__SHAPENAME, GetData("groupshape.shapename"));
AddProp(GROUPSHAPE__DESCRIPTION, GetData("groupshape.description"));
AddProp(GROUPSHAPE__HYPERLINK, GetData("groupshape.hyperlink"));
AddProp(GROUPSHAPE__WRAPPOLYGONVERTICES, GetData("groupshape.wrappolygonvertices", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GROUPSHAPE__WRAPDISTLEFT, GetData("groupshape.wrapdistleft"));
AddProp(GROUPSHAPE__WRAPDISTTOP, GetData("groupshape.wrapdisttop"));
AddProp(GROUPSHAPE__WRAPDISTRIGHT, GetData("groupshape.wrapdistright"));
AddProp(GROUPSHAPE__WRAPDISTBOTTOM, GetData("groupshape.wrapdistbottom"));
AddProp(GROUPSHAPE__REGROUPID, GetData("groupshape.regroupid"));
AddProp(GROUPSHAPE__EDITEDWRAP, GetData("groupshape.editedwrap"));
AddProp(GROUPSHAPE__BEHINDDOCUMENT, GetData("groupshape.behinddocument"));
AddProp(GROUPSHAPE__ONDBLCLICKNOTIFY, GetData("groupshape.ondblclicknotify"));
AddProp(GROUPSHAPE__ISBUTTON, GetData("groupshape.isbutton"));
AddProp(GROUPSHAPE__1DADJUSTMENT, GetData("groupshape.1dadjustment"));
AddProp(GROUPSHAPE__HIDDEN, GetData("groupshape.hidden"));
AddProp(GROUPSHAPE__PRINT, GetData("groupshape.print", EscherPropertyMetaData.TYPE_bool));
}
}
/// <summary>
/// Adds the prop.
/// </summary>
/// <param name="s">The s.</param>
/// <param name="data">The data.</param>
private static void AddProp(int s, EscherPropertyMetaData data)
{
properties[(short)s]= data;
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="propName">Name of the prop.</param>
/// <param name="type">The type.</param>
/// <returns></returns>
private static EscherPropertyMetaData GetData(String propName, byte type)
{
return new EscherPropertyMetaData(propName, type);
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="propName">Name of the prop.</param>
/// <returns></returns>
private static EscherPropertyMetaData GetData(String propName)
{
return new EscherPropertyMetaData(propName);
}
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <param name="propertyId">The property id.</param>
/// <returns></returns>
public static String GetPropertyName(short propertyId)
{
InitProps();
EscherPropertyMetaData o = (EscherPropertyMetaData)properties[propertyId];
return o == null ? "unknown" : o.Description;
}
/// <summary>
/// Gets the type of the property.
/// </summary>
/// <param name="propertyId">The property id.</param>
/// <returns></returns>
public static byte GetPropertyType(short propertyId)
{
InitProps();
EscherPropertyMetaData escherPropertyMetaData = (EscherPropertyMetaData)properties[propertyId];
return escherPropertyMetaData == null ? (byte)0 : escherPropertyMetaData.Type;
}
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : TimeRangeTest.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using Itenso.TimePeriod;
using Xunit;
namespace Itenso.TimePeriodTests
{
// ------------------------------------------------------------------------
public sealed class TimeRangeTest : TestUnitBase
{
// ----------------------------------------------------------------------
public TimeRangeTest()
{
start = ClockProxy.Clock.Now;
end = start.Add( duration );
testData = new TimeRangePeriodRelationTestData( start, end, offset );
} // TimeRangeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void AnytimeTest()
{
Assert.Equal( TimeRange.Anytime.Start, TimeSpec.MinPeriodDate );
Assert.Equal( TimeRange.Anytime.End, TimeSpec.MaxPeriodDate );
Assert.True( TimeRange.Anytime.IsAnytime );
Assert.True( TimeRange.Anytime.IsReadOnly );
Assert.False( TimeRange.Anytime.HasStart );
Assert.False( TimeRange.Anytime.HasEnd );
} // AnytimeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void DefaultTest()
{
TimeRange timeRange = new TimeRange();
Assert.NotEqual( timeRange, TimeRange.Anytime );
Assert.Equal(PeriodRelation.ExactMatch, timeRange.GetRelation( TimeRange.Anytime ));
Assert.True( timeRange.IsAnytime );
Assert.False( timeRange.IsMoment );
Assert.False( timeRange.IsReadOnly );
} // DefaultTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void MomentTest()
{
DateTime moment = ClockProxy.Clock.Now;
TimeRange timeRange = new TimeRange( moment );
Assert.Equal( timeRange.Start, moment );
Assert.Equal( timeRange.End, moment );
Assert.True( timeRange.IsMoment );
} // MomentTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void MomentByPeriodTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now, TimeSpan.Zero );
Assert.True( timeRange.IsMoment );
} // MomentByPeriodTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void NonMomentTest()
{
DateTime moment = ClockProxy.Clock.Now;
TimeRange timeRange = new TimeRange( moment, moment.AddMilliseconds( 1 ) );
Assert.False( timeRange.IsMoment );
} // NonMomentTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void HasStartTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now, TimeSpec.MaxPeriodDate );
Assert.True( timeRange.HasStart );
Assert.False( timeRange.HasEnd );
} // HasStartTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void HasEndTest()
{
TimeRange timeRange = new TimeRange( TimeSpec.MinPeriodDate, ClockProxy.Clock.Now );
Assert.False( timeRange.HasStart );
Assert.True( timeRange.HasEnd );
} // HasEndTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartEndTest()
{
TimeRange timeRange = new TimeRange( start, end );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.End, end );
Assert.Equal( timeRange.Duration, duration );
Assert.False( timeRange.IsAnytime );
Assert.False( timeRange.IsMoment );
Assert.False( timeRange.IsReadOnly );
} // StartEndTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartEndSwapTest()
{
TimeRange timeRange = new TimeRange( end, start );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.Duration, duration );
Assert.Equal( timeRange.End, end );
} // StartEndSwapTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartTimeSpanTest()
{
TimeRange timeRange = new TimeRange( start, duration );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.Duration, duration );
Assert.Equal( timeRange.End, end );
Assert.False( timeRange.IsAnytime );
Assert.False( timeRange.IsMoment );
Assert.False( timeRange.IsReadOnly );
} // StartTimeSpanTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartNegativeTimeSpanTest()
{
TimeSpan timeSpan = Duration.Millisecond.Negate();
TimeRange timeRange = new TimeRange( start, timeSpan );
Assert.Equal( timeRange.Start, start.Add( timeSpan ) );
Assert.Equal( timeRange.Duration, timeSpan.Negate() );
Assert.Equal( timeRange.End, start );
Assert.False( timeRange.IsAnytime );
Assert.False( timeRange.IsMoment );
Assert.False( timeRange.IsReadOnly );
} // StartNegativeTimeSpanTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void CopyConstructorTest()
{
TimeRange source = new TimeRange( start, start.AddHours( 1 ), true );
TimeRange copy = new TimeRange( source );
Assert.Equal( source.Start, copy.Start );
Assert.Equal( source.End, copy.End );
Assert.Equal( source.IsReadOnly, copy.IsReadOnly );
Assert.Equal( source, copy );
} // CopyConstructorTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartTest()
{
TimeRange timeRange = new TimeRange( start, start.AddHours( 1 ) );
Assert.Equal( timeRange.Start, start );
DateTime changedStart = start.AddHours( -1 );
timeRange.Start = changedStart;
Assert.Equal( timeRange.Start, changedStart );
} // StartTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartReadOnlyTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now, ClockProxy.Clock.Now.AddHours( 1 ), true );
Assert.NotNull(Assert.Throws<NotSupportedException>(() =>
timeRange.Start = timeRange.Start.AddHours( -1 )));
} // StartReadOnlyTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void StartOutOfRangeTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now, ClockProxy.Clock.Now.AddHours( 1 ) );
Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() =>
timeRange.Start = timeRange.Start.AddHours( 2 )));
} // StartOutOfRangeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void EndTest()
{
TimeRange timeRange = new TimeRange( end.AddHours( -1 ), end );
Assert.Equal( timeRange.End, end );
DateTime changedEnd = end.AddHours( 1 );
timeRange.End = changedEnd;
Assert.Equal( timeRange.End, changedEnd );
} // EndTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void EndReadOnlyTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now.AddHours( -1 ), ClockProxy.Clock.Now, true );
Assert.NotNull(Assert.Throws<NotSupportedException>(() =>
timeRange.End = timeRange.End.AddHours( 1 )));
} // EndReadOnlyTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void EndOutOfRangeTest()
{
TimeRange timeRange = new TimeRange( ClockProxy.Clock.Now.AddHours( -1 ), ClockProxy.Clock.Now );
Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() =>
timeRange.End = timeRange.End.AddHours( -2 )));
} // EndOutOfRangeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void SetupTest()
{
TimeRange timeRange1 = new TimeRange();
timeRange1.Setup( TimeSpec.MinPeriodDate, TimeSpec.MinPeriodDate );
Assert.Equal( timeRange1.Start, TimeSpec.MinPeriodDate );
Assert.Equal( timeRange1.End, TimeSpec.MinPeriodDate );
TimeRange timeRange2 = new TimeRange();
timeRange2.Setup( TimeSpec.MinPeriodDate, TimeSpec.MaxPeriodDate );
Assert.Equal( timeRange2.Start, TimeSpec.MinPeriodDate );
Assert.Equal( timeRange2.End, TimeSpec.MaxPeriodDate );
TimeRange timeRange3 = new TimeRange();
timeRange3.Setup( TimeSpec.MaxPeriodDate, TimeSpec.MinPeriodDate );
Assert.Equal( timeRange3.Start, TimeSpec.MinPeriodDate );
Assert.Equal( timeRange3.End, TimeSpec.MaxPeriodDate );
} // SetupTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void HasInsideDateTimeTest()
{
TimeRange timeRange = new TimeRange( start, end );
Assert.Equal( timeRange.End, end );
// start
Assert.False( timeRange.HasInside( start.AddMilliseconds( -1 ) ) );
Assert.True( timeRange.HasInside( start ) );
Assert.True( timeRange.HasInside( start.AddMilliseconds( 1 ) ) );
// end
Assert.True( timeRange.HasInside( end.AddMilliseconds( -1 ) ) );
Assert.True( timeRange.HasInside( end ) );
Assert.False( timeRange.HasInside( end.AddMilliseconds( 1 ) ) );
} // HasInsideDateTimeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void HasInsidePeriodTest()
{
TimeRange timeRange = new TimeRange( start, end );
Assert.Equal( timeRange.End, end );
// before
TimeRange before1 = new TimeRange( start.AddHours( -2 ), start.AddHours( -1 ) );
Assert.False( timeRange.HasInside( before1 ) );
TimeRange before2 = new TimeRange( start.AddMilliseconds( -1 ), end );
Assert.False( timeRange.HasInside( before2 ) );
TimeRange before3 = new TimeRange( start.AddMilliseconds( -1 ), start );
Assert.False( timeRange.HasInside( before3 ) );
// after
TimeRange after1 = new TimeRange( end.AddHours( 1 ), end.AddHours( 2 ) );
Assert.False( timeRange.HasInside( after1 ) );
TimeRange after2 = new TimeRange( start, end.AddMilliseconds( 1 ) );
Assert.False( timeRange.HasInside( after2 ) );
TimeRange after3 = new TimeRange( end, end.AddMilliseconds( 1 ) );
Assert.False( timeRange.HasInside( after3 ) );
// inside
Assert.True( timeRange.HasInside( timeRange ) );
TimeRange inside1 = new TimeRange( start.AddMilliseconds( 1 ), end );
Assert.True( timeRange.HasInside( inside1 ) );
TimeRange inside2 = new TimeRange( start.AddMilliseconds( 1 ), end.AddMilliseconds( -1 ) );
Assert.True( timeRange.HasInside( inside2 ) );
TimeRange inside3 = new TimeRange( start, end.AddMilliseconds( -1 ) );
Assert.True( timeRange.HasInside( inside3 ) );
} // HasInsidePeriodTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void CopyTest()
{
TimeRange readOnlyTimeRange = new TimeRange( start, end );
Assert.Equal( readOnlyTimeRange.Copy( TimeSpan.Zero ), readOnlyTimeRange );
TimeRange timeRange = new TimeRange( start, end );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.End, end );
ITimeRange noMoveTimeRange = timeRange.Copy( TimeSpan.Zero );
Assert.Equal( noMoveTimeRange.Start, start );
Assert.Equal( noMoveTimeRange.End, end );
Assert.Equal( noMoveTimeRange.Duration, duration );
TimeSpan forwardOffset = new TimeSpan( 2, 30, 15 );
ITimeRange forwardTimeRange = timeRange.Copy( forwardOffset );
Assert.Equal( forwardTimeRange.Start, start.Add( forwardOffset ) );
Assert.Equal( forwardTimeRange.End, end.Add( forwardOffset ) );
TimeSpan backwardOffset = new TimeSpan( -1, 10, 30 );
ITimeRange backwardTimeRange = timeRange.Copy( backwardOffset );
Assert.Equal( backwardTimeRange.Start, start.Add( backwardOffset ) );
Assert.Equal( backwardTimeRange.End, end.Add( backwardOffset ) );
} // CopyTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void MoveTest()
{
TimeRange timeRangeMoveZero = new TimeRange( start, end );
timeRangeMoveZero.Move( TimeSpan.Zero );
Assert.Equal( timeRangeMoveZero.Start, start );
Assert.Equal( timeRangeMoveZero.End, end );
Assert.Equal( timeRangeMoveZero.Duration, duration );
TimeRange timeRangeMoveForward = new TimeRange( start, end );
TimeSpan forwardOffset = new TimeSpan( 2, 30, 15 );
timeRangeMoveForward.Move( forwardOffset );
Assert.Equal( timeRangeMoveForward.Start, start.Add( forwardOffset ) );
Assert.Equal( timeRangeMoveForward.End, end.Add( forwardOffset ) );
TimeRange timeRangeMoveBackward = new TimeRange( start, end );
TimeSpan backwardOffset = new TimeSpan( -1, 10, 30 );
timeRangeMoveBackward.Move( backwardOffset );
Assert.Equal( timeRangeMoveBackward.Start, start.Add( backwardOffset ) );
Assert.Equal( timeRangeMoveBackward.End, end.Add( backwardOffset ) );
} // MoveTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ExpandStartToTest()
{
TimeRange timeRange = new TimeRange( start, end );
timeRange.ExpandStartTo( start.AddMilliseconds( 1 ) );
Assert.Equal( timeRange.Start, start );
timeRange.ExpandStartTo( start.AddMinutes( -1 ) );
Assert.Equal( timeRange.Start, start.AddMinutes( -1 ) );
} // ExpandStartToTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ExpandEndToTest()
{
TimeRange timeRange = new TimeRange( start, end );
timeRange.ExpandEndTo( end.AddMilliseconds( -1 ) );
Assert.Equal( timeRange.End, end );
timeRange.ExpandEndTo( end.AddMinutes( 1 ) );
Assert.Equal( timeRange.End, end.AddMinutes( 1 ) );
} // ExpandEndToTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ExpandToDateTimeTest()
{
TimeRange timeRange = new TimeRange( start, end );
// start
timeRange.ExpandTo( start.AddMilliseconds( 1 ) );
Assert.Equal( timeRange.Start, start );
timeRange.ExpandTo( start.AddMinutes( -1 ) );
Assert.Equal( timeRange.Start, start.AddMinutes( -1 ) );
// end
timeRange.ExpandTo( end.AddMilliseconds( -1 ) );
Assert.Equal( timeRange.End, end );
timeRange.ExpandTo( end.AddMinutes( 1 ) );
Assert.Equal( timeRange.End, end.AddMinutes( 1 ) );
} // ExpandToDateTimeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ExpandToPeriodTest()
{
TimeRange timeRange = new TimeRange( start, end );
// no expansion
timeRange.ExpandTo( new TimeRange( start.AddMilliseconds( 1 ), end.AddMilliseconds( -1 ) ) );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.End, end );
// start
DateTime changedStart = start.AddMinutes( -1 );
timeRange.ExpandTo( new TimeRange( changedStart, end ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, end );
// end
DateTime changedEnd = end.AddMinutes( 1 );
timeRange.ExpandTo( new TimeRange( changedStart, changedEnd ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, changedEnd );
// start/end
changedStart = changedStart.AddMinutes( -1 );
changedEnd = changedEnd.AddMinutes( 1 );
timeRange.ExpandTo( new TimeRange( changedStart, changedEnd ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, changedEnd );
} // ExpandToPeriodTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ShrinkStartToTest()
{
TimeRange timeRange = new TimeRange( start, end );
timeRange.ShrinkStartTo( start.AddMilliseconds( -1 ) );
Assert.Equal( timeRange.Start, start );
timeRange.ShrinkStartTo( start.AddMinutes( 1 ) );
Assert.Equal( timeRange.Start, start.AddMinutes( 1 ) );
} // ShrinkStartToTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ShrinkEndToTest()
{
TimeRange timeRange = new TimeRange( start, end );
timeRange.ShrinkEndTo( end.AddMilliseconds( 1 ) );
Assert.Equal( timeRange.End, end );
timeRange.ShrinkEndTo( end.AddMinutes( -1 ) );
Assert.Equal( timeRange.End, end.AddMinutes( -1 ) );
} // ShrinkEndToTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ShrinkToTest()
{
TimeRange timeRange = new TimeRange( start, end );
// no shrink
timeRange.ShrinkTo( new TimeRange( start.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) ) );
Assert.Equal( timeRange.Start, start );
Assert.Equal( timeRange.End, end );
// start
DateTime changedStart = start.AddMinutes( 1 );
timeRange.ShrinkTo( new TimeRange( changedStart, end ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, end );
// end
DateTime changedEnd = end.AddMinutes( -1 );
timeRange.ShrinkTo( new TimeRange( changedStart, changedEnd ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, changedEnd );
// start/end
changedStart = changedStart.AddMinutes( 1 );
changedEnd = changedEnd.AddMinutes( -1 );
timeRange.ShrinkTo( new TimeRange( changedStart, changedEnd ) );
Assert.Equal( timeRange.Start, changedStart );
Assert.Equal( timeRange.End, changedEnd );
} // ShrinkToTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void IsSamePeriodTest()
{
TimeRange timeRange1 = new TimeRange( start, end );
TimeRange timeRange2 = new TimeRange( start, end );
Assert.True( timeRange1.IsSamePeriod( timeRange1 ) );
Assert.True( timeRange2.IsSamePeriod( timeRange2 ) );
Assert.True( timeRange1.IsSamePeriod( timeRange2 ) );
Assert.True( timeRange2.IsSamePeriod( timeRange1 ) );
Assert.False( timeRange1.IsSamePeriod( TimeRange.Anytime ) );
Assert.False( timeRange2.IsSamePeriod( TimeRange.Anytime ) );
timeRange1.Move( new TimeSpan( 1 ) );
Assert.False( timeRange1.IsSamePeriod( timeRange2 ) );
Assert.False( timeRange2.IsSamePeriod( timeRange1 ) );
timeRange1.Move( new TimeSpan( -1 ) );
Assert.True( timeRange1.IsSamePeriod( timeRange2 ) );
Assert.True( timeRange2.IsSamePeriod( timeRange1 ) );
} // IsSamePeriodTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void HasInsideTest()
{
Assert.False( testData.Reference.HasInside( testData.Before ) );
Assert.False( testData.Reference.HasInside( testData.StartTouching ) );
Assert.False( testData.Reference.HasInside( testData.StartInside ) );
Assert.False( testData.Reference.HasInside( testData.InsideStartTouching ) );
Assert.True( testData.Reference.HasInside( testData.EnclosingStartTouching ) );
Assert.True( testData.Reference.HasInside( testData.Enclosing ) );
Assert.True( testData.Reference.HasInside( testData.EnclosingEndTouching ) );
Assert.True( testData.Reference.HasInside( testData.ExactMatch ) );
Assert.False( testData.Reference.HasInside( testData.Inside ) );
Assert.False( testData.Reference.HasInside( testData.InsideEndTouching ) );
Assert.False( testData.Reference.HasInside( testData.EndInside ) );
Assert.False( testData.Reference.HasInside( testData.EndTouching ) );
Assert.False( testData.Reference.HasInside( testData.After ) );
} // HasInsideTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void IntersectsWithTest()
{
Assert.False( testData.Reference.IntersectsWith( testData.Before ) );
Assert.True( testData.Reference.IntersectsWith( testData.StartTouching ) );
Assert.True( testData.Reference.IntersectsWith( testData.StartInside ) );
Assert.True( testData.Reference.IntersectsWith( testData.InsideStartTouching ) );
Assert.True( testData.Reference.IntersectsWith( testData.EnclosingStartTouching ) );
Assert.True( testData.Reference.IntersectsWith( testData.Enclosing ) );
Assert.True( testData.Reference.IntersectsWith( testData.EnclosingEndTouching ) );
Assert.True( testData.Reference.IntersectsWith( testData.ExactMatch ) );
Assert.True( testData.Reference.IntersectsWith( testData.Inside ) );
Assert.True( testData.Reference.IntersectsWith( testData.InsideEndTouching ) );
Assert.True( testData.Reference.IntersectsWith( testData.EndInside ) );
Assert.True( testData.Reference.IntersectsWith( testData.EndTouching ) );
Assert.False( testData.Reference.IntersectsWith( testData.After ) );
} // IntersectsWithTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void OverlapsWithTest()
{
Assert.False( testData.Reference.OverlapsWith( testData.Before ) );
Assert.False( testData.Reference.OverlapsWith( testData.StartTouching ) );
Assert.True( testData.Reference.OverlapsWith( testData.StartInside ) );
Assert.True( testData.Reference.OverlapsWith( testData.InsideStartTouching ) );
Assert.True( testData.Reference.OverlapsWith( testData.EnclosingStartTouching ) );
Assert.True( testData.Reference.OverlapsWith( testData.Enclosing ) );
Assert.True( testData.Reference.OverlapsWith( testData.EnclosingEndTouching ) );
Assert.True( testData.Reference.OverlapsWith( testData.ExactMatch ) );
Assert.True( testData.Reference.OverlapsWith( testData.Inside ) );
Assert.True( testData.Reference.OverlapsWith( testData.InsideEndTouching ) );
Assert.True( testData.Reference.OverlapsWith( testData.EndInside ) );
Assert.False( testData.Reference.OverlapsWith( testData.EndTouching ) );
Assert.False( testData.Reference.OverlapsWith( testData.After ) );
} // OverlapsWithTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void IntersectsWithDateTimeTest()
{
TimeRange timeRange = new TimeRange( start, end );
// before
TimeRange before1 = new TimeRange( start.AddHours( -2 ), start.AddHours( -1 ) );
Assert.False( timeRange.IntersectsWith( before1 ) );
TimeRange before2 = new TimeRange( start.AddMilliseconds( -1 ), start );
Assert.True( timeRange.IntersectsWith( before2 ) );
TimeRange before3 = new TimeRange( start.AddMilliseconds( -1 ), start.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( before3 ) );
// after
TimeRange after1 = new TimeRange( end.AddHours( 1 ), end.AddHours( 2 ) );
Assert.False( timeRange.IntersectsWith( after1 ) );
TimeRange after2 = new TimeRange( end, end.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( after2 ) );
TimeRange after3 = new TimeRange( end.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( after3 ) );
// intersect
Assert.True( timeRange.IntersectsWith( timeRange ) );
TimeRange itersect1 = new TimeRange( start.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( itersect1 ) );
TimeRange itersect2 = new TimeRange( start.AddMilliseconds( -1 ), start.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( itersect2 ) );
TimeRange itersect3 = new TimeRange( end.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) );
Assert.True( timeRange.IntersectsWith( itersect3 ) );
} // IntersectsWithDateTimeTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void GetIntersectionTest()
{
TimeRange readOnlyTimeRange = new TimeRange( start, end );
Assert.Equal( readOnlyTimeRange.GetIntersection( readOnlyTimeRange ), new TimeRange( readOnlyTimeRange ) );
TimeRange timeRange = new TimeRange( start, end );
// before
ITimeRange before1 = timeRange.GetIntersection( new TimeRange( start.AddHours( -2 ), start.AddHours( -1 ) ) );
Assert.Null(before1);
ITimeRange before2 = timeRange.GetIntersection( new TimeRange( start.AddMilliseconds( -1 ), start ) );
Assert.Equal( before2, new TimeRange( start ) );
ITimeRange before3 = timeRange.GetIntersection( new TimeRange( start.AddMilliseconds( -1 ), start.AddMilliseconds( 1 ) ) );
Assert.Equal( before3, new TimeRange( start, start.AddMilliseconds( 1 ) ) );
// after
ITimeRange after1 = timeRange.GetIntersection( new TimeRange( end.AddHours( 1 ), end.AddHours( 2 ) ) );
Assert.Null(after1);
ITimeRange after2 = timeRange.GetIntersection( new TimeRange( end, end.AddMilliseconds( 1 ) ) );
Assert.Equal( after2, new TimeRange( end ) );
ITimeRange after3 = timeRange.GetIntersection( new TimeRange( end.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) ) );
Assert.Equal( after3, new TimeRange( end.AddMilliseconds( -1 ), end ) );
// intersect
Assert.Equal( timeRange.GetIntersection( timeRange ), timeRange );
ITimeRange itersect1 = timeRange.GetIntersection( new TimeRange( start.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) ) );
Assert.Equal( itersect1, timeRange );
ITimeRange itersect2 = timeRange.GetIntersection( new TimeRange( start.AddMilliseconds( 1 ), end.AddMilliseconds( -1 ) ) );
Assert.Equal( itersect2, new TimeRange( start.AddMilliseconds( 1 ), end.AddMilliseconds( -1 ) ) );
} // GetIntersectionTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void GetRelationTest()
{
Assert.Equal(PeriodRelation.Before, testData.Reference.GetRelation( testData.Before ));
Assert.Equal(PeriodRelation.StartTouching, testData.Reference.GetRelation( testData.StartTouching ));
Assert.Equal(PeriodRelation.StartInside, testData.Reference.GetRelation( testData.StartInside ));
Assert.Equal(PeriodRelation.InsideStartTouching, testData.Reference.GetRelation( testData.InsideStartTouching ));
Assert.Equal(PeriodRelation.Enclosing, testData.Reference.GetRelation( testData.Enclosing ));
Assert.Equal(PeriodRelation.ExactMatch, testData.Reference.GetRelation( testData.ExactMatch ));
Assert.Equal(PeriodRelation.Inside, testData.Reference.GetRelation( testData.Inside ));
Assert.Equal(PeriodRelation.InsideEndTouching, testData.Reference.GetRelation( testData.InsideEndTouching ));
Assert.Equal(PeriodRelation.EndInside, testData.Reference.GetRelation( testData.EndInside ));
Assert.Equal(PeriodRelation.EndTouching, testData.Reference.GetRelation( testData.EndTouching ));
Assert.Equal(PeriodRelation.After, testData.Reference.GetRelation( testData.After ));
// reference
Assert.Equal( testData.Reference.Start, start );
Assert.Equal( testData.Reference.End, end );
Assert.True( testData.Reference.IsReadOnly );
// after
Assert.True( testData.After.IsReadOnly );
Assert.True( testData.After.Start < start );
Assert.True( testData.After.End < start );
Assert.False( testData.Reference.HasInside( testData.After.Start ) );
Assert.False( testData.Reference.HasInside( testData.After.End ) );
Assert.Equal(PeriodRelation.After, testData.Reference.GetRelation( testData.After ));
// start touching
Assert.True( testData.StartTouching.IsReadOnly );
Assert.True( testData.StartTouching.Start < start );
Assert.Equal( testData.StartTouching.End, start );
Assert.False( testData.Reference.HasInside( testData.StartTouching.Start ) );
Assert.True( testData.Reference.HasInside( testData.StartTouching.End ) );
Assert.Equal(PeriodRelation.StartTouching, testData.Reference.GetRelation( testData.StartTouching ));
// start inside
Assert.True( testData.StartInside.IsReadOnly );
Assert.True( testData.StartInside.Start < start );
Assert.True( testData.StartInside.End < end );
Assert.True( testData.StartInside.End > start );
Assert.False( testData.Reference.HasInside( testData.StartInside.Start ) );
Assert.True( testData.Reference.HasInside( testData.StartInside.End ) );
Assert.Equal(PeriodRelation.StartInside, testData.Reference.GetRelation( testData.StartInside ));
// inside start touching
Assert.True( testData.InsideStartTouching.IsReadOnly );
Assert.Equal( testData.InsideStartTouching.Start, start );
Assert.True( testData.InsideStartTouching.End > end );
Assert.True( testData.Reference.HasInside( testData.InsideStartTouching.Start ) );
Assert.False( testData.Reference.HasInside( testData.InsideStartTouching.End ) );
Assert.Equal(PeriodRelation.InsideStartTouching, testData.Reference.GetRelation( testData.InsideStartTouching ));
// enclosing start touching
Assert.True( testData.EnclosingStartTouching.IsReadOnly );
Assert.Equal( testData.EnclosingStartTouching.Start, start );
Assert.True( testData.EnclosingStartTouching.End < end );
Assert.True( testData.Reference.HasInside( testData.EnclosingStartTouching.Start ) );
Assert.True( testData.Reference.HasInside( testData.EnclosingStartTouching.End ) );
Assert.Equal(PeriodRelation.EnclosingStartTouching, testData.Reference.GetRelation( testData.EnclosingStartTouching ));
// enclosing
Assert.True( testData.Enclosing.IsReadOnly );
Assert.True( testData.Enclosing.Start > start );
Assert.True( testData.Enclosing.End < end );
Assert.True( testData.Reference.HasInside( testData.Enclosing.Start ) );
Assert.True( testData.Reference.HasInside( testData.Enclosing.End ) );
Assert.Equal(PeriodRelation.Enclosing, testData.Reference.GetRelation( testData.Enclosing ));
// enclosing end touching
Assert.True( testData.EnclosingEndTouching.IsReadOnly );
Assert.True( testData.EnclosingEndTouching.Start > start );
Assert.Equal( testData.EnclosingEndTouching.End, end );
Assert.True( testData.Reference.HasInside( testData.EnclosingEndTouching.Start ) );
Assert.True( testData.Reference.HasInside( testData.EnclosingEndTouching.End ) );
Assert.Equal(PeriodRelation.EnclosingEndTouching, testData.Reference.GetRelation( testData.EnclosingEndTouching ));
// exact match
Assert.True( testData.ExactMatch.IsReadOnly );
Assert.Equal( testData.ExactMatch.Start, start );
Assert.Equal( testData.ExactMatch.End, end );
Assert.True( testData.Reference.Equals( testData.ExactMatch ) );
Assert.True( testData.Reference.HasInside( testData.ExactMatch.Start ) );
Assert.True( testData.Reference.HasInside( testData.ExactMatch.End ) );
Assert.Equal(PeriodRelation.ExactMatch, testData.Reference.GetRelation( testData.ExactMatch ));
// inside
Assert.True( testData.Inside.IsReadOnly );
Assert.True( testData.Inside.Start < start );
Assert.True( testData.Inside.End > end );
Assert.False( testData.Reference.HasInside( testData.Inside.Start ) );
Assert.False( testData.Reference.HasInside( testData.Inside.End ) );
Assert.Equal(PeriodRelation.Inside, testData.Reference.GetRelation( testData.Inside ));
// inside end touching
Assert.True( testData.InsideEndTouching.IsReadOnly );
Assert.True( testData.InsideEndTouching.Start < start );
Assert.Equal( testData.InsideEndTouching.End, end );
Assert.False( testData.Reference.HasInside( testData.InsideEndTouching.Start ) );
Assert.True( testData.Reference.HasInside( testData.InsideEndTouching.End ) );
Assert.Equal(PeriodRelation.InsideEndTouching, testData.Reference.GetRelation( testData.InsideEndTouching ));
// end inside
Assert.True( testData.EndInside.IsReadOnly );
Assert.True( testData.EndInside.Start > start );
Assert.True( testData.EndInside.Start < end );
Assert.True( testData.EndInside.End > end );
Assert.True( testData.Reference.HasInside( testData.EndInside.Start ) );
Assert.False( testData.Reference.HasInside( testData.EndInside.End ) );
Assert.Equal(PeriodRelation.EndInside, testData.Reference.GetRelation( testData.EndInside ));
// end touching
Assert.True( testData.EndTouching.IsReadOnly );
Assert.Equal( testData.EndTouching.Start, end );
Assert.True( testData.EndTouching.End > end );
Assert.True( testData.Reference.HasInside( testData.EndTouching.Start ) );
Assert.False( testData.Reference.HasInside( testData.EndTouching.End ) );
Assert.Equal(PeriodRelation.EndTouching, testData.Reference.GetRelation( testData.EndTouching ));
// before
Assert.True( testData.Before.IsReadOnly );
Assert.True( testData.Before.Start > testData.Reference.End );
Assert.True( testData.Before.End > testData.Reference.End );
Assert.False( testData.Reference.HasInside( testData.Before.Start ) );
Assert.False( testData.Reference.HasInside( testData.Before.End ) );
Assert.Equal(PeriodRelation.Before, testData.Reference.GetRelation( testData.Before ));
} // GetRelationTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void ResetTest()
{
TimeRange timeRange = new TimeRange( start, end );
Assert.Equal( timeRange.Start, start );
Assert.True( timeRange.HasStart );
Assert.Equal( timeRange.End, end );
Assert.True( timeRange.HasEnd );
timeRange.Reset();
Assert.Equal( timeRange.Start, TimeSpec.MinPeriodDate );
Assert.False( timeRange.HasStart );
Assert.Equal( timeRange.End, TimeSpec.MaxPeriodDate );
Assert.False( timeRange.HasEnd );
} // ResetTest
// ----------------------------------------------------------------------
[Trait("Category", "TimeRange")]
[Fact]
public void EqualsTest()
{
TimeRange timeRange1 = new TimeRange( start, end );
TimeRange timeRange2 = new TimeRange( start, end );
Assert.True( timeRange1.Equals( timeRange2 ) );
TimeRange timeRange3 = new TimeRange( start.AddMilliseconds( -1 ), end.AddMilliseconds( 1 ) );
Assert.False( timeRange1.Equals( timeRange3 ) );
} // EqualsTest
// ----------------------------------------------------------------------
// members
private readonly TimeSpan duration = Duration.Hour;
private readonly DateTime start;
private readonly DateTime end;
private readonly TimeSpan offset = Duration.Millisecond;
private readonly TimeRangePeriodRelationTestData testData;
} // class TimeRangeTest
} // namespace Itenso.TimePeriodTests
// -- EOF -------------------------------------------------------------------
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Franson.BlueTools;
using Franson.Protocols.Obex;
using Franson.Protocols.Obex.ObjectPush;
namespace ObjectPushSample
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.ListBox deviceList;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button discoverBtn;
private System.Windows.Forms.Button sendBtn;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.StatusBarPanel statusBarPanel;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.StatusBarPanel copyPanel;
private Manager m_manager = null;
private Network m_network = null;
private ObexObjectPush m_objectPush = null;
// these objects should be class global to prevent them from being taken by the garbage collector
private RemoteService m_serviceCurrent = null;
private Stream m_streamCurrent = null;
private System.Windows.Forms.Label informLabel;
// this is to control that the stream is'nt closed before all transfers is done.
private int m_intTransfers = 0;
// this is status booleans
private bool m_boolAborted = false;
private bool m_boolDenied = false;
private bool m_boolUnrecoverableError = false;
private bool m_boolTimeout = false;
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// catch all BlueTools exceptions - like e.g. license expired
try
{
// get your trial license or buy BlueTools at franson.com
Franson.BlueTools.License license = new Franson.BlueTools.License();
license.LicenseKey = "WoK6IL944A9CIONQRXaYUjpRJRiuHYFYWrT7";
// get bluetools manager
m_manager = Manager.GetManager();
// get first network dongle - bluetools 1.0 only supports one!
m_network = m_manager.Networks[0];
// marshal events into this class thread.
m_manager.Parent = this;
// update statusbar panel with name of currently used stack
switch (Manager.StackID)
{
case StackID.STACK_MICROSOFT:
{
statusBarPanel.Text = "Microsoft Stack";
break;
}
case StackID.STACK_WIDCOMM:
{
statusBarPanel.Text = "Widcomm Stack";
break;
}
default:
{
statusBarPanel.Text = "Unknown stack";
break;
}
}
}
catch (Exception exc)
{
// display BlueTools errors here
MessageBox.Show(exc.Message);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
// BlueTools manager must be disposed, otherwise you can't exit application!
Manager.GetManager().Dispose();
if (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.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.deviceList = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.discoverBtn = new System.Windows.Forms.Button();
this.sendBtn = new System.Windows.Forms.Button();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.statusBar = new System.Windows.Forms.StatusBar();
this.statusBarPanel = new System.Windows.Forms.StatusBarPanel();
this.copyPanel = new System.Windows.Forms.StatusBarPanel();
this.informLabel = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.copyPanel)).BeginInit();
this.SuspendLayout();
//
// openFileDialog
//
this.openFileDialog.Multiselect = true;
//
// deviceList
//
this.deviceList.Location = new System.Drawing.Point(16, 32);
this.deviceList.Name = "deviceList";
this.deviceList.Size = new System.Drawing.Size(160, 160);
this.deviceList.TabIndex = 0;
this.deviceList.SelectedIndexChanged += new System.EventHandler(this.deviceList_SelectedIndexChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Devices";
//
// discoverBtn
//
this.discoverBtn.Location = new System.Drawing.Point(16, 216);
this.discoverBtn.Name = "discoverBtn";
this.discoverBtn.TabIndex = 2;
this.discoverBtn.Text = "Discover";
this.discoverBtn.Click += new System.EventHandler(this.discoverBtn_Click);
//
// sendBtn
//
this.sendBtn.Enabled = false;
this.sendBtn.Location = new System.Drawing.Point(104, 216);
this.sendBtn.Name = "sendBtn";
this.sendBtn.TabIndex = 3;
this.sendBtn.Text = "Push";
this.sendBtn.Click += new System.EventHandler(this.sendBtn_Click);
//
// progressBar
//
this.progressBar.Location = new System.Drawing.Point(16, 200);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(160, 8);
this.progressBar.TabIndex = 4;
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 295);
this.statusBar.Name = "statusBar";
this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.statusBarPanel,
this.copyPanel});
this.statusBar.ShowPanels = true;
this.statusBar.Size = new System.Drawing.Size(192, 22);
this.statusBar.SizingGrip = false;
this.statusBar.TabIndex = 5;
//
// statusBarPanel
//
this.statusBarPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
this.statusBarPanel.Width = 182;
//
// copyPanel
//
this.copyPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
this.copyPanel.Width = 10;
//
// informLabel
//
this.informLabel.Location = new System.Drawing.Point(16, 248);
this.informLabel.Name = "informLabel";
this.informLabel.Size = new System.Drawing.Size(160, 40);
this.informLabel.TabIndex = 6;
this.informLabel.Text = "Click Discover to find nearby Bluetooth devices.";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(192, 317);
this.Controls.Add(this.informLabel);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.sendBtn);
this.Controls.Add(this.discoverBtn);
this.Controls.Add(this.label1);
this.Controls.Add(this.deviceList);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "MainForm";
this.Text = "ObjectPush Sample";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.copyPanel)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
private void discoverBtn_Click(object sender, System.EventArgs e)
{
m_network.DeviceDiscovered += new BlueToolsEventHandler(m_network_DeviceDiscovered);
m_network.DeviceDiscoveryStarted += new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted);
m_network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted);
// Start looking for devices on the network
// Use Network.DiscoverDevices() if you don't want to use events.
m_network.DiscoverDevicesAsync();
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// if currentService is available, close the stream
if (m_serviceCurrent != null)
{
if (m_streamCurrent != null)
{
m_streamCurrent.Close();
}
// set these objects to null to mark them for GC
m_streamCurrent = null;
m_serviceCurrent = null;
}
// dispose objects - also makes sure that Manager are disposed.
Dispose();
}
private void m_network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs)
{
// add every device found
RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery;
deviceList.Items.Add(device);
}
private void m_network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs)
{
// disable the Discover button when we begin device discovery
discoverBtn.Enabled = false;
// disable the send button since you can't send while device discovering
sendBtn.Enabled = false;
// disable the device list while searching for devices
deviceList.Enabled = false;
// inform the user what we're doing
informLabel.Text = "Scanning for devices...";
}
private void m_network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs)
{
Device[] devices = (Device[])((DiscoveryEventArgs)eventArgs).Discovery;
// enable Discover button again since device discovery is complete
discoverBtn.Enabled = true;
// enable the device list again
deviceList.Enabled = true;
// inform the user what to do
informLabel.Text = "Click on the device you wish to push a file to.";
m_network.DeviceDiscovered -= new BlueToolsEventHandler(m_network_DeviceDiscovered);
m_network.DeviceDiscoveryStarted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted);
m_network.DeviceDiscoveryCompleted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted);
}
private void deviceList_SelectedIndexChanged(object sender, System.EventArgs e)
{
// get selected item (a remote device)
RemoteDevice selectedDevice = (RemoteDevice)deviceList.SelectedItem;
selectedDevice.ServiceDiscoveryStarted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryStarted);
selectedDevice.ServiceDiscoveryCompleted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryCompleted);
// detect Object Push service (OPP) on this device
deviceList.Enabled = false;
selectedDevice.DiscoverServicesAsync(ServiceType.OBEXObjectPush);
}
private void selectedDevice_ServiceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs)
{
// when beginning to search for services - disable the Discover button
// we shouldn't scan for devices while attempting to scan for services.
discoverBtn.Enabled = false;
sendBtn.Enabled = false;
}
private void selectedDevice_ServiceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs)
{
// when service discovery is complete - let us re-enable the discover button.
// It is okay to try to update the device list
discoverBtn.Enabled = true;
// re-enable the device list
deviceList.Enabled = true;
// set error event handler for the device
RemoteDevice device = (RemoteDevice)sender;
device.Error += new BlueToolsEventHandler(device_Error);
// get all services found
Service[] services = (Service[])((DiscoveryEventArgs)eventArgs).Discovery;
// if we have a service since before, close the stream
if (m_streamCurrent != null)
{
m_streamCurrent.Close();
m_streamCurrent = null;
}
// and remove the service
if (m_serviceCurrent != null)
{
m_serviceCurrent = null;
}
// if we found a new service...
if (services.Length > 0)
{
// ...get OPP service object
m_serviceCurrent = (RemoteService)services[0];
try
{
// create an ObexObjectPush object connected to the ServiceStream
m_objectPush = new ObexObjectPush(1000); // wait forever
// marshal event to this class thread
m_objectPush.Parent = this;
// setup event handlers
m_objectPush.Error += new ObexEventHandler(m_objectPush_Error);
m_objectPush.PutFileBegin += new ObexEventHandler(m_objectPush_PutFileBegin);
m_objectPush.PutFileProgress += new ObexEventHandler(m_objectPush_PutFileProgress);
m_objectPush.PutFileEnd += new ObexEventHandler(m_objectPush_PutFileEnd);
m_objectPush.DisconnectEnd += new ObexEventHandler(m_objectPush_DisconnectEnd);
// enable the push button
sendBtn.Enabled = true;
// inform the user of the next step
informLabel.Text = "Click on Push to select file(s) to push to device.";
}
catch (Exception exc)
{
sendBtn.Enabled = false;
MessageBox.Show(exc.Message);
}
}
}
private void sendBtn_Click(object sender, System.EventArgs e)
{
if (sendBtn.Text.Equals("Push"))
{
try
{
// if we have a service to send to
if (m_serviceCurrent != null)
{
// make sure ObexObjectPush is initialized and select file to push to device
if (m_objectPush != null && openFileDialog.ShowDialog() == DialogResult.OK)
{
foreach(string filename in openFileDialog.FileNames)
{
m_streamCurrent = m_serviceCurrent.Stream;
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
m_objectPush.PushFileAsync(fileStream, Path.GetFileName(filename), m_streamCurrent);
//Increment number of transfers.
m_intTransfers++;
}
}
}
}
catch (Exception)
{
// disable Push button if there was an error
sendBtn.Enabled = false;
informLabel.Text = "Failed to get a socket.\nClick on the device you wish to push a file to.";
}
}
else
{
// if button text isn't Send it will be Cancel -
// if user click it, we tell ObexObjectPush that we want to abort
m_objectPush.Abort();
// only need to press cancel once - won't help you to press it more
sendBtn.Enabled = false;
}
}
private void m_objectPush_PutFileProgress(object sender, ObexEventArgs eventArgs)
{
ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs;
// if size isn't unknown
if (copyArgs.Size != -1)
{
// if max value on progressbar isn't set, set it
if (copyArgs.Size != progressBar.Maximum)
{
progressBar.Maximum = (int)copyArgs.Size;
}
// set position of file copy
progressBar.Value = (int)copyArgs.Position;
// update copy panel to show progress in kb
copyPanel.Text = Convert.ToString(copyArgs.Position / 1024) + " kb / " + Convert.ToString(copyArgs.Size / 1024) + " kb";
}
else
{
// update copy panel to show progress in kb
copyPanel.Text = Convert.ToString(copyArgs.Position / 1024) + " kb / ? kb";
}
}
private void m_objectPush_PutFileEnd(object sender, ObexEventArgs eventArgs)
{
// when finished copying...
// ...close file stream
ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs;
// Close Stream opened by ObexObjectPush
copyArgs.Stream.Close();
// ...enable discover button
discoverBtn.Enabled = true;
// ...change text caption back to Send
sendBtn.Text = "Push";
// set progressbar position back to beginning - just for show, doesn't really matter
progressBar.Value = 0;
// set copy panel to nothing to make it invisible again - it's auto-resizing :)
copyPanel.Text = "";
// inform the user what is happening
if (m_boolAborted)
{
// ...if transfer was aborted..
informLabel.Text = "Push aborted.\nClick on Push to select file(s) to push to device.";
}
else if (m_boolDenied)
{
// .. if push was denied by receiving device
informLabel.Text = "Push denied by device.\nClick on Push to select file(s) to push to device.";
}
else if (m_boolTimeout)
{
// ..if stream was lost because of a timeout
informLabel.Text = "Stream lost to device due to device not responding within timeout interval." +
"\nClick on the device you wish to push file(s) to.";
}
else if (m_boolUnrecoverableError)
{
// ..if stream was lost
informLabel.Text = "Stream lost to device.\nClick on the device you wish to push file(s) to.";
}
else
{
// ...transfer completed
informLabel.Text = "File(s) sent to device.\nClick on Push to select file(s) to push to device.";
}
// enable device list again when finished
deviceList.Enabled = true;
// we enable the Send button again if it was disabled when it was a Cancel button
sendBtn.Enabled = true;
}
private void m_objectPush_PutFileBegin(object sender, ObexEventArgs eventArgs)
{
// this transfer hasn't been aborted (yet!)
m_boolAborted = false;
// this transfer hasn't been denied (yet!)
m_boolDenied = false;
// there hasn't been any unrecoverable error (yet!)
m_boolUnrecoverableError = false;
// no timeout (yet!)
m_boolTimeout = false;
// while copying, disable the discover button
discoverBtn.Enabled = false;
// change the text so the user can Cancel the transfer
sendBtn.Text = "Cancel";
// inform the user what is happening
informLabel.Text = "Sending file(s) to device...";
// disable device list while pushing file
deviceList.Enabled = false;
}
private void m_objectPush_Error(object sender, ObexEventArgs eventArgs)
{
ObexErrorEventArgs errorArgs = (ObexErrorEventArgs)eventArgs;
if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.Timeout)
{
m_boolTimeout = true;
// the Push button
sendBtn.Enabled = false;
// the device list
deviceList.Enabled = true;
}
else if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.StreamError)
{
// since the stream was lost, re-enable the UI
// the Push button
sendBtn.Enabled = false;
// the device list
deviceList.Enabled = true;
// this error can't be recovered from
m_boolUnrecoverableError = true;
// show this error in a box - it's pretty serious
MessageBox.Show(errorArgs.Message);
}
else
{
// if the error is transfer was aborted, set boolean so we can display this to user
if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.Aborted ||
errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SecurityAbort)
{
m_boolAborted = true;
}
// some devices return Forbidden when canceling (like Sony Ericsson phones) so let's tell
// user what really happened
if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SendDenied)
{
m_boolDenied = true;
}
}
}
private void device_Error(object sender, BlueToolsEventArgs eventArgs)
{
Franson.BlueTools.ErrorEventArgs errorArgs = (Franson.BlueTools.ErrorEventArgs)eventArgs;
// show bluetools errors in boxes - they are serious, can't use obex without bluetools in this sample
MessageBox.Show(errorArgs.Message);
}
private void m_objectPush_DisconnectEnd(object sender, ObexEventArgs e)
{
if (m_streamCurrent != null)
{
// Count down disconnections
m_intTransfers--;
// When we have had same number of disconnections as transfers we are done and can safely close the stream.
if(m_intTransfers == 0)
{
m_streamCurrent.Close();
}
}
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
namespace Quartz.Util
{
/// <summary>
/// This is an utility class used to parse the properties.
/// </summary>
/// <author> James House</author>
/// <author>Marko Lahma (.NET)</author>
public class PropertiesParser
{
internal readonly NameValueCollection props;
/// <summary>
/// Gets the underlying properties.
/// </summary>
/// <value>The underlying properties.</value>
public virtual NameValueCollection UnderlyingProperties
{
get { return props; }
}
/// <summary>
/// Initializes a new instance of the <see cref="PropertiesParser"/> class.
/// </summary>
/// <param name="props">The props.</param>
public PropertiesParser(NameValueCollection props)
{
this.props = props;
}
/// <summary>
/// Gets the string property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual string GetStringProperty(string name)
{
string val = props.Get(name);
if (val == null)
{
return null;
}
return val.Trim();
}
/// <summary>
/// Gets the string property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual string GetStringProperty(string name, string defaultValue)
{
string val = props[name] ?? defaultValue;
if (val == null)
{
return defaultValue;
}
val = val.Trim();
if (val.Length == 0)
{
return defaultValue;
}
return val;
}
/// <summary>
/// Gets the string array property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual IList<string> GetStringArrayProperty(string name)
{
return GetStringArrayProperty(name, null);
}
/// <summary>
/// Gets the string array property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual IList<string> GetStringArrayProperty(string name, string[] defaultValue)
{
string vals = GetStringProperty(name);
if (vals == null)
{
return defaultValue;
}
string[] items = vals.Split(',');
List<string> strs = new List<string>(items.Length);
try
{
strs.AddRange(items.Select(s => s.Trim()));
return strs;
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// Gets the boolean property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual bool GetBooleanProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
return false;
}
return val.ToUpper(CultureInfo.InvariantCulture).Equals("TRUE");
}
/// <summary>
/// Gets the boolean property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">if set to <c>true</c> [defaultValue].</param>
/// <returns></returns>
public virtual bool GetBooleanProperty(string name, bool defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
return val.ToUpper(CultureInfo.InvariantCulture).Equals("TRUE");
}
/// <summary>
/// Gets the byte property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual byte GetByteProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Byte.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the byte property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual byte GetByteProperty(string name, byte defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
try
{
return Byte.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the char property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual char GetCharProperty(string name)
{
string param = GetStringProperty(name);
if (param == null)
{
return '\x0000';
}
if (param.Length == 0)
{
return '\x0000';
}
return param[0];
}
/// <summary>
/// Gets the char property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual char GetCharProperty(string name, char defaultValue)
{
string param = GetStringProperty(name);
if (param == null)
{
return defaultValue;
}
if (param.Length == 0)
{
return defaultValue;
}
return param[0];
}
/// <summary>
/// Gets the double property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual double GetDoubleProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Double.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the double property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual double GetDoubleProperty(string name, double defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
try
{
return Double.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the float property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual float GetFloatProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Single.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the float property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual float GetFloatProperty(string name, float defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
try
{
return Single.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the int property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual int GetIntProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Int32.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the int property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual int GetIntProperty(string name, int defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
try
{
return Int32.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the int array property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual IList<int> GetIntArrayProperty(string name)
{
return GetIntArrayProperty(name, null);
}
/// <summary>
/// Gets the int array property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual IList<int> GetIntArrayProperty(string name, IList<int> defaultValue)
{
string vals = GetStringProperty(name);
if (vals == null)
{
return defaultValue;
}
if (!vals.Trim().Equals(""))
{
string[] stok = vals.Split(',');
List<int> ints = new List<int>();
try
{
foreach (string s in stok)
{
try
{
ints.Add(Int32.Parse(s, CultureInfo.InvariantCulture));
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", vals));
}
}
return ints;
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
/// <summary>
/// Gets the long property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual long GetLongProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Int64.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the long property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="def">The def.</param>
/// <returns></returns>
public virtual long GetLongProperty(string name, long def)
{
string val = GetStringProperty(name);
if (val == null)
{
return def;
}
try
{
return Int64.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the TimeSpan property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="def">The def.</param>
/// <returns></returns>
public virtual TimeSpan GetTimeSpanProperty(string name, TimeSpan def)
{
string val = GetStringProperty(name);
if (val == null)
{
return def;
}
try
{
return TimeSpan.FromMilliseconds(Int64.Parse(val, CultureInfo.InvariantCulture));
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the short property.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public virtual short GetShortProperty(string name)
{
string val = GetStringProperty(name);
if (val == null)
{
throw new FormatException(" null string");
}
try
{
return Int16.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the short property.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public virtual short GetShortProperty(string name, short defaultValue)
{
string val = GetStringProperty(name);
if (val == null)
{
return defaultValue;
}
try
{
return Int16.Parse(val, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException(string.Format(CultureInfo.InvariantCulture, " '{0}'", val));
}
}
/// <summary>
/// Gets the property groups.
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <returns></returns>
public virtual IList<string> GetPropertyGroups(string prefix)
{
var groups = new Collection.HashSet<string>();
if (!prefix.EndsWith("."))
{
prefix += ".";
}
foreach (string key in props.Keys)
{
if (key.StartsWith(prefix))
{
string groupName = key.Substring(prefix.Length, (key.IndexOf('.', prefix.Length)) - (prefix.Length));
groups.Add(groupName);
}
}
return new List<string>(groups);
}
/// <summary>
/// Gets the property group.
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <returns></returns>
public virtual NameValueCollection GetPropertyGroup(string prefix)
{
return GetPropertyGroup(prefix, false);
}
/// <summary>
/// Gets the property group.
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <param name="stripPrefix">if set to <c>true</c> [strip prefix].</param>
/// <returns></returns>
public virtual NameValueCollection GetPropertyGroup(string prefix, bool stripPrefix)
{
return GetPropertyGroup(prefix, stripPrefix, null);
}
/// <summary>
/// Get all properties that start with the given prefix.
/// </summary>
/// <param name="prefix">The prefix for which to search. If it does not end in a "." then one will be added to it for search purposes.</param>
/// <param name="stripPrefix">Whether to strip off the given <paramref name="prefix" /> in the result's keys.</param>
/// <param name="excludedPrefixes">Optional array of fully qualified prefixes to exclude. For example if <see paramref="prefix" /> is "a.b.c", then <see paramref="excludedPrefixes" /> might be "a.b.c.ignore".</param>
/// <returns>Group of <see cref="NameValueCollection" /> that start with the given prefix, optionally have that prefix removed, and do not include properties that start with one of the given excluded prefixes.</returns>
public virtual NameValueCollection GetPropertyGroup(string prefix, bool stripPrefix, string[] excludedPrefixes)
{
NameValueCollection group = new NameValueCollection();
if (!prefix.EndsWith("."))
{
prefix += ".";
}
foreach (string key in props.Keys)
{
if (key.StartsWith(prefix))
{
bool exclude = false;
if (excludedPrefixes != null)
{
for (int i = 0; (i < excludedPrefixes.Length) && (exclude == false); i++)
{
exclude = key.StartsWith(excludedPrefixes[i]);
}
}
if (exclude == false)
{
string value = GetStringProperty(key, "");
if (stripPrefix)
{
group[key.Substring(prefix.Length)] = value;
}
else
{
group[key] = value;
}
}
}
}
return group;
}
/// <summary>
/// Reads the properties from assembly (embedded resource).
/// </summary>
/// <param name="resourceName">The file name to read resources from.</param>
/// <returns></returns>
public static PropertiesParser ReadFromEmbeddedAssemblyResource(string resourceName)
{
return ReadFromStream(typeof(IScheduler).Assembly.GetManifestResourceStream(resourceName));
}
/// <summary>
/// Reads the properties from file system.
/// </summary>
/// <param name="fileName">The file name to read resources from.</param>
/// <returns></returns>
public static PropertiesParser ReadFromFileResource(string fileName)
{
return ReadFromStream(File.OpenRead(fileName));
}
private static PropertiesParser ReadFromStream(Stream stream)
{
NameValueCollection props = new NameValueCollection();
using (StreamReader sr = new StreamReader(stream))
{
string line;
while ((line = sr.ReadLine()) != null)
{
line = line.TrimStart();
if (line.StartsWith("#"))
{
// comment line
continue;
}
if (line.StartsWith("!END"))
{
// special end condition
break;
}
string[] lineItems = line.Split(new char[] { '=' }, 2);
if (lineItems.Length == 2)
{
props[lineItems[0].Trim()] = lineItems[1].Trim();
}
}
}
return new PropertiesParser(props);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E07_Country_Child (editable child object).<br/>
/// This is a generated base class of <see cref="E07_Country_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class E07_Country_Child : BusinessBase<E07_Country_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int country_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name");
/// <summary>
/// Gets or sets the Regions Child Name.
/// </summary>
/// <value>The Regions Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E07_Country_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E07_Country_Child"/> object.</returns>
internal static E07_Country_Child NewE07_Country_Child()
{
return DataPortal.CreateChild<E07_Country_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="E07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E07_Country_Child"/> object.</returns>
internal static E07_Country_Child GetE07_Country_Child(SafeDataReader dr)
{
E07_Country_Child obj = new E07_Country_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E07_Country_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E07_Country_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E07_Country_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name"));
// parent properties
country_ID1 = dr.GetInt32("Country_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E07_Country_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E06_Country parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E07_Country_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E06_Country parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="E07_Country_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E06_Country parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteE07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Gaming.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGameServerConfigsServiceClientTest
{
[xunit::FactAttribute]
public void GetGameServerConfigRequestObject()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig response = client.GetGameServerConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerConfigRequestObjectAsync()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerConfig()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig response = client.GetGameServerConfig(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerConfigAsync()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerConfigResourceNames()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig response = client.GetGameServerConfig(request.GameServerConfigName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerConfigResourceNamesAsync()
{
moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient> mockGrpcClient = new moq::Mock<GameServerConfigsService.GameServerConfigsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerConfigRequest request = new GetGameServerConfigRequest
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
};
GameServerConfig expectedResponse = new GameServerConfig
{
GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
FleetConfigs = { new FleetConfig(), },
ScalingConfigs =
{
new ScalingConfig(),
},
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerConfigsServiceClient client = new GameServerConfigsServiceClientImpl(mockGrpcClient.Object, null);
GameServerConfig responseCallSettings = await client.GetGameServerConfigAsync(request.GameServerConfigName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerConfig responseCancellationToken = await client.GetGameServerConfigAsync(request.GameServerConfigName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client;
namespace Adxstudio.Xrm.Search
{
public class SearchManager
{
public static event EventHandler Initializing;
private static readonly object _initializeLock = new object();
private static bool? _enabled;
private static bool _initialized;
private static SearchProvider _provider;
private static ProviderCollection<SearchProvider> _providers;
public static bool Enabled
{
get
{
if (!_initialized && !_enabled.HasValue)
{
_enabled = AdxstudioCrmConfigurationManager.GetCrmSection().Search.Enabled;
}
return _enabled.GetValueOrDefault(false);
}
}
public static SearchProvider Provider
{
get
{
EnsureEnabled();
return _provider;
}
}
public static ProviderCollection<SearchProvider> Providers
{
get
{
EnsureEnabled();
return _providers;
}
}
public static SearchProvider GetProvider(string name)
{
if (string.IsNullOrEmpty(name))
{
return Provider;
}
var provider = Providers[name];
if (provider != null)
{
return provider;
}
throw new ProviderException("Unable to get search provider with name {0}.".FormatWith(name));
}
private static void EnsureEnabled()
{
Initialize();
if (!Enabled)
{
throw new SearchDisabledProviderException("The Search feature has not been enabled. Please check your configuration.");
}
}
private static void Initialize()
{
if (_initialized)
{
return;
}
lock (_initializeLock)
{
if (_initialized)
{
return;
}
OnInitializing();
var searchElement = AdxstudioCrmConfigurationManager.GetCrmSection().Search;
_enabled = searchElement.Enabled;
if (_enabled.GetValueOrDefault(false))
{
_providers = new ProviderCollection<SearchProvider>();
foreach (ProviderSettings providerSettings in searchElement.Providers)
{
_providers.Add(InstantiateProvider<SearchProvider>(providerSettings));
}
_providers.SetReadOnly();
if (searchElement.DefaultProvider == null)
{
throw new ProviderException("Specify a default search provider.");
}
try
{
_provider = _providers[searchElement.DefaultProvider];
}
catch { }
if (_provider == null)
{
var defaultProviderPropertyInformation = searchElement.ElementInformation.Properties["defaultProvider"];
const string message = "Default Search Provider could not be found.";
throw defaultProviderPropertyInformation == null
? (Exception)new ProviderException(message)
: new ConfigurationErrorsException(message, defaultProviderPropertyInformation.Source, defaultProviderPropertyInformation.LineNumber);
}
}
_initialized = true;
}
}
private static void OnInitializing()
{
var handler = Initializing;
if (handler != null)
{
handler(null, new EventArgs());
}
}
private static TProvider InstantiateProvider<TProvider>(ProviderSettings settings) where TProvider : ProviderBase
{
try
{
var typeSetting = settings.Type == null ? null : settings.Type.Trim();
if (string.IsNullOrEmpty(typeSetting))
{
throw new ArgumentException("Type_Name_Required_For_Provider_Exception (Key present in resx file with same string)");
}
var providerType = Type.GetType(settings.Type, true, true);
if (!typeof(TProvider).IsAssignableFrom(providerType))
{
throw new ArgumentException("Provider must implement the class {0}.".FormatWith(typeof(TProvider)));
}
var provider = (TProvider)Activator.CreateInstance(providerType);
var parameters = settings.Parameters;
var config = new NameValueCollection(parameters.Count, StringComparer.Ordinal);
foreach (string key in parameters)
{
config[key] = parameters[key];
}
provider.Initialize(settings.Name, config);
return provider;
}
catch (Exception e)
{
if (e is ConfigurationException)
{
throw;
}
var typePropertyInformation = settings.ElementInformation.Properties["type"];
if (typePropertyInformation == null)
{
throw;
}
throw new ConfigurationErrorsException(e.Message, typePropertyInformation.Source, typePropertyInformation.LineNumber);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
public static class UInt32Tests
{
[Fact]
public static void TestCtor_Empty()
{
var i = new uint();
Assert.Equal((uint)0, i);
}
[Fact]
public static void TestCtor_Value()
{
uint i = 41;
Assert.Equal((uint)41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0xFFFFFFFF, uint.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal((uint)0, uint.MinValue);
}
[Theory]
[InlineData((uint)234, (uint)234, 0)]
[InlineData((uint)234, uint.MinValue, 1)]
[InlineData((uint)234, (uint)0, 1)]
[InlineData((uint)234, (uint)123, 1)]
[InlineData((uint)234, (uint)456, -1)]
[InlineData((uint)234, uint.MaxValue, -1)]
[InlineData((uint)234, null, 1)]
public static void TestCompareTo(uint i, object value, int expected)
{
if (value is uint)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((uint)value)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
}
[Fact]
public static void TestCompareTo_Invalid()
{
IComparable comparable = (uint)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a uint
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a uint
}
[Theory]
[InlineData((uint)789, (uint)789, true)]
[InlineData((uint)788, (uint)0, false)]
[InlineData((uint)0, (uint)0, true)]
[InlineData((uint)789, null, false)]
[InlineData((uint)789, "789", false)]
[InlineData((uint)789, 789, false)]
public static void TestEquals(uint i1, object obj, bool expected)
{
if (obj is uint)
{
uint i2 = (uint)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
Assert.Equal((int)i1, i1.GetHashCode());
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { (uint)0, "G", emptyFormat, "0" };
yield return new object[] { (uint)4567, "G", emptyFormat, "4567" };
yield return new object[] { uint.MaxValue, "G", emptyFormat, "4294967295" };
yield return new object[] { (uint)0x2468, "x", emptyFormat, "2468" };
yield return new object[] { (uint)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (uint)2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void TestToString(uint i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void TestToString_Invalid()
{
uint i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "0", defaultStyle, null, (uint)0 };
yield return new object[] { "123", defaultStyle, null, (uint)123 };
yield return new object[] { "+123", defaultStyle, null, (uint)123 };
yield return new object[] { " 123 ", defaultStyle, null, (uint)123 };
yield return new object[] { "4294967295", defaultStyle, null, 4294967295 };
yield return new object[] { "12", NumberStyles.HexNumber, null, (uint)0x12 };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (uint)1000 };
yield return new object[] { "123", defaultStyle, emptyFormat, (uint)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (uint)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (uint)0x12 };
yield return new object[] { "abc", NumberStyles.HexNumber, emptyFormat, (uint)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, emptyFormat, (uint)0xabc };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (uint)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestParse(string value, NumberStyles style, IFormatProvider provider, uint expected)
{
uint result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(uint.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, uint.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, uint.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(uint.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, uint.Parse(value, style));
}
Assert.Equal(expected, uint.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "678.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-1", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "4294967296", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, typeof(OverflowException) }; // Parentheses = negative
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestParse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
uint result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(uint.TryParse(value, out result));
Assert.Equal(default(uint), result);
Assert.Throws(exceptionType, () => uint.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => uint.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(uint.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(uint), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => uint.Parse(value, style));
}
Assert.Throws(exceptionType, () => uint.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TestTryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
uint result = 0;
Assert.Throws<ArgumentException>(() => uint.TryParse("1", style, null, out result));
Assert.Equal(default(uint), result);
Assert.Throws<ArgumentException>(() => uint.Parse("1", style));
Assert.Throws<ArgumentException>(() => uint.Parse("1", style, null));
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Threading;
namespace System.Reflection.PortableExecutable
{
/// <summary>
/// Portable Executable format reader.
/// </summary>
/// <remarks>
/// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel.
/// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>).
/// </remarks>
public sealed class PEReader : IDisposable
{
// May be null in the event that the entire image is not
// deemed necessary and we have been instructed to read
// the image contents without being lazy.
private MemoryBlockProvider _peImage;
// If we read the data from the image lazily (peImage != null) we defer reading the PE headers.
private PEHeaders _lazyPEHeaders;
private AbstractMemoryBlock _lazyMetadataBlock;
private AbstractMemoryBlock _lazyImageBlock;
private AbstractMemoryBlock[] _lazyPESectionBlocks;
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in memory.
/// </summary>
/// <param name="peImage">Pointer to the start of the PE image.</param>
/// <param name="size">The size of the PE image.</param>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception>
/// <remarks>
/// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>.
/// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>.
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
public unsafe PEReader(byte* peImage, int size)
{
if (peImage == null)
{
throw new ArgumentNullException("peImage");
}
if (size < 0)
{
throw new ArgumentOutOfRangeException("size");
}
_peImage = new ExternalMemoryBlockProvider(peImage, size);
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="BadImageFormatException">
/// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid.
/// </exception>
/// <remarks>
/// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be
/// disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
/// </remarks>
public PEReader(Stream peStream)
: this(peStream, PEStreamOptions.Default)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception>
/// <exception cref="BadImageFormatException">
/// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid.
/// </exception>
public PEReader(Stream peStream, PEStreamOptions options)
: this(peStream, options, (int?)null)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="size">PE image size.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
public PEReader(Stream peStream, PEStreamOptions options, int size)
: this(peStream, options, (int?)size)
{
}
private unsafe PEReader(Stream peStream, PEStreamOptions options, int? sizeOpt)
{
if (peStream == null)
{
throw new ArgumentNullException("peStream");
}
if (!peStream.CanRead || !peStream.CanSeek)
{
throw new ArgumentException(SR.StreamMustSupportReadAndSeek, "peStream");
}
if (!options.IsValid())
{
throw new ArgumentOutOfRangeException("options");
}
long start = peStream.Position;
int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt);
bool closeStream = true;
try
{
bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream);
if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0)
{
_peImage = new StreamMemoryBlockProvider(peStream, start, size, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0);
closeStream = false;
}
else
{
// Read in the entire image or metadata blob:
if ((options & PEStreamOptions.PrefetchEntireImage) != 0)
{
var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, 0, (int)Math.Min(peStream.Length, int.MaxValue));
_lazyImageBlock = imageBlock;
_peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size);
// if the caller asked for metadata initialize the PE headers (calculates metadata offset):
if ((options & PEStreamOptions.PrefetchMetadata) != 0)
{
InitializePEHeaders();
}
}
else
{
// The peImage is left null, but the lazyMetadataBlock is initialized up front.
_lazyPEHeaders = new PEHeaders(peStream);
_lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, _lazyPEHeaders.MetadataStartOffset, _lazyPEHeaders.MetadataSize);
}
// We read all we need, the stream is going to be closed.
}
}
finally
{
if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0)
{
peStream.Dispose();
}
}
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a byte array.
/// </summary>
/// <param name="peImage">PE image.</param>
/// <remarks>
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception>
public PEReader(ImmutableArray<byte> peImage)
{
if (peImage.IsDefault)
{
throw new ArgumentNullException("peImage");
}
_peImage = new ByteArrayMemoryProvider(peImage);
}
/// <summary>
/// Disposes all memory allocated by the reader.
/// </summary>
/// <remarks>
/// <see cref="Dispose"/> can be called multiple times (but not in parallel).
/// It is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/>
/// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader.
/// </remarks>
public void Dispose()
{
var image = _peImage;
if (image != null)
{
image.Dispose();
_peImage = null;
}
var imageBlock = _lazyImageBlock;
if (imageBlock != null)
{
imageBlock.Dispose();
_lazyImageBlock = null;
}
var metadataBlock = _lazyMetadataBlock;
if (metadataBlock != null)
{
metadataBlock.Dispose();
_lazyMetadataBlock = null;
}
var peSectionBlocks = _lazyPESectionBlocks;
if (peSectionBlocks != null)
{
foreach (var block in peSectionBlocks)
{
if (block != null)
{
block.Dispose();
}
}
_lazyPESectionBlocks = null;
}
}
/// <summary>
/// Gets the PE headers.
/// </summary>
/// <exception cref="BadImageFormatException">The headers contain invalid data.</exception>
public PEHeaders PEHeaders
{
get
{
if (_lazyPEHeaders == null)
{
InitializePEHeaders();
}
return _lazyPEHeaders;
}
}
private void InitializePEHeaders()
{
Debug.Assert(_peImage != null);
StreamConstraints constraints;
Stream stream = _peImage.GetStream(out constraints);
PEHeaders headers;
if (constraints.GuardOpt != null)
{
lock (constraints.GuardOpt)
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
}
else
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
Interlocked.CompareExchange(ref _lazyPEHeaders, headers, null);
}
private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize)
{
Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length);
stream.Seek(imageStartPosition, SeekOrigin.Begin);
return new PEHeaders(stream, imageSize);
}
/// <summary>
/// Returns a view of the entire image as a pointer and length.
/// </summary>
/// <exception cref="InvalidOperationException">PE image not available.</exception>
private AbstractMemoryBlock GetEntireImageBlock()
{
if (_lazyImageBlock == null)
{
if (_peImage == null)
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
var newBlock = _peImage.GetMemoryBlock();
if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return _lazyImageBlock;
}
private AbstractMemoryBlock GetMetadataBlock()
{
if (!HasMetadata)
{
throw new InvalidOperationException(SR.PEImageDoesNotHaveMetadata);
}
if (_lazyMetadataBlock == null)
{
Debug.Assert(_peImage != null, "We always have metadata if peImage is not available.");
var newBlock = _peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize);
if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return _lazyMetadataBlock;
}
private AbstractMemoryBlock GetPESectionBlock(int index)
{
Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length);
Debug.Assert(_peImage != null);
if (_lazyPESectionBlocks == null)
{
Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null);
}
var newBlock = _peImage.GetMemoryBlock(
PEHeaders.SectionHeaders[index].PointerToRawData,
PEHeaders.SectionHeaders[index].SizeOfRawData);
if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
return _lazyPESectionBlocks[index];
}
/// <summary>
/// Return true if the reader can access the entire PE image.
/// </summary>
/// <remarks>
/// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory.
/// </remarks>
public bool IsEntireImageAvailable
{
get { return _lazyImageBlock != null || _peImage != null; }
}
/// <summary>
/// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>).
/// </summary>
/// <exception cref="InvalidOperationException">The entire PE image is not available.</exception>
public PEMemoryBlock GetEntireImage()
{
return new PEMemoryBlock(GetEntireImageBlock());
}
/// <summary>
/// Returns true if the PE image contains CLI metadata.
/// </summary>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public bool HasMetadata
{
get { return PEHeaders.MetadataSize > 0; }
}
/// <summary>
/// Loads PE section that contains CLI metadata.
/// </summary>
/// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetMetadata()
{
return new PEMemoryBlock(GetMetadataBlock());
}
/// <summary>
/// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory
/// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section.
/// </summary>
/// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param>
/// <returns>
/// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image.
/// </returns>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetSectionData(int relativeVirtualAddress)
{
var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress);
if (sectionIndex < 0)
{
return default(PEMemoryBlock);
}
int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress;
int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset;
AbstractMemoryBlock block;
if (_peImage != null)
{
block = GetPESectionBlock(sectionIndex);
}
else
{
block = GetEntireImageBlock();
relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData;
}
return new PEMemoryBlock(block, relativeOffset);
}
/// <summary>
/// Reads all Debug Directory table entries.
/// </summary>
/// <exception cref="BadImageFormatException">Bad format of the entry.</exception>
public unsafe ImmutableArray<DebugDirectoryEntry> ReadDebugDirectory()
{
var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory;
if (debugDirectory.Size == 0)
{
return ImmutableArray<DebugDirectoryEntry>.Empty;
}
int position;
if (!PEHeaders.TryGetDirectoryOffset(debugDirectory, out position))
{
throw new BadImageFormatException(SR.InvalidDirectoryRVA);
}
const int entrySize = 0x1c;
if (debugDirectory.Size % entrySize != 0)
{
throw new BadImageFormatException(SR.InvalidDirectorySize);
}
using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(position, debugDirectory.Size))
{
var reader = new BlobReader(block.Pointer, block.Size);
int entryCount = debugDirectory.Size / entrySize;
var builder = ImmutableArray.CreateBuilder<DebugDirectoryEntry>(entryCount);
for (int i = 0; i < entryCount; i++)
{
// Reserved, must be zero.
int characteristics = reader.ReadInt32();
if (characteristics != 0)
{
throw new BadImageFormatException(SR.InvalidDebugDirectoryEntryCharacteristics);
}
uint stamp = reader.ReadUInt32();
ushort majorVersion = reader.ReadUInt16();
ushort minorVersion = reader.ReadUInt16();
var type = (DebugDirectoryEntryType)reader.ReadInt32();
int dataSize = reader.ReadInt32();
int dataRva = reader.ReadInt32();
int dataPointer = reader.ReadInt32();
builder.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRva, dataPointer));
}
return builder.MoveToImmutable();
}
}
/// <summary>
/// Reads the data pointed to by the specifed Debug Directory entry and interprets them as CodeView.
/// </summary>
/// <exception cref="ArgumentException"><paramref name="entry"/> is not a CodeView entry.</exception>
/// <exception cref="BadImageFormatException">Bad format of the data.</exception>
public unsafe CodeViewDebugDirectoryData ReadCodeViewDebugDirectoryData(DebugDirectoryEntry entry)
{
if (entry.Type != DebugDirectoryEntryType.CodeView)
{
throw new ArgumentException("entry");
}
using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(entry.DataPointer, entry.DataSize))
{
var reader = new BlobReader(block.Pointer, block.Size);
if (reader.ReadByte() != (byte)'R' ||
reader.ReadByte() != (byte)'S' ||
reader.ReadByte() != (byte)'D' ||
reader.ReadByte() != (byte)'S')
{
throw new BadImageFormatException(SR.UnexpectedCodeViewDataSignature);
}
Guid guid = reader.ReadGuid();
int age = reader.ReadInt32();
string path = reader.ReadUtf8NullTerminated();
// path may be padded with NULs
while (reader.RemainingBytes > 0)
{
if (reader.ReadByte() != 0)
{
throw new BadImageFormatException(SR.InvalidPathPadding);
}
}
return new CodeViewDebugDirectoryData(guid, age, path);
}
}
}
}
| |
namespace SharpArch.Domain
{
using System;
using System.Diagnostics;
/// <summary>
/// Design by Contract checks developed by http://www.codeproject.com/KB/cs/designbycontract.aspx.
///
/// </summary>
/// <remarks>
/// <para>
/// Each method generates an exception or a trace assertion statement if the contract is
/// broken.
/// </para>
/// <para>
/// This example shows how to call the Require method. Assume DBC_CHECK_PRECONDITION is
/// defined.
/// <code>
/// public void Test(int x)
/// {
/// try
/// {
/// Check.Require(x > 1, "x must be > 1");
/// }
/// catch (System.Exception ex)
/// {
/// Console.WriteLine(ex.ToString());
/// }
/// }
/// </code>
/// </para>
/// <para>
/// If you wish to use trace assertion statements, intended for Debug scenarios,
/// rather than exception handling then set
/// <code>Check.UseAssertions = true</code>
/// </para>
/// <para>
/// You can specify this in your application entry point and maybe make it
/// dependent on conditional compilation flags or configuration file settings, e.g.,
/// <code>
/// #if DBC_USE_ASSERTIONS
/// Check.UseAssertions = true;
/// #endif
/// </code>
/// </para>
/// <para>
/// You can direct output to a Trace listener. For example, you could insert
/// <code>
/// Trace.Listeners.Clear();
/// Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
/// </code>
/// or direct output to a file or the Event Log.
/// Note: For ASP.NET clients use the Listeners collection of the Debug, not the Trace,
/// object and, for a Release build, only exception-handling is possible.
/// </para>
/// </remarks>
public static class Check
{
private static bool useAssertions;
/// <summary>
/// Gets or sets a value indicating whether to use Trace Assert statements instead of
/// exception handling.
/// </summary>
/// <remarks>
/// The <see cref="Check"/> class uses exception handling by default.
/// </remarks>
public static bool UseAssertions
{
get
{
return useAssertions;
}
set
{
useAssertions = value;
}
}
/// <summary>
/// Gets a value indicating whether exception handling is being used.
/// </summary>
private static bool UseExceptions
{
get
{
return !useAssertions;
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
public static void Assert(bool assertion, string message)
{
if (UseExceptions)
{
if (!assertion)
{
throw new AssertionException(message);
}
}
else
{
Trace.Assert(assertion, "Assertion: " + message);
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
/// <param name="inner">The inner exception to pass in the exception that is thrown in case the assertion fails.</param>
public static void Assert(bool assertion, string message, Exception inner)
{
if (UseExceptions)
{
if (!assertion)
{
throw new AssertionException(message, inner);
}
}
else
{
Trace.Assert(assertion, "Assertion: " + message);
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
public static void Assert(bool assertion)
{
if (UseExceptions)
{
if (!assertion)
{
throw new AssertionException("Assertion failed.");
}
}
else
{
Trace.Assert(assertion, "Assertion failed.");
}
}
/// <summary>
/// Checks whether the specified postcondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
public static void Ensure(bool assertion, string message)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PostconditionException(message);
}
}
else
{
Trace.Assert(assertion, "Postcondition: " + message);
}
}
/// <summary>
/// Checks whether the specified postcondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
/// <param name="inner">The inner exception to pass in the exception that is thrown in case the assertion fails.</param>
public static void Ensure(bool assertion, string message, Exception inner)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PostconditionException(message, inner);
}
}
else
{
Trace.Assert(assertion, "Postcondition: " + message);
}
}
/// <summary>
/// Checks whether the specified postcondition assertion expression result is
/// <c>true</c> and throws an exception otherwise.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
public static void Ensure(bool assertion)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PostconditionException("Postcondition failed.");
}
}
else
{
Trace.Assert(assertion, "Postcondition failed.");
}
}
/// <summary>
/// Checks whether the specified invariant assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
public static void Invariant(bool assertion, string message)
{
if (UseExceptions)
{
if (!assertion)
{
throw new InvariantException(message);
}
}
else
{
Trace.Assert(assertion, "Invariant: " + message);
}
}
/// <summary>
/// Checks whether the specified invariant assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
/// <param name="inner">The inner exception to pass in the exception that is thrown in case the assertion fails.</param>
public static void Invariant(bool assertion, string message, Exception inner)
{
if (UseExceptions)
{
if (!assertion)
{
throw new InvariantException(message, inner);
}
}
else
{
Trace.Assert(assertion, "Invariant: " + message);
}
}
/// <summary>
/// Checks whether the specified invariant assertion expression result is
/// <c>true</c> and throws an exception otherwise.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
public static void Invariant(bool assertion)
{
if (UseExceptions)
{
if (!assertion)
{
throw new InvariantException("Invariant failed.");
}
}
else
{
Trace.Assert(assertion, "Invariant failed.");
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
/// <remarks>
/// This should run regardless of preprocessor directives.
/// </remarks>
public static void Require(bool assertion, string message)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PreconditionException(message);
}
}
else
{
Trace.Assert(assertion, "Precondition: " + message);
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise, using a specified message.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <param name="message">The message to use when throwing an exception in case the assertion fails.</param>
/// <param name="inner">The inner exception to pass in the exception that is thrown in case the assertion fails.</param>
/// <remarks>
/// This should run regardless of preprocessor directives.
/// </remarks>
public static void Require(bool assertion, string message, Exception inner)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PreconditionException(message, inner);
}
}
else
{
Trace.Assert(assertion, "Precondition: " + message);
}
}
/// <summary>
/// Checks whether the specified precondition assertion expression result is
/// <c>true</c> and throws an exception otherwise.
/// </summary>
/// <param name="assertion">The assertion expression result.</param>
/// <remarks>
/// This should run regardless of preprocessor directives.
/// </remarks>
public static void Require(bool assertion)
{
if (UseExceptions)
{
if (!assertion)
{
throw new PreconditionException("Precondition failed.");
}
}
else
{
Trace.Assert(assertion, "Precondition failed.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Infrastructure.Constants;
using Microting.eForm.Infrastructure.Data.Entities;
using NUnit.Framework;
namespace eFormSDK.InSight.Tests
{
[TestFixture]
public class QuestionTranslationUTest : DbTestFixture
{
[Test]
public async Task QuestionTranslation_Create_DoesCreate_W_MicrotingUID()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id,
MicrotingUid = rnd.Next(1, 255)
};
// Act
await questionTranslation.Create(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(1, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Create_DoesCreate_WO_MicrotingUID()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id
};
// Act
await questionTranslation.Create(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(1, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(null, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(null, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Update_DoesUpdate_W_MicrotingUID()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Question question2 = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion2.Id
};
await question2.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id,
MicrotingUid = rnd.Next(1, 255)
};
await questionTranslation.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = questionTranslation.LanguageId;
var oldName = questionTranslation.Name;
var oldQuestionId = questionTranslation.QuestionId;
var oldMicrotingUid = questionTranslation.MicrotingUid;
questionTranslation.LanguageId = language2.Id;
questionTranslation.Name = Guid.NewGuid().ToString();
questionTranslation.QuestionId = question2.Id;
questionTranslation.MicrotingUid = rnd.Next(1, 255);
// Act
await questionTranslation.Update(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(2, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[1].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[1].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[1].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslationVersions[1].MicrotingUid);
Assert.AreEqual(oldLanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(oldName, questionTranslationVersions[0].Name);
Assert.AreEqual(oldQuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(oldMicrotingUid, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Update_DoesUpdate_WO_MicrotingUID()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Question question2 = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion2.Id
};
await question2.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id
};
await questionTranslation.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = questionTranslation.LanguageId;
var oldName = questionTranslation.Name;
var oldQuestionId = questionTranslation.QuestionId;
questionTranslation.LanguageId = language2.Id;
questionTranslation.Name = Guid.NewGuid().ToString();
questionTranslation.QuestionId = question2.Id;
// Act
await questionTranslation.Update(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(2, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[1].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[1].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[1].QuestionId);
Assert.AreEqual(null, questionTranslationVersions[1].MicrotingUid);
Assert.AreEqual(oldLanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(oldName, questionTranslationVersions[0].Name);
Assert.AreEqual(oldQuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(null, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Update_DoesUpdate_W_MicrotingUID_RemovesUid()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Question question2 = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion2.Id
};
await question2.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id,
MicrotingUid = rnd.Next(1, 255)
};
await questionTranslation.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = questionTranslation.LanguageId;
var oldName = questionTranslation.Name;
var oldQuestionId = questionTranslation.QuestionId;
var oldMicrotingUid = questionTranslation.MicrotingUid;
questionTranslation.LanguageId = language2.Id;
questionTranslation.Name = Guid.NewGuid().ToString();
questionTranslation.QuestionId = question2.Id;
questionTranslation.MicrotingUid = null;
// Act
await questionTranslation.Update(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(2, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[1].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[1].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[1].QuestionId);
Assert.AreEqual(null, questionTranslationVersions[1].MicrotingUid);
Assert.AreEqual(oldLanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(oldName, questionTranslationVersions[0].Name);
Assert.AreEqual(oldQuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(oldMicrotingUid, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Update_DoesUpdate_WO_MicrotingUID_AddsUID()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
QuestionSet questionSetForQuestion2 = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion2.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Question question2 = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion2.Id
};
await question2.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
Language language2 = new Language
{
LanguageCode = Guid.NewGuid().ToString(),
Name = Guid.NewGuid().ToString()
};
await language2.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id,
};
await questionTranslation.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = questionTranslation.LanguageId;
var oldName = questionTranslation.Name;
var oldQuestionId = questionTranslation.QuestionId;
questionTranslation.LanguageId = language2.Id;
questionTranslation.Name = Guid.NewGuid().ToString();
questionTranslation.QuestionId = question2.Id;
questionTranslation.MicrotingUid = rnd.Next(1, 255);
// Act
await questionTranslation.Update(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(2, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[1].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[1].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[1].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslationVersions[1].MicrotingUid);
Assert.AreEqual(oldLanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(oldName, questionTranslationVersions[0].Name);
Assert.AreEqual(oldQuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(null, questionTranslationVersions[0].MicrotingUid);
}
[Test]
public async Task QuestionTranslation_Delete_DoesDelete()
{
Random rnd = new Random();
bool randomBool = rnd.Next(0, 2) > 0;
QuestionSet questionSetForQuestion = new QuestionSet
{
Name = Guid.NewGuid().ToString(),
Share = randomBool,
HasChild = randomBool,
ParentId = rnd.Next(1, 255),
PossiblyDeployed = randomBool
};
await questionSetForQuestion.Create(DbContext).ConfigureAwait(false);
Question question = new Question
{
Image = randomBool,
Maximum = rnd.Next(1, 255),
Minimum = rnd.Next(1, 255),
Prioritised = randomBool,
Type = Guid.NewGuid().ToString(),
FontSize = Guid.NewGuid().ToString(),
ImagePosition = Guid.NewGuid().ToString(),
MaxDuration = rnd.Next(1, 255),
MinDuration = rnd.Next(1, 255),
QuestionIndex = rnd.Next(1, 255),
QuestionType = Guid.NewGuid().ToString(),
RefId = rnd.Next(1, 255),
ValidDisplay = randomBool,
BackButtonEnabled = randomBool,
ContinuousQuestionId = rnd.Next(1, 255),
QuestionSetId = questionSetForQuestion.Id
};
await question.Create(DbContext).ConfigureAwait(false);
Language language = new Language
{
LanguageCode = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString()
};
await language.Create(DbContext).ConfigureAwait(false);
QuestionTranslation questionTranslation = new QuestionTranslation
{
LanguageId = language.Id,
Name = Guid.NewGuid().ToString(),
QuestionId = question.Id,
MicrotingUid = rnd.Next(1, 255)
};
await questionTranslation.Create(DbContext).ConfigureAwait(false);
var oldLanguageId = questionTranslation.LanguageId;
var oldName = questionTranslation.Name;
var oldQuestionId = questionTranslation.QuestionId;
var oldMicrotingUid = questionTranslation.MicrotingUid;
// Act
await questionTranslation.Delete(DbContext).ConfigureAwait(false);
List<QuestionTranslation> questionTranslations = DbContext.QuestionTranslations.AsNoTracking().ToList();
List<QuestionTranslationVersion> questionTranslationVersions =
DbContext.QuestionTranslationVersions.AsNoTracking().ToList();
// Assert
Assert.NotNull(questionTranslations);
Assert.NotNull(questionTranslationVersions);
Assert.AreEqual(1, questionTranslations.Count);
Assert.AreEqual(2, questionTranslationVersions.Count);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslations[0].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslations[0].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslations[0].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslations[0].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Removed, questionTranslations[0].WorkflowState);
Assert.AreEqual(questionTranslation.LanguageId, questionTranslationVersions[1].LanguageId);
Assert.AreEqual(questionTranslation.Name, questionTranslationVersions[1].Name);
Assert.AreEqual(questionTranslation.QuestionId, questionTranslationVersions[1].QuestionId);
Assert.AreEqual(questionTranslation.MicrotingUid, questionTranslationVersions[1].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Removed, questionTranslationVersions[1].WorkflowState);
Assert.AreEqual(oldLanguageId, questionTranslationVersions[0].LanguageId);
Assert.AreEqual(oldName, questionTranslationVersions[0].Name);
Assert.AreEqual(oldQuestionId, questionTranslationVersions[0].QuestionId);
Assert.AreEqual(oldMicrotingUid, questionTranslationVersions[0].MicrotingUid);
Assert.AreEqual(Constants.WorkflowStates.Created, questionTranslationVersions[0].WorkflowState);
}
}
}
| |
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide
//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats
#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
//#define POOLING //Currently using a build setting for this one (also it's experimental)
using System.Diagnostics;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Debug = UnityEngine.Debug;
/*
* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class
* for use with Unity
* Copyright Matt Schoen 2010 - 2013
*
*
*
*
* The changes from the original version are under this license:
*
* Copyright (C) 2012-2014 Soomla 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.
*/
public class JSONObject : NullCheckable {
#if POOLING
const int MAX_POOL_SIZE = 10000;
public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>();
#endif
const int MAX_DEPTH = 100;
const string INFINITY = "\"INFINITY\"";
const string NEGINFINITY = "\"NEGINFINITY\"";
const string NaN = "\"NaN\"";
static readonly char[] WHITESPACE = new[] { ' ', '\r', '\n', '\t' };
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED }
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
public Type type = Type.NULL;
public int Count {
get {
if(list == null)
return -1;
return list.Count;
}
}
public List<JSONObject> list;
public List<string> keys;
public string str;
#if USEFLOAT
public float n;
public float f {
get {
return n;
}
}
#else
public double n;
public float f {
get {
return (float)n;
}
}
#endif
public bool b;
public delegate void AddJSONConents(JSONObject self);
public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object
public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object
public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array
public JSONObject(Type t) {
type = t;
switch(t) {
case Type.ARRAY:
list = new List<JSONObject>();
break;
case Type.OBJECT:
list = new List<JSONObject>();
keys = new List<string>();
break;
}
}
public JSONObject(bool b) {
type = Type.BOOL;
this.b = b;
}
#if USEFLOAT
public JSONObject(float f) {
type = Type.NUMBER;
n = f;
}
#else
public JSONObject(double d) {
type = Type.NUMBER;
n = d;
}
#endif
public JSONObject(Dictionary<string, string> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, JSONObject> kvp in dic) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONConents content) {
content.Invoke(this);
}
public JSONObject(JSONObject[] objs) {
type = Type.ARRAY;
list = new List<JSONObject>(objs);
}
//Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
public static JSONObject StringObject(string val) { return CreateStringObject(val); }
public void Absorb(JSONObject obj) {
list.AddRange(obj.list);
keys.AddRange(obj.keys);
str = obj.str;
n = obj.n;
b = obj.b;
type = obj.type;
}
public static JSONObject Create() {
#if POOLING
JSONObject result = null;
while(result == null && releaseQueue.Count > 0) {
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.Log("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.Log("wtflist " + result.list.Count);
#endif
}
if(result != null)
return result;
#endif
return new JSONObject();
}
public static JSONObject Create(Type t) {
JSONObject obj = Create();
obj.type = t;
switch(t) {
case Type.ARRAY:
obj.list = new List<JSONObject>();
break;
case Type.OBJECT:
obj.list = new List<JSONObject>();
obj.keys = new List<string>();
break;
}
return obj;
}
public static JSONObject Create(bool val) {
JSONObject obj = Create();
obj.type = Type.BOOL;
obj.b = val;
return obj;
}
public static JSONObject Create(float val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(int val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject CreateStringObject(string val) {
if (!string.IsNullOrEmpty(val)) {
val = EncodeJsString(val);
}
JSONObject obj = Create();
obj.type = Type.STRING;
obj.str = val;
return obj;
}
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
public static JSONObject CreateBakedObject(string val) {
JSONObject bakedObject = Create();
bakedObject.type = Type.BAKED;
bakedObject.str = val;
return bakedObject;
}
/// <summary>
/// Create a JSONObject by parsing string data
/// </summary>
/// <param name="val">The string to be parsed</param>
/// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level,
/// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully
/// parse "a string" into a string-type </param>
/// <returns></returns>
public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
JSONObject obj = Create();
obj.Parse(val, maxDepth, storeExcessLevels, strict);
return obj;
}
public static JSONObject Create(AddJSONConents content) {
JSONObject obj = Create();
content.Invoke(obj);
return obj;
}
public static JSONObject Create(Dictionary<string, string> dic) {
JSONObject obj = Create();
obj.type = Type.OBJECT;
obj.keys = new List<string>();
obj.list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
obj.keys.Add(kvp.Key);
obj.list.Add(CreateStringObject(kvp.Value));
}
return obj;
}
public JSONObject() { }
#region PARSE
public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
Parse(str, maxDepth, storeExcessLevels, strict);
}
void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
if(!string.IsNullOrEmpty(str)) {
str = str.Trim(WHITESPACE);
if(strict) {
if(str[0] != '[' && str[0] != '{') {
type = Type.NULL;
Debug.LogWarning("Improper (strict) JSON formatting. First character must be [ or {");
return;
}
}
if(str.Length > 0) {
if(string.Compare(str, "true", true) == 0) {
type = Type.BOOL;
b = true;
} else if(string.Compare(str, "false", true) == 0) {
type = Type.BOOL;
b = false;
} else if(string.Compare(str, "null", true) == 0) {
type = Type.NULL;
#if USEFLOAT
} else if(str == INFINITY) {
type = Type.NUMBER;
n = float.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = float.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = float.NaN;
#else
} else if(str == INFINITY) {
type = Type.NUMBER;
n = double.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = double.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = double.NaN;
#endif
} else if(str[0] == '"') {
type = Type.STRING;
this.str = Regex.Unescape(str.Substring(1, str.Length - 2));
} else {
int tokenTmp = 1;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
int offset = 0;
switch(str[offset]) {
case '{':
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
break;
case '[':
type = Type.ARRAY;
list = new List<JSONObject>();
break;
default:
try {
#if USEFLOAT
n = System.Convert.ToSingle(str);
#else
n = System.Convert.ToDouble(str);
#endif
type = Type.NUMBER;
} catch(System.FormatException) {
type = Type.NULL;
Debug.LogWarning("improper JSON formatting:" + str);
}
return;
}
string propName = "";
bool openQuote = false;
bool inProp = false;
int depth = 0;
while(++offset < str.Length) {
if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
continue;
if(str[offset] == '\\') {
offset += 1;
continue;
}
if(str[offset] == '"') {
if(openQuote) {
if(!inProp && depth == 0 && type == Type.OBJECT)
propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
openQuote = false;
} else {
if(depth == 0 && type == Type.OBJECT)
tokenTmp = offset;
openQuote = true;
}
}
if(openQuote)
continue;
if(type == Type.OBJECT && depth == 0) {
if(str[offset] == ':') {
tokenTmp = offset + 1;
inProp = true;
}
}
if(str[offset] == '[' || str[offset] == '{') {
depth++;
} else if(str[offset] == ']' || str[offset] == '}') {
depth--;
}
//if (encounter a ',' at top level) || a closing ]/}
if((str[offset] == ',' && depth == 0) || depth < 0) {
inProp = false;
string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
if(inner.Length > 0) {
if(type == Type.OBJECT)
keys.Add(propName);
if(maxDepth != -1) //maxDepth of -1 is the end of the line
list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
else if(storeExcessLevels)
list.Add(CreateBakedObject(inner));
}
tokenTmp = offset + 1;
}
}
}
} else type = Type.NULL;
} else type = Type.NULL; //If the string is missing, this is a null
//Profiler.EndSample();
}
#endregion
public bool IsNumber { get { return type == Type.NUMBER; } }
public bool IsNull { get { return type == Type.NULL; } }
public bool IsString { get { return type == Type.STRING; } }
public bool IsBool { get { return type == Type.BOOL; } }
public bool IsArray { get { return type == Type.ARRAY; } }
public bool IsObject { get { return type == Type.OBJECT; } }
public void Add(bool val) {
Add(Create(val));
}
public void Add(float val) {
Add(Create(val));
}
public void Add(int val) {
Add(Create(val));
}
public void Add(string str) {
Add(CreateStringObject(str));
}
public void Add(AddJSONConents content) {
Add(Create(content));
}
public void Add(JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.ARRAY) {
type = Type.ARRAY; //Congratulations, son, you're an ARRAY now
if(list == null)
list = new List<JSONObject>();
}
list.Add(obj);
}
}
public void AddField(string name, bool val) {
AddField(name, Create(val));
}
public void AddField(string name, float val) {
AddField(name, Create(val));
}
public void AddField(string name, int val) {
AddField(name, Create(val));
}
public void AddField(string name, AddJSONConents content) {
AddField(name, Create(content));
}
public void AddField(string name, string val) {
AddField(name, CreateStringObject(val));
}
public void AddField(string name, JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.OBJECT) {
if(keys == null)
keys = new List<string>();
if(type == Type.ARRAY) {
for(int i = 0; i < list.Count; i++)
keys.Add(i + "");
} else
if(list == null)
list = new List<JSONObject>();
type = Type.OBJECT; //Congratulations, son, you're an OBJECT now
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, bool val) { SetField(name, Create(val)); }
public void SetField(string name, float val) { SetField(name, Create(val)); }
public void SetField(string name, int val) { SetField(name, Create(val)); }
public void SetField(string name, string val) {
SetField(name, CreateStringObject(val));
}
public void SetField(string name, JSONObject obj) {
if(HasField(name)) {
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public void RemoveField(string name) {
if(keys.IndexOf(name) > -1) {
list.RemoveAt(keys.IndexOf(name));
keys.Remove(name);
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject obj);
public void GetField(ref bool field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].b;
return;
}
}
if(fail != null) fail.Invoke(name);
}
#if USEFLOAT
public void GetField(ref float field, string name, FieldNotFound fail = null) {
#else
public void GetField(ref double field, string name, FieldNotFound fail = null) {
#endif
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref int field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (int)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref uint field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (uint)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref string field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].str;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) {
if(response != null && type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
response.Invoke(list[index]);
return;
}
}
if(fail != null) fail.Invoke(name);
}
public JSONObject GetField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return list[i];
return null;
}
public bool HasFields(string[] names) {
for(int i = 0; i < names.Length; i++)
if(!keys.Contains(names[i]))
return false;
return true;
}
public bool HasField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return true;
return false;
}
public void Clear() {
type = Type.NULL;
if(list != null)
list.Clear();
if(keys != null)
keys.Clear();
str = "";
n = 0;
b = false;
}
/// <summary>
/// Copy a JSONObject. This could probably work better
/// </summary>
/// <returns></returns>
public JSONObject Copy() {
return Create(Print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj) {
MergeRecur(this, obj);
}
/// <summary>
/// Merge object right into left recursively
/// </summary>
/// <param name="left">The left (base) object</param>
/// <param name="right">The right (new) object</param>
static void MergeRecur(JSONObject left, JSONObject right) {
if(left.type == Type.NULL)
left.Absorb(right);
else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
for(int i = 0; i < right.list.Count; i++) {
string key = right.keys[i];
if(right[i].isContainer) {
if(left.HasField(key))
MergeRecur(left[key], right[i]);
else
left.AddField(key, right[i]);
} else {
if(left.HasField(key))
left.SetField(key, right[i]);
else
left.AddField(key, right[i]);
}
}
} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
if(right.Count > left.Count) {
Debug.LogError("Cannot merge arrays when right object has more elements");
return;
}
for(int i = 0; i < right.list.Count; i++) {
if(left[i].type == right[i].type) { //Only overwrite with the same type
if(left[i].isContainer)
MergeRecur(left[i], right[i]);
else {
left[i] = right[i];
}
}
}
}
}
public void Bake() {
if(type != Type.BAKED) {
str = Print();
type = Type.BAKED;
}
}
public IEnumerable BakeAsync() {
if(type != Type.BAKED) {
foreach(string s in PrintAsync()) {
if(s == null)
yield return s;
else {
str = s;
}
}
type = Type.BAKED;
}
}
#pragma warning disable 219
public string print(bool pretty = false) {
return Print (pretty);
}
public string Print(bool pretty = false) {
StringBuilder builder = new StringBuilder();
Stringify(0, builder, pretty);
return builder.ToString();
}
public IEnumerable<string> PrintAsync(bool pretty = false) {
StringBuilder builder = new StringBuilder();
printWatch.Reset();
printWatch.Start();
foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) {
yield return null;
}
yield return builder.ToString();
}
#pragma warning restore 219
#region STRINGIFY
const float maxFrameTime = 0.008f;
static readonly Stopwatch printWatch = new Stopwatch();
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
yield break;
}
if(printWatch.Elapsed.TotalSeconds > maxFrameTime) {
printWatch.Reset();
yield return null;
printWatch.Start();
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
//TODO: Refactor Stringify functions to share core logic
/*
* I know, I know, this is really bad form. It turns out that there is a
* significant amount of garbage created when calling as a coroutine, so this
* method is duplicated. Hopefully there won't be too many future changes, but
* I would still like a more elegant way to optionaly yield
*/
void Stringify(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
return;
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
obj.Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
list[i].Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
#endregion
public static implicit operator WWWForm(JSONObject obj) {
WWWForm form = new WWWForm();
for(int i = 0; i < obj.list.Count; i++) {
string key = i + "";
if(obj.type == Type.OBJECT)
key = obj.keys[i];
string val = obj.list[i].ToString();
if(obj.list[i].type == Type.STRING)
val = val.Replace("\"", "");
form.AddField(key, val);
}
return form;
}
public JSONObject this[int index] {
get {
if(list.Count > index) return list[index];
return null;
}
set {
if(list.Count > index)
list[index] = value;
}
}
public JSONObject this[string index] {
get {
return GetField(index);
}
set {
SetField(index, value);
}
}
public override string ToString() {
return Print();
}
public string ToString(bool pretty) {
return Print(pretty);
}
public Dictionary<string, string> ToDictionary() {
if(type == Type.OBJECT) {
Dictionary<string, string> result = new Dictionary<string, string>();
for(int i = 0; i < list.Count; i++) {
JSONObject val = list[i];
switch(val.type) {
case Type.STRING: result.Add(keys[i], val.str); break;
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
case Type.BOOL: result.Add(keys[i], val.b + ""); break;
default: Debug.LogWarning("Omitting object: " + keys[i] + " in dictionary conversion"); break;
}
}
return result;
}
Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary");
return null;
}
public static implicit operator bool(JSONObject o) {
return o != null;
}
#if POOLING
static bool pool = true;
public static void ClearPool() {
pool = false;
releaseQueue.Clear();
pool = true;
}
~JSONObject() {
if(pool && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
releaseQueue.Enqueue(this);
}
}
#endif
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.CLR.Method;
using ILRuntime.CLR.Utils;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
if (type is ILRuntime.Reflection.ILRuntimeWrapperType)
{
var wt = (ILRuntime.Reflection.ILRuntimeWrapperType)type;
if (data.IsArray)
{
data.ElementType = wt.CLRType.ElementType.ReflectionType;
}
else
{
data.ElementType = wt.CLRType.GenericArguments[0].Value.ReflectionType;
}
}
else
{
foreach (PropertyInfo p_info in type.GetProperties())
{
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof(int))
data.ElementType = p_info.PropertyType;
}
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof(string))
{
if (type is ILRuntime.Reflection.ILRuntimeWrapperType)
{
data.ElementType = ((ILRuntime.Reflection.ILRuntimeWrapperType)type).CLRType.GenericArguments[1].Value.ReflectionType;
}
else
data.ElementType = p_info.PropertyType;
}
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
//ILRuntime doesn't support nullable valuetype
Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
Type value_type = inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClass || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType();
var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;
if (vt.IsAssignableFrom(json_type))
return reader.Value;
if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
{
if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
return reader.Value;
}
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
custom_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
base_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe it's an enum
if (vt.IsEnum)
return Enum.ToObject (vt, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (vt, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
item = rt.CheckCLRTypes(item);
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
if (value_type is ILRuntime.Reflection.ILRuntimeType)
instance = ((ILRuntime.Reflection.ILRuntimeType)value_type).ILType.Instantiate();
else
instance = Activator.CreateInstance(value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)t_data.ElementType).RealType : t_data.ElementType;
((IDictionary) instance).Add (
property, rt.CheckCLRTypes(ReadValue (
t_data.ElementType, reader)));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToInt64((int)input);
};
RegisterImporter(base_importers_table, typeof(int),
typeof(long), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type;
if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance)
{
obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType;
}
else if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
{
obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType;
}
else
obj_type = obj.GetType();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
public unsafe static void RegisterILRuntimeCLRRedirection(ILRuntime.Runtime.Enviorment.AppDomain appdomain)
{
foreach(var i in typeof(JsonMapper).GetMethods())
{
if(i.Name == "ToObject" && i.IsGenericMethodDefinition)
{
var param = i.GetParameters();
if(param[0].ParameterType == typeof(string))
{
appdomain.RegisterCLRMethodRedirection(i, JsonToObject);
}
else if(param[0].ParameterType == typeof(JsonReader))
{
appdomain.RegisterCLRMethodRedirection(i, JsonToObject2);
}
else if (param[0].ParameterType == typeof(TextReader))
{
appdomain.RegisterCLRMethodRedirection(i, JsonToObject3);
}
}
}
}
public unsafe static StackObject* JsonToObject(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(esp, 1);
ptr_of_this_method = ILIntepreter.Minus(esp, 1);
System.String json = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack));
intp.Free(ptr_of_this_method);
var type = method.GenericArguments[0].ReflectionType;
var result_of_this_method = ReadValue(type, new JsonReader(json));
return ILIntepreter.PushObject(__ret, mStack, result_of_this_method);
}
public unsafe static StackObject* JsonToObject2(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(esp, 1);
ptr_of_this_method = ILIntepreter.Minus(esp, 1);
JsonReader json = (JsonReader)typeof(JsonReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack));
intp.Free(ptr_of_this_method);
var type = method.GenericArguments[0].ReflectionType;
var result_of_this_method = ReadValue(type, json);
return ILIntepreter.PushObject(__ret, mStack, result_of_this_method);
}
public unsafe static StackObject* JsonToObject3(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(esp, 1);
ptr_of_this_method = ILIntepreter.Minus(esp, 1);
TextReader json = (TextReader)typeof(TextReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack));
intp.Free(ptr_of_this_method);
var type = method.GenericArguments[0].ReflectionType;
var result_of_this_method = ReadValue(type, new JsonReader(json));
return ILIntepreter.PushObject(__ret, mStack, result_of_this_method);
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace WixSharp
{
/// <summary>
/// Defines WiX <c>Condition</c>. <c>Condition</c> is normally associated with <c>CustomActions</c> or WiX elements (e.g. <c>Shortcut</c>).
/// <para>
/// <see cref="Condition"/> is nothing else but an XML friendly string wrapper, containing
/// some predefined (commonly used) condition values. You can either use one of the
/// predefined condition values (static members) or define your by specifying full string representation of
/// the required WiX condition when calling the constructor or static method <c>Create</c>.
/// </para>
/// </summary>
/// <example>The following is an example of initializing the Shortcut.<see cref="Shortcut.Condition"/>
/// with custom value <c>INSTALLDESKTOPSHORTCUT="yes"</c> and
/// the InstalledFileAction.<see cref="T:WixSharp.InstalledFileAction.Condition"/> with perefined value <c>NOT_Installed</c>:
/// <code>
/// var project =
/// new Project("My Product",
/// ...
/// new Dir(@"%Desktop%",
/// new WixSharp.Shortcut("MyApp", "[INSTALL_DIR]MyApp.exe", "")
/// {
/// Condition = new Condition("INSTALLDESKTOPSHORTCUT=\"yes\"")
/// }),
/// new InstalledFileAction("MyApp.exe", "",
/// Return.check,
/// When.After,
/// Step.InstallFinalize,
/// Condition.NOT_Installed),
/// ...
/// </code>
/// </example>
public partial class Condition : WixEntity
{
/// <summary>
/// String value of WiX <c>Condition</c>.
/// </summary>
public string Value = "";
/// <summary>
/// Initializes a new instance of the <see cref="Condition"/> class.
/// </summary>
/// <param name="value">The value of the WiX condition expression.</param>
public Condition(string value)
{
Value = value;
}
/// <summary>
/// Returns the WiX <c>Condition</c> as a string.
/// </summary>
/// <returns>A string representing the condition.</returns>
public override string ToString()
{
return Value.Replace("'", "\"");
}
/// <summary>
/// Extracts the distinct names of properties from the condition string expression.
/// </summary>
/// <returns></returns>
public string[] GetDistinctProperties()
{
//"NETFRAMEWORK30_SP_LEVEL and NOT NETFRAMEWORK30_SP_LEVEL='#0'"
var text = this.ToString();
string[] parts = text.Split("[]()!=><\t \n\r".ToCharArray());
var props = parts.Where(x => x.IsNotEmpty() &&
!x.SameAs("AND", true) &&
!x.SameAs("NOT", true) &&
!x.SameAs("OR", true) &&
!x.StartsWith("\""))
.Distinct()
.ToArray();
return props;
}
/// <summary>
/// Performs an implicit conversion from <see cref="Condition"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator string (Condition obj)
{
return obj.ToString();
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Condition"/>.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator Condition(string obj)
{
return new Condition(obj);
}
/// <summary>
/// Returns the WiX <c>Condition</c> as a <see cref="T:System.Xml.Linq.XCData"/>.
/// <remarks> Normally <c>Condition</c> is not designed to be parsed by the XML parser thus it should be embedded as CDATA</remarks>
/// <code>
/// <Condition><![CDATA[NETFRAMEWORK20="#0"]]></Condition>
/// </code>
/// </summary>
/// <returns>A CDATA string representing the condition.</returns>
public XCData ToCData()
{
return new XCData(Value);
}
/// <summary>
/// String representation of the <c>Custom_UI_Command = "back"</c> condition. This condition is triggered when user presses 'Back' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_BackPressed = new Condition(" Custom_UI_Command = \"back\" ");
/// <summary>
/// String representation of the <c>Custom_UI_Command = "next"</c> condition. This condition is triggered when user presses 'Next' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_NextPressed = new Condition(" Custom_UI_Command = \"next\" ");
/// <summary>
/// String representation of the <c>Custom_UI_Command = "abort"</c> condition. This condition is triggered when user presses 'Cancel' button in the CLR Dialog.
/// </summary>
public readonly static Condition ClrDialog_CancelPressed = new Condition(" Custom_UI_Command = \"abort\" ");
/// <summary>
/// String representation of the <c>NOT Installed</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_Installed = new Condition(" (NOT Installed) ");
/// <summary>
/// String representation of the <c>Installed</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Installed = new Condition(" (Installed) ");
/// <summary>
/// String representation of "always true" condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Always = new Condition(" (1) ");
/// <summary>
/// String representation of the <c>NOT (REMOVE="ALL")</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_BeingRemoved = new Condition(" (NOT (REMOVE=\"ALL\")) ");
/// <summary>
/// String representation of the <c>UILevel > 3</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition NOT_Silent = new Condition(" (UILevel > 3) ");
/// <summary>
/// String representation of the <c>UILevel < 4</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition Silent = new Condition(" (UILevel < 4) ");
/// <summary>
/// String representation of the <c>REMOVE="ALL"</c> condition of the WiX <c>Condition</c>.
/// </summary>
public readonly static Condition BeingRemoved = new Condition(" (REMOVE=\"ALL\") ");
/// <summary>
/// The .NET2.0 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net20_Installed = new Condition(" (NETFRAMEWORK20='#1') ");
/// <summary>
/// The .NET3.5 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net35_Installed = new Condition(" (NETFRAMEWORK35='#1') ");
/// <summary>
/// The .NET4.5 installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net45_Installed = new Condition(" (NETFRAMEWORK45 >= '#378389') ");
/// <summary>
/// The .NET3.0 SP installed. This condition is to be used in Project.SetNetFxPrerequisite.
/// </summary>
public readonly static Condition Net30_SP_Installed = new Condition(" (NETFRAMEWORK30_SP_LEVEL and NOT NETFRAMEWORK30_SP_LEVEL='#0') ");
/// <summary>
/// Creates WiX <c>Condition</c> condition from the given string value.
/// </summary>
/// <param name="value">String value of the <c>Condition</c> to be created.</param>
/// <returns>Instance of the <c>Condition</c></returns>
/// <example>The following is an example of initializing the Shortcut.<see cref="Shortcut.Condition"/>
/// with custom value <c>INSTALLDESKTOPSHORTCUT="yes"</c>:
/// <code>
/// new Dir(@"%Desktop%",
/// new WixSharp.Shortcut("MyApp", "[INSTALL_DIR]MyApp.exe", "")
/// {
/// Condition = Condition.Create("INSTALLDESKTOPSHORTCUT=\"yes\"")
/// })
///
/// </code>
/// </example>
public static Condition Create(string value) { return new Condition(value); }
//public Condition And(Condition condition)
//{
// return Create("(" + this.ToString() + " AND " + condition.ToString() + ")");
//}
//public Condition Or(Condition condition)
//{
// return Create("(" + this.ToString() + " OR " + condition.ToString() + ")");
//}
//public Condition Invert()
//{
// return Create("NOT (" + this.ToString() + ")");
//}
}
/// <summary>
/// Specialized Condition for conditionally installing WiX Features.
/// </summary>
/// <remarks>
/// Setting Attributes on FeatureCondition is ignored.
/// </remarks>
public class FeatureCondition : Condition
{
/// <summary>
/// Initializes a new instance of the <see cref="FeatureCondition"/> class.
/// </summary>
/// <param name="value">The value of the WiX condition expression.</param>
/// <param name="level">The level value of the WiX condition.</param>
public FeatureCondition(string value, int level)
: base(value)
{
Level = level;
}
/// <summary>
/// Allows modifying the level of a Feature based on the result of this condition.
/// </summary>
public int Level { get; set; }
/// <summary>
/// Not Supported.
/// </summary>
/// <exception cref="NotImplementedException">Raised when getting or setting Attributes.</exception>
public new Dictionary<string, string> Attributes
{
get { throw new NotImplementedException("Attributes is not a valid property for FeatureCondition"); }
set { throw new NotImplementedException("Attributes is not a valid property for FeatureCondition"); }
}
}
}
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Web.Security;
using System.Configuration;
using Umbraco.Core;
using Umbraco.Core.Security;
using umbraco.BusinessLogic;
using System.Web.Util;
using System.Configuration.Provider;
using System.Linq;
using Umbraco.Core.Logging;
#endregion
namespace umbraco.providers
{
/// <summary>
/// Custom Membership Provider for Umbraco Users (User authentication for Umbraco Backend CMS)
/// </summary>
[Obsolete("This has been superceded by Umbraco.Web.Security.Providers.UsersMembershipProvider")]
public class UsersMembershipProvider : MembershipProviderBase, IUsersMembershipProvider
{
/// <summary>
/// Override to maintain backwards compatibility with 0 required non-alphanumeric chars
/// </summary>
public override int DefaultMinNonAlphanumericChars
{
get { return 0; }
}
/// <summary>
/// Override to maintain backwards compatibility with only 4 required length
/// </summary>
public override int DefaultMinPasswordLength
{
get { return 4; }
}
/// <summary>
/// Override to maintain backwards compatibility
/// </summary>
public override bool DefaultUseLegacyEncoding
{
get { return true; }
}
/// <summary>
/// For backwards compatibility, this provider supports this option
/// </summary>
public override bool AllowManuallyChangingPassword
{
get { return true; }
}
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
if (config == null) throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name)) name = UmbracoSettings.DefaultBackofficeProvider;
base.Initialize(name, config);
}
#region Methods
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">The current password for the specified user.</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
protected override bool PerformChangePassword(string username, string oldPassword, string newPassword)
{
//NOTE: due to backwards compatibilty reasons (and UX reasons), this provider doesn't care about the old password and
// allows simply setting the password manually so we don't really care about the old password.
// This is allowed based on the overridden AllowManuallyChangingPassword option.
var user = new User(username);
//encrypt/hash the new one
string salt;
var encodedPassword = EncryptOrHashNewPassword(newPassword, out salt);
//Yes, it's true, this actually makes a db call to set the password
user.Password = FormatPasswordForStorage(encodedPassword, salt);
//call this just for fun.
user.Save();
return true;
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
protected override bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
protected override MembershipUser PerformCreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
// TODO: Does umbraco allow duplicate emails??
//if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
//{
// status = MembershipCreateStatus.DuplicateEmail;
// return null;
//}
var u = GetUser(username, false) as UsersMembershipUser;
if (u == null)
{
try
{
//ensure the password is encrypted/hashed
string salt;
var encodedPass = EncryptOrHashNewPassword(password, out salt);
User.MakeNew(username, username, FormatPasswordForStorage(encodedPass, salt), email);
status = MembershipCreateStatus.Success;
}
catch (Exception)
{
status = MembershipCreateStatus.ProviderError;
}
return GetUser(username, false);
}
status = MembershipCreateStatus.DuplicateUserName;
return null;
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
/// <returns>
/// true if the user was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
try
{
User user = new User(username);
user.delete();
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
/// </summary>
/// <param name="emailToMatch">The e-mail address to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
var counter = 0;
var startIndex = pageSize * pageIndex;
var endIndex = startIndex + pageSize - 1;
var usersList = new MembershipUserCollection();
var usersArray = User.getAllByEmail(emailToMatch);
totalRecords = usersArray.Length;
foreach (var user in usersArray)
{
if (counter >= startIndex)
usersList.Add(ConvertToMembershipUser(user));
if (counter >= endIndex) break;
counter++;
}
return usersList;
}
/// <summary>
/// Gets a collection of membership users where the user name contains the specified user name to match.
/// </summary>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
var counter = 0;
var startIndex = pageSize * pageIndex;
var endIndex = startIndex + pageSize - 1;
var usersList = new MembershipUserCollection();
var usersArray = User.GetAllByLoginName(usernameToMatch, true).ToArray();
totalRecords = usersArray.Length;
foreach (var user in usersArray)
{
if (counter >= startIndex)
usersList.Add(ConvertToMembershipUser(user));
if (counter >= endIndex) break;
counter++;
}
return usersList;
}
/// <summary>
/// Gets a collection of all the users in the data source in pages of data.
/// </summary>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
var counter = 0;
var startIndex = pageSize * pageIndex;
var endIndex = startIndex + pageSize - 1;
var usersList = new MembershipUserCollection();
var usersArray = User.getAll();
totalRecords = usersArray.Length;
foreach (User user in usersArray)
{
if (counter >= startIndex)
usersList.Add(ConvertToMembershipUser(user));
if (counter >= endIndex) break;
counter++;
}
return usersList;
}
/// <summary>
/// Gets the number of users currently accessing the application.
/// </summary>
/// <returns>
/// The number of users currently accessing the application.
/// </returns>
public override int GetNumberOfUsersOnline()
{
var fromDate = DateTime.Now.AddMinutes(-Membership.UserIsOnlineTimeWindow);
return Log.Instance.GetLogItems(LogTypes.Login, fromDate).Count;
}
/// <summary>
/// Gets the password for the specified user name from the data source. This is - for security - not
/// supported for Umbraco Users and an exception will be thrown
/// </summary>
/// <param name="username">The user to retrieve the password for.</param>
/// <param name="answer">The password answer for the user.</param>
/// <returns>
/// The password for the specified user name.
/// </returns>
protected override string PerformGetPassword(string username, string answer)
{
var found = User.GetAllByLoginName(username, false).ToArray();
if (found == null || found.Any() == false)
{
throw new MembershipPasswordException("The supplied user is not found");
}
// check if user is locked out
if (found.First().NoConsole)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
if (RequiresQuestionAndAnswer)
{
throw new NotImplementedException("Question/answer is not supported with this membership provider");
}
var decodedPassword = DecryptPassword(found.First().GetPassword());
return decodedPassword;
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="username">The name of the user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
var userId = User.getUserId(username);
if (userId == -1)
{
return null;
}
try
{
var user = new User(userId);
//We need to log this since it's the only way we can determine the number of users online
Log.Add(LogTypes.Login, user, -1, "User " + username + " has logged in");
return (userId != -1) ? ConvertToMembershipUser(user) : null;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
var user = new User(Convert.ToInt32(providerUserKey));
//We need to log this since it's the only way we can determine the number of users online
Log.Add(LogTypes.Login, user, -1, "User " + user.LoginName + " has logged in");
return ConvertToMembershipUser(user);
}
/// <summary>
/// Gets the user name associated with the specified e-mail address.
/// </summary>
/// <param name="email">The e-mail address to search for.</param>
/// <returns>
/// The user name associated with the specified e-mail address. If no match is found, return null.
/// </returns>
public override string GetUserNameByEmail(string email)
{
var found = User.getAllByEmail(email.Trim().ToLower(), true);
if (found == null || found.Any() == false)
{
return null;
}
return found.First().LoginName;
}
/// <summary>
/// Resets a user's password to a new, automatically generated password.
/// </summary>
/// <param name="username">The user to reset the password for.</param>
/// <param name="answer">The password answer for the specified user.</param>
/// <param name="generatedPassword"></param>
/// <returns>The new password for the specified user.</returns>
protected override string PerformResetPassword(string username, string answer, string generatedPassword)
{
//TODO: This should be here - but how do we update failure count in this provider??
//if (answer == null && RequiresQuestionAndAnswer)
//{
// UpdateFailureCount(username, "passwordAnswer");
// throw new ProviderException("Password answer required for password reset.");
//}
var found = User.GetAllByLoginName(username, false).ToArray();
if (found == null || found.Any() == false)
throw new MembershipPasswordException("The supplied user is not found");
var user = found.First();
//Yes, it's true, this actually makes a db call to set the password
string salt;
var encPass = EncryptOrHashNewPassword(generatedPassword, out salt);
user.Password = FormatPasswordForStorage(encPass, salt);
//call this just for fun.
user.Save();
return generatedPassword;
}
/// <summary>
/// Clears a lock so that the membership user can be validated.
/// </summary>
/// <param name="userName">The membership user to clear the lock status for.</param>
/// <returns>
/// true if the membership user was successfully unlocked; otherwise, false.
/// </returns>
public override bool UnlockUser(string userName)
{
try
{
var user = new User(userName)
{
NoConsole = false
};
user.Save();
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Updates information about a user in the data source.
/// </summary>
/// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param>
public override void UpdateUser(MembershipUser user)
{
var found = User.GetAllByLoginName(user.UserName, false).ToArray();
if (found == null || found.Any() == false)
{
throw new ProviderException("The supplied user is not found");
}
var m = found.First();
if (RequiresUniqueEmail && user.Email.Trim().IsNullOrWhiteSpace() == false)
{
var byEmail = User.getAllByEmail(user.Email, true);
if (byEmail.Count(x => x.Id != m.Id) > 0)
{
throw new ProviderException(string.Format("A member with the email '{0}' already exists", user.Email));
}
}
var typedUser = user as UsersMembershipUser;
if (typedUser == null)
{
// update approve status
// update lock status
// TODO: Update last lockout time
// TODO: update comment
User.Update(m.Id, user.Email, user.IsApproved == false, user.IsLockedOut);
}
else
{
//This keeps compatibility - even though this logic to update name should not exist here
User.Update(m.Id, typedUser.FullName.Trim(), typedUser.UserName, typedUser.Email, user.IsApproved == false, user.IsLockedOut);
}
m.Save();
}
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <param name="username">The name of the user to validate.</param>
/// <param name="password">The password for the specified user.</param>
/// <returns>
/// true if the specified username and password are valid; otherwise, false.
/// </returns>
public override bool ValidateUser(string username, string password)
{
var userId = User.getUserId(username);
if (userId != -1)
{
var user = User.GetUser(userId);
if (user != null)
{
if (user.Disabled)
{
LogHelper.Info<UsersMembershipProvider>(
string.Format(
"Login attempt failed for username {0} from IP address {1}, the user is locked",
username,
GetCurrentRequestIpAddress()));
return false;
}
var result = CheckPassword(password, user.Password);
if (result == false)
{
LogHelper.Info<UsersMembershipProvider>(
string.Format(
"Login attempt failed for username {0} from IP address {1}",
username,
GetCurrentRequestIpAddress()));
}
else
{
LogHelper.Info<UsersMembershipProvider>(
string.Format(
"Login attempt succeeded for username {0} from IP address {1}",
username,
GetCurrentRequestIpAddress()));
}
return result;
}
}
return false;
}
#endregion
#region Helper Methods
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
[Obsolete("Do not use this, it is the legacy way to encode a password")]
public string EncodePassword(string password)
{
return base.LegacyEncodePassword(password);
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
[Obsolete("Do not use this, it is the legacy way to decode a password")]
public string UnEncodePassword(string encodedPassword)
{
return LegacyUnEncodePassword(encodedPassword);
}
/// <summary>
/// Converts to membership user.
/// </summary>
/// <param name="user">The user.</param>
/// <returns></returns>
private UsersMembershipUser ConvertToMembershipUser(User user)
{
if (user == null) return null;
return new UsersMembershipUser(base.Name, user.LoginName, user.Id, user.Email,
string.Empty, string.Empty, true, user.Disabled,
DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now,
DateTime.Now, user.Name, user.Language);
}
#endregion
}
}
| |
using System;
using System.Reflection;
using Eto.Drawing;
using Eto.Forms;
using Eto.IO;
using Eto.Mac.Drawing;
using Eto.Mac.IO;
using Eto.Mac.Forms.Controls;
using Eto.Mac.Forms.Printing;
using Eto.Mac.Forms;
using Eto.Mac.Forms.Menu;
using Eto.Mac.Threading;
using Eto.Threading;
using Eto.Mac.Forms.Cells;
using Eto.Mac.Forms.ToolBar;
using Eto.Shared.Forms;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#endif
namespace Eto.Mac
{
[Preserve(AllMembers = true)]
public class Platform : Eto.Platform
{
public override bool IsDesktop { get { return true; } }
public override bool IsMac { get { return true; } }
#if XAMMAC
public override string ID { get { return "xammac"; } }
#else
public override string ID { get { return "mac"; } }
#endif
static bool initialized;
public Platform()
{
#if Mac64
unsafe
{
if (sizeof(IntPtr) != 8)
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "You can only run this platform in 64-bit mode. Use the 32-bit Eto.Mac platform instead."));
}
#endif
if (!initialized)
{
var appType = typeof(NSApplication);
var initField = appType.GetField("initialized", BindingFlags.Static | BindingFlags.NonPublic);
if (initField == null || Equals(initField.GetValue(null), false))
NSApplication.Init();
// until everything is marked as thread safe correctly in monomac
// e.g. overriding NSButtonCell.DrawBezelWithFrame will throw an exception
NSApplication.CheckForIllegalCrossThreadCalls = false;
initialized = true;
}
AddTo(this);
}
public static void AddTo(Eto.Platform p)
{
// Drawing
p.Add<Bitmap.IHandler>(() => new BitmapHandler());
p.Add<FontFamily.IHandler>(() => new FontFamilyHandler());
p.Add<Font.IHandler>(() => new FontHandler());
p.Add<Fonts.IHandler>(() => new FontsHandler());
p.Add<Graphics.IHandler>(() => new GraphicsHandler());
p.Add<GraphicsPath.IHandler>(() => new GraphicsPathHandler());
p.Add<Icon.IHandler>(() => new IconHandler());
p.Add<IndexedBitmap.IHandler>(() => new IndexedBitmapHandler());
p.Add<Matrix.IHandler>(() => new MatrixHandler());
p.Add<Pen.IHandler>(() => new PenHandler());
p.Add<SolidBrush.IHandler>(() => new SolidBrushHandler());
p.Add<TextureBrush.IHandler>(() => new TextureBrushHandler());
p.Add<LinearGradientBrush.IHandler>(() => new LinearGradientBrushHandler());
p.Add<RadialGradientBrush.IHandler>(() => new RadialGradientBrushHandler());
// Forms.Cells
p.Add<CheckBoxCell.IHandler>(() => new CheckBoxCellHandler());
p.Add<ComboBoxCell.IHandler>(() => new ComboBoxCellHandler());
p.Add<ImageTextCell.IHandler>(() => new ImageTextCellHandler());
p.Add<ImageViewCell.IHandler>(() => new ImageViewCellHandler());
p.Add<TextBoxCell.IHandler>(() => new TextBoxCellHandler());
p.Add<DrawableCell.IHandler>(() => new DrawableCellHandler());
p.Add<ProgressCell.IHandler>(() => new ProgressCellHandler());
// Forms.Controls
p.Add<Button.IHandler>(() => new ButtonHandler());
p.Add<Calendar.IHandler>(() => new CalendarHandler());
p.Add<CheckBox.IHandler>(() => new CheckBoxHandler());
p.Add<DropDown.IHandler>(() => new DropDownHandler());
p.Add<ComboBox.IHandler>(() => new ComboBoxHandler());
p.Add<ColorPicker.IHandler>(() => new ColorPickerHandler());
p.Add<DateTimePicker.IHandler>(() => new DateTimePickerHandler());
p.Add<Drawable.IHandler>(() => new DrawableHandler());
p.Add<GridColumn.IHandler>(() => new GridColumnHandler());
p.Add<GridView.IHandler>(() => new GridViewHandler());
p.Add<GroupBox.IHandler>(() => new GroupBoxHandler());
p.Add<ImageView.IHandler>(() => new ImageViewHandler());
p.Add<Label.IHandler>(() => new LabelHandler());
p.Add<LinkButton.IHandler>(() => new LinkButtonHandler());
p.Add<ListBox.IHandler>(() => new ListBoxHandler());
p.Add<NumericUpDown.IHandler>(() => new NumericUpDownHandler());
p.Add<Panel.IHandler>(() => new PanelHandler());
p.Add<PasswordBox.IHandler>(() => new PasswordBoxHandler());
p.Add<ProgressBar.IHandler>(() => new ProgressBarHandler());
p.Add<RadioButton.IHandler>(() => new RadioButtonHandler());
p.Add<Scrollable.IHandler>(() => new ScrollableHandler());
p.Add<SearchBox.IHandler>(() => new SearchBoxHandler());
p.Add<Slider.IHandler>(() => new SliderHandler());
p.Add<Spinner.IHandler>(() => new SpinnerHandler());
p.Add<Splitter.IHandler>(() => new SplitterHandler());
p.Add<TabControl.IHandler>(() => new TabControlHandler());
p.Add<TabPage.IHandler>(() => new TabPageHandler());
p.Add<TextArea.IHandler>(() => new TextAreaHandler());
p.Add<TextBox.IHandler>(() => new TextBoxHandler());
p.Add<TreeGridView.IHandler>(() => new TreeGridViewHandler());
p.Add<TreeView.IHandler>(() => new TreeViewHandler());
p.Add<WebView.IHandler>(() => new WebViewHandler());
p.Add<RichTextArea.IHandler>(() => new RichTextAreaHandler());
// Forms.Menu
p.Add<CheckMenuItem.IHandler>(() => new CheckMenuItemHandler());
p.Add<ContextMenu.IHandler>(() => new ContextMenuHandler());
p.Add<ButtonMenuItem.IHandler>(() => new ButtonMenuItemHandler());
p.Add<MenuBar.IHandler>(() => new MenuBarHandler());
p.Add<RadioMenuItem.IHandler>(() => new RadioMenuItemHandler());
p.Add<SeparatorMenuItem.IHandler>(() => new SeparatorMenuItemHandler());
// Forms.Printing
p.Add<PrintDialog.IHandler>(() => new PrintDialogHandler());
p.Add<PrintDocument.IHandler>(() => new PrintDocumentHandler());
p.Add<PrintSettings.IHandler>(() => new PrintSettingsHandler());
// Forms.ToolBar
p.Add<CheckToolItem.IHandler>(() => new CheckToolItemHandler());
p.Add<RadioToolItem.IHandler>(() => new RadioToolItemHandler());
p.Add<SeparatorToolItem.IHandler>(() => new SeparatorToolItemHandler());
p.Add<ButtonToolItem.IHandler>(() => new ButtonToolItemHandler());
p.Add<ToolBar.IHandler>(() => new ToolBarHandler());
// Forms
p.Add<Application.IHandler>(() => new ApplicationHandler());
p.Add<Clipboard.IHandler>(() => new ClipboardHandler());
p.Add<ColorDialog.IHandler>(() => new ColorDialogHandler());
p.Add<Cursor.IHandler>(() => new CursorHandler());
p.Add<Dialog.IHandler>(() => new DialogHandler());
p.Add<FontDialog.IHandler>(() => new FontDialogHandler());
p.Add<Form.IHandler>(() => new FormHandler());
p.Add<MessageBox.IHandler>(() => new MessageBoxHandler());
p.Add<OpenFileDialog.IHandler>(() => new OpenFileDialogHandler());
p.Add<PixelLayout.IHandler>(() => new PixelLayoutHandler());
p.Add<SaveFileDialog.IHandler>(() => new SaveFileDialogHandler());
p.Add<SelectFolderDialog.IHandler>(() => new SelectFolderDialogHandler());
p.Add<TableLayout.IHandler>(() => new TableLayoutHandler());
p.Add<UITimer.IHandler>(() => new UITimerHandler());
p.Add<Mouse.IHandler>(() => new MouseHandler());
p.Add<Screen.IScreensHandler>(() => new ScreensHandler());
p.Add<Keyboard.IHandler>(() => new KeyboardHandler());
p.Add<FixedMaskedTextProvider.IHandler>(() => new FixedMaskedTextProviderHandler());
// IO
p.Add<SystemIcons.IHandler>(() => new SystemIconsHandler());
// General
p.Add<EtoEnvironment.IHandler>(() => new EtoEnvironmentHandler());
p.Add<Thread.IHandler>(() => new ThreadHandler());
}
public override IDisposable ThreadStart()
{
return new NSAutoreleasePool();
}
public override bool IsValid
{
get
{
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
return assembly.Location.StartsWith(NSBundle.MainBundle.BundlePath, StringComparison.Ordinal);
}
}
static void LinkingOverrides()
{
// Prevent linking system code used via reflection in Eto.dll due to pcl restrictions
Assembly.GetCallingAssembly();
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.XR.iOS;
using System.Text;
using System.Collections.Generic;
namespace UnityEngine.XR.iOS.Utils
{
/// <summary>
/// Since unity doesn't flag the Vector4 as serializable, we
/// need to create our own version. This one will automatically convert
/// between Vector4 and SerializableVector4
/// </summary>
[Serializable]
public class SerializableVector4
{
/// <summary>
/// x component
/// </summary>
public float x;
/// <summary>
/// y component
/// </summary>
public float y;
/// <summary>
/// z component
/// </summary>
public float z;
/// <summary>
/// w component
/// </summary>
public float w;
/// <summary>
/// Constructor
/// </summary>
/// <param name="rX"></param>
/// <param name="rY"></param>
/// <param name="rZ"></param>
/// <param name="rW"></param>
public SerializableVector4(float rX, float rY, float rZ, float rW)
{
x = rX;
y = rY;
z = rZ;
w = rW;
}
/// <summary>
/// Returns a string representation of the object
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("[{0}, {1}, {2}, {3}]", x, y, z, w);
}
/// <summary>
/// Automatic conversion from SerializableVector4 to Vector4
/// </summary>
/// <param name="rValue"></param>
/// <returns></returns>
public static implicit operator Vector4(SerializableVector4 rValue)
{
return new Vector4(rValue.x, rValue.y, rValue.z, rValue.w);
}
/// <summary>
/// Automatic conversion from Vector4 to SerializableVector4
/// </summary>
/// <param name="rValue"></param>
/// <returns></returns>
public static implicit operator SerializableVector4(Vector4 rValue)
{
return new SerializableVector4(rValue.x, rValue.y, rValue.z, rValue.w);
}
}
[Serializable]
public class serializableUnityARMatrix4x4
{
public SerializableVector4 column0;
public SerializableVector4 column1;
public SerializableVector4 column2;
public SerializableVector4 column3;
public serializableUnityARMatrix4x4(SerializableVector4 v0, SerializableVector4 v1, SerializableVector4 v2, SerializableVector4 v3)
{
column0 = v0;
column1 = v1;
column2 = v2;
column3 = v3;
}
/// <summary>
/// Automatic conversion from UnityARMatrix4x4 to serializableUnityARMatrix4x4
/// </summary>
/// <param name="rValue"></param>
/// <returns></returns>
public static implicit operator serializableUnityARMatrix4x4(UnityARMatrix4x4 rValue)
{
return new serializableUnityARMatrix4x4(rValue.column0, rValue.column1, rValue.column2, rValue.column3);
}
/// <summary>
/// Automatic conversion from serializableUnityARMatrix4x4 to UnityARMatrix4x4
/// </summary>
/// <param name="rValue"></param>
/// <returns></returns>
public static implicit operator UnityARMatrix4x4(serializableUnityARMatrix4x4 rValue)
{
return new UnityARMatrix4x4(rValue.column0, rValue.column1, rValue.column2, rValue.column3);
}
public static implicit operator serializableUnityARMatrix4x4(Matrix4x4 rValue)
{
return new serializableUnityARMatrix4x4(rValue.GetColumn(0), rValue.GetColumn(1), rValue.GetColumn(2), rValue.GetColumn(3));
}
public static implicit operator Matrix4x4(serializableUnityARMatrix4x4 rValue)
{
#if UNITY_2017_1_OR_NEWER
return new Matrix4x4(rValue.column0, rValue.column1, rValue.column2, rValue.column3);
#else
Matrix4x4 mRet = new Matrix4x4 ();
mRet.SetColumn (0, rValue.column0);
mRet.SetColumn (1, rValue.column1);
mRet.SetColumn (2, rValue.column2);
mRet.SetColumn (3, rValue.column3);
return mRet;
#endif
}
};
[Serializable]
public class serializableSHC
{
public byte [] shcData;
public serializableSHC(byte [] inputSHCData)
{
shcData = inputSHCData;
}
public static implicit operator serializableSHC(float [] floatsSHC)
{
if (floatsSHC != null)
{
byte [] createBuf = new byte[floatsSHC.Length * sizeof(float)];
for(int i = 0; i < floatsSHC.Length; i++)
{
Buffer.BlockCopy( BitConverter.GetBytes( floatsSHC[i] ), 0, createBuf, (i)*sizeof(float), sizeof(float) );
}
return new serializableSHC (createBuf);
}
else
{
return new serializableSHC(null);
}
}
public static implicit operator float [] (serializableSHC spc)
{
if (spc.shcData != null)
{
int numFloats = spc.shcData.Length / (sizeof(float));
float [] shcFloats = new float[numFloats];
for (int i = 0; i < numFloats; i++)
{
shcFloats [i] = BitConverter.ToSingle (spc.shcData, i * sizeof(float));
}
return shcFloats;
}
else
{
return null;
}
}
};
[Serializable]
public class serializableUnityARLightData
{
public LightDataType whichLight;
public serializableSHC lightSHC;
public SerializableVector4 primaryLightDirAndIntensity;
public float ambientIntensity;
public float ambientColorTemperature;
serializableUnityARLightData(UnityARLightData lightData)
{
whichLight = lightData.arLightingType;
if (whichLight == LightDataType.DirectionalLightEstimate) {
lightSHC = lightData.arDirectonalLightEstimate.sphericalHarmonicsCoefficients;
Vector3 lightDir = lightData.arDirectonalLightEstimate.primaryLightDirection;
float lightIntensity = lightData.arDirectonalLightEstimate.primaryLightIntensity;
primaryLightDirAndIntensity = new SerializableVector4 (lightDir.x, lightDir.y, lightDir.z, lightIntensity);
} else {
ambientIntensity = lightData.arLightEstimate.ambientIntensity;
ambientColorTemperature = lightData.arLightEstimate.ambientColorTemperature;
}
}
public static implicit operator serializableUnityARLightData(UnityARLightData rValue)
{
return new serializableUnityARLightData(rValue);
}
public static implicit operator UnityARLightData(serializableUnityARLightData rValue)
{
UnityARDirectionalLightEstimate udle = null;
UnityARLightEstimate ule = new UnityARLightEstimate (rValue.ambientIntensity, rValue.ambientColorTemperature);
if (rValue.whichLight == LightDataType.DirectionalLightEstimate) {
Vector3 lightDir = new Vector3 (rValue.primaryLightDirAndIntensity.x, rValue.primaryLightDirAndIntensity.y, rValue.primaryLightDirAndIntensity.z);
udle = new UnityARDirectionalLightEstimate (rValue.lightSHC, lightDir, rValue.primaryLightDirAndIntensity.w);
}
return new UnityARLightData(rValue.whichLight, ule, udle);
}
}
[Serializable]
public class serializableUnityARCamera
{
public serializableUnityARMatrix4x4 worldTransform;
public serializableUnityARMatrix4x4 projectionMatrix;
public ARTrackingState trackingState;
public ARTrackingStateReason trackingReason;
public UnityVideoParams videoParams;
public serializableUnityARLightData lightData;
public serializablePointCloud pointCloud;
public serializableUnityARMatrix4x4 displayTransform;
public serializableUnityARCamera( serializableUnityARMatrix4x4 wt, serializableUnityARMatrix4x4 pm, ARTrackingState ats, ARTrackingStateReason atsr, UnityVideoParams uvp, UnityARLightData lightDat, serializableUnityARMatrix4x4 dt, serializablePointCloud spc)
{
worldTransform = wt;
projectionMatrix = pm;
trackingState = ats;
trackingReason = atsr;
videoParams = uvp;
lightData = lightDat;
displayTransform = dt;
pointCloud = spc;
}
public static implicit operator serializableUnityARCamera(UnityARCamera rValue)
{
return new serializableUnityARCamera(rValue.worldTransform, rValue.projectionMatrix, rValue.trackingState, rValue.trackingReason, rValue.videoParams, rValue.lightData, rValue.displayTransform, rValue.pointCloudData);
}
public static implicit operator UnityARCamera(serializableUnityARCamera rValue)
{
return new UnityARCamera (rValue.worldTransform, rValue.projectionMatrix, rValue.trackingState, rValue.trackingReason, rValue.videoParams, rValue.lightData, rValue.displayTransform, rValue.pointCloud);
}
};
[Serializable]
public class serializablePlaneGeometry
{
public byte [] vertices;
public byte [] texCoords;
public byte [] triIndices;
public byte[] boundaryVertices;
public serializablePlaneGeometry(byte [] inputVertices, byte [] inputTexCoords, byte [] inputTriIndices, byte [] boundaryVerts)
{
vertices = inputVertices;
texCoords = inputTexCoords;
triIndices = inputTriIndices;
boundaryVertices = boundaryVerts;
}
#if !UNITY_EDITOR
public static implicit operator serializablePlaneGeometry(ARPlaneGeometry planeGeom)
{
if (planeGeom.vertexCount != 0 && planeGeom.textureCoordinateCount != 0 && planeGeom.triangleCount != 0)
{
Vector3 [] planeVertices = planeGeom.vertices;
byte [] cbVerts = new byte[planeGeom.vertexCount * sizeof(float) * 3];
Buffer.BlockCopy( planeVertices, 0, cbVerts, 0, planeGeom.vertexCount * sizeof(float) * 3 );
Vector3 [] boundaryVertices = planeGeom.boundaryVertices;
byte [] cbBVerts = new byte[planeGeom.boundaryVertexCount * sizeof(float) * 3];
Buffer.BlockCopy( boundaryVertices, 0, cbBVerts, 0, planeGeom.boundaryVertexCount * sizeof(float) * 3 );
Vector2 [] planeTexCoords = planeGeom.textureCoordinates;
byte [] cbTexCoords = new byte[planeGeom.textureCoordinateCount * sizeof(float) * 2];
Buffer.BlockCopy( planeTexCoords, 0, cbTexCoords, 0, planeGeom.textureCoordinateCount * sizeof(float) * 2 );
int [] triIndices = planeGeom.triangleIndices;
byte [] cbTriIndices = triIndices.SerializeToByteArray();
return new serializablePlaneGeometry (cbVerts, cbTexCoords, cbTriIndices, cbBVerts);
}
else
{
return new serializablePlaneGeometry(null, null, null, null);
}
}
#endif //!UNITY_EDITOR
public Vector3 [] Vertices {
get {
if (vertices != null) {
int numVectors = vertices.Length / (3 * sizeof(float));
Vector3[] verticesVec = new Vector3[numVectors];
for (int i = 0; i < numVectors; i++) {
int bufferStart = i * 3;
verticesVec [i].x = BitConverter.ToSingle (vertices, (bufferStart) * sizeof(float));
verticesVec [i].y = BitConverter.ToSingle (vertices, (bufferStart + 1) * sizeof(float));
verticesVec [i].z = BitConverter.ToSingle (vertices, (bufferStart + 2) * sizeof(float));
}
return verticesVec;
} else {
return null;
}
}
}
public Vector3 [] BoundaryVertices {
get {
if (boundaryVertices != null) {
int numVectors = boundaryVertices.Length / (3 * sizeof(float));
Vector3[] verticesVec = new Vector3[numVectors];
for (int i = 0; i < numVectors; i++) {
int bufferStart = i * 3;
verticesVec [i].x = BitConverter.ToSingle (boundaryVertices, (bufferStart) * sizeof(float));
verticesVec [i].y = BitConverter.ToSingle (boundaryVertices, (bufferStart + 1) * sizeof(float));
verticesVec [i].z = BitConverter.ToSingle (boundaryVertices, (bufferStart + 2) * sizeof(float));
}
return verticesVec;
} else {
return null;
}
}
}
public Vector2 [] TexCoords {
get {
if (texCoords != null) {
int numVectors = texCoords.Length / (2 * sizeof(float));
Vector2[] texCoordVec = new Vector2[numVectors];
for (int i = 0; i < numVectors; i++) {
int bufferStart = i * 2;
texCoordVec [i].x = BitConverter.ToSingle (texCoords, (bufferStart) * sizeof(float));
texCoordVec [i].y = BitConverter.ToSingle (texCoords, (bufferStart + 1) * sizeof(float));
}
return texCoordVec;
} else {
return null;
}
}
}
public int [] TriangleIndices {
get {
if (triIndices != null) {
int[] triIndexVec = triIndices.Deserialize<int[]>();
return triIndexVec;
} else {
return null;
}
}
}
};
[Serializable]
public class serializableUnityARPlaneAnchor
{
public serializableUnityARMatrix4x4 worldTransform;
public SerializableVector4 center;
public SerializableVector4 extent;
public ARPlaneAnchorAlignment planeAlignment;
public serializablePlaneGeometry planeGeometry;
public byte[] identifierStr;
public serializableUnityARPlaneAnchor( serializableUnityARMatrix4x4 wt, SerializableVector4 ctr, SerializableVector4 ext, ARPlaneAnchorAlignment apaa,
serializablePlaneGeometry spg, byte [] idstr)
{
worldTransform = wt;
center = ctr;
extent = ext;
planeAlignment = apaa;
identifierStr = idstr;
planeGeometry = spg;
}
#if UNITY_EDITOR
public static implicit operator ARPlaneAnchor(serializableUnityARPlaneAnchor rValue)
{
return new ARPlaneAnchor(rValue);
}
#else //!UNITY_EDITOR
public static implicit operator serializableUnityARPlaneAnchor(ARPlaneAnchor rValue)
{
serializableUnityARMatrix4x4 wt = rValue.transform;
SerializableVector4 ctr = new SerializableVector4 (rValue.center.x, rValue.center.y, rValue.center.z, 1.0f);
SerializableVector4 ext = new SerializableVector4 (rValue.extent.x, rValue.extent.y, rValue.extent.z, 1.0f);
byte[] idstr = Encoding.UTF8.GetBytes (rValue.identifier);
serializablePlaneGeometry spg = rValue.planeGeometry;
return new serializableUnityARPlaneAnchor(wt, ctr, ext, rValue.alignment, spg, idstr);
}
#endif
};
[Serializable]
public class serializableFaceGeometry
{
public byte [] vertices;
public byte [] texCoords;
public byte [] triIndices;
public serializableFaceGeometry(byte [] inputVertices, byte [] inputTexCoords, byte [] inputTriIndices)
{
vertices = inputVertices;
texCoords = inputTexCoords;
triIndices = inputTriIndices;
}
#if !UNITY_EDITOR
public static implicit operator serializableFaceGeometry(ARFaceGeometry faceGeom)
{
if (faceGeom.vertexCount != 0 && faceGeom.textureCoordinateCount != 0 && faceGeom.triangleCount != 0)
{
Vector3 [] faceVertices = faceGeom.vertices;
byte [] cbVerts = new byte[faceGeom.vertexCount * sizeof(float) * 3];
Buffer.BlockCopy( faceVertices, 0, cbVerts, 0, faceGeom.vertexCount * sizeof(float) * 3 );
Vector2 [] faceTexCoords = faceGeom.textureCoordinates;
byte [] cbTexCoords = new byte[faceGeom.textureCoordinateCount * sizeof(float) * 2];
Buffer.BlockCopy( faceTexCoords, 0, cbTexCoords, 0, faceGeom.textureCoordinateCount * sizeof(float) * 2 );
int [] triIndices = faceGeom.triangleIndices;
byte [] cbTriIndices = triIndices.SerializeToByteArray();
return new serializableFaceGeometry (cbVerts, cbTexCoords, cbTriIndices);
}
else
{
return new serializableFaceGeometry(null, null, null);
}
}
#endif //!UNITY_EDITOR
public Vector3 [] Vertices {
get {
if (vertices != null) {
int numVectors = vertices.Length / (3 * sizeof(float));
Vector3[] verticesVec = new Vector3[numVectors];
for (int i = 0; i < numVectors; i++) {
int bufferStart = i * 3;
verticesVec [i].x = BitConverter.ToSingle (vertices, (bufferStart) * sizeof(float));
verticesVec [i].y = BitConverter.ToSingle (vertices, (bufferStart + 1) * sizeof(float));
verticesVec [i].z = BitConverter.ToSingle (vertices, (bufferStart + 2) * sizeof(float));
}
return verticesVec;
} else {
return null;
}
}
}
public Vector2 [] TexCoords {
get {
if (texCoords != null) {
int numVectors = texCoords.Length / (2 * sizeof(float));
Vector2[] texCoordVec = new Vector2[numVectors];
for (int i = 0; i < numVectors; i++) {
int bufferStart = i * 2;
texCoordVec [i].x = BitConverter.ToSingle (texCoords, (bufferStart) * sizeof(float));
texCoordVec [i].y = BitConverter.ToSingle (texCoords, (bufferStart + 1) * sizeof(float));
}
return texCoordVec;
} else {
return null;
}
}
}
public int [] TriangleIndices {
get {
if (triIndices != null) {
int[] triIndexVec = triIndices.Deserialize<int[]>();
return triIndexVec;
} else {
return null;
}
}
}
};
[Serializable]
public class serializableUnityARFaceAnchor
{
public serializableUnityARMatrix4x4 worldTransform;
public serializableFaceGeometry faceGeometry;
public Dictionary<string, float> arBlendShapes;
public byte[] identifierStr;
public serializableUnityARFaceAnchor( serializableUnityARMatrix4x4 wt, serializableFaceGeometry fg, Dictionary<string, float> bs, byte [] idstr)
{
worldTransform = wt;
faceGeometry = fg;
arBlendShapes = bs;
identifierStr = idstr;
}
#if UNITY_EDITOR
public static implicit operator ARFaceAnchor(serializableUnityARFaceAnchor rValue)
{
return new ARFaceAnchor(rValue);
}
#else
public static implicit operator serializableUnityARFaceAnchor(ARFaceAnchor rValue)
{
serializableUnityARMatrix4x4 wt = rValue.transform;
serializableFaceGeometry sfg = rValue.faceGeometry;
byte[] idstr = Encoding.UTF8.GetBytes (rValue.identifierStr);
return new serializableUnityARFaceAnchor(wt, sfg, rValue.blendShapes, idstr);
}
#endif
};
[Serializable]
public class serializablePointCloud
{
public byte [] pointCloudData;
public serializablePointCloud(byte [] inputPoints)
{
pointCloudData = inputPoints;
}
public static implicit operator serializablePointCloud(Vector3 [] vecPointCloud)
{
if (vecPointCloud != null)
{
byte [] createBuf = new byte[vecPointCloud.Length * sizeof(float) * 3];
for(int i = 0; i < vecPointCloud.Length; i++)
{
int bufferStart = i * 3;
Buffer.BlockCopy( BitConverter.GetBytes( vecPointCloud[i].x ), 0, createBuf, (bufferStart)*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vecPointCloud[i].y ), 0, createBuf, (bufferStart+1)*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vecPointCloud[i].z ), 0, createBuf, (bufferStart+2)*sizeof(float), sizeof(float) );
}
return new serializablePointCloud (createBuf);
}
else
{
return new serializablePointCloud(null);
}
}
public static implicit operator Vector3 [] (serializablePointCloud spc)
{
if (spc.pointCloudData != null)
{
int numVectors = spc.pointCloudData.Length / (3 * sizeof(float));
Vector3 [] pointCloudVec = new Vector3[numVectors];
for (int i = 0; i < numVectors; i++)
{
int bufferStart = i * 3;
pointCloudVec [i].x = BitConverter.ToSingle (spc.pointCloudData, (bufferStart) * sizeof(float));
pointCloudVec [i].y = BitConverter.ToSingle (spc.pointCloudData, (bufferStart+1) * sizeof(float));
pointCloudVec [i].z = BitConverter.ToSingle (spc.pointCloudData, (bufferStart+2) * sizeof(float));
}
return pointCloudVec;
}
else
{
return null;
}
}
};
[Serializable]
public class serializableARSessionConfiguration
{
public UnityARAlignment alignment;
public UnityARPlaneDetection planeDetection;
public bool getPointCloudData;
public bool enableLightEstimation;
public bool enableAutoFocus;
public serializableARSessionConfiguration(UnityARAlignment align, UnityARPlaneDetection planeDet, bool getPtCloud, bool enableLightEst, bool enableAutoFoc)
{
alignment = align;
planeDetection = planeDet;
getPointCloudData = getPtCloud;
enableLightEstimation = enableLightEst;
enableAutoFocus = enableAutoFoc;
}
public static implicit operator serializableARSessionConfiguration(ARKitWorldTrackingSessionConfiguration awtsc)
{
return new serializableARSessionConfiguration (awtsc.alignment, awtsc.planeDetection, awtsc.getPointCloudData, awtsc.enableLightEstimation, awtsc.enableAutoFocus);
}
public static implicit operator ARKitWorldTrackingSessionConfiguration (serializableARSessionConfiguration sasc)
{
return new ARKitWorldTrackingSessionConfiguration (sasc.alignment, sasc.planeDetection, sasc.getPointCloudData, sasc.enableLightEstimation, sasc.enableAutoFocus);
}
public static implicit operator ARKitFaceTrackingConfiguration (serializableARSessionConfiguration sasc)
{
return new ARKitFaceTrackingConfiguration (sasc.alignment, sasc.enableLightEstimation);
}
};
[Serializable]
public class serializableARKitInit
{
public serializableARSessionConfiguration config;
public UnityARSessionRunOption runOption;
public serializableARKitInit(serializableARSessionConfiguration cfg, UnityARSessionRunOption option)
{
config = cfg;
runOption = option;
}
};
[Serializable]
public class serializableFromEditorMessage
{
public Guid subMessageId;
public serializableARKitInit arkitConfigMsg;
};
}
| |
//----------------------------------------------------------------------------------------------
// Copyright 2014 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TodoListService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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.Generic;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// </summary>
/// <param name="className">One or more space-separated classes to be added to the class attribute of each matched element.</param>
/// <returns></returns>
public virtual jQuery AddClass(string className)
{
return null;
}
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// </summary>
/// <param name="function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery AddClass(Delegate function)
{
return null;
}
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// </summary>
/// <param name="function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery AddClass(Func<int, string> function)
{
return null;
}
/// <summary>
/// Adds the specified class(es) to each of the set of matched elements.
/// </summary>
/// <param name="function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery AddClass(Func<int, string, string> function)
{
return null;
}
/// <summary>
/// Get the value of an attribute for the first element in the set of matched elements.
/// </summary>
/// <param name="attributeName">The name of the attribute to get.</param>
/// <returns></returns>
public virtual string Attr(string attributeName)
{
return null;
}
/// <summary>
/// Get the value of an attribute for the first element in the set of matched elements.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="attributeName">The name of the attribute to get.</param>
/// <returns></returns>
public virtual T Attr<T>(string attributeName)
{
return default(T);
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributeName">The name of the attribute to set.</param>
/// <param name="value">A value to set for the attribute.</param>
/// <returns></returns>
public virtual jQuery Attr(string attributeName, string value)
{
return null;
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributeName">The name of the attribute to set.</param>
/// <param name="value">A value to set for the attribute.</param>
/// <returns></returns>
public virtual jQuery Attr(string attributeName, int value)
{
return null;
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributes">An object of attribute-value pairs to set.</param>
/// <returns></returns>
public virtual jQuery Attr(Dictionary<string, object> attributes)
{
return null;
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributes">An object of attribute-value pairs to set.</param>
/// <returns></returns>
public virtual jQuery Attr(object attributes)
{
return null;
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributeName">The name of the attribute to set.</param>
/// <param name="function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.</param>
/// <returns></returns>
public virtual jQuery Attr(string attributeName, Delegate function)
{
return null;
}
/// <summary>
/// Set one or more attributes for the set of matched elements.
/// </summary>
/// <param name="attributeName">The name of the attribute to set.</param>
/// <param name="function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.</param>
/// <returns></returns>
public virtual jQuery Attr(string attributeName, Func<int, string> function)
{
return null;
}
/// <summary>
/// Determine whether any of the matched elements are assigned the given class.
/// </summary>
/// <param name="className">The class name to search for.</param>
/// <returns>boolean</returns>
public virtual bool HasClass(string className)
{
return false;
}
/// <summary>
/// Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
/// </summary>
/// <returns></returns>
public virtual string Html()
{
return null;
}
/// <summary>
/// Set the HTML contents of each element in the set of matched elements.
/// </summary>
/// <param name="htmlString">A string of HTML to set as the content of each matched element.</param>
/// <returns></returns>
public virtual jQuery Html(string htmlString)
{
return null;
}
/// <summary>
/// Set the HTML contents of each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Html(Delegate function)
{
return null;
}
/// <summary>
/// Set the HTML contents of each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Html(Func<int, string, string> function)
{
return null;
}
/// <summary>
/// Get the value of a property for the first element in the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to get.</param>
/// <returns></returns>
public virtual string Prop(string propertyName)
{
return null;
}
/// <summary>
/// Get the value of a property for the first element in the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to get.</param>
/// <returns></returns>
public virtual T Prop<T>(string propertyName)
{
return default(T);
}
/// <summary>
/// Set one or more properties for the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to set.</param>
/// <param name="value">A value to set for the property.</param>
/// <returns></returns>
public virtual jQuery Prop(string propertyName, object value)
{
return null;
}
/// <summary>
/// Set one or more properties for the set of matched elements.
/// </summary>
/// <param name="properties">An object of property-value pairs to set.</param>
/// <returns></returns>
public virtual jQuery Prop(Dictionary<string, object> properties)
{
return null;
}
/// <summary>
/// Set one or more properties for the set of matched elements.
/// </summary>
/// <param name="properties">An object of property-value pairs to set.</param>
/// <returns></returns>
public virtual jQuery Prop(object properties)
{
return null;
}
/// <summary>
/// Set one or more properties for the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to set.</param>
/// <param name="function">A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.</param>
/// <returns></returns>
public virtual jQuery Prop(string propertyName, Delegate function)
{
return null;
}
/// <summary>
/// Set one or more properties for the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to set.</param>
/// <param name="function">A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.</param>
/// <returns></returns>
public virtual jQuery Prop(string propertyName, Func<int, object, object> function)
{
return null;
}
/// <summary>
/// Remove an attribute from each element in the set of matched elements.
/// </summary>
/// <param name="attributeName">An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.</param>
/// <returns></returns>
public virtual jQuery RemoveAttr(string attributeName)
{
return null;
}
/// <summary>
/// Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
/// </summary>
/// <param name="className">One or more space-separated classes to be removed from the class attribute of each matched element.</param>
/// <returns></returns>
public virtual jQuery RemoveClass(string className)
{
return null;
}
/// <summary>
/// Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.</param>
/// <returns></returns>
public virtual jQuery RemoveClass(Delegate function)
{
return null;
}
/// <summary>
/// Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.</param>
/// <returns></returns>
public virtual jQuery RemoveClass(Func<int, string, string> function)
{
return null;
}
/// <summary>
/// Remove a property for the set of matched elements.
/// </summary>
/// <param name="propertyName">The name of the property to remove.</param>
/// <returns></returns>
public virtual jQuery RemoveProp(string propertyName)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="className">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(string className)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="className">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param>
/// <param name="switch">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(string className, bool @switch)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <returns></returns>
public virtual jQuery ToggleClass()
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="switch">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(bool @switch)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(Delegate function)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(Func<int, string, bool, string> function)
{
return null;
}
/// <summary>
/// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
/// </summary>
/// <param name="function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param>
/// <param name="switch">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param>
/// <returns></returns>
public virtual jQuery ToggleClass(Func<int, string, bool, string> function, bool @switch)
{
return null;
}
/// <summary>
/// Get the current value of the first element in the set of matched elements.
/// </summary>
/// <returns></returns>
public virtual string Val()
{
return null;
}
/// <summary>
/// Get the current value of the first element in the set of matched elements.
/// </summary>
/// <returns></returns>
public virtual T Val<T>()
{
return default(T);
}
/// <summary>
/// Set the value of each element in the set of matched elements.
/// </summary>
/// <param name="value">A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.</param>
/// <returns></returns>
public virtual jQuery Val(string value)
{
return null;
}
/// <summary>
/// Set the value of each element in the set of matched elements.
/// </summary>
/// <param name="value">A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.</param>
/// <returns></returns>
public virtual jQuery Val(string[] value)
{
return null;
}
/// <summary>
/// Set the value of each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param>
/// <returns></returns>
public virtual jQuery Value(Delegate function)
{
return null;
}
/// <summary>
/// Set the value of each element in the set of matched elements.
/// </summary>
/// <param name="function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param>
/// <returns></returns>
public virtual jQuery Value(Func<int, string, string> function)
{
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Windows.Forms;
namespace AIEdit
{
public abstract class TriggerTypeOption
{
protected string name;
private int sortOrder;
public string Name { get { return name; } }
public int SortOrder { get { return sortOrder; } }
public abstract IList List { get; }
public abstract string ToString(object value);
public abstract TriggerTypeEntry DefaultValue();
public TriggerTypeOption(string name, int sortOrder)
{
this.name = name;
this.sortOrder = sortOrder;
}
public virtual object FindByIndex(int index, object def=null)
{
foreach (AITypeListEntry entry in this.List)
{
if (entry.Index == index) return entry;
}
return def;
}
public virtual object FindByString(string str, object def=null)
{
foreach (AITypeListEntry entry in this.List)
{
if (entry.Name == str) return entry;
}
return def;
}
}
public class TriggerTypeOptionBool : TriggerTypeOptionList
{
private static List<AITypeListEntry> bools = new List<AITypeListEntry>()
{
new AITypeListEntry(0, "no"),
new AITypeListEntry(1, "yes"),
};
public TriggerTypeOptionBool(string name, int sortOrder)
: base(name, sortOrder, bools)
{
}
}
public class TriggerTypeOptionNumber : TriggerTypeOption
{
public override IList List { get { return null; } }
public override string ToString(object value)
{
return value.ToString();
}
public TriggerTypeOptionNumber(string name, int sortOrder)
: base(name, sortOrder)
{
}
public override TriggerTypeEntry DefaultValue()
{
return new TriggerTypeEntry(this, 0U);
}
}
public class TriggerTypeOptionList : TriggerTypeOption
{
protected IList dataList;
public override IList List { get { return dataList; } }
public override string ToString(object value)
{
return (value as AITypeListEntry).Index.ToString();
}
public TriggerTypeOptionList(string name, int sortOrder, IList dataList)
: base(name, sortOrder)
{
this.dataList = dataList;
}
public override TriggerTypeEntry DefaultValue()
{
return new TriggerTypeEntry(this, dataList[0]);
}
}
public class TriggerTypeOptionStringList : TriggerTypeOptionList
{
public override string ToString(object value)
{
return (value as AITypeListEntry).Name;
}
public TriggerTypeOptionStringList(string name, int sortOrder, IList dataList)
: base(name, sortOrder, dataList)
{
}
}
public class TriggerTypeOptionAIObject : TriggerTypeOptionList
{
public override string ToString(object value)
{
return (value as IAIObject).ID;
}
public TriggerTypeOptionAIObject(string name, int sortOrder, IList dataList)
: base(name, sortOrder, dataList)
{
}
public override object FindByString(string str, object def=null)
{
foreach (IAIObject entry in this.List)
{
if (entry.ID == str) return entry;
}
return def;
}
}
public class TriggerTypeOptionTechno : TriggerTypeOptionList
{
public override string ToString(object value)
{
return (value as TechnoType).ID;
}
public TriggerTypeOptionTechno(string name, int sortOrder, IList dataList)
: base(name, sortOrder, dataList)
{
}
public override object FindByString(string str, object def = null)
{
foreach (TechnoType entry in this.List)
{
if (entry.ID == str) return entry;
}
return def;
}
}
public class TriggerTypeEntry
{
private TriggerTypeOption option;
private object value;
public object Value
{
get
{
return value;
}
set
{
if (this.value is IAIObject) (this.value as IAIObject).DecUses();
if (value is IAIObject) (value as IAIObject).IncUses();
this.value = value;
}
}
public void Reset()
{
if (this.value is IAIObject) (this.value as IAIObject).DecUses();
this.value = null;
}
public string Name { get { return option.Name; } }
public int SortOrder { get { return option.SortOrder; } }
public IList List { get { return option.List; } }
public TriggerTypeOption Option { get { return option; } }
public TriggerTypeEntry(TriggerTypeOption option, object value)
{
this.option = option;
this.Value = value;
}
public TriggerTypeEntry(TriggerTypeEntry other)
{
this.option = other.option;
this.Value = other.Value;
}
public override string ToString()
{
return option.ToString(value);
}
}
public class TriggerType : IAIObject, IEnumerable<TriggerTypeEntry>
{
private string id, name;
private Dictionary<string, TriggerTypeEntry> entries;
public string Side { get { return entries["Side"].Value.ToString(); } }
public string Easy { get { return (entries["Easy"].Value as AITypeListEntry).Index == 0 ? "N" : "Y"; } }
public string Medium { get { return (entries["Medium"].Value as AITypeListEntry).Index == 0 ? "N" : "Y"; } }
public string Hard { get { return (entries["Hard"].Value as AITypeListEntry).Index == 0 ? "N" : "Y"; } }
public uint TechLevel { get { return (uint)entries["TechLevel"].Value; } }
public uint InitialWeight { get { return (uint)entries["Prob"].Value; } }
public string ID { get { return id; } }
public string Name { get { return name; } set { name = value.Trim(); } }
public int Uses { get { return 0; } }
public void IncUses() { }
public void DecUses() { }
public bool HasTeamType(TeamType tt)
{
return entries["Team1"].Value == tt || entries["Team2"].Value == tt;
}
public IEnumerator<TriggerTypeEntry> GetEnumerator()
{
return entries.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Reset()
{
foreach (KeyValuePair<string, TriggerTypeEntry> e in entries) e.Value.Reset();
entries.Clear();
}
public TriggerType(string id, string name, Dictionary<string, TriggerTypeEntry> entries)
{
this.id = id;
this.Name = name;
this.entries = entries;
}
public TriggerType(string id, string name, Dictionary<string, TriggerTypeOption> triggerTypeOptions)
{
this.id = id;
this.Name = name;
this.entries = new Dictionary<string, TriggerTypeEntry>();
foreach(KeyValuePair<string, TriggerTypeOption> option in triggerTypeOptions)
{
this.entries.Add(option.Key, option.Value.DefaultValue());
}
}
public IAIObject Copy(string newid, string newname)
{
Dictionary<string, TriggerTypeEntry> newentries = new Dictionary<string, TriggerTypeEntry>();
foreach (var e in this.entries) newentries[e.Key] = new TriggerTypeEntry(e.Value);
return new TriggerType(newid, newname, newentries);
}
public void Write(StreamWriter stream)
{
string s = string.Format("{0}={1},{2},{3},{4},{5},{6},{7}0{8}000000000000000000000000000000000000000000000000000000,{9}.000000,{10}.000000,{11}.000000,{12},0,{13},{14},{15},{16},{17},{18}",
id,
name,
(entries["Team1"].Value as TeamType).ID,
entries["Owner"].Value,
entries["TechLevel"].Value,
(entries["Condition"].Value as AITypeListEntry).Index,
(entries["TechType"].Value as TechnoType).ID,
((uint)entries["Amount"].Value).SwapEndianness().ToString("x8"),
(entries["Operator"].Value as AITypeListEntry).Index,
entries["Prob"].Value,
entries["ProbMin"].Value,
entries["ProbMax"].Value,
(entries["Skirmish"].Value as AITypeListEntry).Index,
(entries["Side"].Value as AITypeListEntry).Index,
(entries["BaseDefense"].Value as AITypeListEntry).Index,
(entries["Team2"].Value as TeamType).ID,
(entries["Easy"].Value as AITypeListEntry).Index,
(entries["Medium"].Value as AITypeListEntry).Index,
(entries["Hard"].Value as AITypeListEntry).Index
);
stream.WriteLine(s);
}
public static TriggerType Parse(string id, string data,
Dictionary<string, TriggerTypeOption> triggerTypeOptions, TeamType noneTeam, TechnoType noneTechno,
Logger logger)
{
string[] split = data.Split(',');
string tag;
string name = split[0];
TriggerTypeOption option;
Dictionary<string, TriggerTypeEntry> entries = new Dictionary<string, TriggerTypeEntry>();
object value;
// no name given
if (name.Length == 0) name = id;
if(split.Length < 18)
{
logger.Add("Trigger [" + name + "] cannot be parsed because it has an invalid number of parameters!");
return null;
}
try
{
// team 1
tag = "Team1";
option = triggerTypeOptions[tag];
value = option.FindByString(split[1], noneTeam);
entries.Add(tag, new TriggerTypeEntry(option, value));
// owner
tag = "Owner";
option = triggerTypeOptions[tag];
value = option.FindByString(split[2]);
entries.Add(tag, new TriggerTypeEntry(option, value));
// techlevel
tag = "TechLevel";
option = triggerTypeOptions[tag];
value = uint.Parse(split[3]);
entries.Add(tag, new TriggerTypeEntry(option, value));
// condition
tag = "Condition";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse(split[4]));
entries.Add(tag, new TriggerTypeEntry(option, value));
// techtype
tag = "TechType";
option = triggerTypeOptions[tag];
string unitid = split[5];
value = noneTechno;
if (unitid != "<none>")
{
value = option.FindByString(unitid);
if (value == null)
{
logger.Add("TechnoType [" + split[5] + "] referenced by Trigger [" + id + "] does not exist!");
value = new TechnoType(unitid, unitid, 0, 0);
option.List.Add(value);
}
}
entries.Add(tag, new TriggerTypeEntry(option, value));
// amount
tag = "Amount";
option = triggerTypeOptions[tag];
value = Convert.ToUInt32(split[6].Substring(0, 8), 16).SwapEndianness();
entries.Add(tag, new TriggerTypeEntry(option, value));
// operator
tag = "Operator";
option = triggerTypeOptions[tag];
value = uint.Parse(split[6].Substring(9, 1));
value = option.FindByIndex((int)(uint)value);
entries.Add(tag, new TriggerTypeEntry(option, value));
// starting probability
tag = "Prob";
option = triggerTypeOptions[tag];
value = (uint)float.Parse(split[7], CultureInfo.InvariantCulture);
entries.Add(tag, new TriggerTypeEntry(option, value));
// minimum probability
tag = "ProbMin";
option = triggerTypeOptions[tag];
value = (uint)float.Parse(split[8], CultureInfo.InvariantCulture);
entries.Add(tag, new TriggerTypeEntry(option, value));
// maximum probability
tag = "ProbMax";
option = triggerTypeOptions[tag];
value = (uint)float.Parse(split[9], CultureInfo.InvariantCulture);
entries.Add(tag, new TriggerTypeEntry(option, value));
// skirmish
tag = "Skirmish";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse("0" + split[10]));
entries.Add(tag, new TriggerTypeEntry(option, value));
// [11] is unknown and always zero
// side
tag = "Side";
option = triggerTypeOptions[tag];
int side = int.Parse(split[12]);
value = option.FindByIndex(side);
entries.Add(tag, new TriggerTypeEntry(option, value));
// base defense
tag = "BaseDefense";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse(split[13]));
entries.Add(tag, new TriggerTypeEntry(option, value));
// team 2
tag = "Team2";
option = triggerTypeOptions[tag];
value = option.FindByString(split[14], noneTeam);
entries.Add(tag, new TriggerTypeEntry(option, value));
// easy
tag = "Easy";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse(split[15]));
entries.Add(tag, new TriggerTypeEntry(option, value));
// medium
tag = "Medium";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse(split[16]));
entries.Add(tag, new TriggerTypeEntry(option, value));
// hard
tag = "Hard";
option = triggerTypeOptions[tag];
value = option.FindByIndex(int.Parse(split[17]));
entries.Add(tag, new TriggerTypeEntry(option, value));
}
catch (Exception )
{
string msg = "Error occured at AITriggerType: " + id + "\nPlease verify its format. Application will now close.";
MessageBox.Show(msg, "Parse Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
Application.Exit();
}
return new TriggerType(id, name, entries);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.IO;
using System.Linq;
using System.Threading.Tasks;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core;
using ASC.Files.Core;
using ASC.Web.Core.Files;
using ASC.Web.Studio.Core;
using Box.V2.Models;
using File = ASC.Files.Core.File;
namespace ASC.Files.Thirdparty.Box
{
internal class BoxFileDao : BoxDaoBase, IFileDao
{
public BoxFileDao(BoxDaoSelector.BoxInfo providerInfo, BoxDaoSelector boxDaoSelector)
: base(providerInfo, boxDaoSelector)
{
}
public void InvalidateCache(object fileId)
{
var boxFileId = MakeBoxId(fileId);
BoxProviderInfo.CacheReset(boxFileId, true);
var boxFile = GetBoxFile(fileId);
var parentPath = GetParentFolderId(boxFile);
if (parentPath != null) BoxProviderInfo.CacheReset(parentPath);
}
public File GetFile(object fileId)
{
return GetFile(fileId, 1);
}
public File GetFile(object fileId, int fileVersion)
{
return ToFile(GetBoxFile(fileId));
}
public File GetFile(object parentId, string title)
{
return ToFile(GetBoxItems(parentId, false)
.FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)) as BoxFile);
}
public File GetFileStable(object fileId, int fileVersion)
{
return ToFile(GetBoxFile(fileId));
}
public List<File> GetFileHistory(object fileId)
{
return new List<File> { GetFile(fileId) };
}
public List<File> GetFiles(IEnumerable<object> fileIds)
{
if (fileIds == null || !fileIds.Any()) return new List<File>();
return fileIds.Select(GetBoxFile).Select(ToFile).ToList();
}
public List<File> GetFilesFiltered(IEnumerable<object> fileIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent)
{
if (fileIds == null || !fileIds.Any() || filterType == FilterType.FoldersOnly) return new List<File>();
var files = GetFiles(fileIds).AsEnumerable();
//Filter
if (subjectID != Guid.Empty)
{
files = files.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID)
: x.CreateBy == subjectID);
}
switch (filterType)
{
case FilterType.FoldersOnly:
return new List<File>();
case FilterType.DocumentsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document);
break;
case FilterType.PresentationsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation);
break;
case FilterType.SpreadsheetsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet);
break;
case FilterType.ImagesOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image);
break;
case FilterType.ArchiveOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive);
break;
case FilterType.MediaOnly:
files = files.Where(x =>
{
FileType fileType;
return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video;
});
break;
case FilterType.ByExtension:
if (!string.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim().ToLower();
files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText));
}
break;
}
if (!string.IsNullOrEmpty(searchText))
files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1);
return files.ToList();
}
public List<object> GetFiles(object parentId)
{
return GetBoxItems(parentId, false).Select(entry => (object)MakeId(entry.Id)).ToList();
}
public List<File> GetFiles(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent, bool withSubfolders = false)
{
if (filterType == FilterType.FoldersOnly) return new List<File>();
//Get only files
var files = GetBoxItems(parentId, false).Select(item => ToFile(item as BoxFile));
//Filter
if (subjectID != Guid.Empty)
{
files = files.Where(x => subjectGroup
? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID)
: x.CreateBy == subjectID);
}
switch (filterType)
{
case FilterType.FoldersOnly:
return new List<File>();
case FilterType.DocumentsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document);
break;
case FilterType.PresentationsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation);
break;
case FilterType.SpreadsheetsOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet);
break;
case FilterType.ImagesOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image);
break;
case FilterType.ArchiveOnly:
files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive);
break;
case FilterType.MediaOnly:
files = files.Where(x =>
{
FileType fileType;
return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video;
});
break;
case FilterType.ByExtension:
if (!string.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim().ToLower();
files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText));
}
break;
}
if (!string.IsNullOrEmpty(searchText))
files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1);
if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false);
switch (orderBy.SortedBy)
{
case SortedByType.Author:
files = orderBy.IsAsc ? files.OrderBy(x => x.CreateBy) : files.OrderByDescending(x => x.CreateBy);
break;
case SortedByType.AZ:
files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title);
break;
case SortedByType.DateAndTime:
files = orderBy.IsAsc ? files.OrderBy(x => x.ModifiedOn) : files.OrderByDescending(x => x.ModifiedOn);
break;
case SortedByType.DateAndTimeCreation:
files = orderBy.IsAsc ? files.OrderBy(x => x.CreateOn) : files.OrderByDescending(x => x.CreateOn);
break;
default:
files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title);
break;
}
return files.ToList();
}
public Stream GetFileStream(File file)
{
return GetFileStream(file, 0);
}
public Stream GetFileStream(File file, long offset)
{
var boxFileId = MakeBoxId(file.ID);
BoxProviderInfo.CacheReset(boxFileId, true);
var boxFile = GetBoxFile(file.ID);
if (boxFile == null) throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound);
if (boxFile is ErrorFile) throw new Exception(((ErrorFile)boxFile).Error);
var fileStream = BoxProviderInfo.Storage.DownloadStream(boxFile, (int)offset);
return fileStream;
}
public Uri GetPreSignedUri(File file, TimeSpan expires)
{
throw new NotSupportedException();
}
public bool IsSupportedPreSignedUri(File file)
{
return false;
}
public File SaveFile(File file, Stream fileStream)
{
if (file == null) throw new ArgumentNullException("file");
if (fileStream == null) throw new ArgumentNullException("fileStream");
BoxFile newBoxFile = null;
if (file.ID != null)
{
var fileId = MakeBoxId(file.ID);
newBoxFile = BoxProviderInfo.Storage.SaveStream(fileId, fileStream);
if (!newBoxFile.Name.Equals(file.Title))
{
var folderId = GetParentFolderId(GetBoxFile(fileId));
file.Title = GetAvailableTitle(file.Title, folderId, IsExist);
newBoxFile = BoxProviderInfo.Storage.RenameFile(fileId, file.Title);
}
}
else if (file.FolderID != null)
{
var folderId = MakeBoxId(file.FolderID);
file.Title = GetAvailableTitle(file.Title, folderId, IsExist);
newBoxFile = BoxProviderInfo.Storage.CreateFile(fileStream, file.Title, folderId);
}
BoxProviderInfo.CacheReset(newBoxFile);
var parentId = GetParentFolderId(newBoxFile);
if (parentId != null) BoxProviderInfo.CacheReset(parentId);
return ToFile(newBoxFile);
}
public File ReplaceFileVersion(File file, Stream fileStream)
{
return SaveFile(file, fileStream);
}
public void DeleteFile(object fileId)
{
var boxFile = GetBoxFile(fileId);
if (boxFile == null) return;
var id = MakeId(boxFile.Id);
using (var db = GetDb())
using (var tx = db.BeginTransaction())
{
var hashIDs = db.ExecuteList(Query("files_thirdparty_id_mapping")
.Select("hash_id")
.Where(Exp.Like("id", id, SqlLike.StartWith)))
.ConvertAll(x => x[0]);
db.ExecuteNonQuery(Delete("files_tag_link").Where(Exp.In("entry_id", hashIDs)));
db.ExecuteNonQuery(Delete("files_security").Where(Exp.In("entry_id", hashIDs)));
db.ExecuteNonQuery(Delete("files_thirdparty_id_mapping").Where(Exp.In("hash_id", hashIDs)));
var tagsToRemove = db.ExecuteList(
Query("files_tag tbl_ft ")
.Select("tbl_ft.id")
.LeftOuterJoin("files_tag_link tbl_ftl", Exp.EqColumns("tbl_ft.tenant_id", "tbl_ftl.tenant_id") &
Exp.EqColumns("tbl_ft.id", "tbl_ftl.tag_id"))
.Where("tbl_ftl.tag_id is null"))
.ConvertAll(r => Convert.ToInt32(r[0]));
db.ExecuteNonQuery(Delete("files_tag").Where(Exp.In("id", tagsToRemove)));
tx.Commit();
}
if (!(boxFile is ErrorFile))
BoxProviderInfo.Storage.DeleteItem(boxFile);
BoxProviderInfo.CacheReset(boxFile.Id, true);
var parentFolderId = GetParentFolderId(boxFile);
if (parentFolderId != null) BoxProviderInfo.CacheReset(parentFolderId);
}
public bool IsExist(string title, object folderId)
{
return GetBoxItems(folderId, false)
.Any(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase));
}
public object MoveFile(object fileId, object toFolderId)
{
var boxFile = GetBoxFile(fileId);
if (boxFile is ErrorFile) throw new Exception(((ErrorFile)boxFile).Error);
var toBoxFolder = GetBoxFolder(toFolderId);
if (toBoxFolder is ErrorFolder) throw new Exception(((ErrorFolder)toBoxFolder).Error);
var fromFolderId = GetParentFolderId(boxFile);
var newTitle = GetAvailableTitle(boxFile.Name, toBoxFolder.Id, IsExist);
boxFile = BoxProviderInfo.Storage.MoveFile(boxFile.Id, newTitle, toBoxFolder.Id);
BoxProviderInfo.CacheReset(boxFile.Id, true);
BoxProviderInfo.CacheReset(fromFolderId);
BoxProviderInfo.CacheReset(toBoxFolder.Id);
return MakeId(boxFile.Id);
}
public File CopyFile(object fileId, object toFolderId)
{
var boxFile = GetBoxFile(fileId);
if (boxFile is ErrorFile) throw new Exception(((ErrorFile)boxFile).Error);
var toBoxFolder = GetBoxFolder(toFolderId);
if (toBoxFolder is ErrorFolder) throw new Exception(((ErrorFolder)toBoxFolder).Error);
var newTitle = GetAvailableTitle(boxFile.Name, toBoxFolder.Id, IsExist);
var newBoxFile = BoxProviderInfo.Storage.CopyFile(boxFile.Id, newTitle, toBoxFolder.Id);
BoxProviderInfo.CacheReset(newBoxFile);
BoxProviderInfo.CacheReset(toBoxFolder.Id);
return ToFile(newBoxFile);
}
public object FileRename(File file, string newTitle)
{
var boxFile = GetBoxFile(file.ID);
newTitle = GetAvailableTitle(newTitle, GetParentFolderId(boxFile), IsExist);
boxFile = BoxProviderInfo.Storage.RenameFile(boxFile.Id, newTitle);
BoxProviderInfo.CacheReset(boxFile);
var parentId = GetParentFolderId(boxFile);
if (parentId != null) BoxProviderInfo.CacheReset(parentId);
return MakeId(boxFile.Id);
}
public string UpdateComment(object fileId, int fileVersion, string comment)
{
return string.Empty;
}
public void CompleteVersion(object fileId, int fileVersion)
{
}
public void ContinueVersion(object fileId, int fileVersion)
{
}
public bool UseTrashForRemove(File file)
{
return false;
}
#region chunking
private File RestoreIds(File file)
{
if (file == null) return null;
if (file.ID != null)
file.ID = MakeId(file.ID.ToString());
if (file.FolderID != null)
file.FolderID = MakeId(file.FolderID.ToString());
return file;
}
public ChunkedUploadSession CreateUploadSession(File file, long contentLength)
{
if (SetupInfo.ChunkUploadSize > contentLength)
return new ChunkedUploadSession(RestoreIds(file), contentLength) { UseChunks = false };
var uploadSession = new ChunkedUploadSession(file, contentLength);
uploadSession.Items["TempPath"] = TempPath.GetTempFileName();
uploadSession.File = RestoreIds(uploadSession.File);
return uploadSession;
}
public File UploadChunk(ChunkedUploadSession uploadSession, Stream stream, long chunkLength)
{
if (!uploadSession.UseChunks)
{
if (uploadSession.BytesTotal == 0)
uploadSession.BytesTotal = chunkLength;
uploadSession.File = SaveFile(uploadSession.File, stream);
uploadSession.BytesUploaded = chunkLength;
return uploadSession.File;
}
var tempPath = uploadSession.GetItemOrDefault<string>("TempPath");
using (var fs = new FileStream(tempPath, FileMode.Append))
{
stream.CopyTo(fs);
}
uploadSession.BytesUploaded += chunkLength;
if (uploadSession.BytesUploaded == uploadSession.BytesTotal)
{
using (var fs = new FileStream(uploadSession.GetItemOrDefault<string>("TempPath"),
FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose))
{
uploadSession.File = SaveFile(uploadSession.File, fs);
}
}
else
{
uploadSession.File = RestoreIds(uploadSession.File);
}
return uploadSession.File;
}
public void AbortUploadSession(ChunkedUploadSession uploadSession)
{
if (uploadSession.Items.ContainsKey("TempPath"))
{
System.IO.File.Delete(uploadSession.GetItemOrDefault<string>("TempPath"));
}
}
#endregion
#region Only in TMFileDao
public void ReassignFiles(IEnumerable<object> fileIds, Guid newOwnerId)
{
}
public List<File> GetFiles(IEnumerable<object> parentIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent)
{
return new List<File>();
}
public IEnumerable<File> Search(string text, bool bunch)
{
return null;
}
public bool IsExistOnStorage(File file)
{
return true;
}
public void SaveEditHistory(File file, string changes, Stream differenceStream)
{
//Do nothing
}
public List<EditHistory> GetEditHistory(object fileId, int fileVersion)
{
return null;
}
public Stream GetDifferenceStream(File file)
{
return null;
}
public bool ContainChanges(object fileId, int fileVersion)
{
return false;
}
public void SaveThumbnail(File file, Stream thumbnail)
{
//Do nothing
}
public Stream GetThumbnail(File file)
{
return null;
}
public Task<Stream> GetFileStreamAsync(File file)
{
return Task.FromResult(GetFileStream(file));
}
public Task<bool> IsExistOnStorageAsync(File file)
{
return Task.FromResult(IsExistOnStorage(file));
}
#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;
/// <summary>
/// System.Convert.ToSByte(double)
/// <summary>
public class ConvertToSByte5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random Double greater than 0.5 to sbyte");
try
{
double i;
do
{
i = TestLibrary.Generator.GetDouble(-55);
}
while (i < 0.5D);
SByte sByte = Convert.ToSByte(i);
if (sByte != 1)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is:"+i);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert a random Double less than 0.5 to sbyte");
try
{
double i;
do
{
i = TestLibrary.Generator.GetDouble(-55);
}
while (i > 0.5D);
SByte sByte = Convert.ToSByte(i);
if (sByte != 0)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,i is: "+i);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert zero to sbyte");
try
{
double i = 0;
SByte sByte = Convert.ToSByte(i);
if (sByte != 0)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert a double whose decimal part is equal to 0.5 exactly");
try
{
double integral = (double)(this.GetSByte(-50, 0) * 2 + 1);
double i = integral - 0.5d;
SByte sByte = Convert.ToSByte(i);
if (sByte != (integral - 1))
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,SByte is:"+sByte+"i is: "+i);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert a double indicating SbyteMaxValue to sbyte");
try
{
double i = (double)SByte.MaxValue;
SByte sByte = Convert.ToSByte(i);
if (sByte != sbyte.MaxValue)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Convert a double indicating SbyteMinValue to sbyte");
try
{
double i = (double)SByte.MinValue;
SByte sByte = Convert.ToSByte(i);
if (sByte != sbyte.MinValue)
{
TestLibrary.TestFramework.LogError("011", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Value is greater than SByte.MaxValue");
try
{
double i = 128.5d;
SByte sByte = Convert.ToSByte(i);
TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: Value is less than SByte.MinValue");
try
{
double i = -150d;
SByte sByte = Convert.ToSByte(i);
TestLibrary.TestFramework.LogError("103", "The OverflowException was not thrown as expected");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToSByte5 test = new ConvertToSByte5();
TestLibrary.TestFramework.BeginTestCase("ConvertToSByte5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private SByte GetSByte(sbyte minValue, sbyte maxValue)
{
try
{
if (minValue == maxValue)
{
return (minValue);
}
if (minValue < maxValue)
{
return (sbyte)(minValue + TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue));
}
}
catch
{
throw;
}
return minValue;
}
}
| |
#region Apache License
//
// 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.
//
#endregion
#if !NETCF
using System;
using System.Diagnostics;
using System.Globalization;
using log4net.Util;
using log4net.Layout;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Writes events to the system event log.
/// </summary>
/// <remarks>
/// <para>
/// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges.
/// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog
/// </para>
/// <para>
/// The <c>EventID</c> of the event log entry can be
/// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// </para>
/// <para>
/// The <c>Category</c> of the event log entry can be
/// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// </para>
/// <para>
/// There is a limit of 32K characters for an event log message
/// </para>
/// <para>
/// When configuring the EventLogAppender a mapping can be
/// specified to map a logging level to an event log entry type. For example:
/// </para>
/// <code lang="XML">
/// <mapping>
/// <level value="ERROR" />
/// <eventLogEntryType value="Error" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <eventLogEntryType value="Information" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and eventLogEntryType can be any value
/// from the <see cref="EventLogEntryType"/> enum, i.e.:
/// <list type="bullet">
/// <item><term>Error</term><description>an error event</description></item>
/// <item><term>Warning</term><description>a warning event</description></item>
/// <item><term>Information</term><description>an informational event</description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Aspi Havewala</author>
/// <author>Douglas de la Torre</author>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Thomas Voss</author>
public class EventLogAppender : AppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EventLogAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public EventLogAppender()
{
m_applicationName = System.Threading.Thread.GetDomain().FriendlyName;
m_logName = "Application"; // Defaults to application log
m_machineName = "."; // Only log on the local machine
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogAppender" /> class
/// with the specified <see cref="ILayout" />.
/// </summary>
/// <param name="layout">The <see cref="ILayout" /> to use with this appender.</param>
/// <remarks>
/// <para>
/// Obsolete constructor.
/// </para>
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property")]
public EventLogAppender(ILayout layout) : this()
{
Layout = layout;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// The name of the log where messages will be stored.
/// </summary>
/// <value>
/// The string name of the log where messages will be stored.
/// </value>
/// <remarks>
/// <para>This is the name of the log as it appears in the Event Viewer
/// tree. The default value is to log into the <c>Application</c>
/// log, this is where most applications write their events. However
/// if you need a separate log for your application (or applications)
/// then you should set the <see cref="LogName"/> appropriately.</para>
/// <para>This should not be used to distinguish your event log messages
/// from those of other applications, the <see cref="ApplicationName"/>
/// property should be used to distinguish events. This property should be
/// used to group together events into a single log.
/// </para>
/// </remarks>
public string LogName
{
get { return m_logName; }
set { m_logName = value; }
}
/// <summary>
/// Property used to set the Application name. This appears in the
/// event logs when logging.
/// </summary>
/// <value>
/// The string used to distinguish events from different sources.
/// </value>
/// <remarks>
/// Sets the event log source property.
/// </remarks>
public string ApplicationName
{
get { return m_applicationName; }
set { m_applicationName = value; }
}
/// <summary>
/// This property is used to return the name of the computer to use
/// when accessing the event logs. Currently, this is the current
/// computer, denoted by a dot "."
/// </summary>
/// <value>
/// The string name of the machine holding the event log that
/// will be logged into.
/// </value>
/// <remarks>
/// This property cannot be changed. It is currently set to '.'
/// i.e. the local machine. This may be changed in future.
/// </remarks>
public string MachineName
{
get { return m_machineName; }
set { /* Currently we do not allow the machine name to be changed */; }
}
/// <summary>
/// Add a mapping of level to <see cref="EventLogEntryType"/> - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="Level2EventLogEntryType"/> mapping to this appender.
/// Each mapping defines the event log entry type for a level.
/// </para>
/// </remarks>
public void AddMapping(Level2EventLogEntryType mapping)
{
m_levelMapping.Add(mapping);
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to write to the EventLog.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to write to the EventLog.
/// </value>
/// <remarks>
/// <para>
/// The system security context used to write to the EventLog.
/// </para>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
/// <summary>
/// Gets or sets the <c>EventId</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
/// <remarks>
/// <para>
/// The <c>EventID</c> of the event log entry will normally be
/// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// This property provides the fallback value which defaults to 0.
/// </para>
/// </remarks>
public int EventId {
get { return m_eventId; }
set { m_eventId = value; }
}
/// <summary>
/// Gets or sets the <c>Category</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Category</c> of the event log entry will normally be
/// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>)
/// on the <see cref="LoggingEvent"/>.
/// This property provides the fallback value which defaults to 0.
/// </para>
/// </remarks>
public short Category
{
get { return m_category; }
set { m_category = value; }
}
#endregion // Public Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
try
{
base.ActivateOptions();
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
bool sourceAlreadyExists = false;
string currentLogName = null;
using (SecurityContext.Impersonate(this))
{
sourceAlreadyExists = EventLog.SourceExists(m_applicationName);
if (sourceAlreadyExists) {
currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
}
if (sourceAlreadyExists && currentLogName != m_logName)
{
LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]");
}
else if (!sourceAlreadyExists)
{
LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]");
}
string registeredLogName = null;
using (SecurityContext.Impersonate(this))
{
if (sourceAlreadyExists && currentLogName != m_logName)
{
//
// Re-register this to the current application if the user has changed
// the application / logfile association
//
EventLog.DeleteEventSource(m_applicationName, m_machineName);
CreateEventSource(m_applicationName, m_logName, m_machineName);
registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
else if (!sourceAlreadyExists)
{
CreateEventSource(m_applicationName, m_logName, m_machineName);
registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
}
}
m_levelMapping.ActivateOptions();
LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]");
}
catch (System.Security.SecurityException ex)
{
ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source "
+ m_applicationName
+ " doesn't exist and must be created by a local administrator. Will disable EventLogAppender."
+ " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog",
ex);
Threshold = Level.Off;
}
}
#endregion // Implementation of IOptionHandler
/// <summary>
/// Create an event log source
/// </summary>
private static void CreateEventSource(string source, string logName, string machineName)
{
EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName);
eventSourceCreationData.MachineName = machineName;
EventLog.CreateEventSource(eventSourceCreationData);
}
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/>
/// method.
/// </summary>
/// <param name="loggingEvent">the event to log</param>
/// <remarks>
/// <para>Writes the event to the system event log using the
/// <see cref="ApplicationName"/>.</para>
///
/// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>)
/// set then this integer will be used as the event log event id.</para>
///
/// <para>
/// There is a limit of 32K characters for an event log message
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
//
// Write the resulting string to the event log system
//
int eventID = m_eventId;
// Look for the EventID property
object eventIDPropertyObj = loggingEvent.LookupProperty("EventID");
if (eventIDPropertyObj != null)
{
if (eventIDPropertyObj is int)
{
eventID = (int)eventIDPropertyObj;
}
else
{
string eventIDPropertyString = eventIDPropertyObj as string;
if (eventIDPropertyString == null)
{
eventIDPropertyString = eventIDPropertyObj.ToString();
}
if (eventIDPropertyString != null && eventIDPropertyString.Length > 0)
{
// Read the string property into a number
int intVal;
if (SystemInfo.TryParse(eventIDPropertyString, out intVal))
{
eventID = intVal;
}
else
{
ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "].");
}
}
}
}
short category = m_category;
// Look for the Category property
object categoryPropertyObj = loggingEvent.LookupProperty("Category");
if (categoryPropertyObj != null)
{
if (categoryPropertyObj is short)
{
category = (short) categoryPropertyObj;
}
else
{
string categoryPropertyString = categoryPropertyObj as string;
if (categoryPropertyString == null)
{
categoryPropertyString = categoryPropertyObj.ToString();
}
if (categoryPropertyString != null && categoryPropertyString.Length > 0)
{
// Read the string property into a number
short shortVal;
if (SystemInfo.TryParse(categoryPropertyString, out shortVal))
{
category = shortVal;
}
else
{
ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "].");
}
}
}
}
// Write to the event log
try
{
string eventTxt = RenderLoggingEvent(loggingEvent);
// There is a limit of about 32K characters for an event log message
if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE)
{
eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE);
}
EventLogEntryType entryType = GetEntryType(loggingEvent.Level);
using(SecurityContext.Impersonate(this))
{
EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category);
}
}
catch(Exception ex)
{
ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex);
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Get the equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/>
/// </summary>
/// <param name="level">the Level to convert to an EventLogEntryType</param>
/// <returns>The equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/></returns>
/// <remarks>
/// Because there are fewer applicable <see cref="EventLogEntryType"/>
/// values to use in logging levels than there are in the
/// <see cref="Level"/> this is a one way mapping. There is
/// a loss of information during the conversion.
/// </remarks>
virtual protected EventLogEntryType GetEntryType(Level level)
{
// see if there is a specified lookup.
Level2EventLogEntryType entryType = m_levelMapping.Lookup(level) as Level2EventLogEntryType;
if (entryType != null)
{
return entryType.EventLogEntryType;
}
// Use default behavior
if (level >= Level.Error)
{
return EventLogEntryType.Error;
}
else if (level == Level.Warn)
{
return EventLogEntryType.Warning;
}
// Default setting
return EventLogEntryType.Information;
}
#endregion // Protected Instance Methods
#region Private Instance Fields
/// <summary>
/// The log name is the section in the event logs where the messages
/// are stored.
/// </summary>
private string m_logName;
/// <summary>
/// Name of the application to use when logging. This appears in the
/// application column of the event log named by <see cref="m_logName"/>.
/// </summary>
private string m_applicationName;
/// <summary>
/// The name of the machine which holds the event log. This is
/// currently only allowed to be '.' i.e. the current machine.
/// </summary>
private string m_machineName;
/// <summary>
/// Mapping from level object to EventLogEntryType
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
/// <summary>
/// The event ID to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
private int m_eventId = 0;
/// <summary>
/// The event category to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties.
/// </summary>
private short m_category = 0;
#endregion // Private Instance Fields
#region Level2EventLogEntryType LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and its event log entry type.
/// </para>
/// </remarks>
public class Level2EventLogEntryType : LevelMappingEntry
{
private EventLogEntryType m_entryType;
/// <summary>
/// The <see cref="EventLogEntryType"/> for this entry
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The <see cref="EventLogEntryType"/> for this entry
/// </para>
/// </remarks>
public EventLogEntryType EventLogEntryType
{
get { return m_entryType; }
set { m_entryType = value; }
}
}
#endregion // LevelColors LevelMapping Entry
#region Private Static Fields
/// <summary>
/// The fully qualified type of the EventLogAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(EventLogAppender);
/// <summary>
/// The maximum size supported by default.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx
/// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766
/// may leave space for a two byte null terminator of #0#0). The 32766 max
/// length is what the .NET 4.0 source code checks for, but this is WRONG!
/// Strings with a length > 31839 on Windows Vista or higher can CORRUPT
/// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent()
/// for the use of the 32766 max size.
/// </remarks>
private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766;
/// <summary>
/// The maximum size supported by a windows operating system that is vista
/// or newer.
/// </summary>
/// <remarks>
/// See ReportEvent API:
/// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx
/// ReportEvent's lpStrings parameter:
/// "A pointer to a buffer containing an array of
/// null-terminated strings that are merged into the message before Event Viewer
/// displays the string to the user. This parameter must be a valid pointer
/// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters."
///
/// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows
/// Vista or higher! It may succeed for a while...but you will eventually run into the
/// error: "System.ComponentModel.Win32Exception : A device attached to the system is
/// not functioning", and the event log will then be corrupt (I was able to corrupt
/// an event log using a length of 31877 on Windows 7).
///
/// The max size for Windows Vista or higher is documented here:
/// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx.
/// Going over this size may succeed a few times but the buffer will overrun and
/// eventually corrupt the log (based on testing).
///
/// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API.
/// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a
/// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the
/// buffer, given enough time).
/// </remarks>
private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2;
/// <summary>
/// The maximum size that the operating system supports for
/// a event log message.
/// </summary>
/// <remarks>
/// Used to determine the maximum string length that can be written
/// to the operating system event log and eventually truncate a string
/// that exceeds the limits.
/// </remarks>
private readonly static int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize();
/// <summary>
/// This method determines the maximum event log message size allowed for
/// the current environment.
/// </summary>
/// <returns></returns>
private static int GetMaxEventLogMessageSize()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER;
return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT;
}
#endregion Private Static Fields
}
}
#endif // !NETCF
| |
// 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.IO;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "SslProtocols property requires .NET 4.7.2")]
public abstract partial class HttpClientHandler_SslProtocols_Test : HttpClientHandlerTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#if !netstandard
[InlineData(SslProtocols.Tls13)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls13)]
[InlineData(SslProtocols.Tls12 | SslProtocols.Tls13)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls13)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13)]
#endif
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
public static IEnumerable<object[]> GetAsync_AllowedSSLVersion_Succeeds_MemberData()
{
// These protocols are all enabled by default, so we can connect with them both when
// explicitly specifying it in the client and when not.
foreach (SslProtocols protocol in new[] { SslProtocols.Tls, SslProtocols.Tls11, SslProtocols.Tls12 })
{
yield return new object[] { protocol, false };
yield return new object[] { protocol, true };
}
// These protocols are disabled by default, so we can only connect with them explicitly.
// On certain platforms these are completely disabled and cannot be used at all.
#pragma warning disable 0618
if (PlatformDetection.SupportsSsl3)
{
yield return new object[] { SslProtocols.Ssl3, true };
}
if (PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1607OrGreater)
{
yield return new object[] { SslProtocols.Ssl2, true };
}
#pragma warning restore 0618
#if !netstandard
// These protocols are new, and might not be enabled everywhere yet
if (PlatformDetection.IsUbuntu1810OrHigher)
{
yield return new object[] { SslProtocols.Tls13, false };
yield return new object[] { SslProtocols.Tls13, true };
}
#endif
}
[ConditionalTheory]
[MemberData(nameof(GetAsync_AllowedSSLVersion_Succeeds_MemberData))]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
#pragma warning disable 0618
if (IsCurlHandler && PlatformDetection.IsRedHatFamily6 && acceptedProtocol == SslProtocols.Ssl3)
{
// Issue: #28790: SSLv3 is supported on RHEL 6, but it fails with curl.
throw new SkipTestException("CurlHandler (libCurl) has problems with SSL3 on RH6");
}
#pragma warning restore 0618
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
public static IEnumerable<object[]> SupportedSSLVersionServers()
{
#pragma warning disable 0618 // SSL2/3 are deprecated
if (PlatformDetection.IsWindows ||
PlatformDetection.IsOSX ||
(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && PlatformDetection.OpenSslVersion < new Version(1, 0, 2) && !PlatformDetection.IsDebian))
{
yield return new object[] { SslProtocols.Ssl3, Configuration.Http.SSLv3RemoteServer };
}
#pragma warning restore 0618
yield return new object[] { SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer };
yield return new object[] { SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer };
yield return new object[] { SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer };
}
// We have tests that validate with SslStream, but that's limited by what the current OS supports.
// This tests provides additional validation against an external server.
[ActiveIssue(26186)]
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
if (UseSocketsHttpHandler)
{
// TODO #26186: SocketsHttpHandler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = sslProtocols;
using (var client = new HttpClient(handler))
{
(await RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)).Dispose();
}
}
}
public Func<Exception, bool> remoteServerExceptionWrapper = (exception) =>
{
Type exceptionType = exception.GetType();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// On linux, taskcanceledexception is thrown.
return exceptionType.Equals(typeof(TaskCanceledException));
}
else
{
// The internal exceptions return operation timed out.
return exceptionType.Equals(typeof(HttpRequestException)) && exception.InnerException.Message.Contains("timed out");
}
};
public static IEnumerable<object[]> NotSupportedSSLVersionServers()
{
#pragma warning disable 0618
if (PlatformDetection.IsWindows10Version1607OrGreater)
{
yield return new object[] { SslProtocols.Ssl2, Configuration.Http.SSLv2RemoteServer };
}
#pragma warning restore 0618
}
// We have tests that validate with SslStream, but that's limited by what the current OS supports.
// This tests provides additional validation against an external server.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(SslProtocols sslProtocols, string url)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = new HttpClient(handler))
{
handler.SslProtocols = sslProtocols;
await Assert.ThrowsAsync<HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url));
}
}
[Fact]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = SslProtocols.Tls12 };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
server.AcceptConnectionAsync(async connection =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(connection.Stream).SslProtocol);
await connection.ReadRequestHeaderAndSendResponseAsync();
}));
}, options);
}
}
[Theory]
#pragma warning disable 0618 // SSL2/3 are deprecated
[InlineData(SslProtocols.Ssl2, SslProtocols.Tls12)]
[InlineData(SslProtocols.Ssl3, SslProtocols.Tls12)]
#pragma warning restore 0618
[InlineData(SslProtocols.Tls11, SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12, SslProtocols.Tls)] // Skip this on WinHttpHandler.
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12)]
public async Task GetAsync_AllowedClientSslVersionDiffersFromServer_ThrowsException(
SslProtocols allowedClientProtocols, SslProtocols acceptedServerProtocols)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (IsWinHttpHandler &&
allowedClientProtocols == (SslProtocols.Tls11 | SslProtocols.Tls12) &&
acceptedServerProtocols == SslProtocols.Tls)
{
// Native WinHTTP sometimes uses multiple TCP connections to try other TLS protocols when
// getting TLS protocol failures as part of its TLS fallback algorithm. The loopback server
// doesn't expect this and stops listening for more connections. This causes unexpected test
// failures. See dotnet/corefx #8538.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = allowedClientProtocols;
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedServerProtocols };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
try
{
await serverTask;
}
catch (Exception e) when (e is IOException || e is AuthenticationException)
{
// Some SSL implementations simply close or reset connection after protocol mismatch.
// Newer OpenSSL sends Fatal Alert message before closing.
return;
}
// We expect negotiation to fail so one or the other expected exception should be thrown.
Assert.True(false, "Expected exception did not happen.");
}, options);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Globalization;
namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines
{
internal static class TaskResources
{
internal static string PlanNotFound(params object[] args)
{
const string Format = @"No plan found for identifier {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanSecurityDeleteError(params object[] args)
{
const string Format = @"Access denied: {0} does not have delete permissions for orchestration plan {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanSecurityWriteError(params object[] args)
{
const string Format = @"Access denied: {0} does not have write permissions for orchestration plan {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HubExtensionNotFound(params object[] args)
{
const string Format = @"No task hub extension was found for hub {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string SecurityTokenNotFound(params object[] args)
{
const string Format = @"No security token was found for artifact {0} using extension {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TimelineNotFound(params object[] args)
{
const string Format = @"No timeline found for plan {0} with identifier {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string LogWithNoContentError(params object[] args)
{
const string Format = @"Content must be provided to create a log.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string LogWithNoContentLengthError(params object[] args)
{
const string Format = @"ContentLength header must be specified to create a log.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UnsupportedRollbackContainers(params object[] args)
{
const string Format = @"Rollback is supported only at the top level container.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HubNotFound(params object[] args)
{
const string Format = @"No hub is registered with name {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string MultipleHubResolversNotSupported(params object[] args)
{
const string Format = @"Only one default task hub resolver may be specified per application. Found {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HubExists(params object[] args)
{
const string Format = @"A hub is already registered with name {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TimelineRecordInvalid(params object[] args)
{
const string Format = @"The timeline record {0} is not valid. Name and Type are required fields.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TimelineRecordNotFound(params object[] args)
{
const string Format = @"No timeline record found for plan {0} and timeline {1} with identifier {2}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string FailedToObtainJobAuthorization(params object[] args)
{
const string Format = @"Unable to obtain an authenticated token for running job {0} with plan type {1} and identifier {2}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskInputRequired(params object[] args)
{
const string Format = @"Task {0} did not specify a value for required input {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanOrchestrationTerminated(params object[] args)
{
const string Format = @"Orchestration plan {0} is not in a runnable state.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanAlreadyStarted(params object[] args)
{
const string Format = @"Orchestration plan {0} version {1} has already been started for hub {2}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TimelineExists(params object[] args)
{
const string Format = @"A timeline already exists for plan {0} with identifier {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidContainer(params object[] args)
{
const string Format = @"Container is not valid for {0} orchestration.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string EndpointNotFound(params object[] args)
{
const string Format = @"No endpoint found with identifier {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string ShouldStartWithEndpointUrl(params object[] args)
{
const string Format = @"EndpointUrl of HttpRequest execution should start with $(endpoint.url).";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskExecutionDefinitionInvalid(params object[] args)
{
const string Format = @"Task execution section of task definition for Id : {0} is either missing or not valid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string ServerExecutionFailure(params object[] args)
{
const string Format = @"Failure occured while sending Http Request : {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UnsupportedTaskCountForServerJob(params object[] args)
{
const string Format = @"Container is not valid for orchestration as job should contain exactly one task.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskServiceBusPublishFailed(params object[] args)
{
const string Format = @"Task {0} failed to publish to message bus {1} configured on service endpoint {2}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskServiceBusExecutionFailure(params object[] args)
{
const string Format = @"Task {0} failed to publish to message bus {1} configured on service endpoint {2}. Error: {3}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TimeoutFormatNotValid(params object[] args)
{
const string Format = @"The Timeout values '{0}' are not valid for job events '{1}' in the task execution section for Id: '{2}'. Specify valid timeout in 'hh:mm:ss' format such as '01:40:00' and try again.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string JobNotFound(params object[] args)
{
const string Format = @"No job found with identifier '{0}' for plan '{1}'.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanGroupNotFound(params object[] args)
{
const string Format = @"No plan group found with identifier {0}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string PlanSecurityReadError(params object[] args)
{
const string Format = @"Access denied: {0} does not have read permissions for orchestration plan {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string SaveJobOutputVariablesError(params object[] args)
{
const string Format = @"Failed to save output variables for job '{0}'. Error: {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsAccessTokenCacheKeyLookupResultIsInvalidError(params object[] args)
{
const string Format = @"Failed to get Visual Studio Team Foundation Service access token from property cache service, cache key is invalid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsAccessTokenKeyNotFoundError(params object[] args)
{
const string Format = @"Visual Studio Team Foundation Service token (AccessTokenKey) is invalid. Try to validate again.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsAccessTokenCacheKeyLookupResultIsNullError(params object[] args)
{
const string Format = @"Failed to get Visual Studio Team Foundation Service access token, cache value is invalid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsAccessTokenIsNullError(params object[] args)
{
const string Format = @"Visual Studio Team Foundation Service access token is invalid, token shouldn't be null.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsIdTokenKeyNotFoundError(params object[] args)
{
const string Format = @"Visual Studio Team Foundation Service token (IdToken) is invalid. Try to validate again.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VstsNonceNotFoundError(params object[] args)
{
const string Format = @"Visual Studio Team Foundation Service token (Nonce) is invalid. Try to validate again.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string FailedToGenerateToken(params object[] args)
{
const string Format = @"Unable to generate a personal access token for service identity '{0}' ('{1}'). Error : {2}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string FailedToObtainToken(params object[] args)
{
const string Format = @"Failed to obtain the Json Web Token(JWT) for service principal id '{0}'";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidAzureEndpointAuthorizer(params object[] args)
{
const string Format = @"No Azure endpoint authorizer found for authentication of type '{0}'";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidAzureManagementCertificate(params object[] args)
{
const string Format = @"Invalid Azure Management certificate";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidEndpointAuthorizer(params object[] args)
{
const string Format = @"No Endpoint Authorizer found for endpoint of type '{0}'";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidEndpointId(params object[] args)
{
const string Format = @"The value {0} provided for the endpoint identifier is not within the permissible values for it.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidScopeId(params object[] args)
{
const string Format = @"The scope {0} is not valid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string ResourceUrlNotSupported(params object[] args)
{
const string Format = @"ResourceUrl is not support for the endpoint type {0} and authentication scheme {1}.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string NoAzureCertificate(params object[] args)
{
const string Format = @"Could not extract certificate for AzureSubscription.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string NoAzureServicePrincipal(params object[] args)
{
const string Format = @"Could not extract service principal information for AzureSubscription.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string NoUsernamePassword(params object[] args)
{
const string Format = @"Could not extract Username and Password for endpoint.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string NullSessionToken(params object[] args)
{
const string Format = @"Unable to generate a personal access token for service identity '{0}' ('{1}') because of null result.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string MissingProperty(params object[] args)
{
const string Format = @"""Expected property {0} in service endpoint defintion""";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string ServiceEndPointNotFound(params object[] args)
{
const string Format = @"Service endpoint with id {0} not found";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidLicenseHub(params object[] args)
{
const string Format = @"This operation is not supported on {0} hub as it is not a licensing hub.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HttpMethodNotRecognized(params object[] args)
{
const string Format = @"The Http Method: {0} is not supported.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskDefinitionInvalid(params object[] args)
{
const string Format = @"Task definition for Id: {0} is either missing or not valid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UrlCannotBeEmpty(params object[] args)
{
const string Format = @"Url for HttpRequest cannot be empty.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UrlIsNotCorrect(params object[] args)
{
const string Format = @"Url {0} for HttpRequest is not correct.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UrlShouldComeFromEndpointOrExplicitelySpecified(params object[] args)
{
const string Format = @"Url for HttpRequest should either come from endpoint or specified explicitely.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string WaitForCompletionInvalid(params object[] args)
{
const string Format = @"Wait for completion can only be true or false. Current value: {0}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HttpRequestTimeoutError(params object[] args)
{
const string Format = @"The request timed out after {0} seconds as no response was recieved.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UnableToAcquireLease(params object[] args)
{
const string Format = @"Unable to acquire lease: {0}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string UnableToCompleteOperationSecurely(params object[] args)
{
const string Format = @"Internal Error: Unable to complete operation securely.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string CancellingHttpRequestException(params object[] args)
{
const string Format = @"An error was encountered while cancelling request. Exception: {0}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string EncryptionKeyNotFound(params object[] args)
{
const string Format = @"Encryption Key should have been present in the drawer: {0} with lookup key: {1}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string ProcessingHttpRequestException(params object[] args)
{
const string Format = @"An error was encountered while processing request. Exception: {0}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string AzureKeyVaultTaskName(params object[] args)
{
const string Format = @"Download secrets: {0}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string AzureKeyVaultServiceEndpointIdMustBeValidGuid(params object[] args)
{
const string Format = @"Azure Key Vault provider's service endpoint id must be non empty and a valid guid.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string AzureKeyVaultKeyVaultNameMustBeValid(params object[] args)
{
const string Format = @"Azure Key Vault provider's vault name must be non empty.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string AzureKeyVaultLastRefreshedOnMustBeValid(params object[] args)
{
const string Format = @"Azure Key Vault provider's last refreshed on must be valid datetime.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string InvalidAzureKeyVaultVariableGroupProviderData(params object[] args)
{
const string Format = @"Either variable group is not an azure key vault variable group or invalid provider data in azure key vault variable group.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string VariableGroupTypeNotSupported(params object[] args)
{
const string Format = @"Variable group type {0} is not supported.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string TaskRequestMessageTypeNotSupported(params object[] args)
{
const string Format = @"This kind of message type: {0}, is not yet supported";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string HttpHandlerUnableToProcessError(params object[] args)
{
const string Format = @"Unable to process messages with count : {0} and message types as: {1}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string YamlFrontMatterNotClosed(params object[] args)
{
const string Format = @"Unexpected end of file '{0}'. The file started with '---' to indicate a preamble data section. The end of the file was reached without finding a corresponding closing '---'.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string YamlFrontMatterNotValid(params object[] args)
{
const string Format = @"Error parsing preamble data section from file '{0}'. {1}";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string YamlFileCount(params object[] args)
{
const string Format = @"A YAML definition may not exceed {0} file references.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
internal static string MustacheEvaluationTimeout(params object[] args)
{
const string Format = @"YAML template preprocessing timed out for the file '{0}'. Template expansion cannot exceed '{1}' seconds.";
if (args == null || args.Length == 0)
{
return Format;
}
return string.Format(CultureInfo.CurrentCulture, Format, args);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer.UnitTests.Validation.Setup;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Xunit;
namespace IdentityServer.UnitTests.Validation
{
public class ResourceValidation
{
private const string Category = "Resource Validation";
private List<IdentityResource> _identityResources = new List<IdentityResource>
{
new IdentityResource
{
Name = "openid",
Required = true
},
new IdentityResource
{
Name = "email"
}
};
private List<ApiResource> _apiResources = new List<ApiResource>
{
new ApiResource
{
Name = "api",
Scopes = { "resource1", "resource2" }
},
new ApiResource
{
Name = "disabled_api",
Enabled = false,
Scopes = { "disabled" }
}
};
private List<ApiScope> _scopes = new List<ApiScope> {
new ApiScope
{
Name = "resource1",
Required = true
},
new ApiScope
{
Name = "resource2"
}
};
private Client _restrictedClient = new Client
{
ClientId = "restricted",
AllowedScopes = new List<string>
{
"openid",
"resource1",
"disabled"
}
};
private IResourceStore _store;
public ResourceValidation()
{
_store = new InMemoryResourcesStore(_identityResources, _apiResources, _scopes);
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Empty_Scope_List()
{
var scopes = string.Empty.ParseScopesString();
scopes.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Sorting()
{
var scopes = "scope3 scope2 scope1".ParseScopesString();
scopes.Count.Should().Be(3);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
scopes[2].Should().Be("scope3");
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Extra_Spaces()
{
var scopes = " scope3 scope2 scope1 ".ParseScopesString();
scopes.Count.Should().Be(3);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
scopes[2].Should().Be("scope3");
}
[Fact]
[Trait("Category", Category)]
public void Parse_Scopes_with_Duplicate_Scope()
{
var scopes = "scope2 scope1 scope2".ParseScopesString();
scopes.Count.Should().Be(2);
scopes[0].Should().Be("scope1");
scopes[1].Should().Be("scope2");
}
[Fact]
[Trait("Category", Category)]
public async Task Only_Offline_Access_Requested()
{
var scopes = "offline_access".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("offline_access");
}
[Fact]
[Trait("Category", Category)]
public async Task All_Scopes_Valid()
{
var scopes = "openid resource1".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeTrue();
result.InvalidScopes.Should().BeEmpty();
}
[Fact]
[Trait("Category", Category)]
public async Task Invalid_Scope()
{
{
var scopes = "openid email resource1 unknown".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("unknown");
result.InvalidScopes.Should().Contain("email");
}
{
var scopes = "openid resource1 resource2".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("resource2");
}
{
var scopes = "openid email resource1".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("email");
}
}
[Fact]
[Trait("Category", Category)]
public async Task Disabled_Scope()
{
var scopes = "openid resource1 disabled".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("disabled");
}
[Fact]
[Trait("Category", Category)]
public async Task All_Scopes_Allowed_For_Restricted_Client()
{
var scopes = "openid resource1".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeTrue();
result.InvalidScopes.Should().BeEmpty();
}
[Fact]
[Trait("Category", Category)]
public async Task Restricted_Scopes()
{
var scopes = "openid email resource1 resource2".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeFalse();
result.InvalidScopes.Should().Contain("email");
result.InvalidScopes.Should().Contain("resource2");
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Resource_and_Identity_Scopes()
{
var scopes = "openid resource1".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeTrue();
result.Resources.IdentityResources.SelectMany(x => x.Name).Should().Contain("openid");
result.Resources.ApiScopes.Select(x => x.Name).Should().Contain("resource1");
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Resource_Scopes_Only()
{
var scopes = "resource1".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeTrue();
result.Resources.IdentityResources.Should().BeEmpty();
result.Resources.ApiScopes.Select(x => x.Name).Should().Contain("resource1");
}
[Fact]
[Trait("Category", Category)]
public async Task Contains_Identity_Scopes_Only()
{
var scopes = "openid".ParseScopesString();
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = _restrictedClient,
Scopes = scopes
});
result.Succeeded.Should().BeTrue();
result.Resources.IdentityResources.SelectMany(x => x.Name).Should().Contain("openid");
result.Resources.ApiResources.Should().BeEmpty();
}
[Fact]
[Trait("Category", Category)]
public async Task Scope_matches_multipls_apis_should_succeed()
{
_apiResources.Clear();
_apiResources.Add(new ApiResource { Name = "api1", Scopes = { "resource" } });
_apiResources.Add(new ApiResource { Name = "api2", Scopes = { "resource" } });
_scopes.Clear();
_scopes.Add(new ApiScope("resource"));
var validator = Factory.CreateResourceValidator(_store);
var result = await validator.ValidateRequestedResourcesAsync(new IdentityServer4.Validation.ResourceValidationRequest
{
Client = new Client { AllowedScopes = { "resource" } },
Scopes = new[] { "resource" }
});
result.Succeeded.Should().BeTrue();
result.Resources.ApiResources.Count.Should().Be(2);
result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "api1", "api2" });
result.RawScopeValues.Count().Should().Be(1);
result.RawScopeValues.Should().BeEquivalentTo(new[] { "resource" });
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Diagnostics;
class WorkflowInstanceLifetimeManagerExtension : IExtension<ServiceHostBase>
{
readonly Action<object> cachedInstanceExpirationTimerCallback;
TimeSpan cachedInstanceExpiration;
bool hasPersistenceService;
Dictionary<Guid, InstanceRecord> instanceRecordMap;
//This class takes self contained lock, never calls out external method with lock taken.
object lockObject;
WorkflowRuntime workflowRuntime;
public WorkflowInstanceLifetimeManagerExtension(WorkflowRuntime workflowRuntime, TimeSpan cachedInstanceExpiration, bool hasPersistenceService)
{
this.workflowRuntime = workflowRuntime;
this.cachedInstanceExpiration = cachedInstanceExpiration;
this.instanceRecordMap = new Dictionary<Guid, InstanceRecord>();
this.lockObject = new object();
this.cachedInstanceExpirationTimerCallback = new Action<object>(this.OnTimer);
this.hasPersistenceService = hasPersistenceService;
RegisterEvents();
}
//This is called when InstanceContext is taken down behind us;
//1. UnhandledException causing InstanceContext to Abort;
//2. Activating Request to Non-Activating operation;
public void CleanUp(Guid instanceId)
{
//If no WorkflowInstance actively running for this InstanceId;
//This will be last opportunity to cleanup their record; to avoid
//growth of this HashTable.
InstanceRecord instanceRecord;
lock (this.lockObject)
{
if (this.instanceRecordMap.TryGetValue(instanceId, out instanceRecord))
{
if (!instanceRecord.InstanceLoadedOrStarted)
{
if (instanceRecord.UnloadTimer != null)
{
instanceRecord.UnloadTimer.Cancel();
}
this.instanceRecordMap.Remove(instanceId);
}
}
}
}
void IExtension<ServiceHostBase>.Attach(ServiceHostBase owner)
{
}
void IExtension<ServiceHostBase>.Detach(ServiceHostBase owner)
{
}
public bool IsInstanceInMemory(Guid instanceId)
{
InstanceRecord instanceRecord;
lock (this.lockObject)
{
if (instanceRecordMap.TryGetValue(instanceId, out instanceRecord))
{
return instanceRecord.InstanceLoadedOrStarted;
}
}
return false;
}
//Assumption: Message arrived means; instance turned to Executing state.
public void NotifyMessageArrived(Guid instanceId)
{
CancelTimer(instanceId, false);
}
public void NotifyWorkflowActivationComplete(Guid instanceId, WaitCallback callback, object state, bool fireImmediatelyIfDontExist)
{
bool instanceFound;
InstanceRecord instanceRecord;
lock (this.lockObject)
{
instanceFound = instanceRecordMap.TryGetValue(instanceId, out instanceRecord);
if (instanceFound)
{
instanceRecord.Callback = callback;
instanceRecord.CallbackState = state;
}
else if (!fireImmediatelyIfDontExist)
{
instanceRecord = new InstanceRecord();
instanceRecord.Callback = callback;
instanceRecord.CallbackState = state;
instanceRecordMap.Add(instanceId, instanceRecord);
}
}
if (!instanceFound && fireImmediatelyIfDontExist)
{
//Instance is not in-memory; Notify immediately.
callback(state);
}
}
public void ScheduleTimer(Guid instanceId)
{
InstanceRecord instanceRecord;
lock (this.lockObject)
{
if (this.instanceRecordMap.TryGetValue(instanceId, out instanceRecord))
{
if (instanceRecord.UnloadTimer != null)
{
instanceRecord.UnloadTimer.Cancel();
}
else
{
instanceRecord.UnloadTimer = new IOThreadTimer(this.cachedInstanceExpirationTimerCallback, instanceId, true);
}
instanceRecord.UnloadTimer.Set(this.cachedInstanceExpiration);
}
}
}
void CancelTimer(Guid instanceId, bool markActivationCompleted)
{
InstanceRecord instanceRecord;
WaitCallback callback = null;
object callbackState = null;
lock (this.lockObject)
{
if (instanceRecordMap.TryGetValue(instanceId, out instanceRecord))
{
if (instanceRecord.UnloadTimer != null)
{
instanceRecord.UnloadTimer.Cancel();
instanceRecord.UnloadTimer = null;
}
if (markActivationCompleted)
{
instanceRecordMap.Remove(instanceId);
callback = instanceRecord.Callback;
callbackState = instanceRecord.CallbackState;
}
}
}
if (callback != null)
{
callback(callbackState);
}
}
void OnTimer(object state)
{
Guid instanceId = (Guid) state;
try
{
if (this.hasPersistenceService)
{
this.workflowRuntime.GetWorkflow(instanceId).TryUnload();
}
else
{
this.workflowRuntime.GetWorkflow(instanceId).Abort();
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.AutoAbortingInactiveInstance, instanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.WorkflowDurableInstanceAborted, SR.GetString(SR.TraceCodeWorkflowDurableInstanceAborted),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
}
catch (PersistenceException)
{
try
{
this.workflowRuntime.GetWorkflow(instanceId).Abort();
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.AutoAbortingInactiveInstance, instanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.WorkflowDurableInstanceAborted, SR.GetString(SR.TraceCodeWorkflowDurableInstanceAborted),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
void OnWorkflowAborted(object sender, WorkflowEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
CancelTimer(args.WorkflowInstance.InstanceId, true);
}
void OnWorkflowCompleted(object sender, WorkflowCompletedEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
CancelTimer(args.WorkflowInstance.InstanceId, true);
}
void OnWorkflowIdled(object sender, WorkflowEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
ScheduleTimer(args.WorkflowInstance.InstanceId);
}
void OnWorkflowLoaded(object sender, WorkflowEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
InstanceRecord instanceRecord;
lock (this.lockObject)
{
if (!this.instanceRecordMap.TryGetValue(args.WorkflowInstance.InstanceId, out instanceRecord))
{
instanceRecord = new InstanceRecord();
this.instanceRecordMap.Add(args.WorkflowInstance.InstanceId, instanceRecord);
}
instanceRecord.InstanceLoadedOrStarted = true;
}
}
void OnWorkflowStarted(object sender, WorkflowEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
InstanceRecord instanceRecord;
lock (this.lockObject)
{
if (!this.instanceRecordMap.TryGetValue(args.WorkflowInstance.InstanceId, out instanceRecord))
{
instanceRecord = new InstanceRecord();
this.instanceRecordMap.Add(args.WorkflowInstance.InstanceId, instanceRecord);
}
instanceRecord.InstanceLoadedOrStarted = true;
}
}
void OnWorkflowTerminated(object sender, WorkflowTerminatedEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
CancelTimer(args.WorkflowInstance.InstanceId, true);
}
void OnWorkflowUnloaded(object sender, WorkflowEventArgs args)
{
if (args == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("args");
}
CancelTimer(args.WorkflowInstance.InstanceId, true);
}
void RegisterEvents()
{
//Events marking the beggining of activation cycle.
this.workflowRuntime.WorkflowLoaded += OnWorkflowLoaded;
this.workflowRuntime.WorkflowCreated += OnWorkflowStarted;
//Events marking the end of activation cycle.
this.workflowRuntime.WorkflowAborted += OnWorkflowAborted;
this.workflowRuntime.WorkflowCompleted += OnWorkflowCompleted;
this.workflowRuntime.WorkflowTerminated += OnWorkflowTerminated;
this.workflowRuntime.WorkflowUnloaded += OnWorkflowUnloaded;
//Event which triggers the idle unload timer.
this.workflowRuntime.WorkflowIdled += OnWorkflowIdled;
}
class InstanceRecord
{
object callbackState;
WaitCallback instanceActivationCompletedCallBack;
bool loadedOrStarted = false;
IOThreadTimer unloadTimer;
public WaitCallback Callback
{
get
{
return this.instanceActivationCompletedCallBack;
}
set
{
this.instanceActivationCompletedCallBack = value;
}
}
public object CallbackState
{
get
{
return this.callbackState;
}
set
{
this.callbackState = value;
}
}
public bool InstanceLoadedOrStarted
{
get
{
return this.loadedOrStarted;
}
set
{
this.loadedOrStarted = value;
}
}
public IOThreadTimer UnloadTimer
{
get
{
return this.unloadTimer;
}
set
{
this.unloadTimer = value;
}
}
}
}
}
| |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
namespace Antlr.Runtime.Tree {
/** <summary>
* A TreeAdaptor that works with any Tree implementation. It provides
* really just factory methods; all the work is done by BaseTreeAdaptor.
* If you would like to have different tokens created than ClassicToken
* objects, you need to override this and then set the parser tree adaptor to
* use your subclass.
* </summary>
*
* <remarks>
* To get your parser to build nodes of a different type, override
* create(Token), errorNode(), and to be safe, YourTreeClass.dupNode().
* dupNode is called to duplicate nodes during rewrite operations.
* </remarks>
*/
public class CommonTreeAdaptor : BaseTreeAdaptor {
/** <summary>
* Duplicate a node. This is part of the factory;
* override if you want another kind of node to be built.
* </summary>
*
* <remarks>
* I could use reflection to prevent having to override this
* but reflection is slow.
* </remarks>
*/
public override object DupNode(object t) {
if (t == null)
return null;
return ((ITree)t).DupNode();
}
public override object Create(IToken payload) {
return new CommonTree(payload);
}
/** <summary>
* Tell me how to create a token for use with imaginary token nodes.
* For example, there is probably no input symbol associated with imaginary
* token DECL, but you need to create it as a payload or whatever for
* the DECL node as in ^(DECL type ID).
* </summary>
*
* <remarks>
* If you care what the token payload objects' type is, you should
* override this method and any other createToken variant.
* </remarks>
*/
public override IToken CreateToken(int tokenType, string text) {
return new CommonToken(tokenType, text);
}
/** <summary>
* Tell me how to create a token for use with imaginary token nodes.
* For example, there is probably no input symbol associated with imaginary
* token DECL, but you need to create it as a payload or whatever for
* the DECL node as in ^(DECL type ID).
* </summary>
*
* <remarks>
* This is a variant of createToken where the new token is derived from
* an actual real input token. Typically this is for converting '{'
* tokens to BLOCK etc... You'll see
*
* r : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ;
*
* If you care what the token payload objects' type is, you should
* override this method and any other createToken variant.
* </remarks>
*/
public override IToken CreateToken(IToken fromToken) {
return new CommonToken(fromToken);
}
/** <summary>
* Track start/stop token for subtree root created for a rule.
* Only works with Tree nodes. For rules that match nothing,
* seems like this will yield start=i and stop=i-1 in a nil node.
* Might be useful info so I'll not force to be i..i.
* </summary>
*/
public override void SetTokenBoundaries(object t, IToken startToken, IToken stopToken) {
if (t == null)
return;
int start = 0;
int stop = 0;
if (startToken != null)
start = startToken.TokenIndex;
if (stopToken != null)
stop = stopToken.TokenIndex;
((ITree)t).TokenStartIndex = start;
((ITree)t).TokenStopIndex = stop;
}
public override int GetTokenStartIndex(object t) {
if (t == null)
return -1;
return ((ITree)t).TokenStartIndex;
}
public override int GetTokenStopIndex(object t) {
if (t == null)
return -1;
return ((ITree)t).TokenStopIndex;
}
public override string GetText(object t) {
if (t == null)
return null;
return ((ITree)t).Text;
}
public override int GetType(object t) {
if (t == null)
return TokenTypes.Invalid;
return ((ITree)t).Type;
}
/** <summary>
* What is the Token associated with this node? If
* you are not using CommonTree, then you must
* override this in your own adaptor.
* </summary>
*/
public override IToken GetToken(object t) {
if (t is CommonTree) {
return ((CommonTree)t).Token;
}
return null; // no idea what to do
}
public override object GetChild(object t, int i) {
if (t == null)
return null;
return ((ITree)t).GetChild(i);
}
public override int GetChildCount(object t) {
if (t == null)
return 0;
return ((ITree)t).ChildCount;
}
public override object GetParent(object t) {
if (t == null)
return null;
return ((ITree)t).Parent;
}
public override void SetParent(object t, object parent) {
if (t != null)
((ITree)t).Parent = (ITree)parent;
}
public override int GetChildIndex(object t) {
if (t == null)
return 0;
return ((ITree)t).ChildIndex;
}
public override void SetChildIndex(object t, int index) {
if (t != null)
((ITree)t).ChildIndex = index;
}
public override void ReplaceChildren(object parent, int startChildIndex, int stopChildIndex, object t) {
if (parent != null) {
((ITree)parent).ReplaceChildren(startChildIndex, stopChildIndex, t);
}
}
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using Microsoft.VisualStudio.Debugger.Interop;
using nanoFramework.Tools.Debugger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace nanoFramework.Tools.VisualStudio.Extension
{
// This Guid needs to match PortSupplierCLSID
[ComVisible(true), Guid("78E48437-246C-4CA2-B66F-4B65AEED8500")]
public class DebugPortSupplier : IDebugPortSupplier2, IDebugPortSupplierEx2, IDebugPortSupplierDescription2
{
public const string PortSupplierId = "D7240956-FE4A-4324-93C9-C56975AF351E";
// This Guid needs to match PortSupplierGuid
public static Guid PortSupplierGuid => new Guid(PortSupplierId);
private static DebugPortSupplierPrivate s_portSupplier;
private class DebugPortSupplierPrivate : DebugPortSupplier
{
private IDebugCoreServer2 _server;
List<DebugPort> _ports = new List<DebugPort>();
public DebugPortSupplierPrivate() : base(true)
{
}
public override DebugPort FindPort(string name)
{
return _ports.FirstOrDefault(p => p.Name == name);
}
public override IDebugCoreServer2 CoreServer
{
[System.Diagnostics.DebuggerHidden]
get { return _server; }
}
public override DebugPort[] Ports
{
get { return (DebugPort[])_ports.ToArray().Clone(); }
}
#region IDebugPortSupplier2 Members
new public int GetPortSupplierId(out Guid pguidPortSupplier)
{
pguidPortSupplier = DebugPortSupplier.PortSupplierGuid;
return COM_HResults.S_OK;
}
new public int EnumPorts(out IEnumDebugPorts2 ppEnum)
{
List<IDebugPort2> ports = new List<IDebugPort2>();
_ports.Clear();
foreach (NanoDeviceBase device in NanoFrameworkPackage.NanoDeviceCommService.DebugClient.NanoFrameworkDevices)
{
ports.Add(new DebugPort(device, this));
_ports.Add(new DebugPort(device, this));
}
ppEnum = new CorDebugEnum(ports, typeof(IDebugPort2), typeof(IEnumDebugPorts2));
return COM_HResults.S_OK;
}
new public int AddPort(IDebugPortRequest2 pRequest, out IDebugPort2 ppPort)
{
IEnumDebugPorts2 portList;
EnumPorts(out portList);
string name;
pRequest.GetPortName(out name);
ppPort = FindPort(name);
if (ppPort != null)
{
return COM_HResults.S_OK;
}
return COM_HResults.E_FAIL;
}
new public int GetPort(ref Guid guidPort, out IDebugPort2 ppPort)
{
Guid guidPortToFind = guidPort;
ppPort = _ports.FirstOrDefault(p => p.PortId == guidPortToFind);
if (ppPort != null)
{
return COM_HResults.S_OK;
}
return COM_HResults.E_FAIL;
}
#endregion
#region IDebugPortSupplierEx2 Members
new public int SetServer(IDebugCoreServer2 pServer)
{
_server = pServer;
return COM_HResults.S_OK;
}
#endregion
}
private DebugPortSupplier( bool fPrivate )
{
}
public DebugPortSupplier()
{
lock (typeof(DebugPortSupplier))
{
if(s_portSupplier == null)
{
s_portSupplier = new DebugPortSupplierPrivate();
}
}
}
public virtual DebugPort[] Ports
{
get { return s_portSupplier.Ports; }
}
public virtual DebugPort FindPort(string name)
{
return s_portSupplier.FindPort(name);
}
public virtual IDebugCoreServer2 CoreServer
{
get { return s_portSupplier.CoreServer; }
}
#region IDebugPortSupplierEx2 Members
public int SetServer(IDebugCoreServer2 pServer)
{
return s_portSupplier.SetServer(pServer);
}
#endregion
#region IDebugPortSupplier2 Members
public int GetPortSupplierId(out Guid pguidPortSupplier)
{
return s_portSupplier.GetPortSupplierId(out pguidPortSupplier);
}
public int RemovePort(IDebugPort2 pPort)
{
return COM_HResults.E_NOTIMPL;
}
public int CanAddPort()
{
return COM_HResults.S_OK;
}
public int GetPortSupplierName(out string name)
{
name = ".NET nanoFramework Device";
return COM_HResults.S_OK;
}
public int EnumPorts(out IEnumDebugPorts2 ppEnum)
{
return s_portSupplier.EnumPorts(out ppEnum);
}
public int AddPort(IDebugPortRequest2 pRequest, out IDebugPort2 ppPort)
{
return s_portSupplier.AddPort(pRequest, out ppPort);
}
public int GetPort(ref Guid guidPort, out IDebugPort2 ppPort)
{
return s_portSupplier.GetPort(ref guidPort, out ppPort);
}
#endregion
#region IDebugPortSupplierDescription2 Members
int IDebugPortSupplierDescription2.GetDescription(enum_PORT_SUPPLIER_DESCRIPTION_FLAGS[] pdwFlags, out string pbstrText)
{
pbstrText = "Use this transport to connect to all nanoFramework devices.";
return COM_HResults.S_OK;
}
#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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Write_byte_int_int : PortsTest
{
//The string size used for large byte array testing
private const int LARGE_BUFFER_SIZE = 2048;
//When we test Write and do not care about actually writing anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int DEFAULT_BUFFER_SIZE = 1;
private const int DEFAULT_BUFFER_OFFSET = 0;
private const int DEFAULT_BUFFER_COUNT = 1;
//The maximum buffer size when a exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
//The maximum buffer size when a exception is not expected
private const int MAX_BUFFER_SIZE = 8;
//The default number of times the write method is called when verifying write
private const int DEFAULT_NUM_WRITES = 3;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyWriteException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
Random rndGen = new Random(-55);
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
Random rndGen = new Random(-55);
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_EQ_Length_Plus_1()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = DEFAULT_BUFFER_COUNT;
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_GT_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = DEFAULT_BUFFER_OFFSET;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void OffsetCount_EQ_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
Type expectedException = typeof(ArgumentException);
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Offset_EQ_Length_Minus_1()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = bufferLength - 1;
int count = 1;
Type expectedException = typeof(ArgumentException);
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Count_EQ_Length()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = 0;
int count = bufferLength;
Type expectedException = typeof(ArgumentException);
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Count_EQ_Zero()
{
int bufferLength = 0;
int offset = 0;
int count = bufferLength;
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UnicodeEncoding()
{
Random rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UnicodeEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeBuffer()
{
int bufferLength = LARGE_BUFFER_SIZE;
int offset = 0;
int count = bufferLength;
VerifyWrite(new byte[bufferLength], offset, count, 1);
}
#endregion
#region Verification for Test Cases
private void VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int bufferLength = null == buffer ? 0 : buffer.Length;
Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count);
com.Open();
try
{
com.Write(buffer, offset, count);
Fail("ERROR!!!: No Exception was thrown");
}
catch (Exception e)
{
if (e.GetType() != expectedException)
{
Fail("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException);
}
}
}
}
private void VerifyWrite(byte[] buffer, int offset, int count)
{
VerifyWrite(buffer, offset, count, new ASCIIEncoding());
}
private void VerifyWrite(byte[] buffer, int offset, int count, int numWrites)
{
VerifyWrite(buffer, offset, count, new ASCIIEncoding(), numWrites);
}
private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding)
{
VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES);
}
private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding, int numWrites)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}",
buffer.Length, offset, count, encoding.EncodingName);
com1.Encoding = encoding;
com2.Encoding = encoding;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites);
}
}
public void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2)
{
VerifyWriteByteArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES);
}
private void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites)
{
byte[] oldBuffer, expectedBytes, actualBytes;
int byteRead;
int index = 0;
oldBuffer = (byte[])buffer.Clone();
expectedBytes = new byte[count];
actualBytes = new byte[expectedBytes.Length * numWrites];
for (int i = 0; i < count; i++)
{
expectedBytes[i] = buffer[i + offset];
}
for (int i = 0; i < numWrites; i++)
{
com1.Write(buffer, offset, count);
}
com2.ReadTimeout = 500;
Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250);
//Make sure buffer was not altered during the write call
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] != oldBuffer[i])
{
Fail("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i);
}
}
while (true)
{
try
{
byteRead = com2.ReadByte();
}
catch (TimeoutException)
{
break;
}
if (actualBytes.Length <= index)
{
//If we have read in more bytes then we expect
Fail("ERROR!!!: We have received more bytes then were sent");
}
actualBytes[index] = (byte)byteRead;
index++;
if (actualBytes.Length - index != com2.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead);
}
}
//Compare the bytes that were read with the ones we expected to read
for (int j = 0; j < numWrites; j++)
{
for (int i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j])
{
Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i);
}
}
}
}
#endregion
}
}
| |
/*
* Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Threading;
using System.Collections;
using System;
using System.IO;
using ThirdParty.Json.LitJson;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using Amazon.Util.Internal;
#if PCL || BCL45
using System.Threading.Tasks;
#endif
#if PCL
using PCLStorage;
#endif
namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal
{
/// <summary>
/// The class controls session start, pause, resume and stop logic.
/// </summary>
[System.Security.SecuritySafeCritical]
public partial class Session
{
private Logger _logger = Logger.GetLogger(typeof(Session));
// session info
/// <summary>
/// Session start Time.
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// Session stop time.
/// </summary>
public DateTime? StopTime { get; set; }
/// <summary>
/// Session latest resume time.
/// </summary>
public DateTime PreStartTime { get; set; }
/// <summary>
/// Session ID.
/// </summary>
public string SessionId { get; set; }
/// <summary>
/// Session duration in milliseconds.
/// </summary>
public long Duration { get; set; }
// lock to guard session info
private Object _lock = new Object();
internal class SessionStorage
{
public SessionStorage()
{
_sessionId = null; _duration = 0;
}
public DateTime _startTime;
public DateTime? _stopTime;
public DateTime _preStartTime;
public string _sessionId;
public long _duration;
}
private MobileAnalyticsManagerConfig _maConfig;
private volatile SessionStorage _sessionStorage = null;
private string _appID = null;
private string _sessionStorageFileName = "_session_storage.json";
private string _sessionStorageFileFullPath = null;
#region public
/// <summary>
/// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session"/>
/// </summary>
/// <param name="appID">Amazon Mobile Analytics App Identifier.</param>
/// <param name="maConfig">Mobile Analytics Manager Configuration.</param>
[System.Security.SecuritySafeCritical]
public Session(string appID, MobileAnalyticsManagerConfig maConfig)
{
_maConfig = maConfig;
_appID = appID;
#if BCL
_sessionStorageFileFullPath = InternalSDKUtils.DetermineAppLocalStoragePath(appID + _sessionStorageFileName);
#elif PCL
_sessionStorageFileFullPath = System.IO.Path.Combine(PCLStorage.FileSystem.Current.LocalStorage.Path, appID + _sessionStorageFileName);
#endif
_logger.InfoFormat("Initialize a new session. The session storage file is {0}.", _sessionStorageFileFullPath);
_sessionStorage = new SessionStorage();
}
/// <summary>
/// Start this session.
/// </summary>
public void Start()
{
lock (_lock)
{
// Read session info from persistent storage, in case app is killed.
RetrieveSessionStorage();
// If session storage is valid, restore session and resume session.
if (_sessionStorage != null && !string.IsNullOrEmpty(_sessionStorage._sessionId))
{
this.StartTime = _sessionStorage._startTime;
this.StopTime = _sessionStorage._stopTime;
this.SessionId = _sessionStorage._sessionId;
this.Duration = _sessionStorage._duration;
Resume();
}
// Otherwise, create a new session.
else
{
NewSessionHelper();
}
}
}
/// <summary>
/// Pause this session.
/// </summary>
public void Pause()
{
lock (_lock)
{
PauseSessionHelper();
SaveSessionStorage();
}
}
/// <summary>
/// Resume this session.
/// </summary>
public void Resume()
{
lock (_lock)
{
if (this.StopTime == null)
{
//this may sometimes be a valid scenario e.g when the applciation starts
_logger.InfoFormat("Call Resume() without calling Pause() first. But this can be valid opertion only when MobileAnalyticsManager instance is created.");
return;
}
DateTime currentTime = DateTime.UtcNow;
if (this.StopTime.Value < currentTime)
{
// new session
if (Convert.ToInt64((currentTime - this.StopTime.Value).TotalMilliseconds) > _maConfig.SessionTimeout * 1000)
{
StopSessionHelper();
NewSessionHelper();
}
// resume old session
else
{
ResumeSessionHelper();
}
}
else
{
InvalidOperationException e = new InvalidOperationException();
_logger.Error(e, "Session stop time is earlier than start time !");
}
}
}
#endregion
private void NewSessionHelper()
{
StartTime = DateTime.UtcNow;
PreStartTime = DateTime.UtcNow;
StopTime = null;
SessionId = Guid.NewGuid().ToString();
Duration = 0;
CustomEvent sessionStartEvent = new CustomEvent(Constants.SESSION_START_EVENT_TYPE);
sessionStartEvent.StartTimestamp = StartTime;
sessionStartEvent.SessionId = SessionId;
MobileAnalyticsManager.GetInstance(_appID).RecordEvent(sessionStartEvent);
}
private void StopSessionHelper()
{
DateTime currentTime = DateTime.UtcNow;
// update session info
StopTime = currentTime;
// record session stop event
CustomEvent stopSessionEvent = new CustomEvent(Constants.SESSION_STOP_EVENT_TYPE);
stopSessionEvent.StartTimestamp = StartTime;
if (StopTime != null)
stopSessionEvent.StopTimestamp = StopTime;
stopSessionEvent.SessionId = SessionId;
stopSessionEvent.Duration = Duration;
MobileAnalyticsManager.GetInstance(_appID).RecordEvent(stopSessionEvent);
}
private void PauseSessionHelper()
{
DateTime currentTime = DateTime.UtcNow;
// update session info
StopTime = currentTime;
Duration += Convert.ToInt64((currentTime - PreStartTime).TotalMilliseconds);
// record session pause event
CustomEvent pauseSessionEvent = new CustomEvent(Constants.SESSION_PAUSE_EVENT_TYPE);
pauseSessionEvent.StartTimestamp = StartTime;
if (StopTime != null)
pauseSessionEvent.StopTimestamp = StopTime;
pauseSessionEvent.SessionId = SessionId;
pauseSessionEvent.Duration = Duration;
MobileAnalyticsManager.GetInstance(_appID).RecordEvent(pauseSessionEvent);
}
private void ResumeSessionHelper()
{
DateTime currentTime = DateTime.UtcNow;
// update session info
PreStartTime = currentTime;
// record session resume event
CustomEvent resumeSessionEvent = new CustomEvent(Constants.SESSION_RESUME_EVENT_TYPE);
resumeSessionEvent.StartTimestamp = StartTime;
if (StopTime != null)
resumeSessionEvent.StopTimestamp = StopTime;
resumeSessionEvent.SessionId = SessionId;
resumeSessionEvent.Duration = Duration;
MobileAnalyticsManager.GetInstance(_appID).RecordEvent(resumeSessionEvent);
}
private void SaveSessionStorage()
{
_sessionStorage._startTime = StartTime;
_sessionStorage._stopTime = StopTime;
_sessionStorage._preStartTime = PreStartTime;
_sessionStorage._sessionId = SessionId;
_sessionStorage._duration = Duration;
// store session into file
_logger.DebugFormat("Mobile Analytics is about to store session info: {0} ", JsonMapper.ToJson(_sessionStorage));
#if PCL
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFile file = rootFolder.CreateFileAsync(_sessionStorageFileFullPath, CreationCollisionOption.ReplaceExisting).Result;
file.WriteAllTextAsync(JsonMapper.ToJson(_sessionStorage)).Wait();
#elif BCL
string directory = Path.GetDirectoryName(_sessionStorageFileFullPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(_sessionStorageFileFullPath, JsonMapper.ToJson(_sessionStorage));
#endif
}
private void RetrieveSessionStorage()
{
string sessionString = null;
#if PCL
IFolder rootFolder = FileSystem.Current.LocalStorage;
if (ExistenceCheckResult.FileExists == rootFolder.CheckExistsAsync(_sessionStorageFileFullPath).Result)
{
IFile file = rootFolder.GetFileAsync(_sessionStorageFileFullPath).Result;
sessionString = file.ReadAllTextAsync().Result;
}
#elif BCL
if (File.Exists(_sessionStorageFileFullPath))
{
using (var sessionFile = new System.IO.StreamReader(_sessionStorageFileFullPath))
{
sessionString = sessionFile.ReadToEnd();
sessionFile.Close();
}
_logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString);
}
else
{
_logger.DebugFormat("Mobile Analytics session file does not exist.");
}
#endif
if (!string.IsNullOrEmpty(sessionString))
{
_sessionStorage = JsonMapper.ToObject<SessionStorage>(sessionString);
}
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Text;
using System.Xml;
using OpenADK.Library.Tools.Cfg;
using OpenADK.Library.Tools.XPath;
using OpenADK.Util;
namespace OpenADK.Library.Tools.Mapping
{
/// <summary> A FieldMapping defines how to map a local application field to an element or
/// attribute of the SIF Data Object type encapsulated by the parent ObjectMapping.
/// Each FieldMapping is associated with a <i>Rule</i> that is evaluated at
/// runtime to carry out the actual mapping operation on a SifDataObject instance.
/// The way the rule behaves is up to its implementation.
///
/// A FieldMapping may have a default value. If set, the default value is
/// assigned to the SIF element or attribute if the corresponding field value is
/// null or undefined. This is useful if you wish to ensure that a specific SIF
/// element/attribute always has a value regardless of whether or not there is a
/// corresponding value in your application's database.
///
///
/// The application-defined field name that is associated with a FieldMapping
/// must be unique; that is, there cannot be more than one FieldMapping for the
/// same application field. However, if you wish to map the same field to more
/// than one SIF element or attribute, you can create an <i>alias</i>. An alias
/// is a FieldMapping that has a unique field name but refers to another field.
/// For example, if your application defines the field STUDENT_NUM and you wish
/// to define two FieldMappings for that field, create an alias:
///
///
/// <code>
/// // Create the default mapping<br/>
/// FieldMapping fm = new FieldMapping("STUDENT_NUM","OtherId[@Type='06']");<br/><br/>
/// <br/>
/// // Create an alias (the field name must be unique)<br/>
/// FieldMapping zz = new FieldMapping("MYALIAS","OtherId[@Type='ZZ']");<br/>
/// zz.setAlias( "STUDENT_NUM" );<br/><br/>
/// </code>
///
/// In the above example, the "STUDENT_NUM" mapping produces an <OtherId>
/// element with its Type attribute set to '06'. The "MYALIAS" mapping produces
/// a second <OtherId> element with its Type attribute set to 'ZZ'. Both
/// elements will have the value of the application-defined STUDENT_NUM field.
/// Note that if MYALIAS were an actual field name of your application, however,
/// the value of the <OtherId Type='ZZ'> element would be equal to that
/// field's value. When creating aliases be sure to choose a name that does not
/// conflict with the real field names used by your application.
///
///
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> Adk 1.0
/// </version>
public class FieldMapping
{
private const String ATTR_VALUESET = "valueset";
private const String ATTR_ALIAS = "alias";
private const String ATTR_DEFAULT = "default";
private const String ATTR_NAME = "name";
private const String ATTR_DATATYPE = "datatype";
private const String ATTR_SIFVERSION = "sifVersion";
private const String ATTR_DIRECTION = "direction";
private const String ATTR_IFNULL = "ifnull";
private MappingBehavior fNullBehavior = MappingBehavior.IfNullUnspecified;
protected internal Rule fRule;
protected string fField;
protected string fDefValue;
protected string fAlias;
protected string fValueSet;
protected MappingsFilter fFilter;
internal XmlElement fNode;
private SifDataType fDatatype = SifDataType.String;
/// <summary> Constructor</summary>
public FieldMapping()
: this(null, (string) null, (XmlElement) null)
{
}
/// <summary> Constructs a FieldMapping with an XPath-like rule</summary>
/// <param name="name">The name of the local application field that maps to the
/// SIF Data Object element or attribute described by this FieldMapping
/// </param>
/// <param name="rule">An XPath-like query string described by the <code>SifDtd.lookupByXPath</code>
/// method
/// </param>
public FieldMapping(string name,
string rule)
: this(name, rule, null)
{
}
public FieldMapping(string name,
string rule,
XmlElement node)
{
fField = name;
if (rule != null)
{
SetRule(rule);
}
fNode = node;
}
/// <summary> Constructs a FieldMapping with an <OtherId> rule.
///
/// </summary>
/// <param name="name">The name of the local application field that maps to the
/// SIF Data Object element or attribute described by this FieldMapping
/// </param>
/// <param name="rule">An OtherIdMapping object that describes how to select
/// a <OtherId> element during a mapping operation
/// </param>
public FieldMapping(string name,
OtherIdMapping rule)
: this(name, rule, null)
{
}
/// <summary> Constructs a FieldMapping with an <OtherId> rule.
///
/// </summary>
/// <param name="name">The name of the local application field that maps to the
/// SIF Data Object element or attribute described by this FieldMapping
/// </param>
/// <param name="rule">An OtherIdMapping object that describes how to select
/// a <OtherId> element during a mapping operation
/// </param>
/// <param name="node">The XmlElement that this FieldMapping draws its configuration from</param>
public FieldMapping(string name,
OtherIdMapping rule,
XmlElement node)
{
fField = name;
SetRule(rule);
fNode = node;
}
/// <summary> Gets the optional DOM XmlElement associated with this FieldMapping instance.
/// The DOM XmlElement is usually set by the parent ObjectMapping instance when a
/// FieldMapping is populated from a DOM Document.
/// </summary>
/// <summary> Sets the optional DOM XmlElement associated with this FieldMapping instance.
/// The DOM XmlElement is usually set by the parent ObjectMapping instance when a
/// FieldMapping is populated from a DOM Document.
/// </summary>
public virtual XmlElement XmlElement
{
get { return fNode; }
set { fNode = value; }
}
/**
* Creates a new FieldMapping instance and populates its properties from
* the given XML Element
* @param parent
* @param element
* @return a new FieldMapping instance
* @throws ADKConfigException If the FieldMapping cannot read expected
* values from the DOM Node
*/
public static FieldMapping FromXml(
ObjectMapping parent,
XmlElement element)
{
if (element == null)
{
throw new ArgumentException("Argument: 'element' cannot be null");
}
String name = element.GetAttribute(ATTR_NAME);
FieldMapping fm = new FieldMapping();
fm.SetNode(element);
fm.FieldName = name;
fm.DefaultValue = XmlUtils.GetAttributeValue(element, ATTR_DEFAULT);
fm.Alias = XmlUtils.GetAttributeValue(element, ATTR_ALIAS);
fm.ValueSetID = XmlUtils.GetAttributeValue(element, ATTR_VALUESET);
String ifNullBehavior = element.GetAttribute(ATTR_IFNULL);
if (ifNullBehavior.Length > 0)
{
if (String.Compare(ifNullBehavior, "default", true) == 0)
{
fm.NullBehavior = MappingBehavior.IfNullDefault;
}
else if (String.Compare(ifNullBehavior, "suppress", true) == 0)
{
fm.NullBehavior = MappingBehavior.IfNullSuppress;
}
}
String dataType = element.GetAttribute(ATTR_DATATYPE);
if (dataType != null && dataType.Length > 0)
{
try
{
fm.DataType = (SifDataType) Enum.Parse(typeof (SifDataType), dataType, true);
}
catch (FormatException iae)
{
Adk.Log.Warn("Unable to parse datatype '" + dataType + "' for field " + name, iae);
}
}
String filtVer = element.GetAttribute(ATTR_SIFVERSION);
String filtDir = element.GetAttribute(ATTR_DIRECTION);
if( !(String.IsNullOrEmpty( filtVer )) || !(String.IsNullOrEmpty(filtDir )) )
{
MappingsFilter filt = new MappingsFilter();
if (!String.IsNullOrEmpty(filtVer))
filt.SifVersion = filtVer;
if (!String.IsNullOrEmpty(filtDir))
{
if (String.Compare(filtDir, "inbound", true) == 0)
filt.Direction = MappingDirection.Inbound;
else if (String.Compare(filtDir, "outbound", true) == 0)
filt.Direction = MappingDirection.Outbound;
else
throw new AdkConfigException(
"Field mapping rule for " + parent.ObjectType + "." + fm.FieldName +
" specifies an unknown Direction flag: '" + filtDir + "'");
}
fm.Filter = filt;
}
// FieldMapping must either have node text or an <otherid> child
XmlElement otherIdNode = XmlUtils.GetFirstElementIgnoreCase(element, "otherid");
if (otherIdNode == null)
{
String def = element.InnerText;
if (def != null)
fm.SetRule(def);
else
fm.SetRule("");
}
else
{
fm.SetRule(OtherIdMapping.FromXml(parent, fm, otherIdNode), otherIdNode);
}
return fm;
}
/**
* Writes the values of this FieldMapping to the specified XML Element
*
* @param element The XML Element to write values to
*/
public void ToXml(XmlElement element)
{
XmlUtils.SetOrRemoveAttribute(element, ATTR_NAME, fField);
if (fDatatype == SifDataType.String)
{
element.RemoveAttribute(ATTR_DATATYPE);
}
else
{
element.SetAttribute(ATTR_DATATYPE, fDatatype.ToString());
}
XmlUtils.SetOrRemoveAttribute(element, ATTR_DEFAULT, fDefValue);
XmlUtils.SetOrRemoveAttribute(element, ATTR_ALIAS, fAlias);
XmlUtils.SetOrRemoveAttribute(element, ATTR_VALUESET, fValueSet);
MappingsFilter filt = Filter;
if (filt != null)
{
WriteFilterToXml(filt, element);
}
WriteNullBehaviorToXml(fNullBehavior, element);
fRule.ToXml(element);
}
/**
* Writes the mapping filter to an XML Element
* @param filter
* @param element The XML Element to write the filter to
*/
private void WriteFilterToXml(MappingsFilter filter, XmlElement element)
{
if (filter == null)
{
element.RemoveAttribute(ATTR_SIFVERSION);
element.RemoveAttribute(ATTR_DIRECTION);
}
else
{
if (filter.HasVersionFilter)
{
element.SetAttribute(ATTR_SIFVERSION, filter.SifVersion);
}
else
{
element.RemoveAttribute(ATTR_SIFVERSION);
}
MappingDirection direction = filter.Direction;
if (direction == MappingDirection.Inbound)
{
element.SetAttribute(ATTR_DIRECTION, "inbound");
}
else if (direction == MappingDirection.Outbound)
{
element.SetAttribute(ATTR_DIRECTION, "outbound");
}
else
{
element.RemoveAttribute(ATTR_DIRECTION);
}
}
}
private void WriteNullBehaviorToXml(MappingBehavior behavior, XmlElement element)
{
switch (behavior)
{
case MappingBehavior.IfNullDefault:
element.SetAttribute(ATTR_IFNULL, "default");
break;
case MappingBehavior.IfNullSuppress:
element.SetAttribute(ATTR_IFNULL, "suppress");
break;
default:
element.RemoveAttribute(ATTR_IFNULL);
break;
}
}
/// <summary> Gets or sets the name of the local application field that maps to the SIF Data
/// Object element or attribute
/// </summary>
/// <value> The local application field name. (This value will be used as
/// the key in HashMaps populated by the Mappings.map methods)
/// </value>
public virtual string FieldName
{
get { return fField; }
set
{
fField = value;
if (fNode != null && value != null)
{
fNode.SetAttribute("name", value);
}
}
}
/// <summary>Gets or sets the ID of the ValueSet that should be used to translate the value
/// of this field.
/// </summary>
/// <remarks>
/// Note: The Mappings classes do not automatically perform translations if
/// this attribute is defined. Rather, it is provided so that agents can
/// associate a ValueSet with a field in the Mappings configuration file,
/// and have a means of looking up that association at runtime.
///
///</remarks>
/// <returns> The value passed to the <code>setValueSetID</code> method
///
/// @since Adk 1.5
///
/// </returns>
public virtual string ValueSetID
{
get { return fValueSet; }
set
{
fValueSet = value;
if (fValueSet != null && fValueSet.Trim().Length == 0)
{
fValueSet = null;
}
if (fNode != null)
{
if (value != null)
{
fNode.SetAttribute("valueset", fValueSet);
}
else
{
fNode.RemoveAttribute("valueset");
}
}
}
}
/// <summary> Gets or sets the default value for this field when no corresponding element or
/// attribute is found in the SIF Data Object. The Mapping.map methods will
/// create an entry in the HashMap with this default value.
///
/// </summary>
/// <value> The default string value for this field
/// </value>
public virtual string DefaultValue
{
get { return fDefValue; }
set
{
fDefValue = value;
if (fNode != null)
{
if (value != null)
{
fNode.SetAttribute("default", value);
}
else
{
fNode.RemoveAttribute("default");
}
}
}
}
/// <summary>
/// Gets the default value
/// </summary>
/// <param name="converter">The type converter to use</param>
/// <param name="formatter">The formatter to use for the version of SIF</param>
/// <returns></returns>
public SifSimpleType GetDefaultValue(TypeConverter converter, SifFormatter formatter)
{
if (fDefValue != null && converter != null)
{
try
{
return converter.Parse(formatter, fDefValue);
}
catch (AdkParsingException adkpe)
{
throw new AdkMappingException(adkpe.Message, null, adkpe);
}
}
return null;
}
/// <summary>
/// Quickly determines whether this field mapping has a default value defined
/// without going through the extra work of actually resolving the default value
/// </summary>
/// <value>True if this field mapping has a default value defined</value>
public bool HasDefaultValue
{
get { return fDefValue != null; }
}
/// <summary>Gets or sets an alias of another field mapping.</summary>
/// <value> The name of the field for which this entry is an alias, or null
/// if this FieldMapping is not an alias.</value>
/// <remarks> Defines this FieldMapping to be an alias of another field mapping. During
/// the mapping process, the FieldMapping will be applied if the referenced
/// field exists in the Map provided to the Mappings.map method. Aliases are
/// required when an application wishes to map a single application field to
/// more than one element or attribute in the SIF Data Object.
///
/// To use aliases, create a FieldMapping where the field name is a unique
/// name and the alias is the name of an existing field. For example, to map
/// an application-defined field named "STUDENT_NUM" to more than one
/// element/attribute in the SIF Data Object,
/// </remarks>
/// <example>
/// <code>
/// // Create the default mapping<br/>
/// FieldMapping fm = new FieldMapping("STUDENT_NUM","OtherId[@Type='06']");
/// // Create an alias; the field name must be unique<br/>
/// FieldMapping fm2 = new FieldMapping("STUDENT_NUM_B","OtherId[@Type='ZZ']=STUDENTID:$(STUDENTNUM)");<br/>
/// </code>
///</example>
public virtual string Alias
{
get { return fAlias; }
set
{
fAlias = value;
if (fNode != null)
{
if (value != null)
{
fNode.SetAttribute("alias", value);
}
else
{
fNode.RemoveAttribute("alias");
}
}
}
}
/// <summary>Gets or sets optional filtering attributes.</summary>
/// <value> A MappingsFilter instance or null if none defined for
/// this field rule
/// </value>
public virtual MappingsFilter Filter
{
get { return fFilter; }
set
{
fFilter = value;
if (fNode != null)
{
MappingsFilter.Save(fFilter, fNode);
}
}
}
/// <summary>
/// Returns the key to a Field Mapping. The Key of a field mapping consists
/// of it's alias or field name and any filters that are defined
/// </summary>
public string Key
{
get
{
StringBuilder key = new StringBuilder();
key.Append(fField);
if (fAlias != null)
{
key.Append('_');
key.Append(fAlias);
}
if (fFilter != null)
{
if (fFilter.HasDirectionFilter)
{
key.Append('_');
key.Append(fFilter.Direction);
}
if (fFilter.HasVersionFilter)
{
key.Append('_');
key.Append(fFilter.SifVersion);
}
}
return key.ToString();
}
}
/// <summary> Creates a copy this ObjectMapping instance.
///
/// </summary>
/// <returns> A "deep copy" of this object
/// </returns>
public virtual FieldMapping Copy(ObjectMapping newParent)
{
FieldMapping m = new FieldMapping();
if (fNode != null && newParent.fNode != null)
{
m.fNode = (XmlElement) newParent.fNode.OwnerDocument.ImportNode(fNode, false);
}
m.FieldName = fField;
m.DefaultValue = fDefValue;
m.Alias = fAlias;
m.ValueSetID = fValueSet;
m.NullBehavior = fNullBehavior;
if (fFilter != null)
{
MappingsFilter filtCopy = new MappingsFilter();
filtCopy.fVersion = fFilter.fVersion;
filtCopy.fDirection = fFilter.fDirection;
m.Filter = filtCopy;
}
m.DataType = fDatatype;
if (fRule != null)
{
m.fRule = fRule.Copy(m);
}
else
{
m.fRule = null;
}
return m;
}
public SifSimpleType Evaluate(SifXPathContext xpathContext, SifVersion version, bool returnDefault)
{
SifSimpleType value = null;
if (fRule != null)
{
value = fRule.Evaluate(xpathContext, version);
}
if (value == null && fDefValue != null && returnDefault)
{
// TODO: Support all data types
try
{
return SifTypeConverters.GetConverter(fDatatype).Parse(Adk.TextFormatter, fDefValue);
}
catch (AdkParsingException adkpe)
{
throw new AdkSchemaException(
"Error parsing default value: '" + fDefValue + "' for field " + fField + " : " + adkpe, null,
adkpe);
}
}
return value;
}
/// <summary> Sets this FieldMapping rule to an XPath-like query string</summary>
/// <param name="definition">An XPath-like query string described by the
/// <code>SifDtd.lookupByXPath</code> method
/// </param>
public void SetRule(string definition)
{
fRule = new XPathRule(definition);
if (fNode != null)
{
fNode.InnerText = definition;
}
}
/// <summary> Sets this object's rule to an "<OtherId> rule"</summary>
/// <param name="otherId">An OtherIdMapping object that describes how to select
/// a <OtherId> element during a mapping operation
/// </param>
public void SetRule(OtherIdMapping otherId)
{
fRule = new OtherIdRule(otherId);
if (fNode != null)
{
fRule.ToXml(fNode);
}
}
public void SetRule(OtherIdMapping otherId,
XmlElement node)
{
fRule = new OtherIdRule(otherId, node);
}
/// <summary> Gets the field mapping rule</summary>
/// <returns> A Rule instance
/// </returns>
public Rule GetRule()
{
return fRule;
}
private void SetNode(XmlElement element)
{
fNode = element;
}
public MappingBehavior NullBehavior
{
get { return fNullBehavior; }
set
{
if (value < MappingBehavior.IfNullUnspecified || value > MappingBehavior.IfNullSuppress)
{
throw new ArgumentException("Value must be one of the FieldMapping.IFNULL_XXX constants.");
}
fNullBehavior = value;
if (fNode != null)
{
WriteNullBehaviorToXml(value, fNode);
}
}
}
/// <summary>
/// Gets or sets the data type that this FieldMapping represents
/// </summary>
public SifDataType DataType
{
get { return fDatatype; }
set
{
fDatatype = value;
if (fNode != null)
{
if (fDatatype == SifDataType.String)
{
fNode.RemoveAttribute(ATTR_DATATYPE);
}
else
{
fNode.SetAttribute(ATTR_DATATYPE, fDatatype.ToString());
}
}
}
}
}
}
| |
// 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.ComponentModel.Tests
{
public class MarshalByValueComponentTests
{
[Fact]
public void Ctor_Default()
{
var component = new SubMarshalByValueComponent();
Assert.NotNull(component.EventsEntryPoint);
Assert.Same(component.EventsEntryPoint, component.EventsEntryPoint);
Assert.Null(component.Container);
Assert.False(component.DesignMode);
Assert.Null(component.Site);
Assert.Null(component.GetService(null));
}
[Fact]
public void Site_Set_GetReturnsExpected()
{
var site = new Site();
var component = new SubMarshalByValueComponent() { Site = site };
Assert.Same(site, component.Site);
Assert.Same(site.Container, component.Container);
Assert.Equal(site.DesignMode, component.DesignMode);
Assert.Equal("service", component.GetService(typeof(int)));
}
[Fact]
public void Disposed_AddRemoveEventHandler_Success()
{
bool calledDisposedHandler = false;
void Handler(object sender, EventArgs e) => calledDisposedHandler = true;
var component = new MarshalByValueComponent();
component.Disposed += Handler;
component.Disposed -= Handler;
component.Dispose();
Assert.False(calledDisposedHandler);
}
[Fact]
public void Dispose_NoSiteNoEventHandler_Nop()
{
var component = new SubMarshalByValueComponent();
component.Dispose();
// With events.
Assert.NotNull(component.EventsEntryPoint);
component.Dispose();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Dispose_DisposingNoSiteNoEventHandler_Nop(bool disposing)
{
var component = new SubMarshalByValueComponent();
component.DisposeEntryPoint(disposing);
// With events.
Assert.NotNull(component.EventsEntryPoint);
component.DisposeEntryPoint(disposing);
}
[Fact]
public void Dispose_NoSiteEventHandler_InvokesEventHandler()
{
bool calledDisposed = false;
var component = new SubMarshalByValueComponent();
component.Disposed += (sender, e) =>
{
Assert.Same(component, sender);
Assert.Same(EventArgs.Empty, e);
calledDisposed = true;
};
Assert.False(calledDisposed);
component.Dispose();
Assert.True(calledDisposed);
// Call multiple times.
calledDisposed = false;
component.Dispose();
Assert.True(calledDisposed);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Dispose_DisposingNoSiteEventHandler_InvokesEventHandler(bool disposing)
{
bool calledDisposed = false;
var component = new SubMarshalByValueComponent();
component.Disposed += (sender, e) =>
{
Assert.Same(component, sender);
Assert.Same(EventArgs.Empty, e);
calledDisposed = true;
};
Assert.False(calledDisposed);
component.DisposeEntryPoint(disposing);
Assert.Equal(disposing, calledDisposed);
// Call multiple times.
calledDisposed = false;
component.DisposeEntryPoint(disposing);
Assert.Equal(disposing, calledDisposed);
}
[Fact]
public void Dispose_SiteEventHandler_InvokesEventHandlerAndRemovesSiteFromComponent()
{
bool calledDisposed = false;
var site = new Site();
var component = new MarshalByValueComponent() { Site = site };
component.Disposed += (sender, e) =>
{
Assert.Same(component, sender);
Assert.Same(EventArgs.Empty, e);
calledDisposed = true;
};
Assert.False(calledDisposed);
site.Container.Add(component);
component.Dispose();
Assert.True(calledDisposed);
Assert.Empty(site.Container.Components);
// Call multiple times.
component.Site = site;
site.Container = null;
calledDisposed = false;
component.Dispose();
Assert.True(calledDisposed);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Dispose_DisposingSiteEventHandler_InvokesEventHandlerAndRemovesSiteFromComponent(bool disposing)
{
bool calledDisposed = false;
var site = new Site();
var component = new SubMarshalByValueComponent() { Site = site };
component.Disposed += (sender, e) =>
{
Assert.Same(component, sender);
Assert.Same(EventArgs.Empty, e);
calledDisposed = true;
};
Assert.False(calledDisposed);
site.Container.Add(component);
component.DisposeEntryPoint(disposing);
Assert.Equal(disposing, calledDisposed);
Assert.Empty(site.Container.Components);
// Call multiple times.
component.Site = site;
site.Container = null;
calledDisposed = false;
component.DisposeEntryPoint(disposing);
Assert.Equal(disposing, calledDisposed);
}
[Fact]
public void ToString_WithSite_ReturnsExpected()
{
var component = new MarshalByValueComponent() { Site = new Site() };
Assert.Equal("name [System.ComponentModel.MarshalByValueComponent]", component.ToString());
}
[Fact]
public void ToString_NoSite_ReturnsExpected()
{
var component = new MarshalByValueComponent();
Assert.Equal("System.ComponentModel.MarshalByValueComponent", component.ToString());
}
public class SubMarshalByValueComponent : MarshalByValueComponent
{
public SubMarshalByValueComponent() : base() { }
public EventHandlerList EventsEntryPoint => Events;
public void DisposeEntryPoint(bool disposing) => Dispose(disposing);
}
public class Site : ISite
{
public IComponent Component { get; set; } = new Component();
public IContainer Container { get; set; } = new Container();
public bool DesignMode { get; set; } = true;
public string Name { get; set; } = "name";
public object GetService(Type serviceType)
{
Assert.Equal(typeof(int), serviceType);
return "service";
}
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
public class SealMethodsThatSatisfyPrivateInterfacesTests
{
[Fact]
public async Task TestCSharp_ClassesThatCannotBeSubClassedOutsideThisAssembly_HasNoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
// Declaring type only accessible to this assembly
internal class C : IFace
{
public virtual void M()
{
}
}
// Declaring type can only be instantiated in this assembly
public class D : IFace
{
internal D()
{
}
public virtual void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_VirtualImplicit_HasDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public class C : IFace
{
public virtual void M()
{
}
}
", GetCSharpResultAt(9, 25));
}
[Fact]
public async Task TestCSharp_AbstractImplicit_HasDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public abstract class C : IFace
{
public abstract void M();
}
", GetCSharpResultAt(9, 26));
}
[Fact]
public async Task TestCSharp_Explicit_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public class C : IFace
{
void IFace.M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_NoInterface_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
public void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_StructImplicit_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public class C : IFace
{
public void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_PublicInterface_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public interface IFace
{
void M();
}
public class C : IFace
{
public void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_OverriddenFromBase_HasDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public abstract class B
{
public abstract void M();
}
public class C : B, IFace
{
public override void M()
{
}
}
", GetCSharpResultAt(14, 26));
}
[Fact]
public async Task TestCSharp_OverriddenFromBaseButMethodIsSealed_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public abstract class B
{
public abstract void M();
}
public class C : B, IFace
{
public sealed override void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_OverriddenFromBaseButClassIsSealed_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public abstract class B
{
public abstract void M();
}
public sealed class C : B, IFace
{
public override void M()
{
}
}
");
}
[Fact]
public async Task TestCSharp_ImplicitlyImplementedFromBaseMember_HasDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal interface IFace
{
void M();
}
public class B
{
public virtual void M()
{
}
}
public class C : B, IFace
{
}
", GetCSharpResultAt(14, 14));
}
[Fact]
public async Task TestCSharp_ImplicitlyImplementedFromBaseMember_Public_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public interface IFace
{
void M();
}
public class B
{
public virtual void M()
{
}
}
class C : B, IFace
{
}
");
}
[Fact]
public async Task TestVB_Overridable_HasDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public Class C
Implements IFace
Public Overridable Sub M() Implements IFace.M
End Sub
End Class
", GetBasicResultAt(9, 28));
}
[Fact]
public async Task TestVB_MustOverride_HasDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public MustInherit Class C
Implements IFace
Public MustOverride Sub M() Implements IFace.M
End Class
", GetBasicResultAt(9, 29));
}
[Fact]
public async Task TestVB_OverridenFromBase_HasDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public MustInherit Class B
Public MustOverride Sub M()
End Class
Public Class C
Inherits B
Implements IFace
Public Overrides Sub M() Implements IFace.M
End Sub
End Class
", GetBasicResultAt(14, 26));
}
[Fact]
public async Task TestVB_OverridenFromBaseButNotOverridable_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public MustInherit Class B
Public MustOverride Sub M()
End Class
Public Class C
Inherits B
Implements IFace
Public NotOverridable Overrides Sub M() Implements IFace.M
End Sub
End Class
");
}
[Fact]
public async Task TestVB_NotExplicit_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public MustInherit Class C
Implements IFace
Public MustOverride Sub M()
Public Sub IFace_M() Implements IFace.M
End Sub
End Class
");
}
[Fact]
public async Task TestVB_PrivateMethod_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public Class C
Implements IFace
Private Sub M() Implements IFace.M
End Sub
End Class
");
}
[Fact]
public async Task TestVB_PublicMethod_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public Class C
Implements IFace
Public Sub M() Implements IFace.M
End Sub
End Class
");
}
[Fact]
public async Task TestVB_FriendMethod_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface IFace
Sub M()
End Interface
Public Class C
Implements IFace
Friend Sub M() Implements IFace.M
End Sub
End Class
");
}
[Fact]
public async Task TestVB_PublicInterface_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Interface IFace
Sub M()
End Interface
Public Class C
Implements IFace
Public Overridable Sub M() Implements IFace.M
End Sub
End Class
");
}
// TODO:
// sealed overrides - no diagnostic
private static DiagnosticResult GetCSharpResultAt(int line, int column)
=> VerifyCS.Diagnostic()
.WithLocation(line, column);
private static DiagnosticResult GetBasicResultAt(int line, int column)
=> VerifyVB.Diagnostic()
.WithLocation(line, column);
}
}
| |
// 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.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class DecryptorPalWindows : DecryptorPal
{
public sealed override ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception)
{
Debug.Assert(recipientInfo != null);
Debug.Assert(cert != null);
Debug.Assert(originatorCerts != null);
Debug.Assert(extraStore != null);
CryptKeySpec keySpec;
exception = TryGetKeySpecForCertificate(cert, out keySpec);
if (exception != null)
return null;
// Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
using (SafeProvOrNCryptKeyHandle hKey = TryGetCertificatePrivateKey(cert, false, out exception))
{
if (hKey == null)
return null;
RecipientInfoType type = recipientInfo.Type;
switch (type)
{
case RecipientInfoType.KeyTransport:
exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
break;
case RecipientInfoType.KeyAgreement:
exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
break;
default:
// Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
// returning to the caller.
Debug.Fail($"Unexpected RecipientInfoType: {type}");
throw new NotSupportedException();
}
if (exception != null)
return null;
// If we got here, we successfully decrypted. Return the decrypted content.
return _hCryptMsg.GetContentInfo();
}
}
private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
{
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
int cbSize = 0;
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
byte[] pData = new byte[cbSize];
unsafe
{
fixed (byte* pvData = pData)
{
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, pData, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
CRYPT_KEY_PROV_INFO* pCryptKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pvData;
keySpec = pCryptKeyProvInfo->dwKeySpec;
return null;
}
}
}
}
private static SafeProvOrNCryptKeyHandle TryGetCertificatePrivateKey(X509Certificate2 cert, bool silent, out Exception exception)
{
CryptAcquireCertificatePrivateKeyFlags flags =
CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG
// Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG because wrapping an NCrypt wrapper over CAPI keys unconditionally
// causes some legacy features (such as RC4 support) to break.
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG;
if (silent)
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG;
}
bool mustFree;
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
IntPtr hKey;
CryptKeySpec keySpec;
if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey(hCertContext, flags, IntPtr.Zero, out hKey, out keySpec, out mustFree))
{
exception = Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
// We need to know whether we got back a CRYPTPROV or NCrypt handle. Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP.
// Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which one we got through the keySpec value.
bool isNCrypt;
switch (keySpec)
{
case CryptKeySpec.AT_KEYEXCHANGE:
case CryptKeySpec.AT_SIGNATURE:
isNCrypt = false;
break;
case CryptKeySpec.CERT_NCRYPT_KEY_SPEC:
isNCrypt = true;
break;
default:
// As of this writing, we've exhausted all the known values of keySpec. We have no idea what kind of key handle we got so
// play it safe and fail fast.
throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec));
}
SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp(hKey, ownsHandle: mustFree, isNcrypt: isNCrypt);
exception = null;
return hProvOrNCryptKey;
}
}
private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
{
KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
CMSG_CTRL_DECRYPT_PARA decryptPara;
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_DECRYPT_PARA>();
decryptPara.hKey = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.dwRecipientIndex = pal.Index;
bool success = Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_DECRYPT, ref decryptPara);
if (!success)
return Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
{
unsafe
{
KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
return pal.WithCmsgCmsRecipientInfo<Exception>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
{
CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
decryptPara.hProv = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
decryptPara.dwRecipientIndex = pal.Index;
decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
switch (originatorChoice)
{
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
{
X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
candidateCerts.AddRange(originatorCerts);
candidateCerts.AddRange(extraStore);
SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
if (originatorCert == null)
return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
{
CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;
// Do not factor this call out of the switch statement as leaving this "using" block will free up
// native memory that decryptPara points to.
return TryExecuteDecryptAgree(ref decryptPara);
}
}
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
{
decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
return TryExecuteDecryptAgree(ref decryptPara);
}
default:
return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
}
});
}
}
private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
{
if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetHRForLastWin32Error());
return errorCode.ToCryptographicException();
}
return null;
}
}
}
| |
using System;
using MagicChunks.Core;
using MagicChunks.Documents;
using Xunit;
namespace MagicChunks.Tests.Core
{
public class TransformerTests
{
[Fact]
public void TransformJson()
{
// Arrange
var transform = new TransformationCollection()
{
{ "a/y", "2" },
{ "a/z/t/w", "3" },
{ "b", "5" },
{ "c/a", "1" },
{ "c/b", "2" },
{ "c/b/t", "3" },
{ "d", "4" },
{ "#e", "" },
{ "f/items[]`1", "1" },
{ "f/items[]`2", "2" }
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new JsonDocument(@"{
'a': {
'x': '1'
},
'b': '2',
'c': '3',
'e': '4'
}"), transform);
// Assert
Assert.Equal(@"{
""a"": {
""x"": ""1"",
""y"": ""2"",
""z"": {
""t"": {
""w"": ""3""
}
}
},
""b"": ""5"",
""c"": {
""a"": ""1"",
""b"": {
""t"": ""3""
}
},
""d"": ""4"",
""f"": {
""items"": [
""1"",
""2""
]
}
}", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformJsonImplicit()
{
// Arrange
var transform = new TransformationCollection("e")
{
{ "a/y", "2" },
{ "a/z/t/w", "3" },
{ "b", "5" },
{ "c/a", "1" },
{ "c/b", "2" },
{ "c/b/t", "3" },
{ "d", "4" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(@"{
'a': {
'x': '1'
},
'b': '2',
'c': '3',
'e': '4'
}", transform);
// Assert
Assert.Equal(@"{
""a"": {
""x"": ""1"",
""y"": ""2"",
""z"": {
""t"": {
""w"": ""3""
}
}
},
""b"": ""5"",
""c"": {
""a"": ""1"",
""b"": {
""t"": ""3""
}
},
""d"": ""4""
}", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformJsonByIndex()
{
// Arrange
var transform = new TransformationCollection()
{
{ "items[2]/data", "EE" },
{ "items[@i='1']/data", "FF" },
{ "#items[0]", "" },
{ "#items[@i='1']/x", "" },
{ "items[@i='3']", "{ y: '20' }" },
{ "items[0]", "{ x: '40' }" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new JsonDocument(@"{
'items': [
{ 'i': 0, data: 'AA' },
{ 'i': 1, data: 'BB', x: '25' },
{ 'i': 2, data: 'CC' },
{ 'i': 3, data: 'DD' },
],
'b': '2',
'c': '3'
}"), transform);
// Assert
Assert.Equal(@"{
""items"": [
{
""x"": ""40""
},
{
""i"": 2,
""data"": ""EE""
},
{
""y"": ""20""
}
],
""b"": ""2"",
""c"": ""3""
}", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformXml()
{
// Arrange
var transform = new TransformationCollection()
{
{ "xml/a/y", "2" },
{ "xml/a/@y", "3" },
{ "xml/a/x/@q", "9" },
{ "xml/a/z/t/w", "3" },
{ "xml/b", "5" },
{ "xml/c/a", "1" },
{ "xml/c/b", "2" },
{ "xml/c/b/t", "3" },
{ "xml/e/item[@key = 'item2']", "5" },
{ "xml/e/item[@key=\"item3\"]", "6" },
{ "xml/f/item[@key = 'item2']/val", "7" },
{ "xml/f/item[@key=\"item3\"]/val", "8" },
{ "xml/d", "4" },
{ "#xml/g", "" },
{ "xml/items[]`1", "<val>1</val>" },
{ "xml/items[]`2", "<val>2</val>" },
{ "xml/data[]`1", "<x>1</x>" },
{ "xml/data[]`2", "<y>2</y>" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new XmlDocument(@"<xml>
<a>
<x>1</x>
</a>
<b>2</b>
<c>3</c>
<e>
<item key=""item1"">1</item>
<item key=""item2"">2</item>
<item key=""item3"">3</item>
</e>
<f>
<item key=""item1"">
<val>1</val>
</item>
<item key=""item2"">
<val>2</val>
</item>
<item key=""item3"">
<val>3</val>
</item>
</f>
<g>
<x></x>
</g>
<items />
</xml>"), transform);
// Assert
Assert.Equal(@"<xml>
<a y=""3"">
<x q=""9"">1</x>
<y>2</y>
<z>
<t>
<w>3</w>
</t>
</z>
</a>
<b>5</b>
<c>
<a>1</a>
<b>
<t>3</t>
</b>
</c>
<e>
<item key=""item1"">1</item>
<item key=""item2"">5</item>
<item key=""item3"">6</item>
</e>
<f>
<item key=""item1"">
<val>1</val>
</item>
<item key=""item2"">
<val>7</val>
</item>
<item key=""item3"">
<val>8</val>
</item>
</f>
<items>
<val>1</val>
<val>2</val>
</items>
<d>4</d>
<data>
<x>1</x>
<y>2</y>
</data>
</xml>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformXmlImplicit()
{
// Arrange
var transform = new TransformationCollection("xml/g")
{
{ "xml/a/y", "2" },
{ "xml/a/@y", "3" },
{ "xml/a/z/t/w", "3" },
{ "xml/b", "5" },
{ "xml/c/a", "1" },
{ "xml/c/b", "2" },
{ "xml/c/b/t", "3" },
{ "xml/e/item[@key = 'item2']", "5" },
{ "xml/e/item[@key=\"item3\"]", "6" },
{ "xml/f/item[@key = 'item2']/val", "7" },
{ "xml/f/item[@key=\"item3\"]/val", "8" },
{ "xml/d", "4" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(@"<xml>
<a>
<x>1</x>
</a>
<b>2</b>
<c>3</c>
<e>
<item key=""item1"">1</item>
<item key=""item2"">2</item>
<item key=""item3"">3</item>
</e>
<f>
<item key=""item1"">
<val>1</val>
</item>
<item key=""item2"">
<val>2</val>
</item>
<item key=""item3"">
<val>3</val>
</item>
</f>
<g>
<x></x>
</g>
</xml>", transform);
// Assert
Assert.Equal(@"<xml>
<a y=""3"">
<x>1</x>
<y>2</y>
<z>
<t>
<w>3</w>
</t>
</z>
</a>
<b>5</b>
<c>
<a>1</a>
<b>
<t>3</t>
</b>
</c>
<e>
<item key=""item1"">1</item>
<item key=""item2"">5</item>
<item key=""item3"">6</item>
</e>
<f>
<item key=""item1"">
<val>1</val>
</item>
<item key=""item2"">
<val>7</val>
</item>
<item key=""item3"">
<val>8</val>
</item>
</f>
<d>4</d>
</xml>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformXmlByIndex()
{
// Arrange
var transform = new TransformationCollection()
{
{ "info/param[1]/option", "DD" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new XmlDocument(@"<info>
<param>
<option>AA</option>
</param>
<param>
<option>BB</option>
<argument>CC</argument>
</param>
</info>"), transform);
// Assert
Assert.Equal(@"<info>
<param>
<option>AA</option>
</param>
<param>
<option>DD</option>
<argument>CC</argument>
</param>
</info>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformXmlWithNamespace()
{
// Arrange
var transform = new TransformationCollection()
{
{ "manifest/@android:versionCode", "10001" }
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new XmlDocument(@"<manifest xmlns:android=""http://schemas.android.com/apk/res/android""
package=""com.myapp.name.here""
android:installLocation=""auto""
android:versionCode=""10000""
android:versionName=""1"">
<uses-sdk android:minSdkVersion=""18"" android:targetSdkVersion=""23"" />
<uses-permission android:name=""android.permission.CHANGE_WIFI_STATE"" />
<uses-permission android:name=""android.permission.ACCESS_WIFI_STATE"" />
<application android:label=""Scan Plan 2 Test"" android:icon="""" android:theme="""" />
</manifest>"), transform);
// Assert
Assert.Equal(@"<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" package=""com.myapp.name.here"" android:installLocation=""auto"" android:versionCode=""10001"" android:versionName=""1"">
<uses-sdk android:minSdkVersion=""18"" android:targetSdkVersion=""23"" />
<uses-permission android:name=""android.permission.CHANGE_WIFI_STATE"" />
<uses-permission android:name=""android.permission.ACCESS_WIFI_STATE"" />
<application android:label=""Scan Plan 2 Test"" android:icon="""" android:theme="""" />
</manifest>", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformYaml()
{
// Arrange
var transform = new TransformationCollection("e")
{
{ "a/y", "2" },
{ "a/z/t/w", "3" },
{ "b", "5" },
{ "c/a", "1" },
{ "c/b", "2" },
{ "c/b/t", "3" },
{ "d", "4" },
{ "f[]`1", "1" },
{ "f[]`2", "2" }
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new YamlDocument(@"a:
x: 1
b: 2
c: 3
e:
x: 5"), transform);
// Assert
Assert.Equal(@"a:
x: 1
y: 2
z:
t:
w: 3
b: 5
c:
a: 1
b:
t: 3
d: 4
f:
- 1
- 2
", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void TransformYamlImplicit()
{
// Arrange
var transform = new TransformationCollection("e")
{
{ "a/y", "2" },
{ "a/z/t/w", "3" },
{ "b", "5" },
{ "c/a", "1" },
{ "c/b", "2" },
{ "c/b/t", "3" },
{ "d", "4" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(@"a:
x: 1
b: 2
c: 3
e:
x: 5", transform);
// Assert
Assert.Equal(@"a:
x: 1
y: 2
z:
t:
w: 3
b: 5
c:
a: 1
b:
t: 3
d: 4
", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void RemoveNode()
{
// Arrange
var transform = new TransformationCollection("e")
{
{ "a/y", "2" },
{ "a/z/t/w", "3" },
{ "#b", "5" },
{ "c/a", "1" },
{ "c/b", "2" },
{ "c/b/t", "3" },
{ "d", "4" },
};
// Act
var transformer = new Transformer();
string result = transformer.Transform(new JsonDocument(@"{
'a': {
'x': '1'
},
'b': '2',
'c': '3',
'e': '4'
}"), transform);
// Assert
Assert.Equal(@"{
""a"": {
""x"": ""1"",
""y"": ""2"",
""z"": {
""t"": {
""w"": ""3""
}
}
},
""c"": {
""a"": ""1"",
""b"": {
""t"": ""3""
}
},
""d"": ""4""
}", result, ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void ValidateTransformationKey()
{// Arrange
var transform = new TransformationCollection()
{
{ "", "1" }
};
// Act
var transformer = new Transformer();
ArgumentException result = Assert.Throws<ArgumentException>(() => transformer.Transform(new JsonDocument(@"{ }"), transform));
// Assert
Assert.True(result.Message?.StartsWith("Transformation key is empty."));
}
[Fact]
public void ValidateWrongDocumentType()
{// Arrange
var transform = new TransformationCollection()
{
{ "x", "1" }
};
// Act
var transformer = new Transformer();
ArgumentException result = Assert.Throws<ArgumentException>(() => transformer.Transform(@"{ <xml> x:y </xml> }", transform));
// Assert
Assert.True(result.Message?.StartsWith("Unknown document type."));
}
}
}
| |
//
// Copyright (c) 2014 .NET Foundation
//
// 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 (c) 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.
//using System;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite
{
/// <summary>A persistent content-addressable store for arbitrary-size data blobs.</summary>
/// <remarks>
/// A persistent content-addressable store for arbitrary-size data blobs.
/// Each blob is stored as a file named by its SHA-1 digest.
/// </remarks>
/// <exclude></exclude>
public class BlobStore
{
public static string FileExtension = ".blob";
public static string TmpFileExtension = ".blobtmp";
public static string TmpFilePrefix = "tmp";
private string path;
public BlobStore(string path)
{
this.path = path;
FilePath directory = new FilePath(path);
directory.Mkdirs();
if (!directory.IsDirectory())
{
throw new InvalidOperationException(string.Format("Unable to create directory for: %s"
, directory));
}
}
public static BlobKey KeyForBlob(byte[] data)
{
MessageDigest md;
try
{
md = MessageDigest.GetInstance("SHA-1");
}
catch (NoSuchAlgorithmException)
{
Log.E(Log.TagBlobStore, "Error, SHA-1 digest is unavailable.");
return null;
}
byte[] sha1hash = new byte[40];
md.Update(data, 0, data.Length);
sha1hash = md.Digest();
BlobKey result = new BlobKey(sha1hash);
return result;
}
public static BlobKey KeyForBlobFromFile(FilePath file)
{
MessageDigest md;
try
{
md = MessageDigest.GetInstance("SHA-1");
}
catch (NoSuchAlgorithmException)
{
Log.E(Log.TagBlobStore, "Error, SHA-1 digest is unavailable.");
return null;
}
byte[] sha1hash = new byte[40];
try
{
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[65536];
int lenRead = fis.Read(buffer);
while (lenRead > 0)
{
md.Update(buffer, 0, lenRead);
lenRead = fis.Read(buffer);
}
fis.Close();
}
catch (IOException)
{
Log.E(Log.TagBlobStore, "Error readin tmp file to compute key");
}
sha1hash = md.Digest();
BlobKey result = new BlobKey(sha1hash);
return result;
}
public virtual string PathForKey(BlobKey key)
{
return path + FilePath.separator + BlobKey.ConvertToHex(key.GetBytes()) + FileExtension;
}
public virtual long GetSizeOfBlob(BlobKey key)
{
string path = PathForKey(key);
FilePath file = new FilePath(path);
return file.Length();
}
public virtual bool GetKeyForFilename(BlobKey outKey, string filename)
{
if (!filename.EndsWith(FileExtension))
{
return false;
}
//trim off extension
string rest = Sharpen.Runtime.Substring(filename, path.Length + 1, filename.Length
- FileExtension.Length);
outKey.SetBytes(BlobKey.ConvertFromHex(rest));
return true;
}
public virtual byte[] BlobForKey(BlobKey key)
{
string path = PathForKey(key);
FilePath file = new FilePath(path);
byte[] result = null;
try
{
result = GetBytesFromFile(file);
}
catch (IOException e)
{
Log.E(Log.TagBlobStore, "Error reading file", e);
}
return result;
}
public virtual InputStream BlobStreamForKey(BlobKey key)
{
string path = PathForKey(key);
FilePath file = new FilePath(path);
if (file.CanRead())
{
try
{
return new FileInputStream(file);
}
catch (FileNotFoundException e)
{
Log.E(Log.TagBlobStore, "Unexpected file not found in blob store", e);
return null;
}
}
return null;
}
public virtual bool StoreBlobStream(InputStream inputStream, BlobKey outKey)
{
FilePath tmp = null;
try
{
tmp = FilePath.CreateTempFile(TmpFilePrefix, TmpFileExtension, new FilePath(path)
);
FileOutputStream fos = new FileOutputStream(tmp);
byte[] buffer = new byte[65536];
int lenRead = inputStream.Read(buffer);
while (lenRead > 0)
{
fos.Write(buffer, 0, lenRead);
lenRead = inputStream.Read(buffer);
}
inputStream.Close();
fos.Close();
}
catch (IOException e)
{
Log.E(Log.TagBlobStore, "Error writing blog to tmp file", e);
return false;
}
BlobKey newKey = KeyForBlobFromFile(tmp);
outKey.SetBytes(newKey.GetBytes());
string path = PathForKey(outKey);
FilePath file = new FilePath(path);
if (file.CanRead())
{
// object with this hash already exists, we should delete tmp file and return true
tmp.Delete();
return true;
}
else
{
// does not exist, we should rename tmp file to this name
tmp.RenameTo(file);
}
return true;
}
public virtual bool StoreBlob(byte[] data, BlobKey outKey)
{
BlobKey newKey = KeyForBlob(data);
outKey.SetBytes(newKey.GetBytes());
string path = PathForKey(outKey);
FilePath file = new FilePath(path);
if (file.CanRead())
{
return true;
}
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
fos.Write(data);
}
catch (FileNotFoundException e)
{
Log.E(Log.TagBlobStore, "Error opening file for output", e);
return false;
}
catch (IOException ioe)
{
Log.E(Log.TagBlobStore, "Error writing to file", ioe);
return false;
}
finally
{
if (fos != null)
{
try
{
fos.Close();
}
catch (IOException)
{
}
}
}
// ignore
return true;
}
/// <exception cref="System.IO.IOException"></exception>
private static byte[] GetBytesFromFile(FilePath file)
{
InputStream @is = new FileInputStream(file);
// Get the size of the file
long length = file.Length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.Length && (numRead = @is.Read(bytes, offset, bytes.Length -
offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.Length)
{
throw new IOException("Could not completely read file " + file.GetName());
}
// Close the input stream and return bytes
@is.Close();
return bytes;
}
public virtual ICollection<BlobKey> AllKeys()
{
ICollection<BlobKey> result = new HashSet<BlobKey>();
FilePath file = new FilePath(path);
FilePath[] contents = file.ListFiles();
foreach (FilePath attachment in contents)
{
if (attachment.IsDirectory())
{
continue;
}
BlobKey attachmentKey = new BlobKey();
GetKeyForFilename(attachmentKey, attachment.GetPath());
result.AddItem(attachmentKey);
}
return result;
}
public virtual int Count()
{
FilePath file = new FilePath(path);
FilePath[] contents = file.ListFiles();
return contents.Length;
}
public virtual long TotalDataSize()
{
long total = 0;
FilePath file = new FilePath(path);
FilePath[] contents = file.ListFiles();
foreach (FilePath attachment in contents)
{
total += attachment.Length();
}
return total;
}
public virtual int DeleteBlobsExceptWithKeys(IList<BlobKey> keysToKeep)
{
int numDeleted = 0;
FilePath file = new FilePath(path);
FilePath[] contents = file.ListFiles();
foreach (FilePath attachment in contents)
{
BlobKey attachmentKey = new BlobKey();
GetKeyForFilename(attachmentKey, attachment.GetPath());
if (!keysToKeep.Contains(attachmentKey))
{
bool result = attachment.Delete();
if (result)
{
++numDeleted;
}
else
{
Log.E(Log.TagBlobStore, "Error deleting attachment: %s", attachment);
}
}
}
return numDeleted;
}
public virtual int DeleteBlobs()
{
return DeleteBlobsExceptWithKeys(new AList<BlobKey>());
}
public virtual bool IsGZipped(BlobKey key)
{
int magic = 0;
string path = PathForKey(key);
FilePath file = new FilePath(path);
if (file.CanRead())
{
try
{
RandomAccessFile raf = new RandomAccessFile(file, "r");
magic = raf.Read() & unchecked((int)(0xff)) | ((raf.Read() << 8) & unchecked((int
)(0xff00)));
raf.Close();
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e, System.Console.Error);
}
}
return magic == GZIPInputStream.GzipMagic;
}
public virtual FilePath TempDir()
{
FilePath directory = new FilePath(path);
FilePath tempDirectory = new FilePath(directory, "temp_attachments");
tempDirectory.Mkdirs();
if (!tempDirectory.IsDirectory())
{
throw new InvalidOperationException(string.Format("Unable to create directory for: %s"
, tempDirectory));
}
return tempDirectory;
}
}
}
| |
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Collections.Generic;
using erl.Oracle.TnsNames.Antlr4.Runtime.Misc;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
using erl.Oracle.TnsNames.Antlr4.Runtime.Tree;
using erl.Oracle.TnsNames.Antlr4.Runtime.Tree.Pattern;
namespace erl.Oracle.TnsNames.Antlr4.Runtime.Tree.Pattern
{
/// <summary>
/// Represents the result of matching a
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// against a tree pattern.
/// </summary>
public class ParseTreeMatch
{
/// <summary>
/// This is the backing field for
/// <see cref="Tree()"/>
/// .
/// </summary>
private readonly IParseTree tree;
/// <summary>
/// This is the backing field for
/// <see cref="Pattern()"/>
/// .
/// </summary>
private readonly ParseTreePattern pattern;
/// <summary>
/// This is the backing field for
/// <see cref="Labels()"/>
/// .
/// </summary>
private readonly MultiMap<string, IParseTree> labels;
/// <summary>
/// This is the backing field for
/// <see cref="MismatchedNode()"/>
/// .
/// </summary>
private readonly IParseTree mismatchedNode;
/// <summary>
/// Constructs a new instance of
/// <see cref="ParseTreeMatch"/>
/// from the specified
/// parse tree and pattern.
/// </summary>
/// <param name="tree">The parse tree to match against the pattern.</param>
/// <param name="pattern">The parse tree pattern.</param>
/// <param name="labels">
/// A mapping from label names to collections of
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// objects located by the tree pattern matching process.
/// </param>
/// <param name="mismatchedNode">
/// The first node which failed to match the tree
/// pattern during the matching process.
/// </param>
/// <exception>
/// IllegalArgumentException
/// if
/// <paramref name="tree"/>
/// is
/// <see langword="null"/>
/// </exception>
/// <exception>
/// IllegalArgumentException
/// if
/// <paramref name="pattern"/>
/// is
/// <see langword="null"/>
/// </exception>
/// <exception>
/// IllegalArgumentException
/// if
/// <paramref name="labels"/>
/// is
/// <see langword="null"/>
/// </exception>
public ParseTreeMatch(IParseTree tree, ParseTreePattern pattern, MultiMap<string, IParseTree> labels, IParseTree mismatchedNode)
{
if (tree == null)
{
throw new ArgumentException("tree cannot be null");
}
if (pattern == null)
{
throw new ArgumentException("pattern cannot be null");
}
if (labels == null)
{
throw new ArgumentException("labels cannot be null");
}
this.tree = tree;
this.pattern = pattern;
this.labels = labels;
this.mismatchedNode = mismatchedNode;
}
/// <summary>
/// Get the last node associated with a specific
/// <paramref name="label"/>
/// .
/// <p>For example, for pattern
/// <c><id:ID></c>
/// ,
/// <c>get("id")</c>
/// returns the
/// node matched for that
/// <c>ID</c>
/// . If more than one node
/// matched the specified label, only the last is returned. If there is
/// no node associated with the label, this returns
/// <see langword="null"/>
/// .</p>
/// <p>Pattern tags like
/// <c><ID></c>
/// and
/// <c><expr></c>
/// without labels are
/// considered to be labeled with
/// <c>ID</c>
/// and
/// <c>expr</c>
/// , respectively.</p>
/// </summary>
/// <param name="label">The label to check.</param>
/// <returns>
/// The last
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// to match a tag with the specified
/// label, or
/// <see langword="null"/>
/// if no parse tree matched a tag with the label.
/// </returns>
[return: Nullable]
public virtual IParseTree Get(string label)
{
IList<IParseTree> parseTrees = labels.Get(label);
if (parseTrees == null || parseTrees.Count == 0)
{
return null;
}
return parseTrees[parseTrees.Count - 1];
}
// return last if multiple
/// <summary>Return all nodes matching a rule or token tag with the specified label.</summary>
/// <remarks>
/// Return all nodes matching a rule or token tag with the specified label.
/// <p>If the
/// <paramref name="label"/>
/// is the name of a parser rule or token in the
/// grammar, the resulting list will contain both the parse trees matching
/// rule or tags explicitly labeled with the label and the complete set of
/// parse trees matching the labeled and unlabeled tags in the pattern for
/// the parser rule or token. For example, if
/// <paramref name="label"/>
/// is
/// <c>"foo"</c>
/// ,
/// the result will contain <em>all</em> of the following.</p>
/// <ul>
/// <li>Parse tree nodes matching tags of the form
/// <c><foo:anyRuleName></c>
/// and
/// <c><foo:AnyTokenName></c>
/// .</li>
/// <li>Parse tree nodes matching tags of the form
/// <c><anyLabel:foo></c>
/// .</li>
/// <li>Parse tree nodes matching tags of the form
/// <c><foo></c>
/// .</li>
/// </ul>
/// </remarks>
/// <param name="label">The label.</param>
/// <returns>
/// A collection of all
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// nodes matching tags with
/// the specified
/// <paramref name="label"/>
/// . If no nodes matched the label, an empty list
/// is returned.
/// </returns>
[return: NotNull]
public virtual IList<IParseTree> GetAll(string label)
{
IList<IParseTree> nodes = labels.Get(label);
if (nodes == null)
{
return Sharpen.Collections.EmptyList<IParseTree>();
}
return nodes;
}
/// <summary>Return a mapping from label → [list of nodes].</summary>
/// <remarks>
/// Return a mapping from label → [list of nodes].
/// <p>The map includes special entries corresponding to the names of rules and
/// tokens referenced in tags in the original pattern. For additional
/// information, see the description of
/// <see cref="GetAll(string)"/>
/// .</p>
/// </remarks>
/// <returns>
/// A mapping from labels to parse tree nodes. If the parse tree
/// pattern did not contain any rule or token tags, this map will be empty.
/// </returns>
[NotNull]
public virtual MultiMap<string, IParseTree> Labels
{
get
{
return labels;
}
}
/// <summary>Get the node at which we first detected a mismatch.</summary>
/// <remarks>Get the node at which we first detected a mismatch.</remarks>
/// <returns>
/// the node at which we first detected a mismatch, or
/// <see langword="null"/>
/// if the match was successful.
/// </returns>
[Nullable]
public virtual IParseTree MismatchedNode
{
get
{
return mismatchedNode;
}
}
/// <summary>Gets a value indicating whether the match operation succeeded.</summary>
/// <remarks>Gets a value indicating whether the match operation succeeded.</remarks>
/// <returns>
///
/// <see langword="true"/>
/// if the match operation succeeded; otherwise,
/// <see langword="false"/>
/// .
/// </returns>
public virtual bool Succeeded
{
get
{
return mismatchedNode == null;
}
}
/// <summary>Get the tree pattern we are matching against.</summary>
/// <remarks>Get the tree pattern we are matching against.</remarks>
/// <returns>The tree pattern we are matching against.</returns>
[NotNull]
public virtual ParseTreePattern Pattern
{
get
{
return pattern;
}
}
/// <summary>Get the parse tree we are trying to match to a pattern.</summary>
/// <remarks>Get the parse tree we are trying to match to a pattern.</remarks>
/// <returns>
/// The
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// we are trying to match to a pattern.
/// </returns>
[NotNull]
public virtual IParseTree Tree
{
get
{
return tree;
}
}
/// <summary><inheritDoc/></summary>
public override string ToString()
{
return string.Format("Match {0}; found {1} labels", Succeeded ? "succeeded" : "failed", Labels.Count);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
{
private const int defaultThreshold = 0;
private IEqualityComparer<TKey> comparer;
private Dictionary<TKey, TItem> dict;
private int keyCount;
private int threshold;
protected KeyedCollection() : this(null, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer) : this(comparer, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
: base(new List<TItem>())
{ // Be explicit about the use of List<T> so we can foreach over
// Items internally without enumerator allocations.
if (comparer == null)
{
comparer = EqualityComparer<TKey>.Default;
}
if (dictionaryCreationThreshold == -1)
{
dictionaryCreationThreshold = int.MaxValue;
}
if (dictionaryCreationThreshold < -1)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold);
}
this.comparer = comparer;
threshold = dictionaryCreationThreshold;
}
/// <summary>
/// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator.
/// </summary>
new private List<TItem> Items
{
get
{
Debug.Assert(base.Items is List<TItem>);
return (List<TItem>)base.Items;
}
}
public IEqualityComparer<TKey> Comparer
{
get
{
return comparer;
}
}
public TItem this[TKey key]
{
get
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (dict != null)
{
return dict[key];
}
foreach (TItem item in Items)
{
if (comparer.Equals(GetKeyForItem(item), key)) return item;
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TItem);
}
}
public bool Contains(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (dict != null)
{
return dict.ContainsKey(key);
}
foreach (TItem item in Items)
{
if (comparer.Equals(GetKeyForItem(item), key)) return true;
}
return false;
}
private bool ContainsItem(TItem item)
{
TKey key;
if ((dict == null) || ((key = GetKeyForItem(item)) == null))
{
return Items.Contains(item);
}
TItem itemInDict;
bool exist = dict.TryGetValue(key, out itemInDict);
if (exist)
{
return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
}
return false;
}
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (dict != null)
{
if (dict.ContainsKey(key))
{
return Remove(dict[key]);
}
return false;
}
for (int i = 0; i < Items.Count; i++)
{
if (comparer.Equals(GetKeyForItem(Items[i]), key))
{
RemoveItem(i);
return true;
}
}
return false;
}
protected IDictionary<TKey, TItem> Dictionary
{
get { return dict; }
}
protected void ChangeItemKey(TItem item, TKey newKey)
{
// check if the item exists in the collection
if (!ContainsItem(item))
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist);
}
TKey oldKey = GetKeyForItem(item);
if (!comparer.Equals(oldKey, newKey))
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
}
protected override void ClearItems()
{
base.ClearItems();
if (dict != null)
{
dict.Clear();
}
keyCount = 0;
}
protected abstract TKey GetKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
AddKey(key, item);
}
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
TKey key = GetKeyForItem(Items[index]);
if (key != null)
{
RemoveKey(key);
}
base.RemoveItem(index);
}
protected override void SetItem(int index, TItem item)
{
TKey newKey = GetKeyForItem(item);
TKey oldKey = GetKeyForItem(Items[index]);
if (comparer.Equals(oldKey, newKey))
{
if (newKey != null && dict != null)
{
dict[newKey] = item;
}
}
else
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
base.SetItem(index, item);
}
private void AddKey(TKey key, TItem item)
{
if (dict != null)
{
dict.Add(key, item);
}
else if (keyCount == threshold)
{
CreateDictionary();
dict.Add(key, item);
}
else
{
if (Contains(key))
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
keyCount++;
}
}
private void CreateDictionary()
{
dict = new Dictionary<TKey, TItem>(comparer);
foreach (TItem item in Items)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
dict.Add(key, item);
}
}
}
private void RemoveKey(TKey key)
{
Debug.Assert(key != null, "key shouldn't be null!");
if (dict != null)
{
dict.Remove(key);
}
else
{
keyCount--;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PrimusFlex.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Collections.Generic;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using RVA = System.UInt32;
#if !READ_ONLY
namespace Mono.Cecil.Cil {
sealed class CodeWriter : ByteBuffer {
readonly RVA code_base;
internal readonly MetadataBuilder metadata;
readonly Dictionary<uint, MetadataToken> standalone_signatures;
RVA current;
MethodBody body;
public CodeWriter (MetadataBuilder metadata)
: base (0)
{
this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader);
this.current = code_base;
this.metadata = metadata;
this.standalone_signatures = new Dictionary<uint, MetadataToken> ();
}
public RVA WriteMethodBody (MethodDefinition method)
{
var rva = BeginMethod ();
if (IsUnresolved (method)) {
if (method.rva == 0)
return 0;
WriteUnresolvedMethodBody (method);
} else {
if (IsEmptyMethodBody (method.Body))
return 0;
WriteResolvedMethodBody (method);
}
Align (4);
EndMethod ();
return rva;
}
static bool IsEmptyMethodBody (MethodBody body)
{
return body.instructions.IsNullOrEmpty ()
&& body.variables.IsNullOrEmpty ();
}
static bool IsUnresolved (MethodDefinition method)
{
return method.HasBody && method.HasImage && method.body == null;
}
void WriteUnresolvedMethodBody (MethodDefinition method)
{
var code_reader = metadata.module.Read (method, (_, reader) => reader.code);
MethodSymbols symbols;
var buffer = code_reader.PatchRawMethodBody (method, this, out symbols);
WriteBytes (buffer);
if (symbols.instructions.IsNullOrEmpty ())
return;
symbols.method_token = method.token;
symbols.local_var_token = GetLocalVarToken (buffer, symbols);
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
symbol_writer.Write (symbols);
}
static MetadataToken GetLocalVarToken (ByteBuffer buffer, MethodSymbols symbols)
{
if (symbols.variables.IsNullOrEmpty ())
return MetadataToken.Zero;
buffer.position = 8;
return new MetadataToken (buffer.ReadUInt32 ());
}
void WriteResolvedMethodBody (MethodDefinition method)
{
body = method.Body;
ComputeHeader ();
if (RequiresFatHeader ())
WriteFatHeader ();
else
WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny
WriteInstructions ();
if (body.HasExceptionHandlers)
WriteExceptionHandlers ();
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
symbol_writer.Write (body);
}
void WriteFatHeader ()
{
var body = this.body;
byte flags = 0x3; // fat
if (body.InitLocals)
flags |= 0x10; // init locals
if (body.HasExceptionHandlers)
flags |= 0x8; // more sections
WriteByte (flags);
WriteByte (0x30);
WriteInt16 ((short) body.max_stack_size);
WriteInt32 (body.code_size);
body.local_var_token = body.HasVariables
? GetStandAloneSignature (body.Variables)
: MetadataToken.Zero;
WriteMetadataToken (body.local_var_token);
}
void WriteInstructions ()
{
var instructions = body.Instructions;
var items = instructions.items;
var size = instructions.size;
for (int i = 0; i < size; i++) {
var instruction = items [i];
WriteOpCode (instruction.opcode);
WriteOperand (instruction);
}
}
void WriteOpCode (OpCode opcode)
{
if (opcode.Size == 1) {
WriteByte (opcode.Op2);
} else {
WriteByte (opcode.Op1);
WriteByte (opcode.Op2);
}
}
void WriteOperand (Instruction instruction)
{
var opcode = instruction.opcode;
var operand_type = opcode.OperandType;
if (operand_type == OperandType.InlineNone)
return;
var operand = instruction.operand;
if (operand == null)
throw new ArgumentException ();
switch (operand_type) {
case OperandType.InlineSwitch: {
var targets = (Instruction []) operand;
WriteInt32 (targets.Length);
var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1));
for (int i = 0; i < targets.Length; i++)
WriteInt32 (GetTargetOffset (targets [i]) - diff);
break;
}
case OperandType.ShortInlineBrTarget: {
var target = (Instruction) operand;
WriteSByte ((sbyte) (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 1)));
break;
}
case OperandType.InlineBrTarget: {
var target = (Instruction) operand;
WriteInt32 (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 4));
break;
}
case OperandType.ShortInlineVar:
WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.ShortInlineArg:
WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineVar:
WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.InlineArg:
WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineSig:
WriteMetadataToken (GetStandAloneSignature ((CallSite) operand));
break;
case OperandType.ShortInlineI:
if (opcode == OpCodes.Ldc_I4_S)
WriteSByte ((sbyte) operand);
else
WriteByte ((byte) operand);
break;
case OperandType.InlineI:
WriteInt32 ((int) operand);
break;
case OperandType.InlineI8:
WriteInt64 ((long) operand);
break;
case OperandType.ShortInlineR:
WriteSingle ((float) operand);
break;
case OperandType.InlineR:
WriteDouble ((double) operand);
break;
case OperandType.InlineString:
WriteMetadataToken (
new MetadataToken (
TokenType.String,
GetUserStringIndex ((string) operand)));
break;
case OperandType.InlineType:
case OperandType.InlineField:
case OperandType.InlineMethod:
case OperandType.InlineTok:
WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand));
break;
default:
throw new ArgumentException ();
}
}
int GetTargetOffset (Instruction instruction)
{
if (instruction == null) {
var last = body.instructions [body.instructions.size - 1];
return last.offset + last.GetSize ();
}
return instruction.offset;
}
uint GetUserStringIndex (string @string)
{
if (@string == null)
return 0;
return metadata.user_string_heap.GetStringIndex (@string);
}
static int GetVariableIndex (VariableDefinition variable)
{
return variable.Index;
}
int GetParameterIndex (ParameterDefinition parameter)
{
if (body.method.HasThis) {
if (parameter == body.this_parameter)
return 0;
return parameter.Index + 1;
}
return parameter.Index;
}
bool RequiresFatHeader ()
{
var body = this.body;
return body.CodeSize >= 64
|| body.InitLocals
|| body.HasVariables
|| body.HasExceptionHandlers
|| body.MaxStackSize > 8;
}
void ComputeHeader ()
{
int offset = 0;
var instructions = body.instructions;
var items = instructions.items;
var count = instructions.size;
var stack_size = 0;
var max_stack = 0;
Dictionary<Instruction, int> stack_sizes = null;
if (body.HasExceptionHandlers)
ComputeExceptionHandlerStackSize (ref stack_sizes);
for (int i = 0; i < count; i++) {
var instruction = items [i];
instruction.offset = offset;
offset += instruction.GetSize ();
ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack);
}
body.code_size = offset;
body.max_stack_size = max_stack;
}
void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes)
{
var exception_handlers = body.ExceptionHandlers;
for (int i = 0; i < exception_handlers.Count; i++) {
var exception_handler = exception_handlers [i];
switch (exception_handler.HandlerType) {
case ExceptionHandlerType.Catch:
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
case ExceptionHandlerType.Filter:
AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes);
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
}
}
}
static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes)
{
if (handler_start == null)
return;
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
stack_sizes [handler_start] = 1;
}
static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack)
{
int computed_size;
if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size))
stack_size = computed_size;
max_stack = System.Math.Max (max_stack, stack_size);
ComputeStackDelta (instruction, ref stack_size);
max_stack = System.Math.Max (max_stack, stack_size);
CopyBranchStackSize (instruction, ref stack_sizes, stack_size);
ComputeStackSize (instruction, ref stack_size);
}
static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size)
{
if (stack_size == 0)
return;
switch (instruction.opcode.OperandType) {
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size);
break;
case OperandType.InlineSwitch:
var targets = (Instruction[]) instruction.operand;
for (int i = 0; i < targets.Length; i++)
CopyBranchStackSize (ref stack_sizes, targets [i], stack_size);
break;
}
}
static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size)
{
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
int branch_stack_size = stack_size;
int computed_size;
if (stack_sizes.TryGetValue (target, out computed_size))
branch_stack_size = System.Math.Max (branch_stack_size, computed_size);
stack_sizes [target] = branch_stack_size;
}
static void ComputeStackSize (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Branch:
case FlowControl.Break:
case FlowControl.Throw:
case FlowControl.Return:
stack_size = 0;
break;
}
}
static void ComputeStackDelta (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Call: {
var method = (IMethodSignature) instruction.operand;
// pop 'this' argument
if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj)
stack_size--;
// pop normal arguments
if (method.HasParameters)
stack_size -= method.Parameters.Count;
// pop function pointer
if (instruction.opcode.Code == Code.Calli)
stack_size--;
// push return value
if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj)
stack_size++;
break;
}
default:
ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size);
ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size);
break;
}
}
static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size)
{
switch (pop_behavior) {
case StackBehaviour.Popi:
case StackBehaviour.Popref:
case StackBehaviour.Pop1:
stack_size--;
break;
case StackBehaviour.Pop1_pop1:
case StackBehaviour.Popi_pop1:
case StackBehaviour.Popi_popi:
case StackBehaviour.Popi_popi8:
case StackBehaviour.Popi_popr4:
case StackBehaviour.Popi_popr8:
case StackBehaviour.Popref_pop1:
case StackBehaviour.Popref_popi:
stack_size -= 2;
break;
case StackBehaviour.Popi_popi_popi:
case StackBehaviour.Popref_popi_popi:
case StackBehaviour.Popref_popi_popi8:
case StackBehaviour.Popref_popi_popr4:
case StackBehaviour.Popref_popi_popr8:
case StackBehaviour.Popref_popi_popref:
stack_size -= 3;
break;
case StackBehaviour.PopAll:
stack_size = 0;
break;
}
}
static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size)
{
switch (push_behaviour) {
case StackBehaviour.Push1:
case StackBehaviour.Pushi:
case StackBehaviour.Pushi8:
case StackBehaviour.Pushr4:
case StackBehaviour.Pushr8:
case StackBehaviour.Pushref:
stack_size++;
break;
case StackBehaviour.Push1_push1:
stack_size += 2;
break;
}
}
void WriteExceptionHandlers ()
{
Align (4);
var handlers = body.ExceptionHandlers;
if (handlers.Count < 0x15 && !RequiresFatSection (handlers))
WriteSmallSection (handlers);
else
WriteFatSection (handlers);
}
static bool RequiresFatSection (Collection<ExceptionHandler> handlers)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
if (IsFatRange (handler.TryStart, handler.TryEnd))
return true;
if (IsFatRange (handler.HandlerStart, handler.HandlerEnd))
return true;
if (handler.HandlerType == ExceptionHandlerType.Filter
&& IsFatRange (handler.FilterStart, handler.HandlerStart))
return true;
}
return false;
}
static bool IsFatRange (Instruction start, Instruction end)
{
if (start == null)
throw new ArgumentException ();
if (end == null)
return true;
return end.Offset - start.Offset > 255 || start.Offset > 65535;
}
void WriteSmallSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
WriteByte (eh_table);
WriteByte ((byte) (handlers.Count * 12 + 4));
WriteBytes (2);
WriteExceptionHandlers (
handlers,
i => WriteUInt16 ((ushort) i),
i => WriteByte ((byte) i));
}
void WriteFatSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
const byte fat_format = 0x40;
WriteByte (eh_table | fat_format);
int size = handlers.Count * 24 + 4;
WriteByte ((byte) (size & 0xff));
WriteByte ((byte) ((size >> 8) & 0xff));
WriteByte ((byte) ((size >> 16) & 0xff));
WriteExceptionHandlers (handlers, WriteInt32, WriteInt32);
}
void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
write_entry ((int) handler.HandlerType);
write_entry (handler.TryStart.Offset);
write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset);
write_entry (handler.HandlerStart.Offset);
write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset);
WriteExceptionHandlerSpecific (handler);
}
}
void WriteExceptionHandlerSpecific (ExceptionHandler handler)
{
switch (handler.HandlerType) {
case ExceptionHandlerType.Catch:
WriteMetadataToken (metadata.LookupToken (handler.CatchType));
break;
case ExceptionHandlerType.Filter:
WriteInt32 (handler.FilterStart.Offset);
break;
default:
WriteInt32 (0);
break;
}
}
public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables)
{
var signature = metadata.GetLocalVariableBlobIndex (variables);
return GetStandAloneSignatureToken (signature);
}
public MetadataToken GetStandAloneSignature (CallSite call_site)
{
var signature = metadata.GetCallSiteBlobIndex (call_site);
var token = GetStandAloneSignatureToken (signature);
call_site.MetadataToken = token;
return token;
}
MetadataToken GetStandAloneSignatureToken (uint signature)
{
MetadataToken token;
if (standalone_signatures.TryGetValue (signature, out token))
return token;
token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
standalone_signatures.Add (signature, token);
return token;
}
RVA BeginMethod ()
{
return current;
}
void WriteMetadataToken (MetadataToken token)
{
WriteUInt32 (token.ToUInt32 ());
}
void Align (int align)
{
align--;
WriteBytes (((position + align) & ~align) - position);
}
void EndMethod ()
{
current = (RVA) (code_base + position);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using RE;
namespace REBasic
{
[REItem("translate","Translate","Translate: perform a series of plain text replaces")]
public partial class RETranslate : REBaseItem
{
private List<RETranslateItem> TranslateItems=new List<RETranslateItem>();
private const int _column1Margin = 8;
private RE.RELinkPointPatch patch;
public RETranslate()
{
InitializeComponent();
lpInput.Signal += new RELinkPointSignal(lpInput_Signal);
patch = new RELinkPointPatch(lpInput, lpOutput);
_column1Left = panColumn1.Left - _column1Margin;
AddNewItem();
ReOrderItems();
}
private RETranslateItem AddNewItem()
{
RETranslateItem i = new RETranslateItem();
i.Enter += new EventHandler(i_Enter);
i.Visible = false;
i.Width = panItems.ClientSize.Width;
panItems.Controls.Add(i);
i.Column1Left = _column1Left;
i.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
TranslateItems.Add(i);
//ReOrderItems(); caller should call after loop
return i;
}
private int lastItemIndex=0;
void i_Enter(object sender, EventArgs e)
{
lastItemIndex = TranslateItems.IndexOf(sender as RETranslateItem);
}
private void ReOrderItems()
{
SuspendLayout();
int y = 0;
foreach (RETranslateItem i in TranslateItems)
{
i.Bounds = new Rectangle(0, y, panItems.ClientRectangle.Width, i.Height);
i.Visible = true;
y += i.Height;
}
ResumeLayout();
}
private void btnPlus_Click(object sender, EventArgs e)
{
AddNewItem();
ReOrderItems();
}
private void btnMinus_Click(object sender, EventArgs e)
{
if (TranslateItems.Count != 0)
{
if (lastItemIndex < 0 || lastItemIndex >= TranslateItems.Count)
lastItemIndex = 0;
RETranslateItem i = TranslateItems[lastItemIndex];
TranslateItems.RemoveAt(lastItemIndex);
panItems.Controls.Remove(i);
ReOrderItems();
}
}
private void btnUp_Click(object sender, EventArgs e)
{
if (TranslateItems.Count > 1)
{
if (lastItemIndex < 0 || lastItemIndex >= TranslateItems.Count)
lastItemIndex = 0;
if (lastItemIndex > 0)
{
RETranslateItem i = TranslateItems[lastItemIndex];
TranslateItems.RemoveAt(lastItemIndex);
lastItemIndex--;
TranslateItems.Insert(lastItemIndex, i);
ReOrderItems();
}
}
}
private void btnDown_Click(object sender, EventArgs e)
{
if (TranslateItems.Count > 1)
{
if (lastItemIndex < 0 || lastItemIndex >= TranslateItems.Count)
lastItemIndex = 0;
if (lastItemIndex < TranslateItems.Count - 1)
{
RETranslateItem i = TranslateItems[lastItemIndex];
TranslateItems.RemoveAt(lastItemIndex);
if (lastItemIndex == TranslateItems.Count - 1)
TranslateItems.Add(i);
else
TranslateItems.Insert(lastItemIndex + 1, i);
lastItemIndex++;
ReOrderItems();
}
}
}
public override void LoadFromXml(XmlElement Element)
{
panItems.Controls.Clear();
TranslateItems.Clear();
base.LoadFromXml(Element);
cbGlobal.Checked = StrToBool(Element.GetAttribute("global"));
cbIgnoreCase.Checked = StrToBool(Element.GetAttribute("ignorecase"));
try
{
Column1Left = Int32.Parse(Element.GetAttribute("column1"));
}
catch
{
//silent
}
foreach (XmlElement t in Element.SelectNodes("translations/translationitem"))
{
RETranslateItem i = AddNewItem();
i.SearchString = t.GetAttribute("search");
i.ReplaceString = t.InnerText;
}
ReOrderItems();
}
public override void SaveToXml(XmlElement Element)
{
base.SaveToXml(Element);
Element.SetAttribute("global", BoolToStr(cbGlobal.Checked));
Element.SetAttribute("ignorecase", BoolToStr(cbIgnoreCase.Checked));
Element.SetAttribute("column1", _column1Left.ToString());
XmlElement tx = Element.OwnerDocument.CreateElement("translations");
Element.AppendChild(tx);
foreach (RETranslateItem i in TranslateItems)
{
XmlElement t = Element.OwnerDocument.CreateElement("translationitem");
t.SetAttribute("search", i.SearchString);
t.InnerText = i.ReplaceString;
tx.AppendChild(t);
}
}
public override void Start()
{
base.Start();
}
void lpInput_Signal(RELinkPoint Sender, object Data)
{
//InvariantCulture?
StringComparison c = StringComparison.CurrentCulture;
if (cbIgnoreCase.Checked) c = StringComparison.CurrentCultureIgnoreCase;
string s = Data.ToString();
foreach (RETranslateItem i in TranslateItems)
if (i.SearchString != "")
{
//s = s.Replace(i.SearchString, i.ReplaceString);
int j = 0;
while (j != -1)
{
j = s.IndexOf(i.SearchString, j, c);
if (j != -1)
{
s = s.Substring(0, j) + i.ReplaceString + s.Substring(j + i.SearchString.Length);
j += i.ReplaceString.Length;
if (!cbGlobal.Checked || j > s.Length) j = -1;
}
}
}
lpOutput.Emit(s);
}
private int _column1Left;
private bool _column1LeftDragging=false;
private int _column1LeftDragStart;
private int _column1LeftDragStartX;
private void panColumn1_MouseDown(object sender, MouseEventArgs e)
{
_column1LeftDragging = true;
_column1LeftDragStart = _column1Left;
_column1LeftDragStartX = MousePosition.X;
}
private int Column1Left
{
get
{
return _column1Left;
}
set
{
_column1Left = value;
if (_column1Left < 32)
_column1Left = 32;
if (_column1Left > panItems.ClientSize.Width - 32)
_column1Left = panItems.ClientSize.Width - 32;
panColumn1.Left = _column1Left + _column1Margin;
lblReplace.Left = _column1Left + _column1Margin + 3;
foreach (RETranslateItem i in TranslateItems) i.Column1Left = _column1Left;
}
}
private void panColumn1_MouseMove(object sender, MouseEventArgs e)
{
if (_column1LeftDragging)
Column1Left = _column1LeftDragStart + MousePosition.X - _column1LeftDragStartX;
}
private void panColumn1_MouseUp(object sender, MouseEventArgs e)
{
_column1LeftDragging = false;
}
protected override void DisconnectAll()
{
//replacing base.DisconnectAll();
patch.Disconnect();
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript{
using Microsoft.JScript.Vsa;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using Microsoft.Vsa;
class VsaReference : VsaItem, IVsaReferenceItem{
private String assemblyName;
private Assembly assembly;
bool loadFailed;
internal VsaReference(VsaEngine engine, string itemName)
: base(engine, itemName, VsaItemType.Reference, VsaItemFlag.None){
this.assemblyName = itemName; // default to item name
this.assembly = null;
this.loadFailed = false;
}
public String AssemblyName{
get{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
return this.assemblyName;
}
set{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
this.assemblyName = value;
this.isDirty = true;
this.engine.IsDirty = true;
}
}
internal Assembly Assembly{
get{
if (this.engine == null)
throw new VsaException(VsaError.EngineClosed);
return this.assembly;
}
}
internal Type GetType(String typeName){
if (this.assembly == null){
if (!loadFailed) {
try {
this.Load();
}catch{
loadFailed = true;
}
}
if (this.assembly == null)
return null;
}
Type result = this.assembly.GetType(typeName, false);
if (result != null && (!result.IsPublic || CustomAttribute.IsDefined(result, typeof(System.Runtime.CompilerServices.RequiredAttributeAttribute), true)))
result = null; //Suppress the type if it is not public or if it is a funky C++ type.
return result;
}
internal override void Compile(){
Compile(true);
}
internal bool Compile(bool throwOnFileNotFound){
try{
String assemblyFileName = Path.GetFileName(this.assemblyName);
String alternateName = assemblyFileName + ".dll";
if (String.Compare(assemblyFileName, "mscorlib.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(alternateName, "mscorlib.dll", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(Object).Assembly;
if (String.Compare(assemblyFileName, "microsoft.jscript.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(alternateName, "microsoft.jscript.dll", StringComparison.OrdinalIgnoreCase) == 0) {
this.assembly = engine.JScriptModule.Assembly;
} else if (String.Compare(assemblyFileName, "microsoft.vsa.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(alternateName, "microsoft.vsa.dll", StringComparison.OrdinalIgnoreCase) == 0) {
this.assembly = engine.VsaModule.Assembly;
} else if (this.engine.ReferenceLoaderAPI != LoaderAPI.ReflectionOnlyLoadFrom) {
if (String.Compare(assemblyFileName, "system.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(alternateName, "system.dll", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(System.Text.RegularExpressions.Regex).Module.Assembly;
}
if (this.assembly == null) {
String path = this.engine.FindAssembly(this.assemblyName);
// if not found, look for the file with ".dll" appended to the assembly name
if (path == null){
// check for duplicates before we add the ".dll" part
alternateName = this.assemblyName + ".dll";
bool fDuplicate = false;
foreach (Object item in this.engine.Items){
if (item is VsaReference && String.Compare(((VsaReference)item).AssemblyName, alternateName, StringComparison.OrdinalIgnoreCase) == 0){
fDuplicate = true;
break;
}
}
if (!fDuplicate){
path = this.engine.FindAssembly(alternateName);
if (path != null)
this.assemblyName = alternateName;
}
}
if (path == null){
if (throwOnFileNotFound)
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, new System.IO.FileNotFoundException());
else
return false;
}
switch (this.engine.ReferenceLoaderAPI) {
case LoaderAPI.LoadFrom: this.assembly = Assembly.LoadFrom(path); break;
case LoaderAPI.LoadFile: this.assembly = Assembly.LoadFile(path); break;
case LoaderAPI.ReflectionOnlyLoadFrom: this.assembly = Assembly.ReflectionOnlyLoadFrom(path); break;
}
// Warn if building a machine specfic assembly and the referenced assembly is machine
// specific but does not match.
CheckCompatibility();
}
}catch(VsaException){
throw;
}catch(System.BadImageFormatException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(System.IO.FileNotFoundException e){
if (throwOnFileNotFound)
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
else
return false;
}catch(System.IO.FileLoadException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(System.ArgumentException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(Exception e){
throw new VsaException(VsaError.InternalCompilerError, e.ToString(), e);
}catch{
throw new VsaException(VsaError.InternalCompilerError);
}
if (this.assembly == null){
if (throwOnFileNotFound)
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName);
else
return false;
}
return true;
}
// This method is called at runtime. When this is called this.assemblyName is the
// actual assembly name ( eg., mscorlib ) rather than the file name ( eg., mscorlib.dll)
private void Load(){
try{
if (String.Compare(this.assemblyName, "mscorlib", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(Object).Module.Assembly;
else if (String.Compare(this.assemblyName, "Microsoft.JScript", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(VsaEngine).Module.Assembly;
else if (String.Compare(this.assemblyName, "Microsoft.Vsa", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(IVsaEngine).Module.Assembly;
else if (String.Compare(this.assemblyName, "System", StringComparison.OrdinalIgnoreCase) == 0)
this.assembly = typeof(System.Text.RegularExpressions.Regex).Module.Assembly;
else{
this.assembly = Assembly.LoadWithPartialName(this.assemblyName);
}
}catch(System.BadImageFormatException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(System.IO.FileNotFoundException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(System.ArgumentException e){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName, e);
}catch(Exception e){
throw new VsaException(VsaError.InternalCompilerError, e.ToString(), e);
}catch{
throw new VsaException(VsaError.InternalCompilerError);
}
if (this.assembly == null){
throw new VsaException(VsaError.AssemblyExpected, this.assemblyName);
}
}
private void CheckCompatibility() {
// If reference is agnostic, then compatible
PortableExecutableKinds RefPEKindFlags;
ImageFileMachine RefPEMachineArchitecture;
this.assembly.ManifestModule.GetPEKind(out RefPEKindFlags, out RefPEMachineArchitecture);
if (RefPEMachineArchitecture == ImageFileMachine.I386 &&
PortableExecutableKinds.ILOnly == (RefPEKindFlags & (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit))) {
return;
}
// Warn if building an agnostic assembly, but referenced assembly is not.
PortableExecutableKinds PEKindFlags = engine.PEKindFlags;
ImageFileMachine PEMachineArchitecture = engine.PEMachineArchitecture;
if (PEMachineArchitecture == ImageFileMachine.I386 &&
PortableExecutableKinds.ILOnly == (PEKindFlags & (PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit))) {
// We are agnostic, but the reference is not. Do not emit a warning - this is a very common
// case. Many of the system libraries are platform specific.
return;
}
// Warning if architectures don't match.
if (RefPEMachineArchitecture != PEMachineArchitecture) {
JScriptException e = new JScriptException(JSError.IncompatibleAssemblyReference);
e.value = this.assemblyName;
this.engine.OnCompilerError(e);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.Null
{
public class NullUserAccountData : IUserAccountData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, UserAccountData> m_DataByUUID = new Dictionary<UUID, UserAccountData>();
private Dictionary<string, UserAccountData> m_DataByName = new Dictionary<string, UserAccountData>();
private Dictionary<string, UserAccountData> m_DataByEmail = new Dictionary<string, UserAccountData>();
public NullUserAccountData(string connectionString, string realm)
{
// m_log.DebugFormat(
// "[NULL USER ACCOUNT DATA]: Initializing new NullUserAccountData with connectionString [{0}], realm [{1}]",
// connectionString, realm);
}
/// <summary>
/// Tries to implement the Get [] semantics, but it cuts corners like crazy.
/// Specifically, it relies on the knowledge that the only Gets used are
/// keyed on PrincipalID, Email, and FirstName+LastName.
/// </summary>
/// <param name="fields"></param>
/// <param name="values"></param>
/// <returns></returns>
public UserAccountData[] Get(string[] fields, string[] values)
{
// if (m_log.IsDebugEnabled)
// {
// m_log.DebugFormat(
// "[NULL USER ACCOUNT DATA]: Called Get with fields [{0}], values [{1}]",
// string.Join(", ", fields), string.Join(", ", values));
// }
UserAccountData[] userAccounts = new UserAccountData[0];
List<string> fieldsLst = new List<string>(fields);
if (fieldsLst.Contains("PrincipalID"))
{
int i = fieldsLst.IndexOf("PrincipalID");
UUID id = UUID.Zero;
if (UUID.TryParse(values[i], out id))
if (m_DataByUUID.ContainsKey(id))
userAccounts = new UserAccountData[] { m_DataByUUID[id] };
}
else if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName"))
{
int findex = fieldsLst.IndexOf("FirstName");
int lindex = fieldsLst.IndexOf("LastName");
if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex]))
{
userAccounts = new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] };
}
}
else if (fieldsLst.Contains("Email"))
{
int i = fieldsLst.IndexOf("Email");
if (m_DataByEmail.ContainsKey(values[i]))
userAccounts = new UserAccountData[] { m_DataByEmail[values[i]] };
}
// if (m_log.IsDebugEnabled)
// {
// StringBuilder sb = new StringBuilder();
// foreach (UserAccountData uad in userAccounts)
// sb.AppendFormat("({0} {1} {2}) ", uad.FirstName, uad.LastName, uad.PrincipalID);
//
// m_log.DebugFormat(
// "[NULL USER ACCOUNT DATA]: Returning {0} user accounts out of {1}: [{2}]", userAccounts.Length, m_DataByName.Count, sb);
// }
return userAccounts;
}
public bool Store(UserAccountData data)
{
if (data == null)
return false;
m_log.DebugFormat(
"[NULL USER ACCOUNT DATA]: Storing user account {0} {1} {2} {3}",
data.FirstName, data.LastName, data.PrincipalID, this.GetHashCode());
m_DataByUUID[data.PrincipalID] = data;
m_DataByName[data.FirstName + " " + data.LastName] = data;
if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty)
m_DataByEmail[data.Data["Email"]] = data;
// m_log.DebugFormat("m_DataByUUID count is {0}, m_DataByName count is {1}", m_DataByUUID.Count, m_DataByName.Count);
return true;
}
public UserAccountData[] GetUsers(UUID scopeID, string query)
{
// m_log.DebugFormat(
// "[NULL USER ACCOUNT DATA]: Called GetUsers with scope [{0}], query [{1}]", scopeID, query);
string[] words = query.Split(new char[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < 3)
{
if (i != words.Length - 1)
Array.Copy(words, i + 1, words, i, words.Length - i - 1);
Array.Resize(ref words, words.Length - 1);
}
}
if (words.Length == 0)
return new UserAccountData[0];
if (words.Length > 2)
return new UserAccountData[0];
List<string> lst = new List<string>(m_DataByName.Keys);
if (words.Length == 1)
{
lst = lst.FindAll(delegate(string s) { return s.StartsWith(words[0]); });
}
else
{
lst = lst.FindAll(delegate(string s) { return s.Contains(words[0]) || s.Contains(words[1]); });
}
if (lst == null || (lst != null && lst.Count == 0))
return new UserAccountData[0];
UserAccountData[] result = new UserAccountData[lst.Count];
int n = 0;
foreach (string key in lst)
result[n++] = m_DataByName[key];
return result;
}
public bool Delete(string field, string val)
{
// Only delete by PrincipalID
if (field.Equals("PrincipalID"))
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(val, out uuid) && m_DataByUUID.ContainsKey(uuid))
{
UserAccountData account = m_DataByUUID[uuid];
m_DataByUUID.Remove(uuid);
if (m_DataByName.ContainsKey(account.FirstName + " " + account.LastName))
m_DataByName.Remove(account.FirstName + " " + account.LastName);
if (account.Data.ContainsKey("Email") && account.Data["Email"] != string.Empty && m_DataByEmail.ContainsKey(account.Data["Email"]))
m_DataByEmail.Remove(account.Data["Email"]);
return true;
}
}
return false;
}
public UserAccountData[] GetUsersWhere(UUID scopeID, string where)
{
return null;
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Text.Json
{
public sealed partial class JsonDocument
{
// The database for the parsed structure of a JSON document.
//
// Every token from the document gets a row, which has one of the following forms:
//
// Number
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is set if the number uses scientific notation
// * 31 bits for the token length
// * Third int
// * 4 bits JsonTokenType
// * 28 bits unassigned / always clear
//
// String, PropertyName
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is set if the string requires unescaping
// * 31 bits for the token length
// * Third int
// * 4 bits JsonTokenType
// * 28 bits unassigned / always clear
//
// Other value types (True, False, Null)
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is unassigned / always clear
// * 31 bits for the token length
// * Third int
// * 4 bits JsonTokenType
// * 28 bits unassigned / always clear
//
// EndObject / EndArray
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is unassigned / always clear
// * 31 bits for the token length (always 1, effectively unassigned)
// * Third int
// * 4 bits JsonTokenType
// * 28 bits for the number of rows until the previous value (never 0)
//
// StartObject
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is unassigned / always clear
// * 31 bits for the token length (always 1, effectively unassigned)
// * Third int
// * 4 bits JsonTokenType
// * 28 bits for the number of rows until the next value (never 0)
//
// StartArray
// * First int
// * Top bit is unassigned / always clear
// * 31 bits for token offset
// * Second int
// * Top bit is set if the array contains other arrays or objects ("complex" types)
// * 31 bits for the number of elements in this array
// * Third int
// * 4 bits JsonTokenType
// * 28 bits for the number of rows until the next value (never 0)
private struct MetadataDb : IDisposable
{
private const int SizeOrLengthOffset = 4;
private const int NumberOfRowsOffset = 8;
internal int Length { get; private set; }
private byte[] _data;
#if DEBUG
private bool _isLocked;
#endif
internal MetadataDb(byte[] completeDb)
{
_data = completeDb;
Length = completeDb.Length;
#if DEBUG
_isLocked = true;
#endif
}
internal MetadataDb(int payloadLength)
{
// Assume that a token happens approximately every 12 bytes.
// int estimatedTokens = payloadLength / 12
// now acknowledge that the number of bytes we need per token is 12.
// So that's just the payload length.
//
// Add one token's worth of data just because.
int initialSize = DbRow.Size + payloadLength;
// Stick with ArrayPool's rent/return range if it looks feasible.
// If it's wrong, we'll just grow and copy as we would if the tokens
// were more frequent anyways.
const int OneMegabyte = 1024 * 1024;
if (initialSize > OneMegabyte && initialSize <= 4 * OneMegabyte)
{
initialSize = OneMegabyte;
}
_data = ArrayPool<byte>.Shared.Rent(initialSize);
Length = 0;
#if DEBUG
_isLocked = false;
#endif
}
internal MetadataDb(MetadataDb source, bool useArrayPools)
{
Length = source.Length;
#if DEBUG
_isLocked = !useArrayPools;
#endif
if (useArrayPools)
{
_data = ArrayPool<byte>.Shared.Rent(Length);
source._data.AsSpan(0, Length).CopyTo(_data);
}
else
{
_data = source._data.AsSpan(0, Length).ToArray();
}
}
public void Dispose()
{
byte[] data = Interlocked.Exchange(ref _data, null);
if (data == null)
{
return;
}
#if DEBUG
Debug.Assert(!_isLocked, "Dispose called on a locked database");
#endif
// The data in this rented buffer only conveys the positions and
// lengths of tokens in a document, but no content; so it does not
// need to be cleared.
ArrayPool<byte>.Shared.Return(data);
Length = 0;
}
internal void TrimExcess()
{
// There's a chance that the size we have is the size we'd get for this
// amount of usage (particularly if Enlarge ever got called); and there's
// the small copy-cost associated with trimming anyways. "Is half-empty" is
// just a rough metric for "is trimming worth it?".
if (Length <= _data.Length / 2)
{
byte[] newRent = ArrayPool<byte>.Shared.Rent(Length);
byte[] returnBuf = newRent;
if (newRent.Length < _data.Length)
{
Buffer.BlockCopy(_data, 0, newRent, 0, Length);
returnBuf = _data;
_data = newRent;
}
// The data in this rented buffer only conveys the positions and
// lengths of tokens in a document, but no content; so it does not
// need to be cleared.
ArrayPool<byte>.Shared.Return(returnBuf);
}
}
internal void Append(JsonTokenType tokenType, int startLocation, int length)
{
// StartArray or StartObject should have length -1, otherwise the length should not be -1.
Debug.Assert(
(tokenType == JsonTokenType.StartArray || tokenType == JsonTokenType.StartObject) ==
(length == DbRow.UnknownSize));
#if DEBUG
Debug.Assert(!_isLocked, "Appending to a locked database");
#endif
if (Length >= _data.Length - DbRow.Size)
{
Enlarge();
}
DbRow row = new DbRow(tokenType, startLocation, length);
MemoryMarshal.Write(_data.AsSpan(Length), ref row);
Length += DbRow.Size;
}
private void Enlarge()
{
byte[] toReturn = _data;
_data = ArrayPool<byte>.Shared.Rent(toReturn.Length * 2);
Buffer.BlockCopy(toReturn, 0, _data, 0, toReturn.Length);
// The data in this rented buffer only conveys the positions and
// lengths of tokens in a document, but no content; so it does not
// need to be cleared.
ArrayPool<byte>.Shared.Return(toReturn);
}
[Conditional("DEBUG")]
private void AssertValidIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index <= Length - DbRow.Size, $"index {index} is out of bounds");
Debug.Assert(index % DbRow.Size == 0, $"index {index} is not at a record start position");
}
internal void SetLength(int index, int length)
{
AssertValidIndex(index);
Debug.Assert(length >= 0);
Span<byte> destination = _data.AsSpan(index + SizeOrLengthOffset);
MemoryMarshal.Write(destination, ref length);
}
internal void SetNumberOfRows(int index, int numberOfRows)
{
AssertValidIndex(index);
Debug.Assert(numberOfRows >= 1 && numberOfRows <= 0x0FFFFFFF);
Span<byte> dataPos = _data.AsSpan(index + NumberOfRowsOffset);
int current = MemoryMarshal.Read<int>(dataPos);
// Persist the most significant nybble
int value = (current & unchecked((int)0xF0000000)) | numberOfRows;
MemoryMarshal.Write(dataPos, ref value);
}
internal void SetHasComplexChildren(int index)
{
AssertValidIndex(index);
// The HasComplexChildren bit is the most significant bit of "SizeOrLength"
Span<byte> dataPos = _data.AsSpan(index + SizeOrLengthOffset);
int current = MemoryMarshal.Read<int>(dataPos);
int value = current | unchecked((int)0x80000000);
MemoryMarshal.Write(dataPos, ref value);
}
internal int FindIndexOfFirstUnsetSizeOrLength(JsonTokenType lookupType)
{
Debug.Assert(lookupType == JsonTokenType.StartObject || lookupType == JsonTokenType.StartArray);
return FindOpenElement(lookupType);
}
private int FindOpenElement(JsonTokenType lookupType)
{
Span<byte> data = _data.AsSpan(0, Length);
for (int i = Length - DbRow.Size; i >= 0; i -= DbRow.Size)
{
DbRow row = MemoryMarshal.Read<DbRow>(data.Slice(i));
if (row.IsUnknownSize && row.TokenType == lookupType)
{
return i;
}
}
// We should never reach here.
Debug.Fail($"Unable to find expected {lookupType} token");
return -1;
}
internal DbRow Get(int index)
{
AssertValidIndex(index);
return MemoryMarshal.Read<DbRow>(_data.AsSpan(index));
}
internal JsonTokenType GetJsonTokenType(int index)
{
AssertValidIndex(index);
uint union = MemoryMarshal.Read<uint>(_data.AsSpan(index + NumberOfRowsOffset));
return (JsonTokenType)(union >> 28);
}
internal MetadataDb CopySegment(int startIndex, int endIndex)
{
Debug.Assert(
endIndex > startIndex,
$"endIndex={endIndex} was at or before startIndex={startIndex}");
AssertValidIndex(startIndex);
Debug.Assert(endIndex <= Length);
DbRow start = Get(startIndex);
#if DEBUG
DbRow end = Get(endIndex - DbRow.Size);
if (start.TokenType == JsonTokenType.StartObject)
{
Debug.Assert(
end.TokenType == JsonTokenType.EndObject,
$"StartObject paired with {end.TokenType}");
}
else if (start.TokenType == JsonTokenType.StartArray)
{
Debug.Assert(
end.TokenType == JsonTokenType.EndArray,
$"StartArray paired with {end.TokenType}");
}
else
{
Debug.Assert(
startIndex + DbRow.Size == endIndex,
$"{start.TokenType} should have been one row");
}
#endif
int length = endIndex - startIndex;
byte[] newDatabase = new byte[length];
_data.AsSpan(startIndex, length).CopyTo(newDatabase);
Span<int> newDbInts = MemoryMarshal.Cast<byte, int>(newDatabase);
int locationOffset = newDbInts[0];
// Need to nudge one forward to account for the hidden quote on the string.
if (start.TokenType == JsonTokenType.String)
{
locationOffset--;
}
for (int i = (length - DbRow.Size) / sizeof(int); i >= 0; i -= DbRow.Size / sizeof(int))
{
Debug.Assert(newDbInts[i] >= locationOffset);
newDbInts[i] -= locationOffset;
}
return new MetadataDb(newDatabase);
}
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
[Target("vs2003")]
public class VS2003Target : ITarget
{
#region Fields
string solutionVersion = "8.00";
string productVersion = "7.10.3077";
string schemaVersion = "2.0";
string versionName = "2003";
VSVersion version = VSVersion.VS71;
readonly Dictionary<string, ToolInfo> m_Tools = new Dictionary<string, ToolInfo>();
Kernel m_Kernel;
/// <summary>
/// Gets or sets the solution version.
/// </summary>
/// <value>The solution version.</value>
protected string SolutionVersion
{
get
{
return solutionVersion;
}
set
{
solutionVersion = value;
}
}
/// <summary>
/// Gets or sets the product version.
/// </summary>
/// <value>The product version.</value>
protected string ProductVersion
{
get
{
return productVersion;
}
set
{
productVersion = value;
}
}
/// <summary>
/// Gets or sets the schema version.
/// </summary>
/// <value>The schema version.</value>
protected string SchemaVersion
{
get
{
return schemaVersion;
}
set
{
schemaVersion = value;
}
}
/// <summary>
/// Gets or sets the name of the version.
/// </summary>
/// <value>The name of the version.</value>
protected string VersionName
{
get
{
return versionName;
}
set
{
versionName = value;
}
}
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
protected VSVersion Version
{
get
{
return version;
}
set
{
version = value;
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="VS2003Target"/> class.
/// </summary>
public VS2003Target()
{
m_Tools["C#"] = new ToolInfo("C#", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "csproj", "CSHARP");
m_Tools["VB.NET"] = new ToolInfo("VB.NET", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", "vbproj", "VisualBasic");
}
#endregion
#region Private Methods
private string MakeRefPath(ProjectNode project)
{
string ret = "";
foreach(ReferencePathNode node in project.ReferencePaths)
{
try
{
string fullPath = Helper.ResolvePath(node.Path);
if(ret.Length < 1)
{
ret = fullPath;
}
else
{
ret += ";" + fullPath;
}
}
catch(ArgumentException)
{
m_Kernel.Log.Write(LogType.Warning, "Could not resolve reference path: {0}", node.Path);
}
}
return ret;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
if(!m_Tools.ContainsKey(project.Language))
{
throw new UnknownLanguageException("Unknown .NET language: " + project.Language);
}
ToolInfo toolInfo = m_Tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
StreamWriter ps = new StreamWriter(projectFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projectFile));
using(ps)
{
ps.WriteLine("<VisualStudioProject>");
ps.WriteLine(" <{0}", toolInfo.XmlTag);
ps.WriteLine("\t\t\t\tProjectType = \"Local\"");
ps.WriteLine("\t\t\t\tProductVersion = \"{0}\"", ProductVersion);
ps.WriteLine("\t\t\t\tSchemaVersion = \"{0}\"", SchemaVersion);
ps.WriteLine("\t\t\t\tProjectGuid = \"{{{0}}}\"", project.Guid.ToString().ToUpper());
ps.WriteLine("\t\t>");
ps.WriteLine("\t\t\t\t<Build>");
ps.WriteLine(" <Settings");
ps.WriteLine("\t\t\t\t ApplicationIcon = \"{0}\"",project.AppIcon);
ps.WriteLine("\t\t\t\t AssemblyKeyContainerName = \"\"");
ps.WriteLine("\t\t\t\t AssemblyName = \"{0}\"", project.AssemblyName);
ps.WriteLine("\t\t\t\t AssemblyOriginatorKeyFile = \"\"");
ps.WriteLine("\t\t\t\t DefaultClientScript = \"JScript\"");
ps.WriteLine("\t\t\t\t DefaultHTMLPageLayout = \"Grid\"");
ps.WriteLine("\t\t\t\t DefaultTargetSchema = \"IE50\"");
ps.WriteLine("\t\t\t\t DelaySign = \"false\"");
if(Version == VSVersion.VS70)
{
ps.WriteLine("\t\t\t\t NoStandardLibraries = \"false\"");
}
ps.WriteLine("\t\t\t\t OutputType = \"{0}\"", project.Type);
foreach(ConfigurationNode conf in project.Configurations)
{
if (conf.Options["PreBuildEvent"] != null && conf.Options["PreBuildEvent"].ToString().Length != 0)
{
ps.WriteLine("\t\t\t\t PreBuildEvent = \"{0}\"", Helper.NormalizePath(conf.Options["PreBuildEvent"].ToString()));
}
else
{
ps.WriteLine("\t\t\t\t PreBuildEvent = \"{0}\"", conf.Options["PreBuildEvent"]);
}
if (conf.Options["PostBuildEvent"] != null && conf.Options["PostBuildEvent"].ToString().Length != 0)
{
ps.WriteLine("\t\t\t\t PostBuildEvent = \"{0}\"", Helper.NormalizePath(conf.Options["PostBuildEvent"].ToString()));
}
else
{
ps.WriteLine("\t\t\t\t PostBuildEvent = \"{0}\"", conf.Options["PostBuildEvent"]);
}
if (conf.Options["RunPostBuildEvent"] == null)
{
ps.WriteLine("\t\t\t\t RunPostBuildEvent = \"{0}\"", "OnBuildSuccess");
}
else
{
ps.WriteLine("\t\t\t\t RunPostBuildEvent = \"{0}\"", conf.Options["RunPostBuildEvent"]);
}
break;
}
ps.WriteLine("\t\t\t\t RootNamespace = \"{0}\"", project.RootNamespace);
ps.WriteLine("\t\t\t\t StartupObject = \"{0}\"", project.StartupObject);
ps.WriteLine("\t\t >");
foreach(ConfigurationNode conf in project.Configurations)
{
ps.WriteLine("\t\t\t\t <Config");
ps.WriteLine("\t\t\t\t Name = \"{0}\"", conf.Name);
ps.WriteLine("\t\t\t\t AllowUnsafeBlocks = \"{0}\"", conf.Options["AllowUnsafe"].ToString().ToLower());
ps.WriteLine("\t\t\t\t BaseAddress = \"{0}\"", conf.Options["BaseAddress"]);
ps.WriteLine("\t\t\t\t CheckForOverflowUnderflow = \"{0}\"", conf.Options["CheckUnderflowOverflow"].ToString().ToLower());
ps.WriteLine("\t\t\t\t ConfigurationOverrideFile = \"\"");
ps.WriteLine("\t\t\t\t DefineConstants = \"{0}\"", conf.Options["CompilerDefines"]);
ps.WriteLine("\t\t\t\t DocumentationFile = \"{0}\"", GetXmlDocFile(project, conf));//default to the assembly name
ps.WriteLine("\t\t\t\t DebugSymbols = \"{0}\"", conf.Options["DebugInformation"].ToString().ToLower());
ps.WriteLine("\t\t\t\t FileAlignment = \"{0}\"", conf.Options["FileAlignment"]);
ps.WriteLine("\t\t\t\t IncrementalBuild = \"{0}\"", conf.Options["IncrementalBuild"].ToString().ToLower());
if(Version == VSVersion.VS71)
{
ps.WriteLine("\t\t\t\t NoStdLib = \"{0}\"", conf.Options["NoStdLib"].ToString().ToLower());
ps.WriteLine("\t\t\t\t NoWarn = \"{0}\"", conf.Options["SuppressWarnings"].ToString().ToLower());
}
ps.WriteLine("\t\t\t\t Optimize = \"{0}\"", conf.Options["OptimizeCode"].ToString().ToLower());
ps.WriteLine(" OutputPath = \"{0}\"",
Helper.EndPath(Helper.NormalizePath(conf.Options["OutputPath"].ToString())));
ps.WriteLine(" RegisterForComInterop = \"{0}\"", conf.Options["RegisterComInterop"].ToString().ToLower());
ps.WriteLine(" RemoveIntegerChecks = \"{0}\"", conf.Options["RemoveIntegerChecks"].ToString().ToLower());
ps.WriteLine(" TreatWarningsAsErrors = \"{0}\"", conf.Options["WarningsAsErrors"].ToString().ToLower());
ps.WriteLine(" WarningLevel = \"{0}\"", conf.Options["WarningLevel"]);
ps.WriteLine(" />");
}
ps.WriteLine(" </Settings>");
ps.WriteLine(" <References>");
foreach(ReferenceNode refr in project.References)
{
ps.WriteLine(" <Reference");
ps.WriteLine(" Name = \"{0}\"", refr.Name);
ps.WriteLine(" AssemblyName = \"{0}\"", refr.Name);
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode refProject = solution.ProjectsTable[refr.Name];
ps.WriteLine(" Project = \"{{{0}}}\"", refProject.Guid.ToString().ToUpper());
ps.WriteLine(" Package = \"{0}\"", toolInfo.Guid.ToUpper());
}
else
{
if(refr.Path != null)
{
ps.WriteLine(" HintPath = \"{0}\"", Helper.MakeFilePath(refr.Path, refr.Name, "dll"));
}
}
if(refr.LocalCopySpecified)
{
ps.WriteLine(" Private = \"{0}\"",refr.LocalCopy);
}
ps.WriteLine(" />");
}
ps.WriteLine(" </References>");
ps.WriteLine(" </Build>");
ps.WriteLine(" <Files>");
ps.WriteLine(" <Include>");
foreach(string file in project.Files)
{
string fileName = file.Replace(".\\", "");
ps.WriteLine(" <File");
ps.WriteLine(" RelPath = \"{0}\"", fileName);
ps.WriteLine(" SubType = \"{0}\"", project.Files.GetSubType(file));
ps.WriteLine(" BuildAction = \"{0}\"", project.Files.GetBuildAction(file));
ps.WriteLine(" />");
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ps.WriteLine(" <File");
ps.WriteLine(" RelPath = \"{0}\"", fileName.Substring(0, fileName.LastIndexOf('.')) + ".resx");
int slash = fileName.LastIndexOf('\\');
if (slash == -1)
{
ps.WriteLine(" DependentUpon = \"{0}\"", fileName);
}
else
{
ps.WriteLine(" DependentUpon = \"{0}\"", fileName.Substring(slash + 1, fileName.Length - slash - 1));
}
ps.WriteLine(" BuildAction = \"{0}\"", "EmbeddedResource");
ps.WriteLine(" />");
}
}
ps.WriteLine(" </Include>");
ps.WriteLine(" </Files>");
ps.WriteLine(" </{0}>", toolInfo.XmlTag);
ps.WriteLine("</VisualStudioProject>");
}
ps = new StreamWriter(projectFile + ".user");
using(ps)
{
ps.WriteLine("<VisualStudioProject>");
ps.WriteLine(" <{0}>", toolInfo.XmlTag);
ps.WriteLine(" <Build>");
ps.WriteLine(" <Settings ReferencePath=\"{0}\">", MakeRefPath(project));
foreach(ConfigurationNode conf in project.Configurations)
{
ps.WriteLine(" <Config");
ps.WriteLine(" Name = \"{0}\"", conf.Name);
ps.WriteLine(" />");
}
ps.WriteLine(" </Settings>");
ps.WriteLine(" </Build>");
ps.WriteLine(" </{0}>", toolInfo.XmlTag);
ps.WriteLine("</VisualStudioProject>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if( conf == null )
{
throw new ArgumentNullException("conf");
}
if( project == null )
{
throw new ArgumentNullException("project");
}
// if(!(bool)conf.Options["GenerateXmlDocFile"]) //default to none, if the generate option is false
// {
// return string.Empty;
// }
//default to "AssemblyName.xml"
//string defaultValue = Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
//return (string)conf.Options["XmlDocFile", defaultValue];
//default to no XmlDocFile file
return (string)conf.Options["XmlDocFile", ""];
}
private void WriteSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Creating Visual Studio {0} solution and project files", VersionName);
foreach(ProjectNode project in solution.Projects)
{
if(m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string solutionFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
StreamWriter ss = new StreamWriter(solutionFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(solutionFile));
using(ss)
{
ss.WriteLine("Microsoft Visual Studio Solution File, Format Version {0}", SolutionVersion);
foreach(ProjectNode project in solution.Projects)
{
if(!m_Tools.ContainsKey(project.Language))
{
throw new UnknownLanguageException("Unknown .NET language: " + project.Language);
}
ToolInfo toolInfo = m_Tools[project.Language];
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine("Project(\"{0}\") = \"{1}\", \"{2}\", \"{{{3}}}\"",
toolInfo.Guid, project.Name, Helper.MakeFilePath(path, project.Name,
toolInfo.FileExtension), project.Guid.ToString().ToUpper());
ss.WriteLine("\tProjectSection(ProjectDependencies) = postProject");
ss.WriteLine("\tEndProjectSection");
ss.WriteLine("EndProject");
}
ss.WriteLine("Global");
ss.WriteLine("\tGlobalSection(SolutionConfiguration) = preSolution");
foreach(ConfigurationNode conf in solution.Configurations)
{
ss.WriteLine("\t\t{0} = {0}", conf.Name);
}
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ProjectDependencies) = postSolution");
foreach(ProjectNode project in solution.Projects)
{
for(int i = 0; i < project.References.Count; i++)
{
ReferenceNode refr = project.References[i];
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode refProject = solution.ProjectsTable[refr.Name];
ss.WriteLine("\t\t({{{0}}}).{1} = ({{{2}}})",
project.Guid.ToString().ToUpper()
, i,
refProject.Guid.ToString().ToUpper()
);
}
}
}
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ProjectConfiguration) = postSolution");
foreach(ProjectNode project in solution.Projects)
{
foreach(ConfigurationNode conf in solution.Configurations)
{
ss.WriteLine("\t\t{{{0}}}.{1}.ActiveCfg = {1}|.NET",
project.Guid.ToString().ToUpper(),
conf.Name);
ss.WriteLine("\t\t{{{0}}}.{1}.Build.0 = {1}|.NET",
project.Guid.ToString().ToUpper(),
conf.Name);
}
}
ss.WriteLine("\tEndGlobalSection");
if(solution.Files != null)
{
ss.WriteLine("\tGlobalSection(SolutionItems) = postSolution");
foreach(string file in solution.Files)
{
ss.WriteLine("\t\t{0} = {0}", file);
}
ss.WriteLine("\tEndGlobalSection");
}
ss.WriteLine("\tGlobalSection(ExtensibilityGlobals) = postSolution");
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ExtensibilityAddIns) = postSolution");
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("EndGlobal");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
ToolInfo toolInfo = m_Tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
string userFile = projectFile + ".user";
Helper.DeleteIfExists(projectFile);
Helper.DeleteIfExists(userFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning Visual Studio {0} solution and project files", VersionName, solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
string suoFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "suo");
Helper.DeleteIfExists(slnFile);
Helper.DeleteIfExists(suoFile);
foreach(ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Write(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode sol in m_Kernel.Solutions)
{
WriteSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode sol in m_Kernel.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public virtual string Name
{
get
{
return "vs2003";
}
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using OpenLiveWriter.Controls;
namespace OpenLiveWriter.ApplicationFramework
{
#region Public Enumeration Declarations
/// <summary>
/// The vertical splitter style.
/// </summary>
internal enum VerticalSplitterStyle
{
None, // No vertical splitter.
Left, // Vertical splitter on the left edge of the column.
Right // Vertical splitter on the right edge of the column.
}
#endregion Public Enumeration Declarations
/// <summary>
/// Provides the workspace column control.
/// </summary>
public class WorkspaceColumnLightweightControl : LightweightControl
{
#region Private Member Variables & Declarations
/// <summary>
/// The minimum horizontal splitter position.
/// </summary>
private static readonly double MINIMUM_HORIZONTAL_SPLITTER_POSITION = 0.20;
/// <summary>
/// The default maximum horizontal splitter position.
/// </summary>
private static readonly double MAXIMUM_HORIZONTAL_SPLITTER_POSITION = 0.80;
/// <summary>
/// Required designer cruft.
/// </summary>
private IContainer components = null;
/// <summary>
/// The vertical splitter lightweight control.
/// </summary>
private SplitterLightweightControl splitterLightweightControlVertical;
/// <summary>
/// The horizontal splitter lightweight control.
/// </summary>
private SplitterLightweightControl splitterLightweightControlHorizontal;
/// <summary>
/// The upper pane WorkspaceColumnPaneLightweightControl.
/// </summary>
private WorkspaceColumnPaneLightweightControl workspaceColumnPaneUpper;
/// <summary>
/// The lower pane WorkspaceColumnPaneLightweightControl.
/// </summary>
private WorkspaceColumnPaneLightweightControl workspaceColumnPaneLower;
/// <summary>
/// The vertical splitter style.
/// </summary>
private VerticalSplitterStyle verticalSplitterStyle = VerticalSplitterStyle.None;
/// <summary>
/// The vertical splitter width.
/// </summary>
private int verticalSplitterWidth = 5;
/// <summary>
/// The horizontal splitter height.
/// </summary>
private int horizontalSplitterHeight = 5;
/// <summary>
/// The maximum horizontal splitter position.
/// </summary>
private double maximumHorizontalSplitterPosition = MAXIMUM_HORIZONTAL_SPLITTER_POSITION;
/// <summary>
/// The starting preferred column width.
/// </summary>
private double startingPreferredColumnWidth;
/// <summary>
/// The preferred column width.
/// </summary>
private int preferredColumnWidth = 0;
/// <summary>
/// The minimum column width.
/// </summary>
private int minimumColumnWidth = 0;
/// <summary>
/// The maximum column width.
/// </summary>
private int maximumColumnWidth = 0;
/// <summary>
/// The starting horizontal splitter position.
/// </summary>
private double startingHorizontalSplitterPosition;
/// <summary>
/// The horizontal splitter position.
/// </summary>
private double horizontalSplitterPosition = 0.50;
#endregion Private Member Variables & Declarations
#region Public Events
/// <summary>
/// Occurs when the PreferredColumnWidth changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the PreferredColumnWidth property is changed.")
]
public event EventHandler PreferredColumnWidthChanged;
/// <summary>
/// Occurs when the MinimumColumnWidth changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the MinimumColumnWidth property is changed.")
]
public event EventHandler MinimumColumnWidthChanged;
/// <summary>
/// Occurs when the MaximumColumnWidth changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the MaximumColumnWidth property is changed.")
]
public event EventHandler MaximumColumnWidthChanged;
/// <summary>
/// Occurs when the HorizontalSplitterPosition changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the HorizontalSplitterPosition property is changed.")
]
public event EventHandler HorizontalSplitterPositionChanged;
/// <summary>
/// Occurs when the horizontal splitter begins moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the horizontal splitter begins moving.")
]
public event EventHandler HorizontalSplitterBeginMove;
/// <summary>
/// Occurs when the horizontal splitter is ends moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the horizontal splitter ends moving.")
]
public event EventHandler HorizontalSplitterEndMove;
/// <summary>
/// Occurs when the horizontal splitter is moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the horizontal splitter is moving.")
]
public event EventHandler HorizontalSplitterMoving;
/// <summary>
/// Occurs when the vertical splitter begins moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the vertical splitter begins moving.")
]
public event EventHandler VerticalSplitterBeginMove;
/// <summary>
/// Occurs when the vertical splitter is ends moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the vertical splitter ends moving.")
]
public event EventHandler VerticalSplitterEndMove;
/// <summary>
/// Occurs when the vertical splitter is moving.
/// </summary>
[
Category("Action"),
Description("Occurs when the vertical splitter is moving.")
]
public event EventHandler VerticalSplitterMoving;
#endregion Public Events
#region Class Initialization & Termination
/// <summary>
/// Initializes a new instance of the WorkspaceColumnLightweightControl class.
/// </summary>
public WorkspaceColumnLightweightControl(IContainer container)
{
/// <summary>
/// Required for Windows.Forms Class Composition Designer support
/// </summary>
container.Add(this);
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the WorkspaceColumnLightweightControl class.
/// </summary>
public WorkspaceColumnLightweightControl()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#endregion Class Initialization & Termination
#region 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();
this.splitterLightweightControlVertical = new OpenLiveWriter.ApplicationFramework.SplitterLightweightControl(this.components);
this.splitterLightweightControlHorizontal = new OpenLiveWriter.ApplicationFramework.SplitterLightweightControl(this.components);
this.workspaceColumnPaneUpper = new OpenLiveWriter.ApplicationFramework.WorkspaceColumnPaneLightweightControl(this.components);
this.workspaceColumnPaneLower = new OpenLiveWriter.ApplicationFramework.WorkspaceColumnPaneLightweightControl(this.components);
((System.ComponentModel.ISupportInitialize)(this.splitterLightweightControlVertical)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.splitterLightweightControlHorizontal)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.workspaceColumnPaneUpper)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.workspaceColumnPaneLower)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// splitterLightweightControlVertical
//
this.splitterLightweightControlVertical.LightweightControlContainerControl = this;
this.splitterLightweightControlVertical.Orientation = OpenLiveWriter.ApplicationFramework.SplitterLightweightControl.SplitterOrientation.Vertical;
this.splitterLightweightControlVertical.SplitterEndMove += new OpenLiveWriter.ApplicationFramework.LightweightSplitterEventHandler(this.splitterLightweightControlVertical_SplitterEndMove);
this.splitterLightweightControlVertical.SplitterBeginMove += new System.EventHandler(this.splitterLightweightControlVertical_SplitterBeginMove);
this.splitterLightweightControlVertical.SplitterMoving += new OpenLiveWriter.ApplicationFramework.LightweightSplitterEventHandler(this.splitterLightweightControlVertical_SplitterMoving);
//
// splitterLightweightControlHorizontal
//
this.splitterLightweightControlHorizontal.LightweightControlContainerControl = this;
this.splitterLightweightControlHorizontal.SplitterEndMove += new OpenLiveWriter.ApplicationFramework.LightweightSplitterEventHandler(this.splitterLightweightControlHorizontal_SplitterEndMove);
this.splitterLightweightControlHorizontal.SplitterBeginMove += new System.EventHandler(this.splitterLightweightControlHorizontal_SplitterBeginMove);
this.splitterLightweightControlHorizontal.SplitterMoving += new OpenLiveWriter.ApplicationFramework.LightweightSplitterEventHandler(this.splitterLightweightControlHorizontal_SplitterMoving);
//
// workspaceColumnPaneUpper
//
this.workspaceColumnPaneUpper.Border = false;
this.workspaceColumnPaneUpper.Control = null;
this.workspaceColumnPaneUpper.FixedHeight = 0;
this.workspaceColumnPaneUpper.FixedHeightLayout = false;
this.workspaceColumnPaneUpper.LightweightControl = null;
this.workspaceColumnPaneUpper.LightweightControlContainerControl = this;
this.workspaceColumnPaneUpper.Visible = false;
this.workspaceColumnPaneUpper.VisibleChanged += new System.EventHandler(this.workspaceColumnPaneUpper_VisibleChanged);
//
// workspaceColumnPaneLower
//
this.workspaceColumnPaneLower.Border = false;
this.workspaceColumnPaneLower.Control = null;
this.workspaceColumnPaneLower.FixedHeight = 0;
this.workspaceColumnPaneLower.FixedHeightLayout = false;
this.workspaceColumnPaneLower.LightweightControl = null;
this.workspaceColumnPaneLower.LightweightControlContainerControl = this;
this.workspaceColumnPaneLower.Visible = false;
this.workspaceColumnPaneLower.VisibleChanged += new System.EventHandler(this.workspaceColumnPaneLower_VisibleChanged);
//
// WorkspaceColumnLightweightControl
//
this.AllowDrop = true;
((System.ComponentModel.ISupportInitialize)(this.splitterLightweightControlVertical)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.splitterLightweightControlHorizontal)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.workspaceColumnPaneUpper)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.workspaceColumnPaneLower)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the upper pane WorkspaceColumnPaneLightweightControl.
/// </summary>
public WorkspaceColumnPaneLightweightControl UpperPane
{
get
{
return workspaceColumnPaneUpper;
}
}
/// <summary>
/// Gets or sets the lower pane WorkspaceColumnPaneLightweightControl.
/// </summary>
public WorkspaceColumnPaneLightweightControl LowerPane
{
get
{
return workspaceColumnPaneLower;
}
}
/// <summary>
/// Gets or sets the control that is attached to the splitter control.
/// </summary>
public LightweightControl HorizontalSplitterAttachedControl
{
get
{
return splitterLightweightControlHorizontal.AttachedControl;
}
set
{
splitterLightweightControlHorizontal.AttachedControl = value;
}
}
/// <summary>
/// Gets or sets the vertical splitter style.
/// </summary>
[
Browsable(false)
]
internal VerticalSplitterStyle VerticalSplitterStyle
{
get
{
return verticalSplitterStyle;
}
set
{
if (verticalSplitterStyle != value)
{
verticalSplitterStyle = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets or sets the vertical splitter width.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(5),
Description("Specifies the initial vertical splitter width.")
]
public int VerticalSplitterWidth
{
get
{
return verticalSplitterWidth;
}
set
{
if (verticalSplitterWidth != value)
{
verticalSplitterWidth = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets or sets the horizontal splitter height.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(5),
Description("Specifies the initial horizontal splitter height.")
]
public int HorizontalSplitterHeight
{
get
{
return horizontalSplitterHeight;
}
set
{
if (horizontalSplitterHeight != value)
{
horizontalSplitterHeight = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets or sets the preferred column width.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(0),
Description("Specifies the preferred column width.")
]
public int PreferredColumnWidth
{
get
{
return preferredColumnWidth;
}
set
{
if (preferredColumnWidth != value)
{
preferredColumnWidth = value;
OnPreferredColumnWidthChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the preferred column width.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(0),
Description("Specifies the minimum column width.")
]
public int MinimumColumnWidth
{
get
{
return minimumColumnWidth;
}
set
{
if (minimumColumnWidth != value)
{
minimumColumnWidth = value;
OnMinimumColumnWidthChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the maximum column width.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(0),
Description("Specifies the maximum column width.")
]
public int MaximumColumnWidth
{
get
{
return maximumColumnWidth;
}
set
{
if (maximumColumnWidth != value)
{
maximumColumnWidth = value;
OnMaximumColumnWidthChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the preferred horizontal splitter position.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(0.50),
Description("Specifies the horizontal splitter position.")
]
public double HorizontalSplitterPosition
{
get
{
return horizontalSplitterPosition;
}
set
{
// Check the new horizontal splitter position.
if (value < MINIMUM_HORIZONTAL_SPLITTER_POSITION)
value = MINIMUM_HORIZONTAL_SPLITTER_POSITION;
else if (value > MaximumHorizontalSplitterPosition)
value = MaximumHorizontalSplitterPosition;
// If the horizontal splitter position is changing, change it.
if (horizontalSplitterPosition != value)
{
// Change it.
horizontalSplitterPosition = value;
// Raise the HorizontalSplitterPositionChanged event.
OnHorizontalSplitterPositionChanged(EventArgs.Empty);
// Layout and invalidate.
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Specifies the maximum horizontal splitter position (as a percentage of the overall column size).
/// </summary>
[
Category("Behavior"),
DefaultValue(0.80),
Description("Specifies the maximum horizontal splitter position (as a percentage of the overall column size).")
]
public double MaximumHorizontalSplitterPosition
{
get
{
return maximumHorizontalSplitterPosition;
}
set
{
maximumHorizontalSplitterPosition = value;
//update the current horizontal position in case it exceeds the new limit.
HorizontalSplitterPosition = HorizontalSplitterPosition;
}
}
/// <summary>
/// Gets or Sets the layout position of the horizontal splitter (in Y pixels).
/// </summary>
public int HorizontalSplitterLayoutPosition
{
set
{
if (value == 0 || PaneLayoutHeight == 0)
HorizontalSplitterPosition = MinimumHorizontalSplitterLayoutPosition;
else
HorizontalSplitterPosition = ((double)value) / PaneLayoutHeight;
}
get
{
return (int)(PaneLayoutHeight * HorizontalSplitterPosition);
}
}
#endregion Public Properties
#region Protected Events
/// <summary>
/// Raises the MaximumColumnWidthChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnMaximumColumnWidthChanged(EventArgs e)
{
if (MaximumColumnWidthChanged != null)
MaximumColumnWidthChanged(this, e);
}
/// <summary>
/// Raises the MinimumColumnWidthChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnMinimumColumnWidthChanged(EventArgs e)
{
if (MinimumColumnWidthChanged != null)
MinimumColumnWidthChanged(this, e);
}
/// <summary>
/// Raises the PreferredColumnWidthChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnPreferredColumnWidthChanged(EventArgs e)
{
if (PreferredColumnWidthChanged != null)
PreferredColumnWidthChanged(this, e);
}
/// <summary>
/// Raises the HorizontalSplitterPositionChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnHorizontalSplitterPositionChanged(EventArgs e)
{
if (HorizontalSplitterPositionChanged != null)
HorizontalSplitterPositionChanged(this, e);
}
/// <summary>
/// Raises the HorizontalSplitterBeginMove event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnHorizontalSplitterBeginMove(EventArgs e)
{
if (HorizontalSplitterBeginMove != null)
HorizontalSplitterBeginMove(this, e);
}
/// <summary>
/// Raises the HorizontalSplitterEndMove event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnHorizontalSplitterEndMove(EventArgs e)
{
if (HorizontalSplitterEndMove != null)
HorizontalSplitterEndMove(this, e);
}
/// <summary>
/// Raises the HorizontalSplitterMoving event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnHorizontalSplitterMoving(EventArgs e)
{
if (HorizontalSplitterMoving != null)
HorizontalSplitterMoving(this, e);
}
/// <summary>
/// Raises the VerticalSplitterBeginMove event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVerticalSplitterBeginMove(EventArgs e)
{
if (VerticalSplitterBeginMove != null)
VerticalSplitterBeginMove(this, e);
}
/// <summary>
/// Raises the VerticalSplitterEndMove event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVerticalSplitterEndMove(EventArgs e)
{
if (VerticalSplitterEndMove != null)
VerticalSplitterEndMove(this, e);
}
/// <summary>
/// Raises the VerticalSplitterMoving event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVerticalSplitterMoving(EventArgs e)
{
if (VerticalSplitterMoving != null)
VerticalSplitterMoving(this, e);
}
#endregion Protected Events
#region Protected Event Overrides
/// <summary>
/// Raises the Layout event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLayout(EventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnLayout(e);
// Layout the vertical splitter.
Rectangle layoutRectangle = LayoutVerticalSplitter();
// Layout the upper and lower panes if they are both visible.
if (workspaceColumnPaneUpper.Visible && workspaceColumnPaneLower.Visible)
{
// Calculate the pane layout height (the area available for layout of the upper
// and lower panes).
int paneLayoutHeight = layoutRectangle.Height - horizontalSplitterHeight;
// If the upper pane is fixed height, layout the column this way.
if (workspaceColumnPaneUpper.FixedHeightLayout)
{
// If the upper pane's fixed height is larger than the layout rectangle height,
// layout just the upper pane.
if (workspaceColumnPaneUpper.FixedHeight > layoutRectangle.Height)
{
workspaceColumnPaneUpper.VirtualBounds = layoutRectangle;
splitterLightweightControlHorizontal.Visible = false;
workspaceColumnPaneLower.VirtualBounds = Rectangle.Empty;
workspaceColumnPaneUpper.PerformLayout();
}
// Layout both the upper and lower panes.
else
{
// Layout the upper pane lightweight control.
workspaceColumnPaneUpper.VirtualBounds = new Rectangle(layoutRectangle.X,
layoutRectangle.Y,
layoutRectangle.Width,
workspaceColumnPaneUpper.FixedHeight);
workspaceColumnPaneUpper.PerformLayout();
// Layout the horizontal splitter lightweight control and disable it.
splitterLightweightControlHorizontal.Visible = true;
splitterLightweightControlHorizontal.Enabled = false;
splitterLightweightControlHorizontal.VirtualBounds = new Rectangle(layoutRectangle.X,
workspaceColumnPaneUpper.VirtualBounds.Bottom,
layoutRectangle.Width,
horizontalSplitterHeight);
// Layout the lower pane lightweight control.
workspaceColumnPaneLower.VirtualBounds = new Rectangle(layoutRectangle.X,
splitterLightweightControlHorizontal.VirtualBounds.Bottom,
layoutRectangle.Width,
layoutRectangle.Height - (workspaceColumnPaneUpper.VirtualHeight + horizontalSplitterHeight));
workspaceColumnPaneLower.PerformLayout();
}
}
// If the lower pane is fixed height, layout the column this way.
else if (workspaceColumnPaneLower.FixedHeightLayout)
{
// If the upper pane's fixed height is larger than the layout rectangle height,
// layout just the upper pane.
if (workspaceColumnPaneLower.FixedHeight > layoutRectangle.Height)
{
workspaceColumnPaneLower.VirtualBounds = layoutRectangle;
splitterLightweightControlHorizontal.Visible = false;
workspaceColumnPaneLower.VirtualBounds = Rectangle.Empty;
workspaceColumnPaneLower.PerformLayout();
}
// Layout both the upper and lower panes.
else
{
// Layout the lower pane lightweight control.
workspaceColumnPaneLower.VirtualBounds = new Rectangle(layoutRectangle.X,
layoutRectangle.Bottom - workspaceColumnPaneLower.FixedHeight,
layoutRectangle.Width,
workspaceColumnPaneLower.FixedHeight);
workspaceColumnPaneLower.PerformLayout();
// Layout the horizontal splitter lightweight control and disable it.
splitterLightweightControlHorizontal.Visible = true;
splitterLightweightControlHorizontal.Enabled = false;
splitterLightweightControlHorizontal.VirtualBounds = new Rectangle(layoutRectangle.X,
workspaceColumnPaneLower.VirtualBounds.Top - horizontalSplitterHeight,
layoutRectangle.Width,
horizontalSplitterHeight);
// Layout the upper pane lightweight control.
workspaceColumnPaneUpper.VirtualBounds = new Rectangle(layoutRectangle.X,
layoutRectangle.Y,
layoutRectangle.Width,
splitterLightweightControlHorizontal.VirtualBounds.Top);
workspaceColumnPaneUpper.PerformLayout();
}
}
// If the pane layout height is too small (i.e. there isn't enough room to show
// both panes), err on the side of showing just the top pane. This is an extreme
// edge condition.
else if (paneLayoutHeight < 10 * horizontalSplitterHeight)
{
// Only the upper pane lightweight control is visible.
workspaceColumnPaneUpper.VirtualBounds = layoutRectangle;
workspaceColumnPaneLower.VirtualBounds = Rectangle.Empty;
splitterLightweightControlHorizontal.Visible = false;
splitterLightweightControlHorizontal.VirtualBounds = Rectangle.Empty;
}
else
{
// Get the horizontal splitter layout position.
int horizontalSplitterLayoutPosition = HorizontalSplitterLayoutPosition;
// Layout the upper pane lightweight control.
workspaceColumnPaneUpper.VirtualBounds = new Rectangle(layoutRectangle.X,
layoutRectangle.Y,
layoutRectangle.Width,
horizontalSplitterLayoutPosition);
workspaceColumnPaneUpper.PerformLayout();
// Layout the horizontal splitter lightweight control and enable it.
splitterLightweightControlHorizontal.Visible = true;
splitterLightweightControlHorizontal.Enabled = true;
splitterLightweightControlHorizontal.VirtualBounds = new Rectangle(layoutRectangle.X,
workspaceColumnPaneUpper.VirtualBounds.Bottom,
layoutRectangle.Width,
horizontalSplitterHeight);
// Layout the lower pane lightweight control.
workspaceColumnPaneLower.VirtualBounds = new Rectangle(layoutRectangle.X,
splitterLightweightControlHorizontal.VirtualBounds.Bottom,
layoutRectangle.Width,
layoutRectangle.Height - (workspaceColumnPaneUpper.VirtualHeight + horizontalSplitterHeight));
workspaceColumnPaneLower.PerformLayout();
}
}
// Layout the upper pane, if it's visible. Note that we ignore the FixedHeight
// property of the pane in this case because it doesn't make sense to layout a
// pane that doesn't fill the entire height of the column.
else if (workspaceColumnPaneUpper.Visible)
{
// Only the upper pane lightweight control is visible.
workspaceColumnPaneUpper.VirtualBounds = layoutRectangle;
splitterLightweightControlHorizontal.Visible = false;
workspaceColumnPaneUpper.PerformLayout();
}
// Layout the lower pane, if it's visible. Note that we ignore the FixedHeight
// property of the pane in this case because it doesn't make sense to layout a
// pane that doesn't fill the entire height of the column.
else if (workspaceColumnPaneLower.Visible)
{
// Only the lower pane lightweight control is visible.
workspaceColumnPaneLower.VirtualBounds = layoutRectangle;
splitterLightweightControlHorizontal.Visible = false;
workspaceColumnPaneLower.PerformLayout();
}
}
#endregion Protected Event Overrides
#region Private Properties
/// <summary>
/// Gets the maximum width increase.
/// </summary>
private int MaximumWidthIncrease
{
get
{
Debug.Assert(VirtualWidth <= MaximumColumnWidth, "The column is wider than it's maximum width.");
return Math.Max(0, MaximumColumnWidth - VirtualWidth);
}
}
/// <summary>
/// Gets the maximum width decrease.
/// </summary>
private int MaximumWidthDecrease
{
get
{
Debug.Assert(VirtualWidth >= MinimumColumnWidth, "The column is narrower than it's minimum width.");
return Math.Max(0, VirtualWidth - MinimumColumnWidth);
}
}
/// <summary>
/// Gets the pane layout height.
/// </summary>
private int PaneLayoutHeight
{
get
{
return Math.Max(0, VirtualClientRectangle.Height - horizontalSplitterHeight);
}
}
/// <summary>
/// Gets the minimum layout position of the horizontal splitter.
/// </summary>
private int MinimumHorizontalSplitterLayoutPosition
{
get
{
return (int)(PaneLayoutHeight * MINIMUM_HORIZONTAL_SPLITTER_POSITION);
}
}
/// <summary>
/// Gets the maximum layout position of the horizontal splitter.
/// </summary>
private int MaximumHorizontalSplitterLayoutPosition
{
get
{
return (int)(PaneLayoutHeight * MaximumHorizontalSplitterPosition);
}
}
#endregion Private Properties
#region Private Metods
/// <summary>
/// Helper that performs layout logic for the vertical splitter.
/// </summary>
/// <returns>The layout rectangle for the next phases of layout.</returns>
private Rectangle LayoutVerticalSplitter()
{
// Obtain the layout rectangle.
Rectangle layoutRectangle = VirtualClientRectangle;
// Layout the vertical splitter lightweight control and adjust the layout rectangle
// as needed.
if (verticalSplitterStyle == VerticalSplitterStyle.None)
{
// No vertical splitter lightweight control.
splitterLightweightControlVertical.Visible = false;
splitterLightweightControlVertical.VirtualBounds = Rectangle.Empty;
}
else if (verticalSplitterStyle == VerticalSplitterStyle.Left)
{
// Left vertical splitter lightweight control.
splitterLightweightControlVertical.Visible = true;
splitterLightweightControlVertical.VirtualBounds = new Rectangle(layoutRectangle.X,
layoutRectangle.Y,
verticalSplitterWidth,
layoutRectangle.Height);
// Adjust the layout rectangle.
layoutRectangle.X += verticalSplitterWidth;
layoutRectangle.Width -= verticalSplitterWidth;
}
else if (verticalSplitterStyle == VerticalSplitterStyle.Right)
{
// Right vertical splitter lightweight control.
splitterLightweightControlVertical.Visible = true;
splitterLightweightControlVertical.VirtualBounds = new Rectangle(layoutRectangle.Right - verticalSplitterWidth,
layoutRectangle.Top,
verticalSplitterWidth,
layoutRectangle.Height);
// Adjust the layout rectangle.
layoutRectangle.Width -= verticalSplitterWidth;
}
// Done! Return the layout rectangle.
return layoutRectangle;
}
private void LayoutWithFixedHeightUpperPane(Rectangle layoutRectangle)
{
}
private void LayoutWithFixedHeightLowerPane(Rectangle layoutRectangle)
{
}
/// <summary>
/// Helper to adjust the Position in the LightweightSplitterEventArgs for the vertical splitter.
/// </summary>
/// <param name="e">LightweightSplitterEventArgs to adjust.</param>
private void AdjustVerticalLightweightSplitterEventArgsPosition(ref LightweightSplitterEventArgs e)
{
// If the vertical splitter style is non, we shouldn't receive this event.
Debug.Assert(verticalSplitterStyle != VerticalSplitterStyle.None);
if (verticalSplitterStyle == VerticalSplitterStyle.None)
return;
// Left or right splitter style.
if (verticalSplitterStyle == VerticalSplitterStyle.Left)
{
if (e.Position < 0)
{
if (Math.Abs(e.Position) > MaximumWidthIncrease)
e.Position = MaximumWidthIncrease * -1;
}
else
{
if (e.Position > MaximumWidthDecrease)
e.Position = MaximumWidthDecrease;
}
}
else if (verticalSplitterStyle == VerticalSplitterStyle.Right)
{
if (e.Position > 0)
{
if (e.Position > MaximumWidthIncrease)
e.Position = MaximumWidthIncrease;
}
else
{
if (Math.Abs(e.Position) > MaximumWidthDecrease)
e.Position = MaximumWidthDecrease * -1;
}
}
}
/// <summary>
/// Helper to adjust the Position in the LightweightSplitterEventArgs for the horizontal splitter.
/// </summary>
/// <param name="e">LightweightSplitterEventArgs to adjust.</param>
private void AdjustHorizontalLightweightSplitterEventArgsPosition(ref LightweightSplitterEventArgs e)
{
int horizontalSplitterLayoutPosition = HorizontalSplitterLayoutPosition;
if (e.Position < 0)
{
if (HorizontalSplitterLayoutPosition + e.Position < MinimumHorizontalSplitterLayoutPosition)
e.Position = MinimumHorizontalSplitterLayoutPosition - horizontalSplitterLayoutPosition;
}
else
{
if (HorizontalSplitterLayoutPosition + e.Position > MaximumHorizontalSplitterLayoutPosition)
e.Position = MaximumHorizontalSplitterLayoutPosition - horizontalSplitterLayoutPosition;
}
}
#endregion Private Metods
#region Private Event Handler
/// <summary>
/// splitterLightweightControlVertical_SplitterBeginMove event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void splitterLightweightControlVertical_SplitterBeginMove(object sender, EventArgs e)
{
startingPreferredColumnWidth = PreferredColumnWidth;
// Raise the VerticalSplitterBeginMove event.
OnVerticalSplitterBeginMove(EventArgs.Empty);
}
/// <summary>
/// splitterLightweightControlVertical_SplitterEndMove event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void splitterLightweightControlVertical_SplitterEndMove(object sender, LightweightSplitterEventArgs e)
{
// If the splitter has moved.
if (e.Position != 0)
{
// Adjust the vertical splitter position.
AdjustVerticalLightweightSplitterEventArgsPosition(ref e);
// Adjust the preferred column width.
if (verticalSplitterStyle == VerticalSplitterStyle.Left)
PreferredColumnWidth -= e.Position;
else if (verticalSplitterStyle == VerticalSplitterStyle.Right)
PreferredColumnWidth += e.Position;
}
// Raise the VerticalSplitterEndMove event.
OnVerticalSplitterEndMove(EventArgs.Empty);
}
/// <summary>
/// splitterLightweightControlVertical_SplitterMoving event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void splitterLightweightControlVertical_SplitterMoving(object sender, LightweightSplitterEventArgs e)
{
// If the splitter has moved.
if (e.Position != 0)
{
// Adjust the splitter position.
AdjustVerticalLightweightSplitterEventArgsPosition(ref e);
// Adjust the preferred column width - in real time.
if (verticalSplitterStyle == VerticalSplitterStyle.Left)
PreferredColumnWidth -= e.Position;
else if (verticalSplitterStyle == VerticalSplitterStyle.Right)
PreferredColumnWidth += e.Position;
// Update manually to keep the screen as up to date as possible.
Update();
}
// Raise the VerticalSplitterMoving event.
OnVerticalSplitterMoving(EventArgs.Empty);
}
/// <summary>
/// splitterLightweightControlHorizontal_SplitterBeginMove event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void splitterLightweightControlHorizontal_SplitterBeginMove(object sender, EventArgs e)
{
startingHorizontalSplitterPosition = HorizontalSplitterPosition;
// Raise the HorizontalSplitterBeginMove event.
OnHorizontalSplitterBeginMove(EventArgs.Empty);
}
/// <summary>
/// splitterLightweightControlHorizontal_SplitterEndMove event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void splitterLightweightControlHorizontal_SplitterEndMove(object sender, LightweightSplitterEventArgs e)
{
// If the splitter has moved.
if (e.Position != 0)
{
// Adjust the horizontal splitter position.
AdjustHorizontalLightweightSplitterEventArgsPosition(ref e);
// Adjust the horizontal splitter position.
HorizontalSplitterPosition += (double)e.Position / PaneLayoutHeight;
}
// Raise the HorizontalSplitterEndMove event.
OnHorizontalSplitterEndMove(EventArgs.Empty);
}
/// <summary>
/// splitterLightweightControlHorizontal_SplitterMoving event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void splitterLightweightControlHorizontal_SplitterMoving(object sender, LightweightSplitterEventArgs e)
{
// If the splitter has moved.
if (e.Position != 0)
{
AdjustHorizontalLightweightSplitterEventArgsPosition(ref e);
// Adjust the horizontal splitter position.
HorizontalSplitterPosition += (double)e.Position / PaneLayoutHeight;
// Update manually to keep the screen as up to date as possible.
Update();
}
// Raise the HorizontalSplitterMoving event.
OnHorizontalSplitterMoving(EventArgs.Empty);
}
/// <summary>
/// workspaceColumnPaneUpper_VisibleChanged event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void workspaceColumnPaneUpper_VisibleChanged(object sender, EventArgs e)
{
PerformLayout();
Invalidate();
}
/// <summary>
/// workspaceColumnPaneLower_VisibleChanged event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void workspaceColumnPaneLower_VisibleChanged(object sender, EventArgs e)
{
PerformLayout();
Invalidate();
}
#endregion Private Event Handler
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the PutLifecycleHook operation.
/// Creates or updates a lifecycle hook for the specified Auto Scaling Group.
///
///
/// <para>
/// A lifecycle hook tells Auto Scaling that you want to perform an action on an instance
/// that is not actively in service; for example, either when the instance launches or
/// before the instance terminates.
/// </para>
///
/// <para>
/// This operation is a part of the basic sequence for adding a lifecycle hook to an Auto
/// Scaling group:
/// </para>
/// <ol> <li>Create a notification target. A target can be either an Amazon SQS queue
/// or an Amazon SNS topic.</li> <li>Create an IAM role. This role allows Auto Scaling
/// to publish lifecycle notifications to the designated SQS queue or SNS topic.</li>
/// <li><b>Create the lifecycle hook. You can create a hook that acts when instances launch
/// or when instances terminate.</b></li> <li>If necessary, record the lifecycle action
/// heartbeat to keep the instance in a pending state.</li> <li>Complete the lifecycle
/// action.</li> </ol>
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingPendingState.html">Auto
/// Scaling Pending State</a> and <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingTerminatingState.html">Auto
/// Scaling Terminating State</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public partial class PutLifecycleHookRequest : AmazonAutoScalingRequest
{
private string _autoScalingGroupName;
private string _defaultResult;
private int? _heartbeatTimeout;
private string _lifecycleHookName;
private string _lifecycleTransition;
private string _notificationMetadata;
private string _notificationTargetARN;
private string _roleARN;
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group to which you want to assign the lifecycle hook.
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property DefaultResult.
/// <para>
/// Defines the action the Auto Scaling group should take when the lifecycle hook timeout
/// elapses or if an unexpected failure occurs. The value for this parameter can be either
/// <code>CONTINUE</code> or <code>ABANDON</code>. The default value for this parameter
/// is <code>ABANDON</code>.
/// </para>
/// </summary>
public string DefaultResult
{
get { return this._defaultResult; }
set { this._defaultResult = value; }
}
// Check to see if DefaultResult property is set
internal bool IsSetDefaultResult()
{
return this._defaultResult != null;
}
/// <summary>
/// Gets and sets the property HeartbeatTimeout.
/// <para>
/// Defines the amount of time, in seconds, that can elapse before the lifecycle hook
/// times out. When the lifecycle hook times out, Auto Scaling performs the action defined
/// in the <code>DefaultResult</code> parameter. You can prevent the lifecycle hook from
/// timing out by calling <a>RecordLifecycleActionHeartbeat</a>. The default value for
/// this parameter is 3600 seconds (1 hour).
/// </para>
/// </summary>
public int HeartbeatTimeout
{
get { return this._heartbeatTimeout.GetValueOrDefault(); }
set { this._heartbeatTimeout = value; }
}
// Check to see if HeartbeatTimeout property is set
internal bool IsSetHeartbeatTimeout()
{
return this._heartbeatTimeout.HasValue;
}
/// <summary>
/// Gets and sets the property LifecycleHookName.
/// <para>
/// The name of the lifecycle hook.
/// </para>
/// </summary>
public string LifecycleHookName
{
get { return this._lifecycleHookName; }
set { this._lifecycleHookName = value; }
}
// Check to see if LifecycleHookName property is set
internal bool IsSetLifecycleHookName()
{
return this._lifecycleHookName != null;
}
/// <summary>
/// Gets and sets the property LifecycleTransition.
/// <para>
/// The Amazon EC2 instance state to which you want to attach the lifecycle hook. See
/// <a>DescribeLifecycleHookTypes</a> for a list of available lifecycle hook types.
/// </para>
/// <note>
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
/// </note>
/// </summary>
public string LifecycleTransition
{
get { return this._lifecycleTransition; }
set { this._lifecycleTransition = value; }
}
// Check to see if LifecycleTransition property is set
internal bool IsSetLifecycleTransition()
{
return this._lifecycleTransition != null;
}
/// <summary>
/// Gets and sets the property NotificationMetadata.
/// <para>
/// Contains additional information that you want to include any time Auto Scaling sends
/// a message to the notification target.
/// </para>
/// </summary>
public string NotificationMetadata
{
get { return this._notificationMetadata; }
set { this._notificationMetadata = value; }
}
// Check to see if NotificationMetadata property is set
internal bool IsSetNotificationMetadata()
{
return this._notificationMetadata != null;
}
/// <summary>
/// Gets and sets the property NotificationTargetARN.
/// <para>
/// The ARN of the notification target that Auto Scaling will use to notify you when an
/// instance is in the transition state for the lifecycle hook. This ARN target can be
/// either an SQS queue or an SNS topic.
/// </para>
/// <note>
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
/// </note>
/// <para>
/// The notification message sent to the target will include:
/// </para>
/// <ul> <li> <b>LifecycleActionToken</b>. The Lifecycle action token.</li> <li> <b>AccountId</b>.
/// The user account ID.</li> <li> <b>AutoScalingGroupName</b>. The name of the Auto Scaling
/// group.</li> <li> <b>LifecycleHookName</b>. The lifecycle hook name.</li> <li> <b>EC2InstanceId</b>.
/// The EC2 instance ID.</li> <li> <b>LifecycleTransition</b>. The lifecycle transition.</li>
/// <li> <b>NotificationMetadata</b>. The notification metadata.</li> </ul>
/// <para>
/// This operation uses the JSON format when sending notifications to an Amazon SQS queue,
/// and an email key/value pair format when sending notifications to an Amazon SNS topic.
/// </para>
///
/// <para>
/// When you call this operation, a test message is sent to the notification target. This
/// test message contains an additional key/value pair: <code>Event:autoscaling:TEST_NOTIFICATION</code>.
/// </para>
/// </summary>
public string NotificationTargetARN
{
get { return this._notificationTargetARN; }
set { this._notificationTargetARN = value; }
}
// Check to see if NotificationTargetARN property is set
internal bool IsSetNotificationTargetARN()
{
return this._notificationTargetARN != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The ARN of the IAM role that allows the Auto Scaling group to publish to the specified
/// notification target.
/// </para>
/// <note>
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
/// </note>
/// </summary>
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ResultOperators;
using Revenj.Common;
using Revenj.DatabasePersistence.Oracle.Plugins.ExpressionSupport;
using Revenj.DatabasePersistence.Oracle.QueryGeneration.Visitors;
using Revenj.DomainPatterns;
namespace Revenj.DatabasePersistence.Oracle.QueryGeneration.QueryComposition
{
public abstract class QueryParts
{
internal static readonly IExpressionMatcher[] StaticExpressionMatchers = new IExpressionMatcher[]{
new LikeStringComparison(),
new LinqMethods(),
new StringMethods()
};
internal static readonly IMemberMatcher[] StaticMemberMatchers = new IMemberMatcher[]{
new CommonMembers(),
new EnumerableMembers()
};
public readonly IServiceProvider Locator;
public readonly IOracleConverterFactory ConverterFactory;
public readonly string ContextName;
public readonly ParameterAggregator Parameters;
public readonly QueryContext Context;
public int CurrentSelectIndex { get; set; }
public readonly List<SelectSource> Selects = new List<SelectSource>();
public MainFromClause MainFrom { get; protected set; }
public readonly List<JoinClause> Joins = new List<JoinClause>();
public readonly List<AdditionalFromClause> AdditionalJoins = new List<AdditionalFromClause>();
public readonly List<GroupJoinClause> GroupJoins = new List<GroupJoinClause>();
public readonly List<Expression> Conditions = new List<Expression>();
public readonly List<OrderByClause> OrderBy = new List<OrderByClause>();
public readonly List<ResultOperatorBase> ResultOperators = new List<ResultOperatorBase>();
internal readonly List<IQuerySimplification> Simplifications;
internal readonly IEnumerable<IExpressionMatcher> ExpressionMatchers;
internal readonly IEnumerable<IMemberMatcher> MemberMatchers;
internal readonly IEnumerable<IProjectionMatcher> ProjectionMatchers;
protected QueryParts(
IServiceProvider locator,
string contextName,
IOracleConverterFactory factory,
ParameterAggregator parameters,
QueryContext context,
IEnumerable<IQuerySimplification> simplifications,
IEnumerable<IExpressionMatcher> expressionMatchers,
IEnumerable<IMemberMatcher> memberMatchers,
IEnumerable<IProjectionMatcher> projectionMatchers)
{
this.Locator = locator;
this.ConverterFactory = factory;
this.Parameters = parameters;
this.Context = context;
this.Simplifications = new List<IQuerySimplification>(simplifications);
this.ExpressionMatchers = expressionMatchers;
this.MemberMatchers = memberMatchers;
this.ProjectionMatchers = projectionMatchers;
this.ContextName = contextName;
}
public class SelectSource
{
public IQuerySource QuerySource { get; set; }
public Expression Expression { get; set; }
public string Sql { get; set; }
public string Name { get; set; }
public Type ItemType { get; set; }
public Func<ResultObjectMapping, IDataReader, object> Instancer { get; set; }
}
public bool AddSelectPart(IQuerySource qs, string sql, string name, Type type, Func<ResultObjectMapping, IDataReader, object> instancer)
{
if (Selects.Any(kv => kv.Name == name))
return false;
Selects.Add(new SelectSource { QuerySource = qs, Sql = sql, Name = name, ItemType = type, Instancer = instancer });
if (sql != null)
CurrentSelectIndex++;
return true;
}
public void SetFrom(MainFromClause from)
{
MainFrom = from;
if (from != QuerySourceConverterFactory.GetOriginalSource(from))
MainFrom = TryToSimplifyMainFrom(MainFrom);
}
internal MainFromClause TryToSimplifyMainFrom(MainFromClause from)
{
var name = from.ItemName;
var sqe = from.FromExpression as SubQueryExpression;
while (sqe != null)
{
var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(sqe.QueryModel, this, ContextName, Context.Select());
if (subquery.Conditions.Count > 0
|| subquery.Joins.Count > 0
|| subquery.ResultOperators.Any(it => it is CastResultOperator == false && it is DefaultIfEmptyResultOperator == false)
|| subquery.AdditionalJoins.Count > 0)
return from;
from = sqe.QueryModel.MainFromClause;
sqe = from.FromExpression as SubQueryExpression;
}
from.ItemName = name;
return from;
}
internal FromClauseBase TryToSimplifyAdditionalFrom(AdditionalFromClause additionalFrom)
{
FromClauseBase from = additionalFrom;
var sqe = from.FromExpression as SubQueryExpression;
if (sqe != null)
{
var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(sqe.QueryModel, this, ContextName, Context.Select());
if (subquery.Joins.Count > 0
|| subquery.ResultOperators.Any(it => it is CastResultOperator == false && it is DefaultIfEmptyResultOperator == false)
|| subquery.AdditionalJoins.Count > 0)
return from;
return TryToSimplifyMainFrom(sqe.QueryModel.MainFromClause);
}
return from;
}
public void AddJoin(JoinClause join)
{
Joins.Add(join);
}
public void AddJoin(AdditionalFromClause join)
{
AdditionalJoins.Add(join);
}
public void AddJoin(GroupJoinClause join)
{
GroupJoins.Add(join);
}
public void AddCondition(Expression condition)
{
var cc = condition as ConstantExpression;
if (cc == null || cc.Type != typeof(bool) || !(bool)cc.Value)
Conditions.Add(condition);
}
public void AddOrderBy(OrderByClause orderBy)
{
OrderBy.Add(orderBy);
}
public void AddResultOperator(ResultOperatorBase resultOperator)
{
if (resultOperator is CastResultOperator == false)
ResultOperators.Add(resultOperator);
}
public string GetSqlExpression(Expression expression)
{
return GetSqlExpression(expression, string.Empty, Context);
}
public string GetSqlExpression(Expression expression, string contextName, QueryContext context)
{
return SqlGeneratorExpressionTreeVisitor.GetSqlExpression(expression, this, contextName, context);
}
public string GetFromPart()
{
if (MainFrom == null)
throw new InvalidOperationException("A query must have a from part");
var sb = new StringBuilder();
var mainFromQuery = GetQuerySourceFromExpression(MainFrom.ItemName, MainFrom.ItemType, MainFrom.FromExpression);
if (AdditionalJoins.Any(it =>
{
var me = it.FromExpression as MemberExpression;
return me != null && me.Expression is QuerySourceReferenceExpression;
}))
{
if (MainFrom.ItemType.AsValue())
{
sb.Append("FROM ").Append(mainFromQuery);
sb.AppendLine();
sb.AppendFormat("INNER JOIN ({0}) sq$ ON sq$.id$ = \"{1}\".ROWID", GetInnerFromPart(true, mainFromQuery), MainFrom.ItemName);
}
else
{
sb.Append("FROM (").Append(GetInnerFromPart(false, mainFromQuery)).Append(") sq");
}
}
else
{
sb.Append("FROM ").Append(mainFromQuery);
}
var emptyJoins =
(from j in AdditionalJoins
let sqe = j.FromExpression as SubQueryExpression
where sqe != null
&& sqe.QueryModel.ResultOperators.Count == 1
&& sqe.QueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator
select new { j, sqe })
.ToList();
var groupPairs =
(from aj in emptyJoins
let mfe = aj.sqe.QueryModel.MainFromClause.FromExpression as QuerySourceReferenceExpression
where mfe != null
select new { aj.j, g = mfe.ReferencedQuerySource })
.ToList();
foreach (var aj in AdditionalJoins)
{
var me = aj.FromExpression as MemberExpression;
if (me != null && me.Expression is QuerySourceReferenceExpression)
continue;
if (groupPairs.Any(it => it.j == aj))
continue;
var ej = emptyJoins.Find(it => it.j == aj);
if (ej != null)
{
var qm = ej.sqe.QueryModel;
var sel = qm.SelectClause.Selector as QuerySourceReferenceExpression;
if (sel != null && sel.ReferencedQuerySource.Equals(qm.MainFromClause) && qm.BodyClauses.Count > 0)
{
var wc = qm.BodyClauses.Where(it => it is WhereClause).Cast<WhereClause>().ToList();
if (wc.Count == qm.BodyClauses.Count)
{
var mfc = qm.MainFromClause;
mfc.ItemName = aj.ItemName;
sb.AppendFormat("{0} LEFT JOIN {1} ON {2}",
Environment.NewLine,
GetQuerySourceFromExpression(mfc.ItemName, mfc.ItemType, mfc.FromExpression),
string.Join(" AND ", wc.Select(it => GetSqlExpression(it.Predicate))));
continue;
}
}
}
sb.AppendFormat("{0} CROSS JOIN {1}",
Environment.NewLine,
GetQuerySourceFromExpression(aj.ItemName, aj.ItemType, aj.FromExpression));
}
if (Joins.Count > 0)
Joins.ForEach(it => sb.AppendFormat("{0} INNER JOIN {1} ON ({2}) = ({3}){0}",
Environment.NewLine,
GetQuerySourceFromExpression(it.ItemName, it.ItemType, it.InnerSequence),
GetSqlExpression(it.InnerKeySelector),
GetSqlExpression(it.OuterKeySelector)));
foreach (var gj in GroupJoins)
{
var aj = groupPairs.FirstOrDefault(it => it.g == gj);
if (aj == null)
throw new FrameworkException("Can't find group join part!");
gj.ItemName = aj.j.ItemName;
gj.JoinClause.ItemName = aj.j.ItemName;
sb.AppendFormat("{0} LEFT JOIN {1} ON ({2}) = ({3}){0}",
Environment.NewLine,
GetQuerySourceFromExpression(gj.ItemName, gj.ItemType, gj.JoinClause.InnerSequence),
GetSqlExpression(gj.JoinClause.InnerKeySelector),
GetSqlExpression(gj.JoinClause.OuterKeySelector));
}
sb.AppendLine();
return sb.ToString();
}
private string GetInnerFromPart(bool asValue, string mainFromQuery)
{
var sb = new StringBuilder("SELECT ");
if (asValue)
sb.AppendFormat("\"{0}\".ROWID as id$", MainFrom.ItemName);
else
sb.AppendFormat("\"{0}\"", MainFrom.ItemName);
foreach (var aj in AdditionalJoins)
{
var me = aj.FromExpression as MemberExpression;
if (me != null)
{
var qsre = me.Expression as QuerySourceReferenceExpression;
if (qsre != null)
sb.Append(", \"").Append(aj.ItemName).Append("\".OBJECT_VALUE AS \"").Append(aj.ItemName).Append("\"");
}
}
sb.Append(" FROM ").Append(mainFromQuery);
foreach (var aj in AdditionalJoins)
{
var me = aj.FromExpression as MemberExpression;
if (me != null)
{
var qsre = me.Expression as QuerySourceReferenceExpression;
if (qsre != null)
{
sb.AppendLine();
sb.AppendFormat(" CROSS JOIN TABLE(\"{0}\".\"{1}\") \"{2}\"", qsre.ReferencedQuerySource.ItemName, me.Member.Name, aj.ItemName);
}
}
}
return sb.ToString();
}
public string GetWherePart()
{
if (Conditions.Count == 0)
return string.Empty;
var whereConditions = new List<string>();
Conditions.ForEach(it => whereConditions.Add(GetSqlExpression(it, ContextName, Context.Where())));
return @"WHERE
{0}
".With(string.Join(Environment.NewLine + " AND ", whereConditions));
}
public string GetOrderPart()
{
return OrderBy.Count == 0
? string.Empty
: @"ORDER BY
{0}
".With(string.Join(@",
", OrderBy.Last().Orderings.Select(o => GetSqlExpression(o.Expression) + (o.OrderingDirection == OrderingDirection.Desc ? " DESC " : " ASC "))));
}
//TODO vjerojatno ponekad ne treba ignorirati expression
public string GetQuerySourceFromExpression(string name, Type type, Expression fromExpression)
{
var me = fromExpression as MemberExpression;
if (me != null)
{
var qse = me.Expression as QuerySourceReferenceExpression;
if (qse != null)
return @"TABLE(""{0}"".""{1}"") ""{2}""".With(
qse.ReferencedQuerySource.ItemName,
me.Member.Name,
name);
}
var sqe = fromExpression as SubQueryExpression;
if (sqe != null)
{
if (sqe.QueryModel.CanUseMain())
return GetQuerySourceFromExpression(name, type, sqe.QueryModel.MainFromClause.FromExpression);
//TODO hack za replaceanje generiranog id-a
var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(sqe.QueryModel, this, ContextName, Context.Select());
var grouping = sqe.QueryModel.ResultOperators.FirstOrDefault(it => it is GroupResultOperator) as GroupResultOperator;
if (grouping == null && subquery.Selects.Count == 1)
{
if (sqe.QueryModel.ResultOperators.Any(it => it is UnionResultOperator || it is ConcatResultOperator))
{
var ind = subquery.Selects[0].Sql.IndexOf(" AS ");
if (ind > 0)
{
var asName = subquery.Selects[0].Sql.Substring(ind + 4).Trim().Replace("\"", "");
if (asName != name)
subquery.Selects[0].Sql = subquery.Selects[0].Sql.Substring(0, ind + 4) + "\"" + name + "\"";
}
else
{
subquery.Selects[0].Sql = subquery.Selects[0].Sql + " AS \"" + name + "\"";
}
return "(" + subquery.BuildSqlString(true) + ") \"" + name + "\"";
}
return "(" + subquery.BuildSqlString(true).Replace("\"" + sqe.QueryModel.MainFromClause.ItemName + "\"", "\"" + name + "\"") + ") \"" + name + "\"";
}
return "(" + subquery.BuildSqlString(true) + ") \"" + name + "\"";
}
var ce = fromExpression as ConstantExpression;
if (ce != null)
{
var queryable = ce.Value as IQueryable;
if (queryable != null)
return GetQueryableExpression(name, queryable);
var ien = ce.Value as IEnumerable;
var array = ien != null ? ien.Cast<object>().ToArray() : null;
var firstElem = array != null ? array.FirstOrDefault(it => it != null) : null;
var elementType = firstElem != null ? firstElem.GetType()
: ce.Type.IsArray ? ce.Type.GetElementType()
: ce.Type.IsGenericType ? ce.Type.GetGenericArguments()[0]
: null;
if (Context.CanUseParams && elementType != null)
{
var factory = ConverterFactory.GetVarrayParameterFactory(elementType);
if (factory != null)
{
var p = Parameters.Add(factory(ce.Value as IEnumerable));
return @"(SELECT sq$.OBJECT_VALUE as ""{1}"" FROM TABLE({0}) sq$)".With(p, name);
}
}
if (ce.Type.IsArray || ce.Value is Array)
return FormatStringArray(ce.Value, name, ce.Type);
else if (ce.Value is IEnumerable)
return FormatStringEnumerable(ce.Value, name, ce.Type);
//TODO: sql injection!?
return "(SELECT {0} AS \"{1}\" FROM dual) \"{1}\"".With(ce.Value, name);
}
var nae = fromExpression as NewArrayExpression;
if (nae != null)
{
if (nae.Expressions.Count == 0)
//TODO support for zero
throw new NotImplementedException("Expecting NewArrayExpression arguments. None found.");
var inner = string.Join(" UNION ALL ", nae.Expressions.Select(it => "SELECT {0} AS \"{1}\"".With(GetSqlExpression(it), name)));
return "(" + inner + ") \"{0}\" ".With(name);
}
if (fromExpression is QuerySourceReferenceExpression && fromExpression.Type.IsGrouping())
{
var qse = fromExpression as QuerySourceReferenceExpression;
//TODO: convert to Oracle version
return
"(SELECT (\"{0}\".\"Values\")[i].* FROM generate_series(1, array_upper(\"{0}\".\"Values\", 1)) i) AS \"{1}\"".With(
qse.ReferencedQuerySource.ItemName,
name);
}
var pe = fromExpression as ParameterExpression;
if (pe != null)
return "TABLE({0}\"{1}\") \"{2}\"".With(ContextName, pe.Name, name);
return FromSqlSource(name, type);
}
private string GetQueryableExpression(string name, IQueryable queryable)
{
var ce = queryable.Expression as ConstantExpression;
if (ce != null)
{
if (ce.Type.IsGenericType)
{
var gtd = ce.Type.GetGenericTypeDefinition();
if (gtd == typeof(Queryable<>))
return FromSqlSource(name, ce.Type.GetGenericArguments()[0]);
if (gtd == typeof(IQueryable<>))
return GetQuerySourceFromExpression(name, queryable.ElementType, queryable.Expression);
}
if (ce.Type.IsArray || ce.Value is Array)
return FormatStringArray(ce.Value, name, ce.Type);
else if (ce.Value is IEnumerable)
return FormatStringEnumerable(ce.Value, name, ce.Type);
//TODO: sql injection!?
return "(SELECT {0} FROM dual) \"{1}\"".With(ce.Value, name);
}
var mce = queryable.Expression as MethodCallExpression;
if (mce != null && mce.Method.DeclaringType == typeof(System.Linq.Queryable) && mce.Method.Name == "Cast")
return GetQuerySourceFromExpression(name, queryable.ElementType, mce.Arguments[0]);
throw new NotSupportedException("unknown query source expression!");
}
private static string FromSqlSource(string name, Type type)
{
var source = SqlSourceAttribute.FindSource(type);
if (!string.IsNullOrEmpty(source))
return "{0} \"{1}\"".With(source, name);
throw new NotSupportedException(@"Unknown sql source {0}!
Add {1} attribute or {2} or {3} or {4} interface".With(
type.FullName,
typeof(SqlSourceAttribute).FullName,
typeof(IAggregateRoot).FullName,
typeof(IIdentifiable).FullName,
typeof(IEntity).FullName));
}
class ColumnValue
{
public string Name;
public Type Type;
public Func<object, object> GetValue;
public ColumnValue(System.Reflection.PropertyInfo pi)
{
Name = pi.Name;
Type = pi.PropertyType;
GetValue = (object v) => pi.GetValue(v, null);
}
public ColumnValue(System.Reflection.FieldInfo fi)
{
Name = fi.Name;
Type = fi.FieldType;
GetValue = (object v) => fi.GetValue(v);
}
public string GetBackendValue(object value)
{
//TODO fix later
//return NpgsqlTypes.TypeConverter.Convert(Type, GetValue(value));
return value.ToString();
}
}
private string FormatStringArray(object value, string name, Type type)
{
if (value != null)
{
var array = ((Array)value).Cast<object>().ToArray();
if (array.Length > 0)
return FormatStringValues(name, type, array);
}
if (value != null)
type = value.GetType();
var elementType = type.GetElementType();
return "(SELECT * FROM {1} WHERE 1=0) \"{0}\"".With(name, FromSqlSource("sq", elementType));
}
private string FormatStringEnumerable(object value, string name, Type type)
{
if (value != null)
{
var array = ((IEnumerable)value).Cast<object>().ToArray();
if (array.Length > 0)
return FormatStringValues(name, type, array);
}
if (value != null)
type = value.GetType();
var elementType = type.GetElementType();
if (type.IsGenericTypeDefinition)
elementType = type.GetGenericArguments()[0];
return "(SELECT * FROM {1} WHERE 1=0) \"{0}\"".With(name, FromSqlSource("sq", elementType));
}
private string FormatStringValues(string name, Type type, object[] array)
{
//TODO find best type
var firstElem = array.FirstOrDefault(it => it != null);
var element = firstElem != null ? firstElem.GetType()
: type.IsArray ? type.GetElementType()
: type.IsGenericType ? type.GetGenericArguments()[0]
: null;
if (element == null)
throw new ArgumentException("Can't convert collection");
if (Context.CanUseParams)
{
var paramFactory = ConverterFactory.GetVarrayParameterFactory(element);
if (paramFactory != null)
{
var pn = Parameters.Add(paramFactory(array));
return "(SELECT * FROM TABLE({0})) \"{1}\"".With(pn, name);
}
}
var stringFactory = ConverterFactory.GetVarrayStringFactory(element);
if (stringFactory == null)
throw new NotSupportedException("Unable to convert collection " + type.FullName);
return "(SELECT * FROM TABLE({0})) \"{1}\"".With(stringFactory(array), name);
}
protected virtual void ProcessResultOperators(StringBuilder sb)
{
ProcessSetOperators(
sb,
ResultOperators
.Where(it => it is ExceptResultOperator || it is IntersectResultOperator
|| it is UnionResultOperator || it is ConcatResultOperator)
.ToList());
ProcessGroupOperators(
sb,
ResultOperators.FindAll(it => it is GroupResultOperator).Cast<GroupResultOperator>().ToList());
ProcessLimitAndOffsetOperators(
sb,
ResultOperators.FindAll(it => it is TakeResultOperator).Cast<TakeResultOperator>().ToList(),
ResultOperators.FindAll(it => it is SkipResultOperator).Cast<SkipResultOperator>().ToList(),
ResultOperators.FindAll(it => it is FirstResultOperator).Cast<FirstResultOperator>().ToList(),
ResultOperators.FindAll(it => it is SingleResultOperator).Cast<SingleResultOperator>().ToList());
ProcessInOperators(
sb,
ResultOperators.FindAll(it => it is ContainsResultOperator).Cast<ContainsResultOperator>().ToList());
ProcessAllOperators(
sb,
ResultOperators.FindAll(it => it is AllResultOperator).Cast<AllResultOperator>().ToList());
if (ResultOperators.Exists(it => it is CountResultOperator || it is LongCountResultOperator))
ProcessCountOperators(sb);
if (ResultOperators.Exists(it => it is AnyResultOperator))
ProcessAnyOperators(sb);
}
private void ProcessSetOperators(StringBuilder sb, List<ResultOperatorBase> operators)
{
operators.ForEach(it =>
{
sb.AppendLine();
var ero = it as ExceptResultOperator;
var iro = it as IntersectResultOperator;
var uro = it as UnionResultOperator;
var cro = it as ConcatResultOperator;
if (ero != null)
{
sb.AppendLine("EXCEPT");
sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(ero.Source2, this));
}
else if (iro != null)
{
sb.AppendLine("INTERSECT");
sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(iro.Source2, this));
}
else
{
SubQueryExpression sqe;
if (uro != null)
{
sb.AppendLine("UNION");
sqe = uro.Source2 as SubQueryExpression;
}
else
{
sb.AppendLine("UNION ALL");
sqe = cro.Source2 as SubQueryExpression;
}
//TODO if order is used, Oracle will fail anyway
foreach (var ro in ResultOperators)
{
if (ro is UnionResultOperator == false && ro is ConcatResultOperator == false)
sqe.QueryModel.ResultOperators.Add(ro);
}
sb.AppendLine(SqlGeneratorExpressionTreeVisitor.GetSqlExpression(sqe, this));
}
});
}
protected virtual void ProcessGroupOperators(StringBuilder sb, List<GroupResultOperator> groupBy)
{
if (groupBy.Count > 1)
throw new NotSupportedException("More than one group operator!?");
else if (groupBy.Count == 1)
{
var group = groupBy[0];
sb.AppendLine("GROUP BY");
sb.AppendLine(GetSqlExpression(group.KeySelector));
}
}
protected virtual void ProcessLimitAndOffsetOperators(
StringBuilder sb,
List<TakeResultOperator> limit,
List<SkipResultOperator> offset,
List<FirstResultOperator> first,
List<SingleResultOperator> single)
{
if (first.Count == 1)
{
if (offset.Count == 0)
{
sb.Insert(0, "SELECT * FROM (");
sb.Append(") sq WHERE RowNum = 1");
}
if (offset.Count == 1)
{
var exp = GetSqlExpression(offset[0].Count);
sb.Insert(0, "SELECT * FROM ( SELECT /*+ FIRST_ROWS(n) */ sq.*, RowNum rn$ FROM (");
sb.Append(") sq WHERE RowNum <= 1 + ");
sb.Append(exp);
sb.Append(") WHERE rn$ > ");
sb.Append(exp);
CurrentSelectIndex++;
}
}
else if (single.Count == 1)
{
var minLimit = "2";
if (limit.Count != 0)
{
if (limit.TrueForAll(it => it.Count is ConstantExpression))
{
var min = limit.Min(it => (int)(it.Count as ConstantExpression).Value);
if (min > 1) min = 2;
minLimit = min.ToString();
}
else
{
minLimit = "LEAST(2," + string.Join(", ", limit.Select(it => GetSqlExpression(it.Count))) + ")";
}
}
if (offset.Count == 0)
{
sb.Insert(0, "SELECT * FROM (");
sb.Append(") sq WHERE RowNum <= ");
sb.Append(minLimit);
}
if (offset.Count == 1)
{
var exp = GetSqlExpression(offset[0].Count);
sb.Insert(0, "SELECT * FROM ( SELECT /*+ FIRST_ROWS(n) */ sq.*, RowNum rn$ FROM (");
sb.Append(") sq WHERE RowNum <= ");
sb.Append(minLimit);
sb.Append(" + ");
sb.Append(exp);
sb.Append(") WHERE rn$ > ");
sb.Append(exp);
CurrentSelectIndex++;
}
}
else if (limit.Count > 0 && offset.Count == 0)
{
sb.Insert(0, "SELECT * FROM (");
sb.Append(") sq WHERE RowNum <= ");
if (limit.Count > 1)
sb.Append("LEAST(")
.Append(
string.Join(
", ",
limit.Select(it => GetSqlExpression(it.Count))))
.AppendLine(")");
else sb.AppendLine(GetSqlExpression(limit[0].Count));
}
else if (limit.Count == 0 && offset.Count > 0)
{
sb.Insert(0, "SELECT * FROM ( SELECT /*+ FIRST_ROWS(n) */ sq.*, RowNum rn$ FROM (");
sb.Append(") sq ) WHERE rn$ > ");
sb.Append(GetSqlExpression(offset[0].Count));
for (int i = 1; i < offset.Count; i++)
sb.Append(" + " + GetSqlExpression(offset[i].Count));
CurrentSelectIndex++;
}
else if (limit.Count == 1 && offset.Count == 1)
{
sb.Insert(0, "SELECT * FROM ( SELECT /*+ FIRST_ROWS(n) */ sq.*, RowNum rn$ FROM (");
sb.Append(") sq WHERE RowNum <= ");
if (ResultOperators.IndexOf(limit[0]) < ResultOperators.IndexOf(offset[0]))
sb.AppendLine(GetSqlExpression(limit[0].Count));
else
sb.AppendLine("{0} + {1}".With(GetSqlExpression(limit[0].Count), GetSqlExpression(offset[0].Count)));
sb.Append(") WHERE rn$ > ");
sb.AppendLine(GetSqlExpression(offset[0].Count));
CurrentSelectIndex++;
}
else if (limit.Count > 1 || offset.Count > 1)
throw new NotSupportedException("Unsupported combination of limits and offsets in query. More than one offset and more than one limit found.");
}
protected virtual void ProcessInOperators(StringBuilder sb, List<ContainsResultOperator> contains)
{
if (contains.Count > 1)
throw new FrameworkException("More than one contains operator!?");
else if (contains.Count == 1)
{
sb.Insert(0, GetSqlExpression(contains[0].Item) + " IN (");
sb.Append(")");
}
}
protected virtual void ProcessAllOperators(StringBuilder sb, List<AllResultOperator> all)
{
if (all.Count > 1)
throw new FrameworkException("More than one all operator!?");
else if (all.Count == 1)
{
sb.Insert(0, "SELECT NOT EXISTS(SELECT * FROM (");
var where = GetSqlExpression(all[0].Predicate);
sb.Append(") sq WHERE (" + where + ") = false)");
}
}
protected virtual void ProcessCountOperators(StringBuilder sb)
{
sb.Insert(0, "SELECT COUNT(*) FROM (");
sb.Append(") sq ");
}
protected virtual void ProcessAnyOperators(StringBuilder sb)
{
//TODO hack to detect bool result
if (Context.InSelect)
{
sb.Insert(0, "CASE WHEN EXISTS(");
sb.Append(") THEN 'Y' ELSE 'N' END");
}
else if (Context.InWhere)
{
sb.Insert(0, "EXISTS(");
sb.Append(")");
}
else
{
sb.Insert(0, "SELECT CASE WHEN EXISTS(");
sb.Append(") THEN 'Y' ELSE 'N' END FROM dual");
}
Selects.Clear();
CurrentSelectIndex = 0;
AddSelectPart(MainFrom, sb.ToString(), "sq", typeof(bool), (_, dr) => dr.GetString(0) == "Y");
}
protected string BuildCountQuery(ResultOperatorBase countOperator)
{
Selects.Clear();
CurrentSelectIndex = 0;
var sb = new StringBuilder();
sb.Append("SELECT ");
if (countOperator is LongCountResultOperator)
AddSelectPart(MainFrom, "COUNT(*)", "count", typeof(long), (_, dr) => (long)dr.GetDecimal(0));
else
AddSelectPart(MainFrom, "COUNT(*)", "count", typeof(int), (_, dr) => (int)dr.GetDecimal(0));
sb.AppendLine("COUNT(*)");
sb.Append(GetFromPart());
sb.Append(GetWherePart());
return sb.ToString();
}
protected string BuildAnyQuery()
{
var sb = new StringBuilder();
if (Context.InSelect)
{
Selects.Clear();
CurrentSelectIndex = 0;
sb.Append("CASE WHEN ");
AddSelectPart(MainFrom, "sq", "any", typeof(bool), (_, dr) => dr.GetString(0) == "Y");
}
sb.Append("EXISTS(SELECT * ");
sb.Append(GetFromPart());
sb.Append(GetWherePart());
sb.Append(")");
if (Context.InSelect)
sb.Append(" THEN 'Y' ELSE 'N' END");
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using org.apache.zookeeper;
using org.apache.zookeeper.data;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OrleansZooKeeperUtils.Configuration;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;
namespace Orleans.Runtime.Membership
{
/// <summary>
/// A Membership Table implementation using Apache Zookeeper 3.4.6 https://zookeeper.apache.org/doc/r3.4.6/
/// </summary>
/// <remarks>
/// A brief overview of ZK features used: The data is represented by a tree of nodes (similar to a file system).
/// Every node is addressed by a path and can hold data as a byte array and has a version. When a node is created,
/// its version is 0. Upon updates, the version is atomically incremented. An update can also be conditional on an
/// expected current version. A transaction can hold several operations, which succeed or fail atomically.
/// when creating a zookeeper client, one can set a base path where all operations are relative to.
///
/// In this implementation:
/// Every Orleans deployment has a node /UniqueDeploymentId
/// Every Silo's state is saved in /UniqueDeploymentId/IP:Port@Gen
/// Every Silo's IAmAlive is saved in /UniqueDeploymentId/IP:Port@Gen/IAmAlive
/// IAmAlive is saved in a separate node because its updates are unconditional.
///
/// a node's ZK version is its ETag:
/// the table version is the version of /UniqueDeploymentId
/// the silo entry version is the version of /UniqueDeploymentId/IP:Port@Gen
/// </remarks>
public class ZooKeeperBasedMembershipTable : IMembershipTable
{
private ILogger logger;
private const int ZOOKEEPER_CONNECTION_TIMEOUT = 2000;
private ZooKeeperWatcher watcher;
/// <summary>
/// The deployment connection string. for eg. "192.168.1.1,192.168.1.2/DeploymentId"
/// </summary>
private string deploymentConnectionString;
/// <summary>
/// the node name for this deployment. for eg. /DeploymentId
/// </summary>
private string deploymentPath;
/// <summary>
/// The root connection string. for eg. "192.168.1.1,192.168.1.2"
/// </summary>
private string rootConnectionString;
public ZooKeeperBasedMembershipTable(ILogger<ZooKeeperBasedMembershipTable> logger, IOptions<ZooKeeperMembershipOptions> membershipTableOptions, GlobalConfiguration globalConfiguration)
{
this.logger = logger;
var options = membershipTableOptions.Value;
watcher = new ZooKeeperWatcher(logger);
InitConfig(options.ConnectionString, globalConfiguration.DeploymentId);
}
/// <summary>
/// Initializes the ZooKeeper based membership table.
/// </summary>
/// <param name="tryInitPath">if set to true, we'll try to create a node named "/DeploymentId"</param>
/// <returns></returns>
public async Task InitializeMembershipTable(bool tryInitPath)
{
// even if I am not the one who created the path,
// try to insert an initial path if it is not already there,
// so we always have the path, before this silo starts working.
// note that when a zookeeper connection adds /DeploymentId to the connection string, the nodes are relative
await UsingZookeeper(rootConnectionString, async zk =>
{
try
{
await zk.createAsync(deploymentPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
await zk.sync(deploymentPath);
//if we got here we know that we've just created the deployment path with version=0
this.logger.Info("Created new deployment path: " + deploymentPath);
}
catch (KeeperException.NodeExistsException)
{
this.logger.Debug("Deployment path already exists: " + deploymentPath);
}
});
}
private void InitConfig(string dataConnectionString, string deploymentId)
{
deploymentPath = "/" + deploymentId;
deploymentConnectionString = dataConnectionString + deploymentPath;
rootConnectionString = dataConnectionString;
}
/// <summary>
/// Atomically reads the Membership Table information about a given silo.
/// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the
/// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically.
/// </summary>
/// <param name="siloAddress">The address of the silo whose membership information needs to be read.</param>
/// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and
/// TableVersion, read atomically.</returns>
public Task<MembershipTableData> ReadRow(SiloAddress siloAddress)
{
return UsingZookeeper(async zk =>
{
var getRowTask = GetRow(zk, siloAddress);
var getTableNodeTask = zk.getDataAsync("/");//get the current table version
List<Tuple<MembershipEntry, string>> rows = new List<Tuple<MembershipEntry, string>>(1);
try
{
await Task.WhenAll(getRowTask, getTableNodeTask);
rows.Add(await getRowTask);
}
catch (KeeperException.NoNodeException)
{
//that's ok because orleans expects an empty list in case of a missing row
}
var tableVersion = ConvertToTableVersion((await getTableNodeTask).Stat);
return new MembershipTableData(rows, tableVersion);
}, this.deploymentConnectionString, this.watcher, true);
}
/// <summary>
/// Atomically reads the full content of the Membership Table.
/// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the
/// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically.
/// </summary>
/// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and
/// TableVersion, all read atomically.</returns>
public Task<MembershipTableData> ReadAll()
{
return ReadAll(this.deploymentConnectionString, this.watcher);
}
internal static Task<MembershipTableData> ReadAll(string deploymentConnectionString, ZooKeeperWatcher watcher)
{
return UsingZookeeper(async zk =>
{
var childrenResult = await zk.getChildrenAsync("/");//get all the child nodes (without the data)
var childrenTasks = //get the data from each child node
childrenResult.Children.Select(child => GetRow(zk, SiloAddress.FromParsableString(child))).ToList();
var childrenTaskResults = await Task.WhenAll(childrenTasks);
var tableVersion = ConvertToTableVersion(childrenResult.Stat);//this is the current table version
return new MembershipTableData(childrenTaskResults.ToList(), tableVersion);
}, deploymentConnectionString, watcher, true);
}
/// <summary>
/// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) New MembershipEntry will be added to the table.
/// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo already exist in the table
/// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be inserted.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the insert operation succeeded and false otherwise.</returns>
public Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowData = Serialize(entry);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.create(rowPath, newRowData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
.create(rowIAmAlivePath, newRowIAmAliveData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
}
/// <summary>
/// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry)
/// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo does not exist in the table
/// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag.
/// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be updated.</param>
/// <param name="etag">The etag for the given MembershipEntry.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the update operation succeeded and false otherwise.</returns>
public Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
string rowPath = ConvertToRowPath(entry.SiloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
var newRowData = Serialize(entry);
var newRowIAmAliveData = Serialize(entry.IAmAliveTime);
int expectedTableVersion = int.Parse(tableVersion.VersionEtag, CultureInfo.InvariantCulture);
int expectedRowVersion = int.Parse(etag, CultureInfo.InvariantCulture);
return TryTransaction(t => t
.setData("/", null, expectedTableVersion)//increments the version of node "/"
.setData(rowPath, newRowData, expectedRowVersion)//increments the version of node "/IP:Port@Gen"
.setData(rowIAmAlivePath, newRowIAmAliveData));
}
/// <summary>
/// Updates the IAmAlive part (column) of the MembershipEntry for this silo.
/// This operation should only update the IAmAlive collumn and not change other columns.
/// This operation is a "dirty write" or "in place update" and is performed without etag validation.
/// With regards to eTags update:
/// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write").
/// With regards to TableVersion:
/// this operation should not change the TableVersion of the table. It should leave it untouched.
/// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability.
/// </summary>
/// <param name="entry">The target MembershipEntry tp update</param>
/// <returns>Task representing the successful execution of this operation. </returns>
public Task UpdateIAmAlive(MembershipEntry entry)
{
string rowIAmAlivePath = ConvertToRowIAmAlivePath(entry.SiloAddress);
byte[] newRowIAmAliveData = Serialize(entry.IAmAliveTime);
//update the data for IAmAlive unconditionally
return UsingZookeeper(zk => zk.setDataAsync(rowIAmAlivePath, newRowIAmAliveData), this.deploymentConnectionString, this.watcher);
}
/// <summary>
/// Deletes all table entries of the given deploymentId
/// </summary>
public Task DeleteMembershipTableEntries(string deploymentId)
{
string pathToDelete = "/" + deploymentId;
return UsingZookeeper(rootConnectionString, async zk =>
{
await ZKUtil.deleteRecursiveAsync(zk, pathToDelete);
await zk.sync(pathToDelete);
});
}
private async Task<bool> TryTransaction(Func<Transaction, Transaction> transactionFunc)
{
try
{
await UsingZookeeper(zk => transactionFunc(zk.transaction()).commitAsync(), this.deploymentConnectionString, this.watcher);
return true;
}
catch (KeeperException e)
{
//these exceptions are thrown when the transaction fails to commit due to semantical reasons
if (e is KeeperException.NodeExistsException || e is KeeperException.NoNodeException ||
e is KeeperException.BadVersionException)
{
return false;
}
throw;
}
}
/// <summary>
/// Reads the nodes /IP:Port@Gen and /IP:Port@Gen/IAmAlive (which together is one row)
/// </summary>
/// <param name="zk">The zookeeper instance used for the read</param>
/// <param name="siloAddress">The silo address.</param>
private static async Task<Tuple<MembershipEntry, string>> GetRow(ZooKeeper zk, SiloAddress siloAddress)
{
string rowPath = ConvertToRowPath(siloAddress);
string rowIAmAlivePath = ConvertToRowIAmAlivePath(siloAddress);
var rowDataTask = zk.getDataAsync(rowPath);
var rowIAmAliveDataTask = zk.getDataAsync(rowIAmAlivePath);
await Task.WhenAll(rowDataTask, rowIAmAliveDataTask);
MembershipEntry me = Deserialize<MembershipEntry>((await rowDataTask).Data);
me.IAmAliveTime = Deserialize<DateTime>((await rowIAmAliveDataTask).Data);
int rowVersion = (await rowDataTask).Stat.getVersion();
return new Tuple<MembershipEntry, string>(me, rowVersion.ToString(CultureInfo.InvariantCulture));
}
private static Task<T> UsingZookeeper<T>(Func<ZooKeeper, Task<T>> zkMethod, string deploymentConnectionString, ZooKeeperWatcher watcher, bool canBeReadOnly = false)
{
return ZooKeeper.Using(deploymentConnectionString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod, canBeReadOnly);
}
private Task UsingZookeeper(string connectString, Func<ZooKeeper, Task> zkMethod)
{
return ZooKeeper.Using(connectString, ZOOKEEPER_CONNECTION_TIMEOUT, watcher, zkMethod);
}
private static string ConvertToRowPath(SiloAddress siloAddress)
{
return "/" + siloAddress.ToParsableString();
}
private static string ConvertToRowIAmAlivePath(SiloAddress siloAddress)
{
return ConvertToRowPath(siloAddress) + "/IAmAlive";
}
private static TableVersion ConvertToTableVersion(Stat stat)
{
int version = stat.getVersion();
return new TableVersion(version, version.ToString(CultureInfo.InvariantCulture));
}
private static byte[] Serialize(object obj)
{
return
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj, Formatting.None,
MembershipSerializerSettings.Instance));
}
private static T Deserialize<T>(byte[] data)
{
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data), MembershipSerializerSettings.Instance);
}
}
/// <summary>
/// the state of every ZooKeeper client and its push notifications are published using watchers.
/// in orleans the watcher is only for debugging purposes
/// </summary>
internal class ZooKeeperWatcher : Watcher
{
private readonly ILogger logger;
public ZooKeeperWatcher(ILogger logger)
{
this.logger = logger;
}
public override Task process(WatchedEvent @event)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.Debug(@event.ToString());
}
return Task.CompletedTask;
}
}
}
| |
//
// Copyright 2011-2014, Xamarin 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.Expressions;
using System.Reflection;
using Android.Provider;
using Uri = Android.Net.Uri;
namespace Xamarin.Contacts
{
internal class ContactTableFinder
: ExpressionVisitor,
ITableFinder
{
private String mimeType;
private Uri table;
public Uri DefaultTable
{
get
{
return (UseRawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri;
}
}
public Boolean UseRawContacts { get; set; }
public TableFindResult Find( Expression expression )
{
Visit( expression );
var result = new TableFindResult( table, mimeType );
table = null;
mimeType = null;
return result;
}
public ContentResolverColumnMapping GetColumn( MemberInfo member )
{
if(member.DeclaringType == typeof(Contact))
{
return GetContactColumn( member );
}
if(member.DeclaringType == typeof(Email))
{
return GetEmailColumn( member );
}
if(member.DeclaringType == typeof(Phone))
{
return GetPhoneColumn( member );
}
if(member.DeclaringType == typeof(Address))
{
return GetAddressColumn( member );
}
if(member.DeclaringType == typeof(Relationship))
{
return GetRelationshipColumn( member );
}
if(member.DeclaringType == typeof(InstantMessagingAccount))
{
return GetImColumn( member );
}
if(member.DeclaringType == typeof(Website))
{
return GetWebsiteColumn( member );
}
if(member.DeclaringType == typeof(Organization))
{
return GetOrganizationColumn( member );
}
if(member.DeclaringType == typeof(Note))
{
return GetNoteColumn( member );
}
return null;
}
public Boolean IsSupportedType( Type type )
{
return type == typeof(Contact) || type == typeof(Phone) || type == typeof(Email) || type == typeof(Address) ||
type == typeof(Relationship) || type == typeof(InstantMessagingAccount) || type == typeof(Website) ||
type == typeof(Organization) || type == typeof(Note);
}
protected override Expression VisitMember( MemberExpression member )
{
member = (MemberExpression)base.VisitMember( member );
if(table == null)
{
if(member.Member.DeclaringType == typeof(Contact))
{
table = GetContactTable( member );
}
else if(member.Member.DeclaringType == typeof(Phone))
{
table = ContactsContract.CommonDataKinds.Phone.ContentUri;
}
else if(member.Member.DeclaringType == typeof(Email))
{
table = ContactsContract.CommonDataKinds.Email.ContentUri;
}
}
return member;
}
private ContentResolverColumnMapping GetAddressColumn( MemberInfo member )
{
switch(member.Name)
{
case "City":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredPostal.City,
typeof(String) );
case "Region":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredPostal.Region,
typeof(String) );
case "Country":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredPostal.Country,
typeof(String) );
case "PostalCode":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredPostal.Postcode,
typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetContactColumn( MemberInfo member )
{
switch(member.Name)
{
case "DisplayName":
return new ContentResolverColumnMapping( ContactsContract.ContactsColumns.DisplayName, typeof(String) );
case "Prefix":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredName.Prefix,
typeof(String) );
case "FirstName":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredName.GivenName,
typeof(String) );
case "LastName":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredName.FamilyName,
typeof(String) );
case "Suffix":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.StructuredName.Suffix,
typeof(String) );
case "Phones":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Phone>) );
case "Emails":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Email>) );
case "Addresses":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Address>) );
case "Notes":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Note>) );
case "Relationships":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Relationship>) );
case "InstantMessagingAccounts":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<InstantMessagingAccount>) );
case "Websites":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Website>) );
case "Organizations":
return new ContentResolverColumnMapping( (String)null, typeof(IEnumerable<Organization>) );
default:
return null;
}
}
private Uri GetContactTable( MemberExpression expression )
{
switch(expression.Member.Name)
{
case "DisplayName":
return (UseRawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri;
case "Prefix":
case "FirstName":
case "MiddleName":
case "LastName":
case "Suffix":
mimeType = ContactsContract.CommonDataKinds.StructuredName.ContentItemType;
return ContactsContract.Data.ContentUri;
case "Relationships":
mimeType = ContactsContract.CommonDataKinds.Relation.ContentItemType;
return ContactsContract.Data.ContentUri;
case "Organizations":
mimeType = ContactsContract.CommonDataKinds.Organization.ContentItemType;
return ContactsContract.Data.ContentUri;
case "Notes":
mimeType = ContactsContract.CommonDataKinds.Note.ContentItemType;
return ContactsContract.Data.ContentUri;
case "Phones":
return ContactsContract.CommonDataKinds.Phone.ContentUri;
case "Emails":
return ContactsContract.CommonDataKinds.Email.ContentUri;
case "Addresses":
return ContactsContract.CommonDataKinds.StructuredPostal.ContentUri;
case "Websites":
mimeType = ContactsContract.CommonDataKinds.Website.ContentItemType;
return ContactsContract.Data.ContentUri;
case "InstantMessagingAccounts":
mimeType = ContactsContract.CommonDataKinds.Im.ContentItemType;
return ContactsContract.Data.ContentUri;
default:
return null;
}
}
private ContentResolverColumnMapping GetEmailColumn( MemberInfo member )
{
switch(member.Name)
{
case "Address":
return new ContentResolverColumnMapping( ContactsContract.DataColumns.Data1, typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetImColumn( MemberInfo member )
{
switch(member.Name)
{
case "Account":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.CommonColumns.Data,
typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetNoteColumn( MemberInfo member )
{
switch(member.Name)
{
case "Contents":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.CommonColumns.Data,
typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetOrganizationColumn( MemberInfo member )
{
switch(member.Name)
{
case "ContactTitle":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.Organization.Title,
typeof(String) );
case "Name":
return new ContentResolverColumnMapping(
ContactsContract.CommonDataKinds.Organization.Company,
typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetPhoneColumn( MemberInfo member )
{
switch(member.Name)
{
case "Number":
return new ContentResolverColumnMapping( ContactsContract.CommonDataKinds.Phone.Number, typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetRelationshipColumn( MemberInfo member )
{
switch(member.Name)
{
case "Name":
return new ContentResolverColumnMapping( ContactsContract.CommonDataKinds.Relation.Name, typeof(String) );
}
return null;
}
private ContentResolverColumnMapping GetWebsiteColumn( MemberInfo member )
{
switch(member.Name)
{
case "Address":
return new ContentResolverColumnMapping( ContactsContract.CommonDataKinds.Website.Url, typeof(String) );
}
return null;
}
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerNegativeCriterionServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerNegativeCriterionRequestObject()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion response = client.GetCustomerNegativeCriterion(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerNegativeCriterionRequestObjectAsync()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerNegativeCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion responseCallSettings = await client.GetCustomerNegativeCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerNegativeCriterion responseCancellationToken = await client.GetCustomerNegativeCriterionAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerNegativeCriterion()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion response = client.GetCustomerNegativeCriterion(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerNegativeCriterionAsync()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerNegativeCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion responseCallSettings = await client.GetCustomerNegativeCriterionAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerNegativeCriterion responseCancellationToken = await client.GetCustomerNegativeCriterionAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerNegativeCriterionResourceNames()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion response = client.GetCustomerNegativeCriterion(request.ResourceNameAsCustomerNegativeCriterionName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerNegativeCriterionResourceNamesAsync()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
GetCustomerNegativeCriterionRequest request = new GetCustomerNegativeCriterionRequest
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
};
gagvr::CustomerNegativeCriterion expectedResponse = new gagvr::CustomerNegativeCriterion
{
ResourceNameAsCustomerNegativeCriterionName = gagvr::CustomerNegativeCriterionName.FromCustomerCriterion("[CUSTOMER_ID]", "[CRITERION_ID]"),
Type = gagve::CriterionTypeEnum.Types.CriterionType.Webpage,
ContentLabel = new gagvc::ContentLabelInfo(),
MobileApplication = new gagvc::MobileApplicationInfo(),
MobileAppCategory = new gagvc::MobileAppCategoryInfo(),
Placement = new gagvc::PlacementInfo(),
YoutubeVideo = new gagvc::YouTubeVideoInfo(),
YoutubeChannel = new gagvc::YouTubeChannelInfo(),
Id = -6774108720365892680L,
};
mockGrpcClient.Setup(x => x.GetCustomerNegativeCriterionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerNegativeCriterion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerNegativeCriterion responseCallSettings = await client.GetCustomerNegativeCriterionAsync(request.ResourceNameAsCustomerNegativeCriterionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerNegativeCriterion responseCancellationToken = await client.GetCustomerNegativeCriterionAsync(request.ResourceNameAsCustomerNegativeCriterionName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerNegativeCriteriaRequestObject()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCustomerNegativeCriteriaRequest request = new MutateCustomerNegativeCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerNegativeCriterionOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerNegativeCriteriaResponse expectedResponse = new MutateCustomerNegativeCriteriaResponse
{
Results =
{
new MutateCustomerNegativeCriteriaResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerNegativeCriteria(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerNegativeCriteriaResponse response = client.MutateCustomerNegativeCriteria(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerNegativeCriteriaRequestObjectAsync()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCustomerNegativeCriteriaRequest request = new MutateCustomerNegativeCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerNegativeCriterionOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerNegativeCriteriaResponse expectedResponse = new MutateCustomerNegativeCriteriaResponse
{
Results =
{
new MutateCustomerNegativeCriteriaResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerNegativeCriteriaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerNegativeCriteriaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerNegativeCriteriaResponse responseCallSettings = await client.MutateCustomerNegativeCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerNegativeCriteriaResponse responseCancellationToken = await client.MutateCustomerNegativeCriteriaAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerNegativeCriteria()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCustomerNegativeCriteriaRequest request = new MutateCustomerNegativeCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerNegativeCriterionOperation(),
},
};
MutateCustomerNegativeCriteriaResponse expectedResponse = new MutateCustomerNegativeCriteriaResponse
{
Results =
{
new MutateCustomerNegativeCriteriaResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerNegativeCriteria(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerNegativeCriteriaResponse response = client.MutateCustomerNegativeCriteria(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerNegativeCriteriaAsync()
{
moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient> mockGrpcClient = new moq::Mock<CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient>(moq::MockBehavior.Strict);
MutateCustomerNegativeCriteriaRequest request = new MutateCustomerNegativeCriteriaRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerNegativeCriterionOperation(),
},
};
MutateCustomerNegativeCriteriaResponse expectedResponse = new MutateCustomerNegativeCriteriaResponse
{
Results =
{
new MutateCustomerNegativeCriteriaResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerNegativeCriteriaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerNegativeCriteriaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerNegativeCriterionServiceClient client = new CustomerNegativeCriterionServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerNegativeCriteriaResponse responseCallSettings = await client.MutateCustomerNegativeCriteriaAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerNegativeCriteriaResponse responseCancellationToken = await client.MutateCustomerNegativeCriteriaAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using gView.Framework.Geometry;
using gView.Framework.Data;
using gView.Framework.UI.Controls.Filter;
using gView.Framework.FDB;
using gView.Framework.UI.Dialogs;
namespace gView.Framework.UI.Controls
{
public partial class SpatialIndexControl : UserControl
{
public enum IndexType { gView = 0, GEOMETRY = 1, GEOGRAPHY = 2 }
private ISpatialReference _sRef = null;
private IndexType _type = IndexType.gView;
public SpatialIndexControl()
{
InitializeComponent();
cmbIndexType.SelectedIndex = 0;
}
public ISpatialReference SpatialReference
{
set { _sRef = value; }
}
public IndexType Type
{
get { return _type; }
set
{
cmbIndexType.SelectedIndex = (int)value;
}
}
#region Extent
public IEnvelope Extent
{
get
{
return new Envelope(
(double)numLeft.Value, (double)numBottom.Value,
(double)numRight.Value, (double)numTop.Value);
}
set
{
if (value == null) return;
numLeft.Value = (decimal)value.minx;
numBottom.Value = (decimal)value.miny;
numRight.Value = (decimal)value.maxx;
numTop.Value = (decimal)value.maxy;
CalcCellSize();
}
}
#endregion
#region Levels
public int Levels
{
get { return (int)numLevels.Value; }
set
{
try
{
numLevels.Value = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void numLevels_ValueChanged(object sender, EventArgs e)
{
CalcCellSize();
}
private void CalcCellSize()
{
BinaryTree2 tree = new BinaryTree2(Extent, (int)numLevels.Value, 100);
IEnvelope cell = tree[(long)numLevels.Value];
numCellSizeX.Value = (decimal)Math.Sqrt(cell.Width * cell.Width + cell.Height * cell.Height);
}
#endregion
#region MSSpatial
public MSSpatialIndex MSIndex
{
get
{
if (_type == IndexType.GEOMETRY)
{
MSSpatialIndex index = new MSSpatialIndex();
index.GeometryType = GeometryFieldType.MsGeometry;
index.SpatialIndexBounds = this.Extent;
index.CellsPerObject = (int)numCellsPerObject.Value;
index.Level1 = (MSSpatialIndexLevelSize)cmbLevel1.SelectedIndex;
index.Level2 = (MSSpatialIndexLevelSize)cmbLevel2.SelectedIndex;
index.Level3 = (MSSpatialIndexLevelSize)cmbLevel3.SelectedIndex;
index.Level4 = (MSSpatialIndexLevelSize)cmbLevel4.SelectedIndex;
return index;
}
else if (_type == IndexType.GEOGRAPHY)
{
MSSpatialIndex index = new MSSpatialIndex();
index.GeometryType = GeometryFieldType.MsGeography;
index.CellsPerObject = (int)numCellsPerObject.Value;
index.Level1 = (MSSpatialIndexLevelSize)cmbLevel1.SelectedIndex;
index.Level2 = (MSSpatialIndexLevelSize)cmbLevel2.SelectedIndex;
index.Level3 = (MSSpatialIndexLevelSize)cmbLevel3.SelectedIndex;
index.Level4 = (MSSpatialIndexLevelSize)cmbLevel4.SelectedIndex;
return index;
}
return null;
}
set
{
// TODO
}
}
#endregion
#region Properties
public ISpatialIndexDef SpatialIndexDef
{
get
{
switch (_type)
{
case IndexType.gView:
return new gViewSpatialIndexDef(
this.Extent,
this.Levels);
case IndexType.GEOMETRY:
case IndexType.GEOGRAPHY:
return MSIndex;
}
return null;
}
set
{
if (value is gViewSpatialIndexDef)
{
gViewSpatialIndexDef gvIndex = (gViewSpatialIndexDef)value;
this.Extent = gvIndex.SpatialIndexBounds;
this.Levels = gvIndex.Levels;
cmbIndexType.SelectedIndex = 0;
}
else if (value is MSSpatialIndex)
{
MSSpatialIndex msIndex = (MSSpatialIndex)value;
this.Extent = new Envelope(msIndex.SpatialIndexBounds);
numCellsPerObject.Value = msIndex.CellsPerObject;
cmbLevel1.SelectedIndex = (int)msIndex.Level1;
cmbLevel2.SelectedIndex = (int)msIndex.Level2;
cmbLevel3.SelectedIndex = (int)msIndex.Level3;
cmbLevel4.SelectedIndex = (int)msIndex.Level4;
if (msIndex.GeometryType == GeometryFieldType.MsGeometry)
{
cmbIndexType.SelectedIndex = 1;
}
else
{
cmbIndexType.SelectedIndex = 2;
}
}
}
}
public bool IndexTypeIsEditable
{
get { return cmbIndexType.Enabled; }
set { cmbIndexType.Enabled = value; }
}
#endregion
private void btnImport_Click(object sender, EventArgs e)
{
List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>();
filters.Add(new OpenDataFilter());
ExplorerDialog dlg = new ExplorerDialog("Import Extent", filters, true);
dlg.MulitSelection = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
IEnvelope bounds = null;
foreach (IExplorerObject exObject in dlg.ExplorerObjects)
{
if (exObject == null || exObject.Object == null) continue;
IEnvelope objEnvelope = null;
if (exObject.Object is IDataset)
{
foreach (IDatasetElement element in ((IDataset)exObject.Object).Elements)
{
if (element == null) continue;
objEnvelope = ClassEnvelope(element.Class);
}
}
else
{
objEnvelope = ClassEnvelope(exObject.Object as IClass);
}
if (objEnvelope != null)
{
if (bounds == null)
bounds = new Envelope(objEnvelope);
else
bounds.Union(objEnvelope);
}
}
if (bounds != null)
{
this.Extent = bounds;
}
}
}
private void btnImportDef_Click(object sender, EventArgs e)
{
List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>();
filters.Add(new OpenFDBFeatureclassFilter());
ExplorerDialog dlg = new ExplorerDialog("Import Spatial Index", filters, true);
dlg.MulitSelection = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
IEnvelope bounds = null;
int levels = 0;
foreach (IExplorerObject exObject in dlg.ExplorerObjects)
{
if (exObject == null || exObject.Object == null) continue;
if (exObject.Object is IFeatureClass &&
((IFeatureClass)exObject.Object).Dataset != null &&
((IFeatureClass)exObject.Object).Dataset.Database is IImplementsBinarayTreeDef)
{
IFeatureClass fc = (IFeatureClass)exObject.Object;
IImplementsBinarayTreeDef fdb = (IImplementsBinarayTreeDef)fc.Dataset.Database;
BinaryTreeDef def = fdb.BinaryTreeDef(fc.Name);
if (def != null)
{
if (bounds == null)
bounds = new Envelope(def.Bounds);
else
bounds.Union(def.Bounds);
levels = Math.Max(levels, def.MaxLevel);
}
}
}
if (bounds != null)
{
this.Extent = bounds;
this.Levels = levels;
}
}
}
private IEnvelope ClassEnvelope(IClass Class)
{
if (Class is IFeatureClass)
{
return ProjectEnvelope(
((IFeatureClass)Class).Envelope,
((IFeatureClass)Class).SpatialReference);
}
else if (Class is IRasterClass && ((IRasterClass)Class).Polygon != null)
{
return ProjectEnvelope(
((IRasterClass)Class).Polygon.Envelope,
((IRasterClass)Class).SpatialReference);
}
return null;
}
private IEnvelope ProjectEnvelope(IEnvelope env, ISpatialReference sRef)
{
if (sRef == null || env == null || _sRef == null) return env;
IGeometry geom = GeometricTransformer.Transform2D(env, sRef, _sRef);
if (geom != null) return geom.Envelope;
return null;
}
private void cmbIndexType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbIndexType.SelectedIndex == 0)
{
panelLevels.Visible = true;
panelRaster.Visible = false;
}
else
{
panelLevels.Visible = false;
panelRaster.Visible = true;
if (cmbLevel1.SelectedIndex == -1)
cmbLevel1.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3);
if (cmbLevel2.SelectedIndex == -1)
cmbLevel2.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3);
if (cmbLevel3.SelectedIndex == -1)
cmbLevel3.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3);
if (cmbLevel4.SelectedIndex == -1)
cmbLevel4.SelectedIndex = (cmbIndexType.SelectedIndex == 1 ? 1 : 3);
}
gpExtent.Enabled = cmbIndexType.SelectedIndex != 2;
_type = (IndexType)cmbIndexType.SelectedIndex;
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class PersistentStorageTests : IDisposable
{
private const int NumThreads = 10;
private const string PersistentFolderPrefix = "PersistentStorageTests_";
private readonly Encoding _encoding = Encoding.UTF8;
private readonly IOptionService _persistentEnabledOptionService = new OptionServiceMock(new Dictionary<IOption, object>
{
{ PersistentStorageOptions.Enabled, true },
{ PersistentStorageOptions.EsentPerformanceMonitor, false }
});
private readonly string _persistentFolder;
private const string Data1 = "Hello ESENT";
private const string Data2 = "Goodbye ESENT";
public PersistentStorageTests()
{
_persistentFolder = Path.Combine(Path.GetTempPath(), PersistentFolderPrefix + Guid.NewGuid());
Directory.CreateDirectory(_persistentFolder);
int workerThreads, completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(Math.Max(workerThreads, NumThreads), completionPortThreads);
}
public void Dispose()
{
if (Directory.Exists(_persistentFolder))
{
Directory.Delete(_persistentFolder, true);
}
}
private void CleanUpPersistentFolder()
{
}
[Fact]
public async Task PersistentService_Solution_WriteReadDifferentInstances()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadDifferentInstances1";
var streamName2 = "PersistentService_Solution_WriteReadDifferentInstances2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
}
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_WriteReadReopenSolution()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadReopenSolution1";
var streamName2 = "PersistentService_Solution_WriteReadReopenSolution2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
}
solution = CreateOrOpenSolution();
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadSameInstance1";
var streamName2 = "PersistentService_Solution_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Project_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_WriteReadSameInstance1";
var streamName2 = "PersistentService_Project_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var project = solution.Projects.Single();
Assert.True(await storage.WriteStreamAsync(project, streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(project, streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(project, streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(project, streamName2)));
}
}
[Fact]
public async Task PersistentService_Document_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_WriteReadSameInstance1";
var streamName2 = "PersistentService_Document_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var document = solution.Projects.Single().Documents.Single();
Assert.True(await storage.WriteStreamAsync(document, streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(document, streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(document, streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(document, streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public async Task PersistentService_Project_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single(), streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public async Task PersistentService_Document_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
private void DoSimultaneousWrites(Func<string, Task> write)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
int id = (int)s;
barrier.SignalAndWait();
write(id + "").Wait();
countdown.Signal();
}, i);
}
countdown.Wait();
}
[Fact]
public async Task PersistentService_Solution_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(streamName1)), Data1);
}
}
[Fact]
public async Task PersistentService_Project_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single(), streamName1)), Data1);
}
}
[Fact]
public async Task PersistentService_Document_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1)), Data1);
}
}
private void DoSimultaneousReads(Func<Task<string>> read, string expectedValue)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
Task.Run(async () =>
{
barrier.SignalAndWait();
Assert.Equal(expectedValue, await read());
countdown.Signal();
});
}
countdown.Wait();
}
[Fact]
public async Task PersistentService_IdentifierSet()
{
var solution = CreateOrOpenSolution();
var newId = DocumentId.CreateNewId(solution.ProjectIds[0]);
string documentFile = Path.Combine(Path.GetDirectoryName(solution.FilePath), "IdentifierSet.cs");
File.WriteAllText(documentFile, @"
class A
{
public int Test(int i, A a)
{
return a;
}
}");
var newSolution = solution.AddDocument(DocumentInfo.Create(newId, "IdentifierSet", loader: new FileTextLoader(documentFile, Encoding.UTF8), filePath: documentFile));
using (var storage = GetStorage(newSolution))
{
var syntaxTreeStorage = storage as ISyntaxTreeInfoPersistentStorage;
Assert.NotNull(syntaxTreeStorage);
var document = newSolution.GetDocument(newId);
var version = await document.GetSyntaxVersionAsync();
var root = await document.GetSyntaxRootAsync();
Assert.True(syntaxTreeStorage.WriteIdentifierLocations(document, version, root, CancellationToken.None));
Assert.Equal(version, syntaxTreeStorage.GetIdentifierSetVersion(document));
List<int> positions = new List<int>();
Assert.True(syntaxTreeStorage.ReadIdentifierPositions(document, version, "Test", positions, CancellationToken.None));
Assert.Equal(1, positions.Count);
Assert.Equal(29, positions[0]);
}
}
private Solution CreateOrOpenSolution()
{
string solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
bool newSolution;
if (newSolution = !File.Exists(solutionFile))
{
File.WriteAllText(solutionFile, "");
}
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile);
var workspace = new AdhocWorkspace();
workspace.AddSolution(info);
var solution = workspace.CurrentSolution;
if (newSolution)
{
string projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
File.WriteAllText(projectFile, "");
solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp, projectFile));
var project = solution.Projects.Single();
string documentFile = Path.Combine(Path.GetDirectoryName(projectFile), "Document1.cs");
File.WriteAllText(documentFile, "");
solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1", filePath: documentFile));
}
return solution;
}
private IPersistentStorage GetStorage(Solution solution)
{
var storage = new PersistentStorageService(_persistentEnabledOptionService, testing: true).GetStorage(solution);
Assert.NotEqual(PersistentStorageService.NoOpPersistentStorageInstance, storage);
return storage;
}
private Stream EncodeString(string text)
{
var bytes = _encoding.GetBytes(text);
var stream = new MemoryStream(bytes);
return stream;
}
private string ReadStringToEnd(Stream stream)
{
using (stream)
{
var bytes = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
count = stream.Read(bytes, count, (int)stream.Length - count);
}
return _encoding.GetString(bytes);
}
}
}
}
| |
/*
*************************************************************************
** Custom classes used by C#
*************************************************************************
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
#if SQLITE_WINRT
using System.Reflection;
#endif
using i64 = System.Int64;
using u32 = System.UInt32;
using time_t = System.Int64;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
static int atoi( byte[] inStr )
{
return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) );
}
static int atoi( string inStr )
{
int i;
for ( i = 0; i < inStr.Length; i++ )
{
if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' )
break;
}
int result = 0;
#if WINDOWS_MOBILE
try { result = Int32.Parse(inStr.Substring(0, i)); }
catch { }
return result;
#else
return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 );
#endif
}
static void fprintf( TextWriter tw, string zFormat, params object[] ap )
{
tw.Write( sqlite3_mprintf( zFormat, ap ) );
}
static void printf( string zFormat, params object[] ap )
{
#if !SQLITE_WINRT
Console.Out.Write( sqlite3_mprintf( zFormat, ap ) );
#endif
}
//Byte Buffer Testing
static int memcmp( byte[] bA, byte[] bB, int Limit )
{
if ( bA.Length < Limit )
return ( bA.Length < bB.Length ) ? -1 : +1;
if ( bB.Length < Limit )
return +1;
for ( int i = 0; i < Limit; i++ )
{
if ( bA[i] != bB[i] )
return ( bA[i] < bB[i] ) ? -1 : 1;
}
return 0;
}
//Byte Buffer & String Testing
static int memcmp( string A, byte[] bB, int Limit )
{
if ( A.Length < Limit )
return ( A.Length < bB.Length ) ? -1 : +1;
if ( bB.Length < Limit )
return +1;
char[] cA = A.ToCharArray();
for ( int i = 0; i < Limit; i++ )
{
if ( cA[i] != bB[i] )
return ( cA[i] < bB[i] ) ? -1 : 1;
}
return 0;
}
//byte with Offset & String Testing
static int memcmp( byte[] a, int Offset, byte[] b, int Limit )
{
if ( a.Length < Offset + Limit )
return ( a.Length - Offset < b.Length ) ? -1 : +1;
if ( b.Length < Limit )
return +1;
for ( int i = 0; i < Limit; i++ )
{
if ( a[i + Offset] != b[i] )
return ( a[i + Offset] < b[i] ) ? -1 : 1;
}
return 0;
}
//byte with Offset & String Testing
static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit )
{
if ( a.Length < Aoffset + Limit )
return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1;
if ( b.Length < Boffset + Limit )
return +1;
for ( int i = 0; i < Limit; i++ )
{
if ( a[i + Aoffset] != b[i + Boffset] )
return ( a[i + Aoffset] < b[i + Boffset] ) ? -1 : 1;
}
return 0;
}
static int memcmp( byte[] a, int Offset, string b, int Limit )
{
if ( a.Length < Offset + Limit )
return ( a.Length - Offset < b.Length ) ? -1 : +1;
if ( b.Length < Limit )
return +1;
for ( int i = 0; i < Limit; i++ )
{
if ( a[i + Offset] != b[i] )
return ( a[i + Offset] < b[i] ) ? -1 : 1;
}
return 0;
}
//String Testing
static int memcmp( string A, string B, int Limit )
{
if ( A.Length < Limit )
return ( A.Length < B.Length ) ? -1 : +1;
if ( B.Length < Limit )
return +1;
int rc;
if ( ( rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal ) ) == 0 )
return 0;
return rc < 0 ? -1 : +1;
}
// ----------------------------
// ** Builtin Functions
// ----------------------------
static Regex oRegex = null;
/*
** The regexp() function. two arguments are both strings
** Collating sequences are not used.
*/
static void regexpFunc(
sqlite3_context context,
int argc,
sqlite3_value[] argv
)
{
string zTest; /* The input string A */
string zRegex; /* The regex string B */
Debug.Assert( argc == 2 );
UNUSED_PARAMETER( argc );
zRegex = sqlite3_value_text( argv[0] );
zTest = sqlite3_value_text( argv[1] );
if ( zTest == null || String.IsNullOrEmpty( zRegex ) )
{
sqlite3_result_int( context, 0 );
return;
}
if ( oRegex == null || oRegex.ToString() == zRegex )
{
oRegex = new Regex( zRegex, RegexOptions.IgnoreCase );
}
sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 );
}
// ----------------------------
// ** Convertion routines
// ----------------------------
static Object lock_va_list = new Object();
static string vaFORMAT;
static int vaNEXT;
static void va_start( object[] ap, string zFormat )
{
vaFORMAT = zFormat;
vaNEXT = 0;
}
static Boolean va_arg( object[] ap, Boolean sysType )
{
return Convert.ToBoolean( ap[vaNEXT++] );
}
static Byte[] va_arg( object[] ap, Byte[] sysType )
{
return (Byte[])ap[vaNEXT++];
}
static Byte[][] va_arg( object[] ap, Byte[][] sysType )
{
if ( ap[vaNEXT] == null )
{
{
vaNEXT++;
return null;
}
}
else
{
return (Byte[][])ap[vaNEXT++];
}
}
static Char va_arg( object[] ap, Char sysType )
{
if ( ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0 )
{
vaNEXT++;
return (char)'0';
}
else
{
if ( ap[vaNEXT] is Int64 )
if ( (i64)ap[vaNEXT] == 0 )
{
vaNEXT++;
return (char)'0';
}
else
return (char)( (i64)ap[vaNEXT++] );
else
return (char)ap[vaNEXT++];
}
}
static Double va_arg( object[] ap, Double sysType )
{
return Convert.ToDouble( ap[vaNEXT++] );
}
static dxLog va_arg( object[] ap, dxLog sysType )
{
return (dxLog)ap[vaNEXT++];
}
static Int64 va_arg( object[] ap, Int64 sysType )
{
if ( ap[vaNEXT] is System.Int64)
return Convert.ToInt64( ap[vaNEXT++] );
else
return (Int64)( ap[vaNEXT++].GetHashCode() );
}
static Int32 va_arg( object[] ap, Int32 sysType )
{
if ( Convert.ToInt64( ap[vaNEXT] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT] ) > Int32.MaxValue ) )
return (Int32)( Convert.ToUInt32( ap[vaNEXT++] ) - System.UInt32.MaxValue - 1 );
else
return (Int32)Convert.ToInt32( ap[vaNEXT++] );
}
static Int32[] va_arg( object[] ap, Int32[] sysType )
{
if ( ap[vaNEXT] == null )
{
{
vaNEXT++;
return null;
}
}
else
{
return (Int32[])ap[vaNEXT++];
}
}
static MemPage va_arg( object[] ap, MemPage sysType )
{
return (MemPage)ap[vaNEXT++];
}
static Object va_arg( object[] ap, Object sysType )
{
return (Object)ap[vaNEXT++];
}
static sqlite3 va_arg( object[] ap, sqlite3 sysType )
{
return (sqlite3)ap[vaNEXT++];
}
static sqlite3_mem_methods va_arg( object[] ap, sqlite3_mem_methods sysType )
{
return (sqlite3_mem_methods)ap[vaNEXT++];
}
static sqlite3_mutex_methods va_arg( object[] ap, sqlite3_mutex_methods sysType )
{
return (sqlite3_mutex_methods)ap[vaNEXT++];
}
static SrcList va_arg( object[] ap, SrcList sysType )
{
return (SrcList)ap[vaNEXT++];
}
static String va_arg( object[] ap, String sysType )
{
if ( ap.Length < vaNEXT - 1 || ap[vaNEXT] == null )
{
vaNEXT++;
return "NULL";
}
else
{
if ( ap[vaNEXT] is Byte[] )
if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT] ).Length ) == "\0" )
{
vaNEXT++;
return "";
}
else
return Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT++] ).Length );
else if ( ap[vaNEXT] is Int32 )
{
vaNEXT++;
return null;
}
else if ( ap[vaNEXT] is StringBuilder )
return (String)ap[vaNEXT++].ToString();
else if ( ap[vaNEXT] is Char )
return ( (Char)ap[vaNEXT++] ).ToString();
else
return (String)ap[vaNEXT++];
}
}
static Token va_arg( object[] ap, Token sysType )
{
return (Token)ap[vaNEXT++];
}
static UInt32 va_arg( object[] ap, UInt32 sysType )
{
#if SQLITE_WINRT
Type t = ap[vaNEXT].GetType();
if ( t.IsClass )
#else
if ( ap[vaNEXT].GetType().IsClass )
#endif
{
return (UInt32)ap[vaNEXT++].GetHashCode();
}
else
{
return (UInt32)Convert.ToUInt32( ap[vaNEXT++] );
}
}
static UInt64 va_arg( object[] ap, UInt64 sysType )
{
#if SQLITE_WINRT
Type t = ap[vaNEXT].GetType();
if (t.IsClass)
#else
if ( ap[vaNEXT].GetType().IsClass )
#endif
{
return (UInt64)ap[vaNEXT++].GetHashCode();
}
else
{
return (UInt64)Convert.ToUInt64( ap[vaNEXT++] );
}
}
static void_function va_arg( object[] ap, void_function sysType )
{
return (void_function)ap[vaNEXT++];
}
static void va_end( ref string[] ap )
{
ap = null;
vaNEXT = -1;
vaFORMAT = "";
}
static void va_end( ref object[] ap )
{
ap = null;
vaNEXT = -1;
vaFORMAT = "";
}
public static tm localtime( time_t baseTime )
{
System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime();
tm tm = new tm();
tm.tm_sec = RefTime.Second;
tm.tm_min = RefTime.Minute;
tm.tm_hour = RefTime.Hour;
tm.tm_mday = RefTime.Day;
tm.tm_mon = RefTime.Month;
tm.tm_year = RefTime.Year;
tm.tm_wday = (int)RefTime.DayOfWeek;
tm.tm_yday = RefTime.DayOfYear;
tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0;
return tm;
}
public static long ToUnixtime( System.DateTime date )
{
System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
System.TimeSpan timeSpan = date - unixStartTime;
return Convert.ToInt64( timeSpan.TotalSeconds );
}
public static System.DateTime ToCSharpTime( long unixTime )
{
System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) );
}
public class tm
{
public int tm_sec; /* seconds after the minute - [0,59] */
public int tm_min; /* minutes after the hour - [0,59] */
public int tm_hour; /* hours since midnight - [0,23] */
public int tm_mday; /* day of the month - [1,31] */
public int tm_mon; /* months since January - [0,11] */
public int tm_year; /* years since 1900 */
public int tm_wday; /* days since Sunday - [0,6] */
public int tm_yday; /* days since January 1 - [0,365] */
public int tm_isdst; /* daylight savings time flag */
};
public struct FILETIME
{
public u32 dwLowDateTime;
public u32 dwHighDateTime;
}
static void SWAP<T>( ref T A, ref T B )
{
T t = A;
A = B;
B = t;
}
static void x_CountStep(
sqlite3_context context,
int argc,
sqlite3_value[] argv
)
{
SumCtx p;
int type;
Debug.Assert( argc <= 1 );
Mem pMem = sqlite3_aggregate_context( context, 1 );//sizeof(*p));
if ( pMem._SumCtx == null )
pMem._SumCtx = new SumCtx();
p = pMem._SumCtx;
if ( p.Context == null )
p.Context = pMem;
if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) )
{
p.cnt++;
p.iSum += 1;
}
else
{
type = sqlite3_value_numeric_type( argv[0] );
if ( p != null && type != SQLITE_NULL )
{
p.cnt++;
if ( type == SQLITE_INTEGER )
{
i64 v = sqlite3_value_int64( argv[0] );
if ( v == 40 || v == 41 )
{
sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 );
return;
}
else
{
p.iSum += v;
if ( !( p.approx | p.overflow != 0 ) )
{
i64 iNewSum = p.iSum + v;
int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) );
int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) );
int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) );
p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0;
p.iSum = iNewSum;
}
}
}
else
{
p.rSum += sqlite3_value_double( argv[0] );
p.approx = true;
}
}
}
}
static void x_CountFinalize( sqlite3_context context )
{
SumCtx p;
Mem pMem = sqlite3_aggregate_context( context, 0 );
p = pMem._SumCtx;
if ( p != null && p.cnt > 0 )
{
if ( p.overflow != 0 )
{
sqlite3_result_error( context, "integer overflow", -1 );
}
else if ( p.approx )
{
sqlite3_result_double( context, p.rSum );
}
else if ( p.iSum == 42 )
{
sqlite3_result_error( context, "x_count totals to 42", -1 );
}
else
{
sqlite3_result_int64( context, p.iSum );
}
}
}
#if SQLITE_MUTEX_W32
//---------------------WIN32 Definitions
static int GetCurrentThreadId()
{
return Thread.CurrentThread.ManagedThreadId;
}
static long InterlockedIncrement( long location )
{
Interlocked.Increment( ref location );
return location;
}
static void EnterCriticalSection( Object mtx )
{
//long mid = mtx.GetHashCode();
//int tid = Thread.CurrentThread.ManagedThreadId;
//long ticks = cnt++;
//Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) );
Monitor.Enter( mtx );
}
static void InitializeCriticalSection( Object mtx )
{
//Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
}
static void DeleteCriticalSection( Object mtx )
{
//Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) );
}
static void LeaveCriticalSection( Object mtx )
{
//Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
Monitor.Exit( mtx );
}
#endif
// Miscellaneous Windows Constants
//#define ERROR_FILE_NOT_FOUND 2L
//#define ERROR_HANDLE_DISK_FULL 39L
//#define ERROR_NOT_SUPPORTED 50L
//#define ERROR_DISK_FULL 112L
const long ERROR_FILE_NOT_FOUND = 2L;
const long ERROR_HANDLE_DISK_FULL = 39L;
const long ERROR_NOT_SUPPORTED = 50L;
const long ERROR_DISK_FULL = 112L;
private class SQLite3UpperToLower
{
static int[] sqlite3UpperToLower = new int[] {
#if SQLITE_ASCII
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
252,253,254,255
#endif
};
public int this[int index]
{
get
{
if ( index < sqlite3UpperToLower.Length )
return sqlite3UpperToLower[index];
else
return index;
}
}
public int this[u32 index]
{
get
{
if ( index < sqlite3UpperToLower.Length )
return sqlite3UpperToLower[index];
else
return (int)index;
}
}
}
static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower();
static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower;
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Xml;
struct MessageAttemptInfo
{
readonly Message message;
readonly int retryCount;
readonly Int64 sequenceNumber;
readonly object state;
public MessageAttemptInfo(Message message, Int64 sequenceNumber, int retryCount, object state)
{
this.message = message;
this.sequenceNumber = sequenceNumber;
this.retryCount = retryCount;
this.state = state;
}
public Message Message
{
get { return this.message; }
}
public int RetryCount
{
get { return this.retryCount; }
}
public object State
{
get { return this.state; }
}
public Int64 GetSequenceNumber()
{
if (this.sequenceNumber <= 0)
{
throw Fx.AssertAndThrow("The caller is not allowed to get an invalid SequenceNumber.");
}
return this.sequenceNumber;
}
}
sealed class TransmissionStrategy
{
bool aborted;
bool closed;
int congestionControlModeAcks;
UniqueId id;
Int64 last = 0;
int lossWindowSize;
int maxWindowSize;
Int64 meanRtt;
ComponentExceptionHandler onException;
Int32 quotaRemaining;
ReliableMessagingVersion reliableMessagingVersion;
List<Int64> retransmissionWindow = new List<Int64>();
IOThreadTimer retryTimer;
RetryHandler retryTimeoutElapsedHandler;
bool requestAcks;
Int64 serrRtt;
int slowStartThreshold;
bool startup = true;
object thisLock = new object();
Int64 timeout;
Queue<IQueueAdder> waitQueue = new Queue<IQueueAdder>();
SlidingWindow window;
int windowSize = 1;
Int64 windowStart = 1;
public TransmissionStrategy(ReliableMessagingVersion reliableMessagingVersion, TimeSpan initRtt,
int maxWindowSize, bool requestAcks, UniqueId id)
{
if (initRtt < TimeSpan.Zero)
{
if (DiagnosticUtility.ShouldTrace(TraceEventType.Warning))
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.WsrmNegativeElapsedTimeDetected,
SR.GetString(SR.TraceCodeWsrmNegativeElapsedTimeDetected), this);
}
initRtt = ReliableMessagingConstants.UnknownInitiationTime;
}
if (maxWindowSize <= 0)
{
throw Fx.AssertAndThrow("Argument maxWindow size must be positive.");
}
this.id = id;
this.maxWindowSize = this.lossWindowSize = maxWindowSize;
this.meanRtt = Math.Min((long)initRtt.TotalMilliseconds, Constants.MaxMeanRtt >> Constants.TimeMultiplier) << Constants.TimeMultiplier;
this.serrRtt = this.meanRtt >> 1;
this.window = new SlidingWindow(maxWindowSize);
this.slowStartThreshold = maxWindowSize;
this.timeout = Math.Max(((200 << Constants.TimeMultiplier) * 2) + this.meanRtt, this.meanRtt + (this.serrRtt << Constants.ChebychevFactor));
this.quotaRemaining = Int32.MaxValue;
this.retryTimer = new IOThreadTimer(new Action<object>(OnRetryElapsed), null, true);
this.requestAcks = requestAcks;
this.reliableMessagingVersion = reliableMessagingVersion;
}
public bool DoneTransmitting
{
get
{
return (this.last != 0 && this.windowStart == this.last + 1);
}
}
public bool HasPending
{
get
{
return (this.window.Count > 0 || this.waitQueue.Count > 0);
}
}
public Int64 Last
{
get
{
return this.last;
}
}
// now in 128ths of a millisecond.
static Int64 Now
{
get
{
return (Ticks.Now / TimeSpan.TicksPerMillisecond) << Constants.TimeMultiplier;
}
}
public ComponentExceptionHandler OnException
{
set
{
this.onException = value;
}
}
public RetryHandler RetryTimeoutElapsed
{
set
{
this.retryTimeoutElapsedHandler = value;
}
}
public int QuotaRemaining
{
get
{
return this.quotaRemaining;
}
}
object ThisLock
{
get
{
return this.thisLock;
}
}
public int Timeout
{
get
{
return (int)(this.timeout >> Constants.TimeMultiplier);
}
}
public void Abort(ChannelBase channel)
{
lock (this.ThisLock)
{
this.aborted = true;
if (this.closed)
return;
this.closed = true;
this.retryTimer.Cancel();
while (waitQueue.Count > 0)
waitQueue.Dequeue().Abort(channel);
window.Close();
}
}
public bool Add(Message message, TimeSpan timeout, object state, out MessageAttemptInfo attemptInfo)
{
return InternalAdd(message, false, timeout, state, out attemptInfo);
}
public MessageAttemptInfo AddLast(Message message, TimeSpan timeout, object state)
{
if (this.reliableMessagingVersion != ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
throw Fx.AssertAndThrow("Last message supported only in February 2005.");
}
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
InternalAdd(message, true, timeout, state, out attemptInfo);
return attemptInfo;
}
// Must call in a lock(this.ThisLock).
MessageAttemptInfo AddToWindow(Message message, bool isLast, object state)
{
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
Int64 sequenceNumber;
sequenceNumber = this.windowStart + this.window.Count;
WsrmUtilities.AddSequenceHeader(this.reliableMessagingVersion, message, this.id, sequenceNumber, isLast);
if (this.requestAcks && (this.window.Count == this.windowSize - 1 || this.quotaRemaining == 1)) // can't add any more
{
message.Properties.AllowOutputBatching = false;
WsrmUtilities.AddAckRequestedHeader(this.reliableMessagingVersion, message, this.id);
}
if (this.window.Count == 0)
{
this.retryTimer.Set(this.Timeout);
}
this.window.Add(message, Now, state);
this.quotaRemaining--;
if (isLast)
this.last = sequenceNumber;
int index = (int)(sequenceNumber - this.windowStart);
attemptInfo = new MessageAttemptInfo(this.window.GetMessage(index), sequenceNumber, 0, state);
return attemptInfo;
}
public IAsyncResult BeginAdd(Message message, TimeSpan timeout, object state, AsyncCallback callback, object asyncState)
{
return InternalBeginAdd(message, false, timeout, state, callback, asyncState);
}
public IAsyncResult BeginAddLast(Message message, TimeSpan timeout, object state, AsyncCallback callback, object asyncState)
{
if (this.reliableMessagingVersion != ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
throw Fx.AssertAndThrow("Last message supported only in February 2005.");
}
return InternalBeginAdd(message, true, timeout, state, callback, asyncState);
}
bool CanAdd()
{
return (this.window.Count < this.windowSize && // Does the message fit in the transmission window?
this.quotaRemaining > 0 && // Can the receiver handle another message?
this.waitQueue.Count == 0); // Don't get ahead of anyone in the wait queue.
}
public void Close()
{
lock (this.ThisLock)
{
if (this.closed)
return;
this.closed = true;
this.retryTimer.Cancel();
if (waitQueue.Count != 0)
{
throw Fx.AssertAndThrow("The reliable channel must throw prior to the call to Close() if there are outstanding send or request operations.");
}
window.Close();
}
}
public void DequeuePending()
{
Queue<IQueueAdder> adders = null;
lock (this.ThisLock)
{
if (this.closed || this.waitQueue.Count == 0)
return;
int count = Math.Min(this.windowSize, this.quotaRemaining) - this.window.Count;
if (count <= 0)
return;
count = Math.Min(count, this.waitQueue.Count);
adders = new Queue<IQueueAdder>(count);
while (count-- > 0)
{
IQueueAdder adder = waitQueue.Dequeue();
adder.Complete0();
adders.Enqueue(adder);
}
}
while (adders.Count > 0)
adders.Dequeue().Complete1();
}
public bool EndAdd(IAsyncResult result, out MessageAttemptInfo attemptInfo)
{
return InternalEndAdd(result, out attemptInfo);
}
public MessageAttemptInfo EndAddLast(IAsyncResult result)
{
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
InternalEndAdd(result, out attemptInfo);
return attemptInfo;
}
bool IsAddValid()
{
return (!this.aborted && !this.closed);
}
public void OnRetryElapsed(object state)
{
try
{
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
lock (this.ThisLock)
{
if (this.closed)
return;
if (this.window.Count == 0)
return;
this.window.RecordRetry(0, Now);
this.congestionControlModeAcks = 0;
this.slowStartThreshold = Math.Max(1, this.windowSize >> 1);
this.lossWindowSize = this.windowSize;
this.windowSize = 1;
this.timeout <<= 1;
this.startup = false;
attemptInfo = new MessageAttemptInfo(this.window.GetMessage(0), this.windowStart, this.window.GetRetryCount(0), this.window.GetState(0));
}
retryTimeoutElapsedHandler(attemptInfo);
lock (this.ThisLock)
{
if (!this.closed && (this.window.Count > 0))
{
this.retryTimer.Set(this.Timeout);
}
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
this.onException(e);
}
}
public void Fault(ChannelBase channel)
{
lock (this.ThisLock)
{
if (this.closed)
return;
this.closed = true;
this.retryTimer.Cancel();
while (waitQueue.Count > 0)
waitQueue.Dequeue().Fault(channel);
window.Close();
}
}
public MessageAttemptInfo GetMessageInfoForRetry(bool remove)
{
lock (this.ThisLock)
{
// Closed, no need to retry.
if (this.closed)
{
return default(MessageAttemptInfo);
}
if (remove)
{
if (this.retransmissionWindow.Count == 0)
{
throw Fx.AssertAndThrow("The caller is not allowed to remove a message attempt when there are no message attempts.");
}
this.retransmissionWindow.RemoveAt(0);
}
while (this.retransmissionWindow.Count > 0)
{
Int64 next = this.retransmissionWindow[0];
if (next < this.windowStart)
{
// Already removed from the window, no need to retry.
this.retransmissionWindow.RemoveAt(0);
}
else
{
int index = (int)(next - this.windowStart);
if (this.window.GetTransferred(index))
this.retransmissionWindow.RemoveAt(0);
else
return new MessageAttemptInfo(this.window.GetMessage(index), next, this.window.GetRetryCount(index), this.window.GetState(index));
}
}
// Nothing left to retry.
return default(MessageAttemptInfo);
}
}
public bool SetLast()
{
if (this.reliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
{
throw Fx.AssertAndThrow("SetLast supported only in 1.1.");
}
lock (this.ThisLock)
{
if (this.last != 0)
{
throw Fx.AssertAndThrow("Cannot set last more than once.");
}
this.last = this.windowStart + this.window.Count - 1;
return (this.last == 0) || this.DoneTransmitting;
}
}
bool InternalAdd(Message message, bool isLast, TimeSpan timeout, object state, out MessageAttemptInfo attemptInfo)
{
attemptInfo = default(MessageAttemptInfo);
WaitQueueAdder adder;
lock (this.ThisLock)
{
if (isLast && this.last != 0)
{
throw Fx.AssertAndThrow("Can't add more than one last message.");
}
if (!this.IsAddValid())
return false;
ThrowIfRollover();
if (CanAdd())
{
attemptInfo = AddToWindow(message, isLast, state);
return true;
}
adder = new WaitQueueAdder(this, message, isLast, state);
this.waitQueue.Enqueue(adder);
}
attemptInfo = adder.Wait(timeout);
return true;
}
IAsyncResult InternalBeginAdd(Message message, bool isLast, TimeSpan timeout, object state, AsyncCallback callback, object asyncState)
{
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
bool isAddValid;
lock (this.ThisLock)
{
if (isLast && this.last != 0)
{
throw Fx.AssertAndThrow("Can't add more than one last message.");
}
isAddValid = this.IsAddValid();
if (isAddValid)
{
ThrowIfRollover();
if (CanAdd())
{
attemptInfo = AddToWindow(message, isLast, state);
}
else
{
AsyncQueueAdder adder = new AsyncQueueAdder(message, isLast, timeout, state, this, callback, asyncState);
this.waitQueue.Enqueue(adder);
return adder;
}
}
}
return new CompletedAsyncResult<bool, MessageAttemptInfo>(isAddValid, attemptInfo, callback, asyncState);
}
bool InternalEndAdd(IAsyncResult result, out MessageAttemptInfo attemptInfo)
{
if (result is CompletedAsyncResult<bool, MessageAttemptInfo>)
{
return CompletedAsyncResult<bool, MessageAttemptInfo>.End(result, out attemptInfo);
}
else
{
attemptInfo = AsyncQueueAdder.End((AsyncQueueAdder)result);
return true;
}
}
public bool IsFinalAckConsistent(SequenceRangeCollection ranges)
{
lock (this.ThisLock)
{
if (this.closed)
{
return true;
}
// Nothing sent, ensure ack is empty.
if ((this.windowStart == 1) && (this.window.Count == 0))
{
return ranges.Count == 0;
}
// Ack is empty or first range is invalid.
if (ranges.Count == 0 || ranges[0].Lower != 1)
{
return false;
}
return ranges[0].Upper >= (this.windowStart - 1);
}
}
public void ProcessAcknowledgement(SequenceRangeCollection ranges, out bool invalidAck, out bool inconsistentAck)
{
invalidAck = false;
inconsistentAck = false;
bool newAck = false;
bool oldAck = false;
lock (this.ThisLock)
{
if (this.closed)
{
return;
}
Int64 lastMessageSent = this.windowStart + this.window.Count - 1;
Int64 lastMessageAcked = this.windowStart - 1;
int transferredInWindow = this.window.TransferredCount;
for (int i = 0; i < ranges.Count; i++)
{
SequenceRange range = ranges[i];
// Ack for a message not yet sent.
if (range.Upper > lastMessageSent)
{
invalidAck = true;
return;
}
if (((range.Lower > 1) && (range.Lower <= lastMessageAcked)) || (range.Upper < lastMessageAcked))
{
oldAck = true;
}
if (range.Upper >= this.windowStart)
{
if (range.Lower <= this.windowStart)
{
newAck = true;
}
if (!newAck)
{
int beginIndex = (int)(range.Lower - this.windowStart);
int endIndex = (int)((range.Upper > lastMessageSent) ? (this.window.Count - 1) : (range.Upper - this.windowStart));
newAck = this.window.GetTransferredInRangeCount(beginIndex, endIndex) < (endIndex - beginIndex + 1);
}
if (transferredInWindow > 0 && !oldAck)
{
int beginIndex = (int)((range.Lower < this.windowStart) ? 0 : (range.Lower - this.windowStart));
int endIndex = (int)((range.Upper > lastMessageSent) ? (this.window.Count - 1) : (range.Upper - this.windowStart));
transferredInWindow -= this.window.GetTransferredInRangeCount(beginIndex, endIndex);
}
}
}
if (transferredInWindow > 0)
oldAck = true;
}
inconsistentAck = oldAck && newAck;
}
// Called for RequestReply.
// Argument transferred is the request sequence number and it is assumed to be positive.
public bool ProcessTransferred(Int64 transferred, int quotaRemaining)
{
if (transferred <= 0)
{
throw Fx.AssertAndThrow("Argument transferred must be a valid sequence number.");
}
lock (this.ThisLock)
{
if (this.closed)
{
return false;
}
return ProcessTransferred(new SequenceRange(transferred), quotaRemaining);
}
}
// Called for Duplex and Output
public bool ProcessTransferred(SequenceRangeCollection ranges, int quotaRemaining)
{
if (ranges.Count == 0)
{
return false;
}
lock (this.ThisLock)
{
if (this.closed)
{
return false;
}
bool send = false;
for (int rangeIndex = 0; rangeIndex < ranges.Count; rangeIndex++)
{
if (this.ProcessTransferred(ranges[rangeIndex], quotaRemaining))
{
send = true;
}
}
return send;
}
}
// It is necessary that ProcessAcknowledgement be called prior, as
// this method does not check for valid ack ranges.
// This method returns true if the calling method should start sending retries
// obtained from GetMessageInfoForRetry.
bool ProcessTransferred(SequenceRange range, int quotaRemaining)
{
if (range.Upper < this.windowStart)
{
if (range.Upper == this.windowStart - 1 && (quotaRemaining != -1) && quotaRemaining > this.quotaRemaining)
this.quotaRemaining = quotaRemaining - Math.Min(this.windowSize, this.window.Count);
return false;
}
else if (range.Lower <= this.windowStart)
{
bool send = false;
this.retryTimer.Cancel();
Int64 slide = range.Upper - this.windowStart + 1;
// For Request Reply: Requests are transferred 1 at a time, (i.e. when the reply comes back).
// The TransmissionStrategy only removes messages if the window start is removed.
// Because of this, RequestReply messages transferred out of order will cause many, many retries.
// To avoid extraneous retries we mark each message transferred, and we remove our virtual slide.
if (slide == 1)
{
for (int i = 1; i < this.window.Count; i++)
{
if (this.window.GetTransferred(i))
{
slide++;
}
else
{
break;
}
}
}
Int64 now = Now;
Int64 oldWindowEnd = this.windowStart + this.windowSize;
for (int i = 0; i < (int)slide; i++)
UpdateStats(now, this.window.GetLastAttemptTime(i));
if (quotaRemaining != -1)
{
int inFlightAfterAck = Math.Min(this.windowSize, this.window.Count) - (int)slide;
this.quotaRemaining = quotaRemaining - Math.Max(0, inFlightAfterAck);
}
this.window.Remove((int)slide);
this.windowStart += slide;
int sendBeginIndex = 0;
if (this.windowSize <= this.slowStartThreshold)
{
this.windowSize = Math.Min(this.maxWindowSize, Math.Min(this.slowStartThreshold + 1, this.windowSize + (int)slide));
if (!startup)
sendBeginIndex = 0;
else
sendBeginIndex = Math.Max(0, (int)oldWindowEnd - (int)this.windowStart);
}
else
{
this.congestionControlModeAcks += (int)slide;
// EXPERIMENTAL, needs optimizing ///
int segmentSize = Math.Max(1, (this.lossWindowSize - this.slowStartThreshold) / 8);
int windowGrowthAckThreshold = ((this.windowSize - this.slowStartThreshold) * this.windowSize) / segmentSize;
if (this.congestionControlModeAcks > windowGrowthAckThreshold)
{
this.congestionControlModeAcks = 0;
this.windowSize = Math.Min(this.maxWindowSize, this.windowSize + 1);
}
sendBeginIndex = Math.Max(0, (int)oldWindowEnd - (int)this.windowStart);
}
int sendEndIndex = Math.Min(this.windowSize, this.window.Count);
if (sendBeginIndex < sendEndIndex)
{
send = (this.retransmissionWindow.Count == 0);
for (int i = sendBeginIndex; i < this.windowSize && i < this.window.Count; i++)
{
Int64 sequenceNumber = this.windowStart + i;
if (!this.window.GetTransferred(i) && !this.retransmissionWindow.Contains(sequenceNumber))
{
this.window.RecordRetry(i, Now);
retransmissionWindow.Add(sequenceNumber);
}
}
}
if (window.Count > 0)
{
this.retryTimer.Set(this.Timeout);
}
return send;
}
else
{
for (Int64 i = range.Lower; i <= range.Upper; i++)
{
this.window.SetTransferred((int)(i - this.windowStart));
}
}
return false;
}
bool RemoveAdder(IQueueAdder adder)
{
lock (this.ThisLock)
{
if (this.closed)
return false;
bool removed = false;
for (int i = 0; i < this.waitQueue.Count; i++)
{
IQueueAdder current = this.waitQueue.Dequeue();
if (Object.ReferenceEquals(adder, current))
removed = true;
else
this.waitQueue.Enqueue(current);
}
return removed;
}
}
void ThrowIfRollover()
{
if (this.windowStart + this.window.Count + this.waitQueue.Count == Int64.MaxValue)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageNumberRolloverFault(this.id).CreateException());
}
void UpdateStats(Int64 now, Int64 lastAttemptTime)
{
now = Math.Max(now, lastAttemptTime);
Int64 measuredRtt = now - lastAttemptTime;
Int64 error = measuredRtt - this.meanRtt;
this.serrRtt = Math.Min(this.serrRtt + ((Math.Abs(error) - this.serrRtt) >> Constants.Gain), Constants.MaxSerrRtt);
this.meanRtt = Math.Min(this.meanRtt + (error >> Constants.Gain), Constants.MaxMeanRtt);
this.timeout = Math.Max(((200 << Constants.TimeMultiplier) * 2) + this.meanRtt, this.meanRtt + (this.serrRtt << Constants.ChebychevFactor));
}
class AsyncQueueAdder : WaitAsyncResult, IQueueAdder
{
bool isLast;
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
TransmissionStrategy strategy;
public AsyncQueueAdder(Message message, bool isLast, TimeSpan timeout, object state, TransmissionStrategy strategy, AsyncCallback callback, object asyncState)
: base(timeout, true, callback, asyncState)
{
// MessageAttemptInfo(Message message, Int64 sequenceNumber, int retryCount, object state)
// this.attemptInfo is just a state bag, thus sequenceNumber can be 0 and should never be read.
this.attemptInfo = new MessageAttemptInfo(message, 0, 0, state);
this.isLast = isLast;
this.strategy = strategy;
base.Begin();
}
public void Abort(CommunicationObject communicationObject)
{
this.attemptInfo.Message.Close();
OnAborted(communicationObject);
}
public void Complete0()
{
this.attemptInfo = strategy.AddToWindow(this.attemptInfo.Message, this.isLast, this.attemptInfo.State);
}
public void Complete1()
{
OnSignaled();
}
public static MessageAttemptInfo End(AsyncQueueAdder result)
{
AsyncResult.End<AsyncQueueAdder>(result);
return result.attemptInfo;
}
public void Fault(CommunicationObject communicationObject)
{
this.attemptInfo.Message.Close();
OnFaulted(communicationObject);
}
protected override string GetTimeoutString(TimeSpan timeout)
{
return SR.GetString(SR.TimeoutOnAddToWindow, timeout);
}
protected override void OnTimerElapsed(object state)
{
if (this.strategy.RemoveAdder(this))
base.OnTimerElapsed(state);
}
}
static class Constants
{
// Used to adjust the timeout calculation, according to Chebychev's theorem,
// to fit ~98% of actual rtt's within our timeout.
public const int ChebychevFactor = 2;
// Gain of 0.125 (1/8). Shift right by 3 to apply the gain to a term.
public const int Gain = 3;
// 1ms == 128 of our time units. Shift left by 7 to perform the multiplication.
public const int TimeMultiplier = 7;
// These guarantee no overflows when calculating timeout.
public const long MaxMeanRtt = long.MaxValue / 3;
public const long MaxSerrRtt = MaxMeanRtt / 2;
}
interface IQueueAdder
{
void Abort(CommunicationObject communicationObject);
void Fault(CommunicationObject communicationObject);
void Complete0();
void Complete1();
}
class SlidingWindow
{
TransmissionInfo[] buffer;
int head = 0;
int tail = 0;
int maxSize;
public SlidingWindow(int maxSize)
{
this.maxSize = maxSize + 1;
this.buffer = new TransmissionInfo[this.maxSize];
}
public int Count
{
get
{
if (this.tail >= this.head)
return (this.tail - this.head);
else
return (this.tail - this.head + this.maxSize);
}
}
public int TransferredCount
{
get
{
if (this.Count == 0)
return 0;
else
return this.GetTransferredInRangeCount(0, this.Count - 1);
}
}
public void Add(Message message, Int64 addTime, object state)
{
if (this.Count >= (this.maxSize - 1))
{
throw Fx.AssertAndThrow("The caller is not allowed to add messages beyond the sliding window's maximum size.");
}
this.buffer[this.tail] = new TransmissionInfo(message, addTime, state);
this.tail = (this.tail + 1) % this.maxSize;
}
void AssertIndex(int index)
{
if (index >= Count)
{
throw Fx.AssertAndThrow("Argument index must be less than Count.");
}
if (index < 0)
{
throw Fx.AssertAndThrow("Argument index must be positive.");
}
}
public void Close()
{
this.Remove(Count);
}
public Int64 GetLastAttemptTime(int index)
{
this.AssertIndex(index);
return this.buffer[(head + index) % this.maxSize].LastAttemptTime;
}
public Message GetMessage(int index)
{
this.AssertIndex(index);
if (!this.buffer[(head + index) % this.maxSize].Transferred)
return this.buffer[(head + index) % this.maxSize].Buffer.CreateMessage();
else
return null;
}
public int GetRetryCount(int index)
{
this.AssertIndex(index);
return this.buffer[(this.head + index) % this.maxSize].RetryCount;
}
public object GetState(int index)
{
this.AssertIndex(index);
return this.buffer[(this.head + index) % this.maxSize].State;
}
public bool GetTransferred(int index)
{
this.AssertIndex(index);
return this.buffer[(this.head + index) % this.maxSize].Transferred;
}
public int GetTransferredInRangeCount(int beginIndex, int endIndex)
{
if (beginIndex < 0)
{
throw Fx.AssertAndThrow("Argument beginIndex cannot be negative.");
}
if (endIndex >= this.Count)
{
throw Fx.AssertAndThrow("Argument endIndex cannot be greater than Count.");
}
if (endIndex < beginIndex)
{
throw Fx.AssertAndThrow("Argument endIndex cannot be less than argument beginIndex.");
}
int result = 0;
for (int index = beginIndex; index <= endIndex; index++)
{
if (this.buffer[(head + index) % this.maxSize].Transferred)
result++;
}
return result;
}
public int RecordRetry(int index, Int64 retryTime)
{
this.AssertIndex(index);
this.buffer[(head + index) % this.maxSize].LastAttemptTime = retryTime;
return ++this.buffer[(head + index) % this.maxSize].RetryCount;
}
public void Remove(int count)
{
if (count > this.Count)
{
Fx.Assert("Cannot remove more messages than the window's Count.");
}
while (count-- > 0)
{
this.buffer[head].Buffer.Close();
this.buffer[head].Buffer = null;
this.head = (this.head + 1) % this.maxSize;
}
}
public void SetTransferred(int index)
{
this.AssertIndex(index);
this.buffer[(head + index) % this.maxSize].Transferred = true;
}
struct TransmissionInfo
{
internal MessageBuffer Buffer;
internal Int64 LastAttemptTime;
internal int RetryCount;
internal object State;
internal bool Transferred;
public TransmissionInfo(Message message, Int64 lastAttemptTime, object state)
{
this.Buffer = message.CreateBufferedCopy(int.MaxValue);
this.LastAttemptTime = lastAttemptTime;
this.RetryCount = 0;
this.State = state;
this.Transferred = false;
}
}
}
class WaitQueueAdder : IQueueAdder
{
ManualResetEvent completeEvent = new ManualResetEvent(false);
Exception exception;
bool isLast;
MessageAttemptInfo attemptInfo = default(MessageAttemptInfo);
TransmissionStrategy strategy;
public WaitQueueAdder(TransmissionStrategy strategy, Message message, bool isLast, object state)
{
this.strategy = strategy;
this.isLast = isLast;
this.attemptInfo = new MessageAttemptInfo(message, 0, 0, state);
}
public void Abort(CommunicationObject communicationObject)
{
this.exception = communicationObject.CreateClosedException();
completeEvent.Set();
}
public void Complete0()
{
attemptInfo = this.strategy.AddToWindow(this.attemptInfo.Message, this.isLast, this.attemptInfo.State);
this.completeEvent.Set();
}
public void Complete1()
{
}
public void Fault(CommunicationObject communicationObject)
{
this.exception = communicationObject.GetTerminalException();
completeEvent.Set();
}
public MessageAttemptInfo Wait(TimeSpan timeout)
{
if (!TimeoutHelper.WaitOne(this.completeEvent, timeout))
{
if (this.strategy.RemoveAdder(this) && this.exception == null)
this.exception = new TimeoutException(SR.GetString(SR.TimeoutOnAddToWindow, timeout));
}
if (this.exception != null)
{
this.attemptInfo.Message.Close();
this.completeEvent.Close();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.exception);
}
// This is safe because, Abort, Complete0, Fault, and RemoveAdder all occur under
// the TransmissionStrategy's lock and RemoveAdder ensures that the
// TransmissionStrategy will never call into this object again.
this.completeEvent.Close();
return this.attemptInfo;
}
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using SalesAssister.Models;
namespace SalesAssister.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.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")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.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.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.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.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.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.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("SalesAssister.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")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("SalesAssister.Models.Client", b =>
{
b.Property<int>("ClientId")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("Name");
b.Property<string>("Phone");
b.Property<string>("UserId");
b.HasKey("ClientId");
b.HasAnnotation("Relational:TableName", "Clients");
});
modelBuilder.Entity("SalesAssister.Models.Contact", b =>
{
b.Property<int>("ContactId")
.ValueGeneratedOnAdd();
b.Property<int>("ClientId");
b.Property<DateTime>("Date");
b.Property<string>("Notes");
b.Property<string>("UserId");
b.HasKey("ContactId");
b.HasAnnotation("Relational:TableName", "Contacts");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("SalesAssister.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("SalesAssister.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("SalesAssister.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("SalesAssister.Models.Client", b =>
{
b.HasOne("SalesAssister.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("SalesAssister.Models.Contact", b =>
{
b.HasOne("SalesAssister.Models.Client")
.WithMany()
.HasForeignKey("ClientId");
b.HasOne("SalesAssister.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
using OpenLiveWriter.CoreServices.Marketization;
using OpenLiveWriter.PostEditor.PostHtmlEditing;
using OpenLiveWriter.PostEditor.BlogProviderButtons;
namespace OpenLiveWriter.PostEditor.Configuration.Wizard
{
internal class WeblogConfigurationWizardPanelBlogType : WeblogConfigurationWizardPanel
{
private System.Windows.Forms.Label labelWelcomeText;
private System.Windows.Forms.Panel panelRadioButtons;
private System.Windows.Forms.RadioButton radioButtonSharePoint;
private System.Windows.Forms.RadioButton radioButtonBlogger;
private System.Windows.Forms.RadioButton radioButtonOther;
private System.Windows.Forms.Label labelOtherDesc;
private System.Windows.Forms.RadioButton radioButtonWordpress;
private System.Windows.Forms.Panel panelComboBox;
private System.Windows.Forms.ComboBox comboBoxSelectWeblogType;
private LinkLabel privacyPolicyLabel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public WeblogConfigurationWizardPanelBlogType()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
labelOtherDesc.Visible = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.ToLowerInvariant() == "en";
labelHeader.Text = Res.Get(StringId.WizardBlogTypeWhatBlogType);
labelWelcomeText.Text = Res.Get(StringId.WizardBlogTypeWelcome);
radioButtonSharePoint.Text = Res.Get(StringId.WizardBlogTypeSharePoint);
radioButtonBlogger.Text = Res.Get(StringId.WizardBlogTypeGoogleBlogger);
radioButtonOther.Text = Res.Get(StringId.WizardBlogTypeOther);
radioButtonWordpress.Text = Res.Get(StringId.CWWelcomeWP);
labelOtherDesc.Text = Res.Get(StringId.BlogServiceNames);
labelWelcomeText.Text = string.Format(CultureInfo.CurrentCulture, labelWelcomeText.Text, ApplicationEnvironment.ProductNameQualified);
// is there at least one provider wizard definition?
// (if so then we override the choose account ui to bury the ms-specific blog providers)
if (BlogProviderAccountWizard.InstalledAccountWizards.Length > 0)
{
// toggle visibility of UI
panelRadioButtons.Visible = false;
panelComboBox.Visible = true;
comboBoxSelectWeblogType.Items.Add(new WeblogType(radioButtonWordpress));
// add standard selections
comboBoxSelectWeblogType.Items.Add(new WeblogType(radioButtonSharePoint));
// add all known provider customizations
foreach (IBlogProviderAccountWizardDescription accountWizard in BlogProviderAccountWizard.InstalledAccountWizards)
comboBoxSelectWeblogType.Items.Add(new WeblogType(accountWizard));
// add other weblog types which have been added on this machine
foreach (string serviceName in WeblogConfigurationWizardSettings.ServiceNamesUsed)
{
if (!SelectWeblogComboContainsServiceName(serviceName))
comboBoxSelectWeblogType.Items.Add(new WeblogType(serviceName));
}
comboBoxSelectWeblogType.Items.Add(new WeblogType(radioButtonBlogger));
// add "another weblog type" entry
comboBoxSelectWeblogType.Items.Add(new WeblogType(radioButtonOther));
// select first item by default
comboBoxSelectWeblogType.SelectedIndex = 0;
// improve on the default selection
if (WeblogConfigurationWizardSettings.LastServiceName != String.Empty)
{
SelectServiceName(WeblogConfigurationWizardSettings.LastServiceName);
}
else // no last added (first run), use provider customization
{
SelectServiceName(BlogProviderAccountWizard.InstalledAccountWizards[0].ServiceName);
}
}
// track changing of selection (used to clear credentials)
comboBoxSelectWeblogType.SelectedIndexChanged += new EventHandler(UserChangedSelectionHandler);
radioButtonWordpress.CheckedChanged += new EventHandler(UserChangedSelectionHandler);
radioButtonSharePoint.CheckedChanged += new EventHandler(UserChangedSelectionHandler);
radioButtonBlogger.CheckedChanged += new EventHandler(UserChangedSelectionHandler);
radioButtonOther.CheckedChanged += new EventHandler(UserChangedSelectionHandler);
}
public override void NaturalizeLayout()
{
if (!DesignMode)
{
//labelWelcomeText.Visible = false;
//panelRadioButtons.Top = 0;
MaximizeWidth(labelWelcomeText);
LayoutHelper.NaturalizeHeightAndDistribute(10, labelWelcomeText, panelRadioButtons, panelComboBox);
MaximizeWidth(panelRadioButtons);
MaximizeWidth(radioButtonWordpress);
MaximizeWidth(radioButtonSharePoint);
MaximizeWidth(radioButtonBlogger);
MaximizeWidth(radioButtonOther);
MaximizeWidth(labelOtherDesc);
using (new AutoGrow(panelRadioButtons, AnchorStyles.Bottom, true))
{
LayoutHelper.NaturalizeHeightAndDistribute(3, radioButtonWordpress, radioButtonSharePoint, radioButtonBlogger, radioButtonOther);
labelOtherDesc.Top = radioButtonOther.Bottom;
}
}
}
public override ConfigPanelId? PanelId
{
get { return ConfigPanelId.BlogType; }
}
public void OnDisplayPanel()
{
_userChangedSelection = false;
}
public bool UserChangedSelection
{
get
{
return _userChangedSelection;
}
}
private bool _userChangedSelection;
public bool IsSharePointBlog
{
get
{
if (panelRadioButtons.Visible)
{
return radioButtonSharePoint.Checked;
}
else
{
return SelectedWeblog.RadioButton == radioButtonSharePoint;
}
}
}
public bool IsGoogleBloggerBlog
{
get
{
if (panelRadioButtons.Visible)
{
return radioButtonBlogger.Checked;
}
else
{
return SelectedWeblog.RadioButton == radioButtonBlogger;
}
}
}
public IBlogProviderAccountWizardDescription ProviderAccountWizard
{
get
{
if (panelRadioButtons.Visible)
{
return null;
}
else
{
return SelectedWeblog.ProviderAccountWizard;
}
}
}
private WeblogType SelectedWeblog
{
get
{
return comboBoxSelectWeblogType.SelectedItem as WeblogType;
}
}
private void UserChangedSelectionHandler(object sender, EventArgs ea)
{
_userChangedSelection = true;
}
private bool SelectWeblogComboContainsServiceName(string serviceName)
{
// scan for service name
foreach (WeblogType weblogType in comboBoxSelectWeblogType.Items)
if (weblogType.ServiceName.Equals(serviceName))
return true;
// didn't find it
return false;
}
private void SelectServiceName(string serviceName)
{
foreach (WeblogType weblogType in comboBoxSelectWeblogType.Items)
{
if (weblogType.ServiceName.Equals(serviceName))
{
comboBoxSelectWeblogType.SelectedItem = weblogType;
break;
}
}
}
private class WeblogType
{
public WeblogType(IBlogProviderAccountWizardDescription providerAccountWizard)
{
_providerAccountWizard = providerAccountWizard;
_name = providerAccountWizard.ServiceName;
}
public WeblogType(RadioButton radioButton)
{
_radioButton = radioButton;
_name = radioButton.Text.Replace("&", String.Empty);
}
public WeblogType(string name)
{
_name = name;
}
public string ServiceName
{
get
{
// remove numonics
return _name;
}
}
public override string ToString()
{
return ServiceName;
}
public RadioButton RadioButton
{
get
{
return _radioButton;
}
}
public IBlogProviderAccountWizardDescription ProviderAccountWizard
{
get
{
return _providerAccountWizard;
}
}
private string _name;
private RadioButton _radioButton;
private IBlogProviderAccountWizardDescription _providerAccountWizard;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component 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.labelWelcomeText = new System.Windows.Forms.Label();
this.panelRadioButtons = new System.Windows.Forms.Panel();
this.radioButtonWordpress = new System.Windows.Forms.RadioButton();
this.radioButtonSharePoint = new System.Windows.Forms.RadioButton();
this.radioButtonBlogger = new System.Windows.Forms.RadioButton();
this.radioButtonOther = new System.Windows.Forms.RadioButton();
this.labelOtherDesc = new System.Windows.Forms.Label();
this.panelComboBox = new System.Windows.Forms.Panel();
this.comboBoxSelectWeblogType = new System.Windows.Forms.ComboBox();
this.privacyPolicyLabel = new System.Windows.Forms.LinkLabel();
this.panelMain.SuspendLayout();
this.panelRadioButtons.SuspendLayout();
this.panelComboBox.SuspendLayout();
this.SuspendLayout();
//
// panelMain
//
this.panelMain.Controls.Add(this.privacyPolicyLabel);
this.panelMain.Controls.Add(this.panelRadioButtons);
this.panelMain.Controls.Add(this.labelWelcomeText);
this.panelMain.Controls.Add(this.panelComboBox);
//
// labelWelcomeText
//
this.labelWelcomeText.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelWelcomeText.Location = new System.Drawing.Point(20, 0);
this.labelWelcomeText.Name = "labelWelcomeText";
this.labelWelcomeText.Size = new System.Drawing.Size(332, 40);
this.labelWelcomeText.TabIndex = 2;
this.labelWelcomeText.Text = "{0} can create and post entries on your blog, and works with a wide variety of we" +
"blog services. Select the type of weblog service to continue.";
//
// panelRadioButtons
//
this.panelRadioButtons.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelRadioButtons.Controls.Add(this.radioButtonWordpress);
this.panelRadioButtons.Controls.Add(this.radioButtonSharePoint);
this.panelRadioButtons.Controls.Add(this.radioButtonBlogger);
this.panelRadioButtons.Controls.Add(this.radioButtonOther);
this.panelRadioButtons.Controls.Add(this.labelOtherDesc);
this.panelRadioButtons.Location = new System.Drawing.Point(20, 88);
this.panelRadioButtons.Name = "panelRadioButtons";
this.panelRadioButtons.Size = new System.Drawing.Size(388, 72);
this.panelRadioButtons.TabIndex = 4;
//
// radioButtonWordpress
//
this.radioButtonWordpress.Location = new System.Drawing.Point(0, 0);
this.radioButtonWordpress.Name = "radioButtonWordpress";
this.radioButtonWordpress.Size = new System.Drawing.Size(104, 24);
this.radioButtonWordpress.TabIndex = 1;
this.radioButtonWordpress.TabStop = true;
this.radioButtonWordpress.Text = "Wordpress";
//
// radioButtonSharePoint
//
this.radioButtonSharePoint.Location = new System.Drawing.Point(0, 24);
this.radioButtonSharePoint.Name = "radioButtonSharePoint";
this.radioButtonSharePoint.Size = new System.Drawing.Size(104, 24);
this.radioButtonSharePoint.TabIndex = 2;
this.radioButtonSharePoint.Text = "Share&Point weblog";
//
// radioButtonBlogger
//
this.radioButtonBlogger.Location = new System.Drawing.Point(0, 72);
this.radioButtonBlogger.Name = "radioButtonBlogger";
this.radioButtonBlogger.Size = new System.Drawing.Size(104, 24);
this.radioButtonBlogger.TabIndex = 3;
this.radioButtonBlogger.Text = "&Google Blogger";
//
// radioButtonOther
//
this.radioButtonOther.Location = new System.Drawing.Point(0, 48);
this.radioButtonOther.Name = "radioButtonOther";
this.radioButtonOther.Size = new System.Drawing.Size(104, 24);
this.radioButtonOther.TabIndex = 4;
this.radioButtonOther.Text = "Another &weblog service";
//
// labelOtherDesc
//
this.labelOtherDesc.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelOtherDesc.ForeColor = System.Drawing.SystemColors.GrayText;
this.labelOtherDesc.Location = new System.Drawing.Point(18, 0);
this.labelOtherDesc.Name = "labelOtherDesc";
this.labelOtherDesc.Size = new System.Drawing.Size(332, 40);
this.labelOtherDesc.TabIndex = 5;
this.labelOtherDesc.Text = "TypePad and others";
//
// panelComboBox
//
this.panelComboBox.Controls.Add(this.comboBoxSelectWeblogType);
this.panelComboBox.Location = new System.Drawing.Point(20, 88);
this.panelComboBox.Name = "panelComboBox";
this.panelComboBox.Size = new System.Drawing.Size(328, 21);
this.panelComboBox.TabIndex = 5;
this.panelComboBox.Visible = false;
//
// comboBoxSelectWeblogType
//
this.comboBoxSelectWeblogType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxSelectWeblogType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectWeblogType.Location = new System.Drawing.Point(0, 0);
this.comboBoxSelectWeblogType.Name = "comboBoxSelectWeblogType";
this.comboBoxSelectWeblogType.Size = new System.Drawing.Size(328, 21);
this.comboBoxSelectWeblogType.TabIndex = 0;
//
// privacyPolicyLabel
//
this.privacyPolicyLabel.AutoSize = true;
this.privacyPolicyLabel.Location = new System.Drawing.Point(23, 167);
this.privacyPolicyLabel.Name = "privacyPolicyLabel";
this.privacyPolicyLabel.Size = new System.Drawing.Size(256, 13);
this.privacyPolicyLabel.TabIndex = 6;
this.privacyPolicyLabel.TabStop = true;
this.privacyPolicyLabel.Text = "We follow the privacy policy of the .NET Foundation.";
this.privacyPolicyLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.privacyPolicyLabel_LinkClicked);
//
// WeblogConfigurationWizardPanelBlogType
//
this.Name = "WeblogConfigurationWizardPanelBlogType";
this.panelMain.ResumeLayout(false);
this.panelMain.PerformLayout();
this.panelRadioButtons.ResumeLayout(false);
this.panelComboBox.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void privacyPolicyLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ShellHelper.LaunchUrl("http://www.dotnetfoundation.org/privacy-policy");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.