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 ShiftRightArithmeticInt3232()
{
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt3232();
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();
// 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();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmUnaryOpTest__ShiftRightArithmeticInt3232
{
private struct TestStruct
{
public Vector256<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticInt3232 testClass)
{
var result = Avx2.ShiftRightArithmetic(_fld, 32);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector256<Int32> _clsVar;
private Vector256<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftRightArithmeticInt3232()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public ImmUnaryOpTest__ShiftRightArithmeticInt3232()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightArithmetic(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightArithmetic(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt3232();
var result = Avx2.ShiftRightArithmetic(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightArithmetic(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightArithmetic(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(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<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] >> 31) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] >> 31) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightArithmetic)}<Int32>(Vector256<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.NativeFormat;
namespace Internal.TypeSystem.Ecma
{
/// <summary>
/// Override of MetadataType that uses actual Ecma335 metadata.
/// </summary>
public sealed partial class EcmaType : MetadataType, EcmaModule.IEntityHandleObject
{
private EcmaModule _module;
private TypeDefinitionHandle _handle;
private TypeDefinition _typeDefinition;
// Cached values
private string _typeName;
private string _typeNamespace;
private TypeDesc[] _genericParameters;
private MetadataType _baseType;
private int _hashcode;
internal EcmaType(EcmaModule module, TypeDefinitionHandle handle)
{
_module = module;
_handle = handle;
_typeDefinition = module.MetadataReader.GetTypeDefinition(handle);
_baseType = this; // Not yet initialized flag
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
public override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return InitializeHashCode();
}
private int InitializeHashCode()
{
TypeDesc containingType = ContainingType;
if (containingType == null)
{
string ns = Namespace;
var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns);
if (ns.Length > 0)
hashCodeBuilder.Append(".");
hashCodeBuilder.Append(Name);
_hashcode = hashCodeBuilder.ToHashCode();
}
else
{
_hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(
containingType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
return _hashcode;
}
EntityHandle EcmaModule.IEntityHandleObject.Handle
{
get
{
return _handle;
}
}
public override TypeSystemContext Context
{
get
{
return _module.Context;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = _typeDefinition.GetGenericParameters();
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new EcmaGenericParameter(_module, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override ModuleDesc Module
{
get
{
return _module;
}
}
public EcmaModule EcmaModule
{
get
{
return _module;
}
}
public MetadataReader MetadataReader
{
get
{
return _module.MetadataReader;
}
}
public TypeDefinitionHandle Handle
{
get
{
return _handle;
}
}
private MetadataType InitializeBaseType()
{
var baseTypeHandle = _typeDefinition.BaseType;
if (baseTypeHandle.IsNil)
{
_baseType = null;
return null;
}
var type = _module.GetType(baseTypeHandle) as MetadataType;
if (type == null)
{
// PREFER: "new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this)" but the metadata is too broken
throw new TypeSystemException.TypeLoadException(Namespace, Name, Module);
}
_baseType = type;
return type;
}
public override DefType BaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
public override MetadataType MetadataBaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0)
{
TypeDesc baseType = this.BaseType;
if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType))
{
flags |= TypeFlags.ValueType;
}
else
if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum))
{
flags |= TypeFlags.Enum;
}
else
{
if ((_typeDefinition.Attributes & TypeAttributes.Interface) != 0)
flags |= TypeFlags.Interface;
else
flags |= TypeFlags.Class;
}
// All other cases are handled during TypeSystemContext intitialization
}
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
foreach (GenericParameterDesc genericParam in Instantiation)
{
if (genericParam.Variance != GenericVariance.None)
{
flags |= TypeFlags.HasGenericVariance;
break;
}
}
}
if ((mask & TypeFlags.HasFinalizerComputed) != 0)
{
flags |= TypeFlags.HasFinalizerComputed;
if (GetFinalizer() != null)
flags |= TypeFlags.HasFinalizer;
}
return flags;
}
private string InitializeName()
{
var metadataReader = this.MetadataReader;
_typeName = metadataReader.GetString(_typeDefinition.Name);
return _typeName;
}
public override string Name
{
get
{
if (_typeName == null)
return InitializeName();
return _typeName;
}
}
private string InitializeNamespace()
{
var metadataReader = this.MetadataReader;
_typeNamespace = metadataReader.GetString(_typeDefinition.Namespace);
return _typeNamespace;
}
public override string Namespace
{
get
{
if (_typeNamespace == null)
return InitializeNamespace();
return _typeNamespace;
}
}
public override IEnumerable<MethodDesc> GetMethods()
{
foreach (var handle in _typeDefinition.GetMethods())
{
yield return (MethodDesc)_module.GetObject(handle);
}
}
public override MethodDesc GetMethod(string name, MethodSignature signature)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
if (stringComparer.Equals(metadataReader.GetMethodDefinition(handle).Name, name))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
if (signature == null || signature.Equals(method.Signature))
return method;
}
}
return null;
}
public override MethodDesc GetStaticConstructor()
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
var methodDefinition = metadataReader.GetMethodDefinition(handle);
if (methodDefinition.Attributes.IsRuntimeSpecialName() &&
stringComparer.Equals(methodDefinition.Name, ".cctor"))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
return method;
}
}
return null;
}
public override MethodDesc GetDefaultConstructor()
{
if (IsAbstract)
return null;
MetadataReader metadataReader = this.MetadataReader;
MetadataStringComparer stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetMethods())
{
var methodDefinition = metadataReader.GetMethodDefinition(handle);
MethodAttributes attributes = methodDefinition.Attributes;
if (attributes.IsRuntimeSpecialName() && attributes.IsPublic()
&& stringComparer.Equals(methodDefinition.Name, ".ctor"))
{
MethodDesc method = (MethodDesc)_module.GetObject(handle);
if (method.Signature.Length != 0)
continue;
return method;
}
}
return null;
}
public override MethodDesc GetFinalizer()
{
// System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer
// by checking for a virtual method override that lands anywhere other than Object in the inheritance
// chain.
if (!HasBaseType)
return null;
TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object);
MethodDesc decl = objectType.GetMethod("Finalize", null);
if (decl != null)
{
MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl == null)
{
// TODO: invalid input: the type doesn't derive from our System.Object
throw new TypeLoadException(this.GetFullName());
}
if (impl.OwningType != objectType)
{
return impl;
}
return null;
}
// TODO: Better exception type. Should be: "CoreLib doesn't have a required thing in it".
throw new NotImplementedException();
}
public override IEnumerable<FieldDesc> GetFields()
{
foreach (var handle in _typeDefinition.GetFields())
{
var field = (EcmaField)_module.GetObject(handle);
yield return field;
}
}
public override FieldDesc GetField(string name)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetFields())
{
if (stringComparer.Equals(metadataReader.GetFieldDefinition(handle).Name, name))
{
var field = (EcmaField)_module.GetObject(handle);
return field;
}
}
return null;
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
foreach (var handle in _typeDefinition.GetNestedTypes())
{
yield return (MetadataType)_module.GetObject(handle);
}
}
public override MetadataType GetNestedType(string name)
{
var metadataReader = this.MetadataReader;
var stringComparer = metadataReader.StringComparer;
foreach (var handle in _typeDefinition.GetNestedTypes())
{
if (stringComparer.Equals(metadataReader.GetTypeDefinition(handle).Name, name))
return (MetadataType)_module.GetObject(handle);
}
return null;
}
public TypeAttributes Attributes
{
get
{
return _typeDefinition.Attributes;
}
}
public override DefType ContainingType
{
get
{
if (!_typeDefinition.Attributes.IsNested())
return null;
var handle = _typeDefinition.GetDeclaringType();
return (DefType)_module.GetType(handle);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return !MetadataReader.GetCustomAttributeHandle(_typeDefinition.GetCustomAttributes(),
attributeNamespace, attributeName).IsNil;
}
public override string ToString()
{
return "[" + _module.ToString() + "]" + this.GetFullName();
}
public override ClassLayoutMetadata GetClassLayout()
{
TypeLayout layout = _typeDefinition.GetLayout();
ClassLayoutMetadata result;
result.PackingSize = layout.PackingSize;
result.Size = layout.Size;
// Skip reading field offsets if this is not explicit layout
if (IsExplicitLayout)
{
var fieldDefinitionHandles = _typeDefinition.GetFields();
var numInstanceFields = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
numInstanceFields++;
}
result.Offsets = new FieldAndOffset[numInstanceFields];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
// Note: GetOffset() returns -1 when offset was not set in the metadata
int specifiedOffset = fieldDefinition.GetOffset();
result.Offsets[index] =
new FieldAndOffset((FieldDesc)_module.GetObject(handle), specifiedOffset == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(specifiedOffset));
index++;
}
}
else
result.Offsets = null;
return result;
}
public override MarshalAsDescriptor[] GetFieldMarshalAsDescriptors()
{
var fieldDefinitionHandles = _typeDefinition.GetFields();
MarshalAsDescriptor[] marshalAsDescriptors = new MarshalAsDescriptor[fieldDefinitionHandles.Count];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
continue;
MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(fieldDefinition);
marshalAsDescriptors[index++] = marshalAsDescriptor;
}
return marshalAsDescriptors;
}
private MarshalAsDescriptor GetMarshalAsDescriptor(FieldDefinition fieldDefinition)
{
if ((fieldDefinition.Attributes & FieldAttributes.HasFieldMarshal) == FieldAttributes.HasFieldMarshal)
{
MetadataReader metadataReader = MetadataReader;
BlobReader marshalAsReader = metadataReader.GetBlobReader(fieldDefinition.GetMarshallingDescriptor());
EcmaSignatureParser parser = new EcmaSignatureParser(EcmaModule, marshalAsReader);
MarshalAsDescriptor marshalAs = parser.ParseMarshalAsDescriptor();
Debug.Assert(marshalAs != null);
return marshalAs;
}
return null;
}
public override bool IsExplicitLayout
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.ExplicitLayout) != 0;
}
}
public override bool IsSequentialLayout
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.SequentialLayout) != 0;
}
}
public override bool IsBeforeFieldInit
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.BeforeFieldInit) != 0;
}
}
public override bool IsModuleType
{
get
{
return _handle.Equals(MetadataTokens.TypeDefinitionHandle(0x00000001 /* COR_GLOBAL_PARENT_TOKEN */));
}
}
public override bool IsSealed
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.Sealed) != 0;
}
}
public override bool IsAbstract
{
get
{
return (_typeDefinition.Attributes & TypeAttributes.Abstract) != 0;
}
}
public override PInvokeStringFormat PInvokeStringFormat
{
get
{
return (PInvokeStringFormat)(_typeDefinition.Attributes & TypeAttributes.StringFormatMask);
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System
{
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
// ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
// is stored as an Int16 internally to save space, but presented as a TimeSpan.
//
// The range is constrained so that both the represented clock time and the represented
// UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
// for actual UTC times, and a slightly constrained range on one end when an offset is
// present.
//
// This class should be substitutable for date time in most cases; so most operations
// effectively work on the clock time. However, the underlying UTC time is what counts
// for the purposes of identity, sorting and subtracting two instances.
//
//
// There are theoretically two date times stored, the UTC and the relative local representation
// or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
// for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
// out and for internal readability.
[StructLayout(LayoutKind.Auto)]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback
{
// Constants
internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
internal const Int64 MinOffset = -MaxOffset;
private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000
private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800
private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000
internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
// Instance Fields
private DateTime _dateTime;
private Int16 _offsetMinutes;
// Constructors
// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset)
{
_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime)
{
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc)
{
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else
{
offset = new TimeSpan(0);
}
_offsetMinutes = ValidateOffset(offset);
_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
// consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
// the offset corresponds to the local.
public DateTimeOffset(DateTime dateTime, TimeSpan offset)
{
if (dateTime.Kind == DateTimeKind.Local)
{
if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime))
{
throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset));
}
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
if (offset != TimeSpan.Zero)
{
throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset));
}
}
_offsetMinutes = ValidateOffset(offset);
_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset)
{
_offsetMinutes = ValidateOffset(offset);
_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond and offset
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset)
{
_offsetMinutes = ValidateOffset(offset);
_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond, Calendar and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset)
{
_offsetMinutes = ValidateOffset(offset);
_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
}
// Returns a DateTimeOffset representing the current date and time. The
// resolution of the returned value depends on the system timer.
public static DateTimeOffset Now
{
get
{
return new DateTimeOffset(DateTime.Now);
}
}
public static DateTimeOffset UtcNow
{
get
{
return new DateTimeOffset(DateTime.UtcNow);
}
}
public DateTime DateTime
{
get
{
return ClockDateTime;
}
}
public DateTime UtcDateTime
{
get
{
return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc);
}
}
public DateTime LocalDateTime
{
get
{
return UtcDateTime.ToLocalTime();
}
}
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
public DateTimeOffset ToOffset(TimeSpan offset)
{
return new DateTimeOffset((_dateTime + offset).Ticks, offset);
}
// Instance Properties
// The clock or visible time represented. This is just a wrapper around the internal date because this is
// the chosen storage mechanism. Going through this helper is good for readability and maintainability.
// This should be used for display but not identity.
private DateTime ClockDateTime
{
get
{
return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}
// Returns the date part of this DateTimeOffset. The resulting value
// corresponds to this DateTimeOffset with the time-of-day part set to
// zero (midnight).
//
public DateTime Date
{
get
{
return ClockDateTime.Date;
}
}
// Returns the day-of-month part of this DateTimeOffset. The returned
// value is an integer between 1 and 31.
//
public int Day
{
get
{
return ClockDateTime.Day;
}
}
// Returns the day-of-week part of this DateTimeOffset. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek DayOfWeek
{
get
{
return ClockDateTime.DayOfWeek;
}
}
// Returns the day-of-year part of this DateTimeOffset. The returned value
// is an integer between 1 and 366.
//
public int DayOfYear
{
get
{
return ClockDateTime.DayOfYear;
}
}
// Returns the hour part of this DateTimeOffset. The returned value is an
// integer between 0 and 23.
//
public int Hour
{
get
{
return ClockDateTime.Hour;
}
}
// Returns the millisecond part of this DateTimeOffset. The returned value
// is an integer between 0 and 999.
//
public int Millisecond
{
get
{
return ClockDateTime.Millisecond;
}
}
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Minute
{
get
{
return ClockDateTime.Minute;
}
}
// Returns the month part of this DateTimeOffset. The returned value is an
// integer between 1 and 12.
//
public int Month
{
get
{
return ClockDateTime.Month;
}
}
public TimeSpan Offset
{
get
{
return new TimeSpan(0, _offsetMinutes, 0);
}
}
// Returns the second part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Second
{
get
{
return ClockDateTime.Second;
}
}
// Returns the tick count for this DateTimeOffset. The returned value is
// the number of 100-nanosecond intervals that have elapsed since 1/1/0001
// 12:00am.
//
public long Ticks
{
get
{
return ClockDateTime.Ticks;
}
}
public long UtcTicks
{
get
{
return UtcDateTime.Ticks;
}
}
// Returns the time-of-day part of this DateTimeOffset. The returned value
// is a TimeSpan that indicates the time elapsed since midnight.
//
public TimeSpan TimeOfDay
{
get
{
return ClockDateTime.TimeOfDay;
}
}
// Returns the year part of this DateTimeOffset. The returned value is an
// integer between 1 and 9999.
//
public int Year
{
get
{
return ClockDateTime.Year;
}
}
// Returns the DateTimeOffset resulting from adding the given
// TimeSpan to this DateTimeOffset.
//
public DateTimeOffset Add(TimeSpan timeSpan)
{
return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// days to this DateTimeOffset. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddDays(double days)
{
return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// hours to this DateTimeOffset. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddHours(double hours)
{
return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
}
// Returns the DateTimeOffset resulting from the given number of
// milliseconds to this DateTimeOffset. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to this DateTimeOffset. The value
// argument is permitted to be negative.
//
public DateTimeOffset AddMilliseconds(double milliseconds)
{
return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// minutes to this DateTimeOffset. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddMinutes(double minutes)
{
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
public DateTimeOffset AddMonths(int months)
{
return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// seconds to this DateTimeOffset. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddSeconds(double seconds)
{
return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// 100-nanosecond ticks to this DateTimeOffset. The value argument
// is permitted to be negative.
//
public DateTimeOffset AddTicks(long ticks)
{
return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// years to this DateTimeOffset. The result is computed by incrementing
// (or decrementing) the year part of this DateTimeOffset by value
// years. If the month and day of this DateTimeOffset is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of this DateTimeOffset.
//
public DateTimeOffset AddYears(int years)
{
return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
}
// Compares two DateTimeOffset values, returning an integer that indicates
// their relationship.
//
public static int Compare(DateTimeOffset first, DateTimeOffset second)
{
return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
}
// Compares this DateTimeOffset to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTimeOffset, or otherwise an exception
// occurs. Null is considered less than any instance.
//
int IComparable.CompareTo(Object obj)
{
if (obj == null) return 1;
if (!(obj is DateTimeOffset))
{
throw new ArgumentException(SR.Arg_MustBeDateTimeOffset);
}
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
if (utc < objUtc) return -1;
return 0;
}
public int CompareTo(DateTimeOffset other)
{
DateTime otherUtc = other.UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > otherUtc) return 1;
if (utc < otherUtc) return -1;
return 0;
}
// Checks if this DateTimeOffset is equal to a given object. Returns
// true if the given object is a boxed DateTimeOffset and its value
// is equal to the value of this DateTimeOffset. Returns false
// otherwise.
//
public override bool Equals(Object obj)
{
if (obj is DateTimeOffset)
{
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
public bool Equals(DateTimeOffset other)
{
return UtcDateTime.Equals(other.UtcDateTime);
}
public bool EqualsExact(DateTimeOffset other)
{
//
// returns true when the ClockDateTime, Kind, and Offset match
//
// currently the Kind should always be Unspecified, but there is always the possibility that a future version
// of DateTimeOffset overloads the Kind field
//
return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
}
// Compares two DateTimeOffset values for equality. Returns true if
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
public static bool Equals(DateTimeOffset first, DateTimeOffset second)
{
return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
}
// Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
// a long representing the date and time as the number of
// 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
//
public static DateTimeOffset FromFileTime(long fileTime)
{
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
public static DateTimeOffset FromUnixTimeSeconds(long seconds)
{
if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds)
{
throw new ArgumentOutOfRangeException(nameof(seconds),
SR.Format(SR.ArgumentOutOfRange_Range, UnixMinSeconds, UnixMaxSeconds));
}
long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
{
const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds)
{
throw new ArgumentOutOfRangeException(nameof(milliseconds),
SR.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds));
}
long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
// ----- SECTION: private serialization instance methods ----------------*
void IDeserializationCallback.OnDeserialization(Object sender)
{
try
{
_offsetMinutes = ValidateOffset(Offset);
_dateTime = ValidateDate(ClockDateTime, Offset);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue("DateTime", _dateTime); // Do not rename (binary serialization)
info.AddValue("OffsetMinutes", _offsetMinutes); // Do not rename (binary serialization)
}
private DateTimeOffset(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization)
_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); // Do not rename (binary serialization)
}
// Returns the hash code for this DateTimeOffset.
//
public override int GetHashCode()
{
return UtcDateTime.GetHashCode();
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input.AsReadOnlySpan(),
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
return Parse(input, formatProvider, DateTimeStyles.None);
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input.AsReadOnlySpan(),
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null, DateTimeStyles styles = DateTimeStyles.None)
{
styles = ValidateStyles(styles, nameof(styles));
DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExact(input.AsReadOnlySpan(),
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None)
{
styles = ValidateStyles(styles, nameof(styles));
DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.index); // TODO: index => input
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExactMultiple(input.AsReadOnlySpan(),
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None)
{
styles = ValidateStyles(styles, nameof(styles));
DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public TimeSpan Subtract(DateTimeOffset value)
{
return UtcDateTime.Subtract(value.UtcDateTime);
}
public DateTimeOffset Subtract(TimeSpan value)
{
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
public long ToFileTime()
{
return UtcDateTime.ToFileTime();
}
public long ToUnixTimeSeconds()
{
// Truncate sub-second precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times.
//
// For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0
// ticks = 621355967990010000
// ticksFromEpoch = ticks - UnixEpochTicks = -9990000
// secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0
//
// Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division,
// whereas we actually always want to round *down* when converting to Unix time. This happens
// automatically for positive Unix time values. Now the example becomes:
// seconds = ticks / TimeSpan.TicksPerSecond = 62135596799
// secondsFromEpoch = seconds - UnixEpochSeconds = -1
//
// In other words, we want to consistently round toward the time 1/1/0001 00:00:00,
// rather than toward the Unix Epoch (1/1/1970 00:00:00).
long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
return seconds - UnixEpochSeconds;
}
public long ToUnixTimeMilliseconds()
{
// Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times
long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond;
return milliseconds - UnixEpochMilliseconds;
}
public DateTimeOffset ToLocalTime()
{
return ToLocalTime(false);
}
internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
public override String ToString()
{
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(String format)
{
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(IFormatProvider formatProvider)
{
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public String ToString(String format, IFormatProvider formatProvider)
{
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public bool TryFormat(Span<char> destination, out int charsWritten, string format = null, IFormatProvider formatProvider = null) =>
DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
public DateTimeOffset ToUniversalTime()
{
return new DateTimeOffset(UtcDateTime);
}
public static Boolean TryParse(String input, out DateTimeOffset result)
{
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input.AsReadOnlySpan(),
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static bool TryParse(ReadOnlySpan<char> input, out DateTimeOffset result)
{
bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out DateTime dateResult, out TimeSpan offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null)
{
result = default(DateTimeOffset);
return false;
}
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input.AsReadOnlySpan(),
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null)
{
result = default(DateTimeOffset);
return false;
}
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExact(input.AsReadOnlySpan(),
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static bool TryParseExact(
ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
if (input == null)
{
result = default(DateTimeOffset);
return false;
}
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExactMultiple(input.AsReadOnlySpan(),
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static bool TryParseExact(
ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
{
styles = ValidateStyles(styles, nameof(styles));
bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
// Ensures the TimeSpan is valid to go in a DateTimeOffset.
private static Int16 ValidateOffset(TimeSpan offset)
{
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0)
{
throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset));
}
if (ticks < MinOffset || ticks > MaxOffset)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange);
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
// Ensures that the time and offset are in range.
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset)
{
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange);
}
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
}
private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName)
{
if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName);
}
if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0))
{
throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName);
}
if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
{
throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName);
}
// RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime
style &= ~DateTimeStyles.RoundtripKind;
// AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
style &= ~DateTimeStyles.AssumeLocal;
return style;
}
// Operators
public static implicit operator DateTimeOffset(DateTime dateTime)
{
return new DateTimeOffset(dateTime);
}
public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
{
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
{
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime - right.UtcDateTime;
}
public static bool operator ==(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime == right.UtcDateTime;
}
public static bool operator !=(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime != right.UtcDateTime;
}
public static bool operator <(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime < right.UtcDateTime;
}
public static bool operator <=(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime <= right.UtcDateTime;
}
public static bool operator >(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime > right.UtcDateTime;
}
public static bool operator >=(DateTimeOffset left, DateTimeOffset right)
{
return left.UtcDateTime >= right.UtcDateTime;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D02Level1 (editable child object).<br/>
/// This is a generated base class of <see cref="D02Level1"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D03Level11Objects"/> of type <see cref="D03Level11Coll"/> (1:M relation to <see cref="D04Level11"/>)<br/>
/// This class is an item of <see cref="D01Level1Coll"/> collection.
/// </remarks>
[Serializable]
public partial class D02Level1 : BusinessBase<D02Level1>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_IDProperty = RegisterProperty<int>(p => p.Level_1_ID, "Level_1 ID");
/// <summary>
/// Gets the Level_1 ID.
/// </summary>
/// <value>The Level_1 ID.</value>
public int Level_1_ID
{
get { return GetProperty(Level_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_NameProperty = RegisterProperty<string>(p => p.Level_1_Name, "Level_1 Name");
/// <summary>
/// Gets or sets the Level_1 Name.
/// </summary>
/// <value>The Level_1 Name.</value>
public string Level_1_Name
{
get { return GetProperty(Level_1_NameProperty); }
set { SetProperty(Level_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03Level11SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03Level11Child> D03Level11SingleObjectProperty = RegisterProperty<D03Level11Child>(p => p.D03Level11SingleObject, "B3 Level11 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Level11 Single Object ("self load" child property).
/// </summary>
/// <value>The D03 Level11 Single Object.</value>
public D03Level11Child D03Level11SingleObject
{
get { return GetProperty(D03Level11SingleObjectProperty); }
private set { LoadProperty(D03Level11SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03Level11ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03Level11ReChild> D03Level11ASingleObjectProperty = RegisterProperty<D03Level11ReChild>(p => p.D03Level11ASingleObject, "B3 Level11 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Level11 ASingle Object ("self load" child property).
/// </summary>
/// <value>The D03 Level11 ASingle Object.</value>
public D03Level11ReChild D03Level11ASingleObject
{
get { return GetProperty(D03Level11ASingleObjectProperty); }
private set { LoadProperty(D03Level11ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03Level11Objects"/> property.
/// </summary>
public static readonly PropertyInfo<D03Level11Coll> D03Level11ObjectsProperty = RegisterProperty<D03Level11Coll>(p => p.D03Level11Objects, "B3 Level11 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Level11 Objects ("self load" child property).
/// </summary>
/// <value>The D03 Level11 Objects.</value>
public D03Level11Coll D03Level11Objects
{
get { return GetProperty(D03Level11ObjectsProperty); }
private set { LoadProperty(D03Level11ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D02Level1"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D02Level1"/> object.</returns>
internal static D02Level1 NewD02Level1()
{
return DataPortal.CreateChild<D02Level1>();
}
/// <summary>
/// Factory method. Loads a <see cref="D02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="D02Level1"/> object.</returns>
internal static D02Level1 GetD02Level1(SafeDataReader dr)
{
D02Level1 obj = new D02Level1();
// 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="D02Level1"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private D02Level1()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D02Level1"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D03Level11SingleObjectProperty, DataPortal.CreateChild<D03Level11Child>());
LoadProperty(D03Level11ASingleObjectProperty, DataPortal.CreateChild<D03Level11ReChild>());
LoadProperty(D03Level11ObjectsProperty, DataPortal.CreateChild<D03Level11Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_IDProperty, dr.GetInt32("Level_1_ID"));
LoadProperty(Level_1_NameProperty, dr.GetString("Level_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D03Level11SingleObjectProperty, D03Level11Child.GetD03Level11Child(Level_1_ID));
LoadProperty(D03Level11ASingleObjectProperty, D03Level11ReChild.GetD03Level11ReChild(Level_1_ID));
LoadProperty(D03Level11ObjectsProperty, D03Level11Coll.GetD03Level11Coll(Level_1_ID));
}
/// <summary>
/// Inserts a new <see cref="D02Level1"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_IDProperty, (int) cmd.Parameters["@Level_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D02Level1"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D02Level1"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteD02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(D03Level11SingleObjectProperty, DataPortal.CreateChild<D03Level11Child>());
LoadProperty(D03Level11ASingleObjectProperty, DataPortal.CreateChild<D03Level11ReChild>());
LoadProperty(D03Level11ObjectsProperty, DataPortal.CreateChild<D03Level11Coll>());
}
#endregion
#region Pseudo Events
/// <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
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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.
*
* 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.
*
*<author>James Nies</author>
*<contributor>Justin Dearing</contributor>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core
{
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using NArrange.Core.CodeElements;
using NArrange.Core.Configuration;
/// <summary>
/// Abstract code write visitor implementation.
/// </summary>
public abstract class CodeWriteVisitor : ICodeElementVisitor
{
#region Fields
/// <summary>
/// Default element block length.
/// </summary>
protected const int DefaultBlockLength = 256;
/// <summary>
/// Code configuration.
/// </summary>
private readonly CodeConfiguration _configuration;
/// <summary>
/// The text writer to write elements to.
/// </summary>
private readonly TextWriter _writer;
/// <summary>
/// Tab count used to control the indentation level at which elements are written.
/// </summary>
private int _tabCount;
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new VBWriteVisitor.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="configuration">The configuration.</param>
protected CodeWriteVisitor(TextWriter writer, CodeConfiguration configuration)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
Debug.Assert(configuration != null, "Configuration should not be null.");
_writer = writer;
_configuration = configuration;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the code configuration.
/// </summary>
protected CodeConfiguration Configuration
{
get
{
return _configuration;
}
}
/// <summary>
/// Gets or sets the current tab count used for writing indented text.
/// </summary>
protected int TabCount
{
get
{
return _tabCount;
}
set
{
_tabCount = value;
}
}
/// <summary>
/// Gets the writer.
/// </summary>
protected TextWriter Writer
{
get
{
return _writer;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Processes an attribute element.
/// </summary>
/// <param name="element">Attribute code element.</param>
public abstract void VisitAttributeElement(AttributeElement element);
/// <summary>
/// Processes a comment element.
/// </summary>
/// <param name="element">Comment code element.</param>
public abstract void VisitCommentElement(CommentElement element);
/// <summary>
/// Processes a condition directive element.
/// </summary>
/// <param name="element">Condition directive code element.</param>
public abstract void VisitConditionDirectiveElement(ConditionDirectiveElement element);
/// <summary>
/// Processes a constructor element.
/// </summary>
/// <param name="element">Constructor code element.</param>
public abstract void VisitConstructorElement(ConstructorElement element);
/// <summary>
/// Processes a delegate element.
/// </summary>
/// <param name="element">Delegate code element.</param>
public abstract void VisitDelegateElement(DelegateElement element);
/// <summary>
/// Processes a event element.
/// </summary>
/// <param name="element">Event code element.</param>
public abstract void VisitEventElement(EventElement element);
/// <summary>
/// Processes a field element.
/// </summary>
/// <param name="element">Field code element.</param>
public abstract void VisitFieldElement(FieldElement element);
/// <summary>
/// Processes a group element.
/// </summary>
/// <param name="element">Group element.</param>
public virtual void VisitGroupElement(GroupElement element)
{
//
// Process all children
//
for (int childIndex = 0; childIndex < element.Children.Count; childIndex++)
{
ICodeElement childElement = element.Children[childIndex];
FieldElement childFieldElement = childElement as FieldElement;
if (childIndex > 0 && childFieldElement != null &&
childFieldElement.HeaderComments.Count > 0)
{
WriteIndentedLine();
}
childElement.Accept(this);
if (childIndex < element.Children.Count - 1)
{
if (element.SeparatorType == GroupSeparatorType.Custom)
{
WriteIndentedLine(element.CustomSeparator);
}
else
{
WriteIndentedLine();
}
if (childElement is GroupElement)
{
WriteIndentedLine();
}
}
}
}
/// <summary>
/// Processes a method element.
/// </summary>
/// <param name="element">Method code element.</param>
public abstract void VisitMethodElement(MethodElement element);
/// <summary>
/// Processes a namespace element.
/// </summary>
/// <param name="element">Namespace code element.</param>
public abstract void VisitNamespaceElement(NamespaceElement element);
/// <summary>
/// Processes a property element.
/// </summary>
/// <param name="element">Property code element.</param>
public abstract void VisitPropertyElement(PropertyElement element);
/// <summary>
/// Processes a region element.
/// </summary>
/// <param name="element">Region code element.</param>
public void VisitRegionElement(RegionElement element)
{
RegionStyle regionStyle = _configuration.Formatting.Regions.Style;
if (regionStyle == RegionStyle.Default)
{
// Use the default region style
regionStyle = RegionStyle.Directive;
}
if (regionStyle == RegionStyle.NoDirective ||
!element.DirectivesEnabled)
{
CodeWriter.WriteVisitElements(element.Children, Writer, this);
}
else
{
if (regionStyle == RegionStyle.Directive)
{
WriteRegionBeginDirective(element);
}
else if (regionStyle == RegionStyle.CommentDirective)
{
CommentElement commentDirective = new CommentElement(
string.Format(
CultureInfo.InvariantCulture,
Configuration.Formatting.Regions.CommentDirectiveBeginFormat,
element.Name).TrimEnd());
VisitCommentElement(commentDirective);
}
Writer.WriteLine();
WriteChildren(element);
if (element.Children.Count > 0)
{
Writer.WriteLine();
}
if (regionStyle == RegionStyle.Directive)
{
WriteRegionEndDirective(element);
}
else if (regionStyle == RegionStyle.CommentDirective)
{
string regionName = string.Empty;
if (Configuration.Formatting.Regions.EndRegionNameEnabled)
{
regionName = element.Name;
}
CommentElement commentDirective = new CommentElement(
string.Format(
CultureInfo.InvariantCulture,
Configuration.Formatting.Regions.CommentDirectiveEndFormat,
regionName).TrimEnd());
VisitCommentElement(commentDirective);
}
}
}
/// <summary>
/// Processes a type element.
/// </summary>
/// <param name="element">Type code element.</param>
public abstract void VisitTypeElement(TypeElement element);
/// <summary>
/// Processes a using element.
/// </summary>
/// <param name="element">Using/Import directive code element.</param>
public abstract void VisitUsingElement(UsingElement element);
/// <summary>
/// Gets the formatted text to write for a comment.
/// </summary>
/// <param name="comment">Comment with text.</param>
/// <returns>Formatted comment text.</returns>
protected string FormatCommentText(ICommentElement comment)
{
string commentText = null;
if (comment != null)
{
switch (comment.Type)
{
case CommentType.Line:
int tabCount = 0;
string commentLine = ProcessLineWhitepace(comment.Text, ref tabCount);
string leadingSpace = CreateTabWhitespace(tabCount);
commentText = leadingSpace + commentLine;
break;
default:
commentText = comment.Text;
break;
}
}
return commentText;
}
/// <summary>
/// Writes children for a block element.
/// </summary>
/// <param name="element">Element whose children will be written.</param>
protected virtual void WriteBlockChildren(ICodeElement element)
{
if (element.Children.Count == 0)
{
Writer.WriteLine();
}
else
{
//
// Process all children
//
WriteChildren(element);
}
}
/// <summary>
/// Writes child elements.
/// </summary>
/// <param name="element">Element whose children will be written.</param>
protected void WriteChildren(ICodeElement element)
{
if (element.Children.Count > 0)
{
Writer.WriteLine();
}
CodeWriter.WriteVisitElements(element.Children, Writer, this);
if (element.Children.Count > 0)
{
Writer.WriteLine();
}
}
/// <summary>
/// Writes a closing comment.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="commentPrefix">Comment prefix.</param>
protected void WriteClosingComment(TextCodeElement element, string commentPrefix)
{
if (Configuration.Formatting.ClosingComments.Enabled)
{
string format = Configuration.Formatting.ClosingComments.Format;
if (!string.IsNullOrEmpty(format))
{
string formatted = element.ToString(format);
Writer.Write(
string.Format(CultureInfo.InvariantCulture, " {0}{1}", commentPrefix, formatted));
}
}
}
/// <summary>
/// Writes a collection of comment lines.
/// </summary>
/// <param name="comments">The comments.</param>
protected void WriteComments(ReadOnlyCollection<ICommentElement> comments)
{
foreach (ICommentElement comment in comments)
{
comment.Accept(this);
WriteIndentedLine();
}
}
/// <summary>
/// Writes the specified text using the current TabCount.
/// </summary>
/// <param name="text">The text to write.</param>
protected void WriteIndented(string text)
{
_writer.Write(CreateTabWhitespace(_tabCount));
_writer.Write(text);
}
/// <summary>
/// Writes a line of text using the current TabCount.
/// </summary>
/// <param name="text">The text to write.</param>
protected void WriteIndentedLine(string text)
{
if (!string.IsNullOrEmpty(text))
{
WriteIndented(text);
}
_writer.WriteLine();
}
/// <summary>
/// Writes a new line using the current TabCount.
/// </summary>
protected void WriteIndentedLine()
{
WriteIndentedLine(string.Empty);
}
/// <summary>
/// Writes a starting region directive.
/// </summary>
/// <param name="element">The region element.</param>
protected abstract void WriteRegionBeginDirective(RegionElement element);
/// <summary>
/// Writes an ending region directive.
/// </summary>
/// <param name="element">The region element.</param>
protected abstract void WriteRegionEndDirective(RegionElement element);
/// <summary>
/// Writes a block of text.
/// </summary>
/// <param name="text">Block of text to write.</param>
protected void WriteTextBlock(string text)
{
if (!string.IsNullOrEmpty(text))
{
int originalTabCount = TabCount;
string[] lines = text.Split(new char[] { '\n' }, StringSplitOptions.None);
bool previousLineBlank = false;
for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
{
string line = lines[lineIndex];
bool isLineBlank = line.Trim().Length == 0;
if (!isLineBlank ||
!Configuration.Formatting.LineSpacing.RemoveConsecutiveBlankLines ||
!previousLineBlank)
{
int lineTabCount = 0;
string formattedLine = ProcessLineWhitepace(line, ref lineTabCount);
if (lineTabCount > TabCount)
{
TabCount = lineTabCount;
}
if (lineIndex < lines.Length - 1)
{
WriteIndentedLine(formattedLine);
}
else
{
WriteIndented(formattedLine);
}
}
previousLineBlank = isLineBlank;
TabCount = originalTabCount;
}
}
}
/// <summary>
/// Creates whitespace for the specified number of tabs.
/// </summary>
/// <param name="tabCount">Number of tabs worth of whiespace to create.</param>
/// <returns>Whitespace string.</returns>
private string CreateTabWhitespace(int tabCount)
{
string leadingSpace;
if (Configuration.Formatting.Tabs.TabStyle == TabStyle.Spaces)
{
leadingSpace = new string(' ', Configuration.Formatting.Tabs.SpacesPerTab * tabCount);
}
else if (Configuration.Formatting.Tabs.TabStyle == TabStyle.Tabs)
{
leadingSpace = new string('\t', tabCount);
}
else
{
throw new InvalidOperationException(
string.Format(
Thread.CurrentThread.CurrentCulture,
"Unknown tab style {0}.",
_configuration.Formatting.Tabs.TabStyle));
}
return leadingSpace;
}
/// <summary>
/// Processes leading/trailing whitespace for a line of text.
/// </summary>
/// <param name="line">Line to process.</param>
/// <param name="lineTabCount">Number of preceding tabs.</param>
/// <returns>Processed line.</returns>
private string ProcessLineWhitepace(string line, ref int lineTabCount)
{
string formattedLine;
StringBuilder lineBuilder = new StringBuilder(line);
while (lineBuilder.Length > 0 && CodeParser.IsWhiteSpace(lineBuilder[0]))
{
if (lineBuilder[0] == '\t')
{
lineBuilder.Remove(0, 1);
lineTabCount++;
}
else if (lineBuilder[0] == ' ')
{
int spaceCount = 0;
int index = 0;
while (lineBuilder.Length > 0 && index < lineBuilder.Length &&
lineBuilder[index] == ' ')
{
spaceCount++;
if (spaceCount == Configuration.Formatting.Tabs.SpacesPerTab)
{
lineBuilder.Remove(0, Configuration.Formatting.Tabs.SpacesPerTab);
spaceCount = 0;
index = 0;
lineTabCount++;
}
else
{
index++;
}
}
if (!(lineBuilder.Length > 0 && lineBuilder[0] == '\t'))
{
break;
}
}
else
{
break;
}
}
formattedLine = lineBuilder.ToString().TrimEnd();
return formattedLine;
}
#endregion Methods
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Authentication;
namespace System.DirectoryServices.AccountManagement
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
abstract public class PrincipalException : SystemException
{
internal PrincipalException() : base() { }
internal PrincipalException(string message) : base(message) { }
internal PrincipalException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PrincipalException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class MultipleMatchesException : PrincipalException
{
public MultipleMatchesException() : base() { }
public MultipleMatchesException(string message) : base(message) { }
public MultipleMatchesException(string message, Exception innerException) :
base(message, innerException)
{ }
protected MultipleMatchesException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class NoMatchingPrincipalException : PrincipalException
{
public NoMatchingPrincipalException() : base() { }
public NoMatchingPrincipalException(string message) : base(message) { }
public NoMatchingPrincipalException(string message, Exception innerException) :
base(message, innerException)
{ }
protected NoMatchingPrincipalException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
throw new PlatformNotSupportedException();
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class PasswordException : PrincipalException
{
public PasswordException() : base() { }
public PasswordException(string message) : base(message) { }
public PasswordException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PasswordException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class PrincipalExistsException : PrincipalException
{
public PrincipalExistsException() : base() { }
public PrincipalExistsException(string message) : base(message) { }
public PrincipalExistsException(string message, Exception innerException) :
base(message, innerException)
{ }
protected PrincipalExistsException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class PrincipalServerDownException : PrincipalException
{
private int _errorCode = 0;
private string _serverName = null;
public PrincipalServerDownException() : base() { }
public PrincipalServerDownException(string message) : base(message) { }
public PrincipalServerDownException(string message, Exception innerException) :
base(message, innerException)
{ }
public PrincipalServerDownException(string message, int errorCode) : base(message)
{
_errorCode = errorCode;
}
public PrincipalServerDownException(string message, Exception innerException, int errorCode) : base(message, innerException)
{
_errorCode = errorCode;
}
public PrincipalServerDownException(string message, Exception innerException, int errorCode, string serverName) : base(message, innerException)
{
_errorCode = errorCode;
_serverName = serverName;
}
protected PrincipalServerDownException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
_errorCode = info.GetInt32("errorCode");
_serverName = (string)info.GetValue("serverName", typeof(string));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("errorCode", _errorCode);
info.AddValue("serverName", _serverName, typeof(string));
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class PrincipalOperationException : PrincipalException
{
private int _errorCode = 0;
public PrincipalOperationException() : base() { }
public PrincipalOperationException(string message) : base(message) { }
public PrincipalOperationException(string message, Exception innerException) :
base(message, innerException)
{ }
public PrincipalOperationException(string message, int errorCode) : base(message)
{
_errorCode = errorCode;
}
public PrincipalOperationException(string message, Exception innerException, int errorCode) : base(message, innerException)
{
_errorCode = errorCode;
}
protected PrincipalOperationException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
_errorCode = info.GetInt32("errorCode");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("errorCode", _errorCode);
}
public int ErrorCode
{
get
{
return _errorCode;
}
}
}
internal class ExceptionHelper
{
// Put a private constructor because this class should only be used as static methods
private ExceptionHelper() { }
private static int s_ERROR_NOT_ENOUGH_MEMORY = 8; // map to outofmemory exception
private static int s_ERROR_OUTOFMEMORY = 14; // map to outofmemory exception
private static int s_ERROR_DS_DRA_OUT_OF_MEM = 8446; // map to outofmemory exception
private static int s_ERROR_NO_SUCH_DOMAIN = 1355; // map to ActiveDirectoryServerDownException
private static int s_ERROR_ACCESS_DENIED = 5; // map to UnauthorizedAccessException
private static int s_ERROR_NO_LOGON_SERVERS = 1311; // map to ActiveDirectoryServerDownException
private static int s_ERROR_DS_DRA_ACCESS_DENIED = 8453; // map to UnauthorizedAccessException
private static int s_RPC_S_OUT_OF_RESOURCES = 1721; // map to outofmemory exception
internal static int RPC_S_SERVER_UNAVAILABLE = 1722; // map to ActiveDirectoryServerDownException
internal static int RPC_S_CALL_FAILED = 1726; // map to ActiveDirectoryServerDownException
// internal static int ERROR_DS_DRA_BAD_DN = 8439; //fix error CS0414: Warning as Error: is assigned but its value is never used
// internal static int ERROR_DS_NAME_UNPARSEABLE = 8350; //fix error CS0414: Warning as Error: is assigned but its value is never used
// internal static int ERROR_DS_UNKNOWN_ERROR = 8431; //fix error CS0414: Warning as Error: is assigned but its value is never used
// public static uint ERROR_HRESULT_ACCESS_DENIED = 0x80070005; //fix error CS0414: Warning as Error: is assigned but its value is never used
public static uint ERROR_HRESULT_LOGON_FAILURE = 0x8007052E;
public static uint ERROR_HRESULT_CONSTRAINT_VIOLATION = 0x8007202f;
public static uint ERROR_LOGON_FAILURE = 0x31;
// public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used
//
// This method maps some common COM Hresults to
// existing clr exceptions
//
internal static Exception GetExceptionFromCOMException(COMException e)
{
Exception exception;
int errorCode = e.ErrorCode;
string errorMessage = e.Message;
//
// Check if we can throw a more specific exception
//
if (errorCode == unchecked((int)0x80070005))
{
//
// Access Denied
//
exception = new UnauthorizedAccessException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052))
{
//
// Password does not meet complexity requirements or old password does not match or policy restriction has been enforced.
//
exception = new PasswordException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392))
{
//
// Principal already exists
//
exception = new PrincipalExistsException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007052e))
{
//
// Logon Failure
//
exception = new AuthenticationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007202f))
{
//
// Constraint Violation
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80072035))
{
//
// Unwilling to perform
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80070008))
{
//
// No Memory
//
exception = new OutOfMemoryException();
}
else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f)))
{
exception = new PrincipalServerDownException(errorMessage, e, errorCode, null);
}
else
{
//
// Wrap the exception in a generic OperationException
//
exception = new PrincipalOperationException(errorMessage, e, errorCode);
}
return exception;
}
internal static Exception GetExceptionFromErrorCode(int errorCode)
{
return GetExceptionFromErrorCode(errorCode, null);
}
internal static Exception GetExceptionFromErrorCode(int errorCode, string targetName)
{
string errorMsg = GetErrorMessage(errorCode, false);
if ((errorCode == s_ERROR_ACCESS_DENIED) || (errorCode == s_ERROR_DS_DRA_ACCESS_DENIED))
return new UnauthorizedAccessException(errorMsg);
else if ((errorCode == s_ERROR_NOT_ENOUGH_MEMORY) || (errorCode == s_ERROR_OUTOFMEMORY) || (errorCode == s_ERROR_DS_DRA_OUT_OF_MEM) || (errorCode == s_RPC_S_OUT_OF_RESOURCES))
return new OutOfMemoryException();
else if ((errorCode == s_ERROR_NO_LOGON_SERVERS) || (errorCode == s_ERROR_NO_SUCH_DOMAIN) || (errorCode == RPC_S_SERVER_UNAVAILABLE) || (errorCode == RPC_S_CALL_FAILED))
{
return new PrincipalServerDownException(errorMsg, errorCode);
}
else
{
return new PrincipalOperationException(errorMsg, errorCode);
}
}
internal static string GetErrorMessage(int errorCode, bool hresult)
{
uint temp = (uint)errorCode;
if (!hresult)
{
temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000));
}
return new Win32Exception((int)temp).Message;
}
}
}
| |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Examples.Tasks.HelloTask;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Examples;
using Org.Apache.REEF.Tang.Exceptions;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Types;
using Org.Apache.REEF.Tang.Util;
using Xunit;
namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy
{
public class TestClassHierarchy
{
public IClassHierarchy ns = null;
public TestClassHierarchy()
{
if (ns == null)
{
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
}
}
[Fact]
public void TestString()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.Null(n);
Assert.NotNull(ns.GetNode(typeof(string).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestInt()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.Null(n);
Assert.NotNull(ns.GetNode(typeof(int).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (ApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestSimpleConstructors()
{
IClassNode cls = (IClassNode)ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.True(cls.GetChildren().Count == 0);
IList<IConstructorDef> def = cls.GetInjectableConstructors();
Assert.Equal(3, def.Count);
}
[Fact]
public void TestTimer()
{
IClassNode timerClassNode = (IClassNode)ns.GetNode(typeof(Timer).AssemblyQualifiedName);
INode secondNode = ns.GetNode(typeof(Timer.Seconds).AssemblyQualifiedName);
Assert.Equal(secondNode.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(Timer.Seconds)));
}
[Fact]
public void TestNamedParameterConstructors()
{
var node = ns.GetNode(typeof(NamedParameterConstructors).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(NamedParameterConstructors)));
}
[Fact]
public void TestArray()
{
Type t = (new string[0]).GetType();
INode node = ns.GetNode(t.AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), t.AssemblyQualifiedName);
}
[Fact]
public void TestRepeatConstructorArg()
{
TestNegativeCase(typeof(RepeatConstructorArg),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArg(int,int).");
}
[Fact]
public void TestRepeatConstructorArgClasses()
{
TestNegativeCase(typeof(RepeatConstructorArgClasses),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArgClasses(A, A).");
}
[Fact]
public void testLeafRepeatedConstructorArgClasses()
{
INode node = ns.GetNode(typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
}
[Fact]
public void TestNamedRepeatConstructorArgClasses()
{
INode node = ns.GetNode(typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
}
[Fact]
public void TestResolveDependencies()
{
ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.NotNull(ns.GetNode(typeof(string).AssemblyQualifiedName));
}
[Fact]
public void TestDocumentedLocalNamedParameter()
{
var node = ns.GetNode(typeof(DocumentedLocalNamedParameter).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(DocumentedLocalNamedParameter)));
}
[Fact]
public void TestNamedParameterTypeMismatch()
{
TestNegativeCase(typeof(NamedParameterTypeMismatch),
"Named parameter type mismatch in NamedParameterTypeMismatch. Constructor expects a System.String but Foo is a System.Int32.");
}
[Fact]
public void TestUnannotatedName()
{
TestNegativeCase(typeof(UnannotatedName),
"Named parameter UnannotatedName is missing its [NamedParameter] attribute.");
}
[Fact]
public void TestAnnotatedNotName()
{
TestNegativeCase(typeof(AnnotatedNotName),
"Found illegal [NamedParameter] AnnotatedNotName does not implement Name<T>.");
}
[Fact]
public void TestAnnotatedNameWrongInterface()
{
TestNegativeCase(typeof(AnnotatedNameWrongInterface),
"Found illegal [NamedParameter] AnnotatedNameWrongInterface does not implement Name<T>.");
}
[Fact]
public void TestAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(AnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.AnnotatedNameMultipleInterfaces implements multiple interfaces. It is only allowed to implement Name<T>.");
}
[Fact]
public void TestUnAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(UnAnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.UnAnnotatedNameMultipleInterfaces is missing its @NamedParameter annotation.");
}
[Fact]
public void TestNameWithConstructor()
{
TestNegativeCase(typeof(NameWithConstructor),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithConstructor has a constructor. Named parameters must not declare any constructors.");
}
[Fact]
public void TestNameWithZeroArgInject()
{
TestNegativeCase(typeof(NameWithZeroArgInject),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithZeroArgInject has an injectable constructor. Named parameters must not declare any constructors.");
}
[Fact]
public void TestInjectNonStaticLocalArgClass()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
}
[Fact]
public void TestInjectNonStaticLocalType()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
}
[Fact]
public void TestOKShortNames()
{
var node = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(ShortNameFooA).AssemblyQualifiedName);
}
public void TestConflictingShortNames()
{
string msg = null;
try
{
var nodeA = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
var nodeB = ns.GetNode(typeof(ShortNameFooB).AssemblyQualifiedName);
msg =
"ShortNameFooA and ShortNameFooB have the same short name" +
nodeA.GetName() + nodeB.GetName();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestRoundTripInnerClassNames()
{
INode node = ns.GetNode(typeof(Nested.Inner).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(Nested.Inner).AssemblyQualifiedName);
}
[Fact]
public void TestRoundTripAnonInnerClassNames()
{
INode node1 = ns.GetNode(typeof(AnonNested.X1).AssemblyQualifiedName);
INode node2 = ns.GetNode(typeof(AnonNested.Y1).AssemblyQualifiedName);
Assert.NotEqual(node1.GetFullName(), node2.GetFullName());
Type t1 = ReflectionUtilities.GetTypeByName(node1.GetFullName());
Type t2 = ReflectionUtilities.GetTypeByName(node2.GetFullName());
Assert.NotSame(t1, t2);
}
[Fact]
public void TestNameCantBindWrongSubclassAsDefault()
{
TestNegativeCase(typeof(BadName),
"class org.apache.reef.tang.implementation.BadName defines a default class Int32 with a type that does not extend of its target's type string");
}
[Fact]
public void TestNameCantBindWrongSubclassOfArgumentAsDefault()
{
TestNegativeCase(typeof(BadNameForGeneric),
"class BadNameForGeneric defines a default class Int32 with a type that does not extend of its target's string in ISet<string>");
}
[Fact]
public void TestNameCantBindSubclassOfArgumentAsDefault()
{
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
INode node = ns.GetNode(typeof(GoodNameForGeneric).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(GoodNameForGeneric).AssemblyQualifiedName);
}
[Fact]
public void TestInterfaceCantBindWrongImplAsDefault()
{
TestNegativeCase(typeof(IBadIfaceDefault),
"interface IBadIfaceDefault declares its default implementation to be non-subclass class string");
}
private void TestNegativeCase(Type clazz, string message)
{
string msg = null;
try
{
var node = ns.GetNode(typeof(IBadIfaceDefault).AssemblyQualifiedName);
msg = message + node.GetName();
}
catch (Exception)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestParseableDefaultClassNotOK()
{
TestNegativeCase(typeof(BadParsableDefaultClass),
"Named parameter BadParsableDefaultClass defines default implementation for parsable type System.string");
}
[Fact]
public void testGenericTorture1()
{
g(typeof(GenericTorture1));
}
[Fact]
public void testGenericTorture2()
{
g(typeof(GenericTorture2));
}
[Fact]
public void testGenericTorture3()
{
g(typeof(GenericTorture3));
}
[Fact]
public void testGenericTorture4()
{
g(typeof(GenericTorture4));
}
public string s(Type t)
{
return ReflectionUtilities.GetAssemblyQualifiedName(t);
}
public INode g(Type t)
{
INode n = ns.GetNode(s(t));
Assert.NotNull(n);
return n;
}
[Fact]
public void TestHelloTaskNode()
{
var node = ns.GetNode(typeof(HelloTask).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(HelloTask)));
}
[Fact]
public void TestITackNode()
{
var node = ns.GetNode(typeof(ITask).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(ITask)));
}
[Fact]
public void TestNamedParameterIdentifier()
{
var node = ns.GetNode(typeof(TaskConfigurationOptions.Identifier).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(TaskConfigurationOptions.Identifier)));
}
[Fact]
public void TestInterface()
{
g(typeof(A));
g(typeof(MyInterface<int>));
g(typeof(MyInterface<string>));
g(typeof(B));
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder();
cb.BindImplementation(GenericType<MyInterface<string>>.Class, GenericType<MyImplString>.Class);
cb.BindImplementation(GenericType<MyInterface<int>>.Class, GenericType<MyImplInt>.Class);
IConfiguration conf = cb.Build();
IInjector i = tang.NewInjector(conf);
var a = (A)i.GetInstance(typeof(A));
var implString = (MyImplString)i.GetInstance(typeof(MyImplString));
var implInt = (MyImplString)i.GetInstance(typeof(MyImplString));
var b = (B)i.GetInstance(typeof(B));
var c = (C)i.GetInstance(typeof(C));
Assert.NotNull(a);
Assert.NotNull(implString);
Assert.NotNull(implInt);
Assert.NotNull(b);
Assert.NotNull(c);
}
}
[NamedParameter]
class GenericTorture1 : Name<ISet<string>>
{
}
[NamedParameter]
class GenericTorture2 : Name<ISet<ISet<string>>>
{
}
[NamedParameter]
class GenericTorture3 : Name<IDictionary<ISet<string>, ISet<string>>>
{
}
[NamedParameter]
class GenericTorture4 : Name<IDictionary<string, string>>
{
}
public interface MyInterface<T>
{
}
public class RepeatConstructorArg
{
[Inject]
public RepeatConstructorArg(int x, int y)
{
}
}
public class RepeatConstructorArgClasses
{
[Inject]
public RepeatConstructorArgClasses(A x, A y)
{
}
}
public class A : MyInterface<int>, MyInterface<string>
{
[Inject]
A()
{
}
}
public class MyImplString : MyInterface<string>
{
[Inject]
public MyImplString()
{
}
}
public class B
{
[Inject]
public B(MyInterface<string> b)
{
}
}
public class MyImplInt : MyInterface<int>
{
[Inject]
public MyImplInt()
{
}
}
public class C
{
[Inject]
public C(MyInterface<int> b)
{
}
}
public class LeafRepeatedConstructorArgClasses
{
public static class A
{
public class AA
{
}
}
public static class B
{
public class AA
{
}
}
public class C
{
[Inject]
public C(A.AA a, B.AA b)
{
}
}
}
class D
{
}
[NamedParameter]
class D1 : Name<D>
{
}
[NamedParameter]
class D2 : Name<D>
{
}
class NamedRepeatConstructorArgClasses
{
[Inject]
public NamedRepeatConstructorArgClasses([Parameter(typeof(D1))] D x, [Parameter(typeof(D2))] D y)
{
}
}
class NamedParameterTypeMismatch
{
[NamedParameter(Documentation = "doc.stuff", DefaultValue = "1")]
class Foo : Name<int>
{
}
[Inject]
public NamedParameterTypeMismatch([Parameter(Value = typeof(Foo))] string s)
{
}
}
class UnannotatedName : Name<string>
{
}
interface I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNotName
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameWrongInterface : I1
{
}
class UnAnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class NameWithConstructor : Name<object>
{
private NameWithConstructor(int i)
{
}
}
[NamedParameter]
class NameWithZeroArgInject : Name<object>
{
[Inject]
public NameWithZeroArgInject()
{
}
}
class InjectNonStaticLocalArgClass
{
class NonStaticLocal
{
}
[Inject]
InjectNonStaticLocalArgClass(NonStaticLocal x)
{
}
}
class InjectNonStaticLocalType
{
class NonStaticLocal
{
[Inject]
NonStaticLocal(NonStaticLocal x)
{
}
}
}
[NamedParameter(ShortName = "foo")]
public class ShortNameFooA : Name<string>
{
}
// when same short name is used, exception would throw when building the class hierarchy
[NamedParameter(ShortName = "foo")]
public class ShortNameFooB : Name<int>
{
}
class Nested
{
public class Inner
{
}
}
class AnonNested
{
public interface X
{
}
public class X1 : X
{
// int i;
}
public class Y1 : X
{
// int j;
}
public static X XObj = new X1();
public static X YObj = new Y1();
}
// Negative case: Int32 doesn't match string
[NamedParameter(DefaultClass = typeof(Int32))]
class BadName : Name<string>
{
}
// Negative case: Int32 doesn't match string in the ISet
[NamedParameter(DefaultClass = typeof(Int32))]
class BadNameForGeneric : Name<ISet<string>>
{
}
// Positive case: type matched. ISet is not in parsable list
[NamedParameter(DefaultClass = typeof(string))]
class GoodNameForGeneric : Name<ISet<string>>
{
}
[DefaultImplementation(typeof(string))]
interface IBadIfaceDefault
{
}
// negative case: type matched. However, string is in the parsable list and DefaultClass is not null.
[NamedParameter(DefaultClass = typeof(string))]
class BadParsableDefaultClass : Name<string>
{
}
}
| |
using Android.Animation;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Util;
using Android.Views;
using Android.Views.Animations;
using Android.Widget;
using System;
using System.Collections.Generic;
using JavaObject = Java.Lang.Object;
using Orientation = Android.Content.Res.Orientation;
namespace AndroidResideMenu
{
public class ResideMenu : FrameLayout
{
public event EventHandler MenuOpened;
public event EventHandler MenuClosed;
private readonly ImageView _imageViewShadow;
private readonly ImageView _imageViewBackground;
private readonly LinearLayout _layoutLeftMenu;
private readonly LinearLayout _layoutRightMenu;
private readonly ScrollView _scrollViewLeftMenu;
private readonly ScrollView _scrollViewRightMenu;
private ScrollView _scrollViewMenu;
/** Current attaching activity. */
private Activity _activity;
/** The DecorView of current activity. */
private ViewGroup _viewDecor;
private TouchDisableView _viewActivity;
/** The flag of menu opening status. */
public bool IsOpened { get; private set; }
private float _shadowAdjustScaleX;
private float _shadowAdjustScaleY;
/** Views which need stop to intercept touch events. */
private List<View> _ignoredViews;
private List<ResideMenuItem> _leftMenuItems;
private List<ResideMenuItem> _rightMenuItems;
private DisplayMetrics _displayMetrics = new DisplayMetrics();
private IOnMenuListener _menuListener;
private float _lastRawX;
private bool _isInIgnoredView;
private global::AndroidResideMenu.ResideMenu.Direction _scaleDirection = Direction.Left;
private PressedState _pressedState = PressedState.Down;
private List<Direction> _disabledSwipeDirection = new List<Direction>();
// Valid scale factor is between 0.0f and 1.0f.
private float _scaleValue = 0.5f;
IOnClickListener _clickListener;
Animator.IAnimatorListener _animatorListener;
public ResideMenu(Context context)
: base(context)
{
LayoutInflater inflater = context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
inflater.Inflate(global::ResideMenu.Resource.Layout.residemenu, this);
_scrollViewLeftMenu = FindViewById<ScrollView>(global::ResideMenu.Resource.Id.sv_left_menu);
_scrollViewRightMenu = FindViewById<ScrollView>(global::ResideMenu.Resource.Id.sv_right_menu);
_imageViewShadow = FindViewById<ImageView>(global::ResideMenu.Resource.Id.iv_shadow);
_layoutLeftMenu = FindViewById<LinearLayout>(global::ResideMenu.Resource.Id.layout_left_menu);
_layoutRightMenu = FindViewById<LinearLayout>(global::ResideMenu.Resource.Id.layout_right_menu);
_imageViewBackground = FindViewById<ImageView>(global::ResideMenu.Resource.Id.iv_background);
_clickListener = new ClickListener(this);
_animatorListener = new AnimatorListener(this);
}
protected override bool FitSystemWindows(Rect insets)
{
SetPadding(_viewActivity.PaddingLeft + insets.Left, _viewActivity.PaddingTop + insets.Top, _viewActivity.PaddingRight + insets.Right, _viewActivity.PaddingBottom + insets.Bottom);
insets.Left = insets.Top = insets.Right = insets.Bottom = 0;
return true;
}
public void AttachToActivity(Activity activity)
{
_activity = activity;
_leftMenuItems = new List<ResideMenuItem>();
_rightMenuItems = new List<ResideMenuItem>();
_ignoredViews = new List<View>();
_viewDecor = activity.Window.DecorView as ViewGroup;
_viewActivity = new TouchDisableView(activity);
View mContent = _viewDecor.GetChildAt(0);
_viewDecor.RemoveViewAt(0);
_viewActivity.Content = mContent;
AddView(_viewActivity);
ViewGroup parent = _scrollViewLeftMenu.Parent as ViewGroup;
parent.RemoveView(_scrollViewLeftMenu);
parent.RemoveView(_scrollViewRightMenu);
SetShadowAdjustScaleXByOrientation();
_viewDecor.AddView(this, 0);
}
private void SetShadowAdjustScaleXByOrientation()
{
Orientation orientation = Resources.Configuration.Orientation;
if (orientation == Orientation.Landscape)
{
_shadowAdjustScaleX = 0.034f;
_shadowAdjustScaleY = 0.12f;
}
else if (orientation == Orientation.Portrait)
{
_shadowAdjustScaleX = 0.06f;
_shadowAdjustScaleY = 0.07f;
}
}
public void SetBackground(int imageResource)
{
_imageViewBackground.SetImageResource(imageResource);
}
public void SetShadowVisible(bool isVisible)
{
if (isVisible)
_imageViewShadow.SetBackgroundResource(global::ResideMenu.Resource.Drawable.shadow);
else
_imageViewShadow.SetBackgroundResource(0);
}
public void AddMenuItem(ResideMenuItem menuItem, Direction direction)
{
switch (direction)
{
case Direction.Left:
this._leftMenuItems.Add(menuItem);
_layoutLeftMenu.AddView(menuItem);
break;
case Direction.Right:
this._rightMenuItems.Add(menuItem);
_layoutRightMenu.AddView(menuItem);
break;
default:
throw new Exception();
}
}
public void SetMenuItems(List<ResideMenuItem> menuItems, Direction direction)
{
switch (direction)
{
case Direction.Left:
this._leftMenuItems = menuItems;
break;
case Direction.Right:
this._rightMenuItems = menuItems;
break;
default:
break;
}
RebuildMenu();
}
private void RebuildMenu()
{
_layoutLeftMenu.RemoveAllViews();
_layoutRightMenu.RemoveAllViews();
foreach (ResideMenuItem leftMenuItem in _leftMenuItems)
_layoutLeftMenu.AddView(leftMenuItem);
foreach (ResideMenuItem rightMenuItem in _rightMenuItems)
_layoutRightMenu.AddView(rightMenuItem);
}
public List<ResideMenuItem> GetMenuItems(Direction direction)
{
switch (direction)
{
case Direction.Left:
return _leftMenuItems;
case Direction.Right:
return _rightMenuItems;
default:
throw new Exception();
}
}
public void SetMenuListener(IOnMenuListener menuListener)
{
this._menuListener = menuListener;
}
public IOnMenuListener GetMenuListener()
{
return _menuListener;
}
public void OpenMenu(Direction direction)
{
SetScaleDirection(direction);
IsOpened = true;
AnimatorSet scaleDown_activity = BuildScaleDownAnimation(_viewActivity, _scaleValue, _scaleValue);
AnimatorSet scaleDown_shadow = BuildScaleDownAnimation(_imageViewShadow, _scaleValue + _shadowAdjustScaleX, _scaleValue + _shadowAdjustScaleY);
AnimatorSet alpha_menu = BuildMenuAnimation(_scrollViewMenu, 1.0f);
scaleDown_shadow.AddListener(_animatorListener);
scaleDown_activity.PlayTogether(scaleDown_shadow);
scaleDown_activity.PlayTogether(alpha_menu);
scaleDown_activity.Start();
}
public void CloseMenu()
{
IsOpened = false;
AnimatorSet scaleUp_activity = BuildScaleUpAnimation(_viewActivity, 1.0f, 1.0f);
AnimatorSet scaleUp_shadow = BuildScaleUpAnimation(_imageViewShadow, 1.0f, 1.0f);
AnimatorSet alpha_menu = BuildMenuAnimation(_scrollViewMenu, 0.0f);
scaleUp_activity.AddListener(_animatorListener);
scaleUp_activity.PlayTogether(scaleUp_shadow);
scaleUp_activity.PlayTogether(alpha_menu);
scaleUp_activity.Start();
}
public void SetSwipeDirectionDisable(Direction direction)
{
_disabledSwipeDirection.Add(direction);
}
private bool IsInDisableDirection(Direction direction)
{
return _disabledSwipeDirection.Contains(direction);
}
private void SetScaleDirection(Direction direction)
{
int screenWidth = GetScreenWidth();
float pivotX;
float pivotY = GetScreenHeight() * 0.5f;
switch (direction)
{
case Direction.Left:
_scrollViewMenu = _scrollViewLeftMenu;
pivotX = screenWidth * 1.5f;
break;
case Direction.Right:
_scrollViewMenu = _scrollViewRightMenu;
pivotX = screenWidth * -0.5f;
break;
default:
throw new Exception();
}
_viewActivity.PivotX = pivotX;
_viewActivity.PivotY = pivotY;
_imageViewShadow.PivotX = pivotX;
_imageViewShadow.PivotY = pivotY;
_scaleDirection = direction;
}
private class ClickListener : JavaObject, IOnClickListener
{
private readonly ResideMenu _outerInstance;
public ClickListener(ResideMenu outerInstance)
{
_outerInstance = outerInstance;
}
public void OnClick(View v)
{
if (_outerInstance.IsOpened)
{
_outerInstance.CloseMenu();
}
}
}
private class AnimatorListener : JavaObject, Animator.IAnimatorListener
{
private readonly ResideMenu _outerInstance;
public AnimatorListener(ResideMenu outerInstance)
{
_outerInstance = outerInstance;
}
public void OnAnimationCancel(Animator animation)
{
throw new NotImplementedException();
}
public void OnAnimationRepeat(Animator animation)
{
throw new NotImplementedException();
}
public void OnAnimationStart(Animator animation)
{
if (_outerInstance.IsOpened)
{
_outerInstance.ShowScrollViewMenu(_outerInstance._scrollViewMenu);
if (_outerInstance._menuListener != null)
{
_outerInstance._menuListener.OpenMenu();
}
var handler = _outerInstance.MenuOpened;
if(handler != null)
{
handler(_outerInstance, EventArgs.Empty);
}
}
}
public void OnAnimationEnd(Animator animation)
{
if (_outerInstance.IsOpened)
{
_outerInstance._viewActivity.IsTouchDisabled = true;
_outerInstance._viewActivity.SetOnClickListener(_outerInstance._clickListener);
}
else
{
_outerInstance._viewActivity.IsTouchDisabled = false;
_outerInstance._viewActivity.SetOnClickListener(null);
_outerInstance.HideScrollViewMenu(_outerInstance._scrollViewLeftMenu);
_outerInstance.HideScrollViewMenu(_outerInstance._scrollViewRightMenu);
if (_outerInstance._menuListener != null)
{
_outerInstance._menuListener.CloseMenu();
}
var handler = _outerInstance.MenuClosed;
if (handler != null)
{
handler(_outerInstance, EventArgs.Empty);
}
}
}
}
private AnimatorSet BuildScaleDownAnimation(View target, float targetScaleX, float targetScaleY)
{
AnimatorSet scaleDown = new AnimatorSet();
scaleDown.PlayTogether(ObjectAnimator.OfFloat(target, "scaleX", targetScaleX), ObjectAnimator.OfFloat(target, "scaleY", targetScaleY));
scaleDown.SetInterpolator(AnimationUtils.LoadInterpolator(_activity, Android.Resource.Animation.DecelerateInterpolator));
scaleDown.SetDuration(250);
return scaleDown;
}
private AnimatorSet BuildScaleUpAnimation(View target, float targetScaleX, float targetScaleY)
{
AnimatorSet scaleUp = new AnimatorSet();
scaleUp.PlayTogether(ObjectAnimator.OfFloat(target, "scaleX", targetScaleX), ObjectAnimator.OfFloat(target, "scaleY", targetScaleY));
scaleUp.SetDuration(250);
return scaleUp;
}
private AnimatorSet BuildMenuAnimation(View target, float alpha)
{
AnimatorSet alphaAnimation = new AnimatorSet();
alphaAnimation.PlayTogether(ObjectAnimator.OfFloat(target, "alpha", alpha));
alphaAnimation.SetDuration(250);
return alphaAnimation;
}
public void AddIgnoredView(View v)
{
_ignoredViews.Add(v);
}
public void RemoveIgnoredView(View v)
{
_ignoredViews.Remove(v);
}
public void ClearIgnoredViewList()
{
_ignoredViews.Clear();
}
private bool IsInIgnoredView(MotionEvent ev)
{
Rect rect = new Rect();
foreach (View v in _ignoredViews)
{
v.GetGlobalVisibleRect(rect);
if (rect.Contains((int)ev.GetX(), (int)ev.GetY()))
return true;
}
return false;
}
private void SetScaleDirectionByRawX(float currentRawX)
{
if (currentRawX < _lastRawX)
SetScaleDirection(global::AndroidResideMenu.ResideMenu.Direction.Right);
else
SetScaleDirection(global::AndroidResideMenu.ResideMenu.Direction.Left);
}
private float GetTargetScale(float currentRawX)
{
float scaleFloatX = ((currentRawX - _lastRawX) / GetScreenWidth()) * 0.75f;
scaleFloatX = _scaleDirection == Direction.Right ? -scaleFloatX : scaleFloatX;
float targetScale = _viewActivity.ScaleX - scaleFloatX;
targetScale = targetScale > 1.0f ? 1.0f : targetScale;
targetScale = targetScale < 0.5f ? 0.5f : targetScale;
return targetScale;
}
private float lastActionDownX, lastActionDownY;
public override bool DispatchTouchEvent(MotionEvent ev)
{
float currentActivityScaleX = _viewActivity.ScaleX;
if (currentActivityScaleX == 1.0f)
SetScaleDirectionByRawX(ev.RawX);
switch (ev.Action)
{
case MotionEventActions.Down:
lastActionDownX = ev.GetX();
lastActionDownY = ev.GetY();
_isInIgnoredView = IsInIgnoredView(ev) && !IsOpened;
_pressedState = PressedState.Down;
break;
case MotionEventActions.Move:
if (_isInIgnoredView || IsInDisableDirection(_scaleDirection))
break;
if (_pressedState != PressedState.Down && _pressedState != PressedState.Horizontal)
break;
int xOffset = (int)(ev.GetX() - lastActionDownX);
int yOffset = (int)(ev.GetY() - lastActionDownY);
if (_pressedState == PressedState.Down)
{
if (yOffset > 25 || yOffset < -25)
{
_pressedState = PressedState.Vertical;
break;
}
if (xOffset < -50 || xOffset > 50)
{
_pressedState = PressedState.Horizontal;
ev.Action = MotionEventActions.Cancel;
}
}
else if (_pressedState == PressedState.Horizontal)
{
if (currentActivityScaleX < 0.95)
ShowScrollViewMenu(_scrollViewMenu);
float targetScale = GetTargetScale(ev.RawX);
_viewActivity.ScaleX = targetScale;
_viewActivity.ScaleY = targetScale;
_imageViewShadow.ScaleX = targetScale + _shadowAdjustScaleX;
_imageViewShadow.ScaleY = targetScale + _shadowAdjustScaleY;
_scrollViewMenu.Alpha = (1 - targetScale) * 2.0F;
_lastRawX = ev.RawX;
return true;
}
break;
case MotionEventActions.Up:
if (_isInIgnoredView) break;
if (_pressedState != PressedState.Horizontal) break;
_pressedState = PressedState.Done;
if (IsOpened)
{
if (currentActivityScaleX > 0.56f)
CloseMenu();
else
OpenMenu(_scaleDirection);
}
else
{
if (currentActivityScaleX < 0.94f)
{
OpenMenu(_scaleDirection);
}
else
{
CloseMenu();
}
}
break;
}
_lastRawX = ev.RawX;
return base.DispatchTouchEvent(ev);
}
public int GetScreenHeight()
{
_activity.WindowManager.DefaultDisplay.GetMetrics(_displayMetrics);
return _displayMetrics.HeightPixels;
}
public int GetScreenWidth()
{
_activity.WindowManager.DefaultDisplay.GetMetrics(_displayMetrics);
return _displayMetrics.WidthPixels;
}
public void SetScaleValue(float scaleValue)
{
_scaleValue = scaleValue;
}
private void ShowScrollViewMenu(ScrollView scrollViewMenu)
{
if (scrollViewMenu != null && scrollViewMenu.Parent == null)
{
AddView(scrollViewMenu);
}
}
private void HideScrollViewMenu(ScrollView scrollViewMenu)
{
if (scrollViewMenu != null && scrollViewMenu.Parent != null)
{
RemoveView(scrollViewMenu);
}
}
public enum Direction
{
Left,
Right
}
private enum PressedState
{
Horizontal = 2,
Down = 3,
Done = 4,
Vertical = 5
}
public interface IOnMenuListener
{
void OpenMenu();
void CloseMenu();
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
namespace System.Text
{
public static class EncodingExtensions
{
/// <summary>
/// The maximum number of input elements after which we'll begin to chunk the input.
/// </summary>
/// <remarks>
/// The reason for this chunking is that the existing Encoding / Encoder / Decoder APIs
/// like GetByteCount / GetCharCount will throw if an integer overflow occurs. Since
/// we may be working with large inputs in these extension methods, we don't want to
/// risk running into this issue. While it's technically possible even for 1 million
/// input elements to result in an overflow condition, such a scenario is unrealistic,
/// so we won't worry about it.
/// </remarks>
private const int MaxInputElementsPerIteration = 1 * 1024 * 1024;
/// <summary>
/// Encodes the specified <see cref="ReadOnlySpan{Char}"/> to <see langword="byte"/>s using the specified <see cref="Encoding"/>
/// and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="chars"/> should be encoded.</param>
/// <param name="chars">The <see cref="ReadOnlySequence{Char}"/> to encode to <see langword="byte"/>s.</param>
/// <param name="writer">The buffer to which the encoded bytes will be written.</param>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static long GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, IBufferWriter<byte> writer)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
if (chars.Length <= MaxInputElementsPerIteration)
{
// The input span is small enough where we can one-shot this.
int byteCount = encoding.GetByteCount(chars);
Span<byte> scratchBuffer = writer.GetSpan(byteCount);
int actualBytesWritten = encoding.GetBytes(chars, scratchBuffer);
writer.Advance(actualBytesWritten);
return actualBytesWritten;
}
else
{
// Allocate a stateful Encoder instance and chunk this.
Convert(encoding.GetEncoder(), chars, writer, flush: true, out long totalBytesWritten, out bool completed);
return totalBytesWritten;
}
}
/// <summary>
/// Decodes the specified <see cref="ReadOnlySequence{Char}"/> to <see langword="byte"/>s using the specified <see cref="Encoding"/>
/// and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="chars"/> should be encoded.</param>
/// <param name="chars">The <see cref="ReadOnlySequence{Char}"/> whose contents should be encoded.</param>
/// <param name="writer">The buffer to which the encoded bytes will be written.</param>
/// <returns>The number of bytes written to <paramref name="writer"/>.</returns>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static long GetBytes(this Encoding encoding, in ReadOnlySequence<char> chars, IBufferWriter<byte> writer)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
// Delegate to the Span-based method if possible.
// If that doesn't work, allocate the Encoder instance and run a loop.
if (chars.IsSingleSegment)
{
return GetBytes(encoding, chars.FirstSpan, writer);
}
else
{
Convert(encoding.GetEncoder(), chars, writer, flush: true, out long bytesWritten, out bool completed);
return bytesWritten;
}
}
/// <summary>
/// Encodes the specified <see cref="ReadOnlySequence{Char}"/> to <see langword="byte"/>s using the specified <see cref="Encoding"/>
/// and outputs the result to <paramref name="bytes"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="chars"/> should be encoded.</param>
/// <param name="chars">The <see cref="ReadOnlySequence{Char}"/> to encode to <see langword="byte"/>s.</param>
/// <param name="bytes">The destination buffer to which the encoded bytes will be written.</param>
/// <returns>The number of bytes written to <paramref name="bytes"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="bytes"/> is not large enough to contain the encoded form of <paramref name="chars"/>.</exception>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static int GetBytes(this Encoding encoding, in ReadOnlySequence<char> chars, Span<byte> bytes)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (chars.IsSingleSegment)
{
// If the incoming sequence is single-segment, one-shot this.
return encoding.GetBytes(chars.FirstSpan, bytes);
}
else
{
// If the incoming sequence is multi-segment, create a stateful Encoder
// and use it as the workhorse. On the final iteration we'll pass flush=true.
ReadOnlySequence<char> remainingChars = chars;
int originalBytesLength = bytes.Length;
Encoder encoder = encoding.GetEncoder();
bool isFinalSegment;
do
{
remainingChars.GetFirstSpan(out ReadOnlySpan<char> firstSpan, out SequencePosition next);
isFinalSegment = remainingChars.IsSingleSegment;
int bytesWrittenJustNow = encoder.GetBytes(firstSpan, bytes, flush: isFinalSegment);
bytes = bytes.Slice(bytesWrittenJustNow);
remainingChars = remainingChars.Slice(next);
} while (!isFinalSegment);
return originalBytesLength - bytes.Length; // total number of bytes we wrote
}
}
/// <summary>
/// Encodes the specified <see cref="ReadOnlySequence{Char}"/> into a <see cref="byte"/> array using the specified <see cref="Encoding"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="chars"/> should be encoded.</param>
/// <param name="chars">The <see cref="ReadOnlySequence{Char}"/> to encode to <see langword="byte"/>s.</param>
/// <returns>A <see cref="byte"/> array which represents the encoded contents of <paramref name="chars"/>.</returns>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static byte[] GetBytes(this Encoding encoding, in ReadOnlySequence<char> chars)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (chars.IsSingleSegment)
{
// If the incoming sequence is single-segment, one-shot this.
ReadOnlySpan<char> span = chars.FirstSpan;
byte[] retVal = new byte[encoding.GetByteCount(span)];
encoding.GetBytes(span, retVal);
return retVal;
}
else
{
// If the incoming sequence is multi-segment, create a stateful Encoder
// and use it as the workhorse. On the final iteration we'll pass flush=true.
Encoder encoder = encoding.GetEncoder();
// Maintain a list of all the segments we'll need to concat together.
// These will be released back to the pool at the end of the method.
List<(byte[], int)> listOfSegments = new List<(byte[], int)>();
int totalByteCount = 0;
ReadOnlySequence<char> remainingChars = chars;
bool isFinalSegment;
do
{
remainingChars.GetFirstSpan(out ReadOnlySpan<char> firstSpan, out SequencePosition next);
isFinalSegment = remainingChars.IsSingleSegment;
int byteCountThisIteration = encoder.GetByteCount(firstSpan, flush: isFinalSegment);
byte[] rentedArray = ArrayPool<byte>.Shared.Rent(byteCountThisIteration);
int actualBytesWrittenThisIteration = encoder.GetBytes(firstSpan, rentedArray, flush: isFinalSegment); // could throw ArgumentException if overflow would occur
listOfSegments.Add((rentedArray, actualBytesWrittenThisIteration));
totalByteCount += actualBytesWrittenThisIteration;
if (totalByteCount < 0)
{
// If we overflowed, call the array ctor, passing int.MaxValue.
// This will end up throwing the expected OutOfMemoryException
// since arrays are limited to under int.MaxValue elements in length.
totalByteCount = int.MaxValue;
break;
}
remainingChars = remainingChars.Slice(next);
} while (!isFinalSegment);
// Now build up the byte[] to return, then release all of our scratch buffers
// back to the shared pool.
byte[] retVal = new byte[totalByteCount];
Span<byte> remainingBytes = retVal;
foreach ((byte[] array, int length) in listOfSegments)
{
array.AsSpan(0, length).CopyTo(remainingBytes);
ArrayPool<byte>.Shared.Return(array);
remainingBytes = remainingBytes.Slice(length);
}
Debug.Assert(remainingBytes.IsEmpty, "Over-allocated the byte[] instance?");
return retVal;
}
}
/// <summary>
/// Decodes the specified <see cref="ReadOnlySpan{Byte}"/> to <see langword="char"/>s using the specified <see cref="Encoding"/>
/// and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="bytes"/> should be decoded.</param>
/// <param name="bytes">The <see cref="ReadOnlySpan{Byte}"/> whose bytes should be decoded.</param>
/// <param name="writer">The buffer to which the decoded chars will be written.</param>
/// <returns>The number of chars written to <paramref name="writer"/>.</returns>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be decoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static long GetChars(this Encoding encoding, ReadOnlySpan<byte> bytes, IBufferWriter<char> writer)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
if (bytes.Length <= MaxInputElementsPerIteration)
{
// The input span is small enough where we can one-shot this.
int charCount = encoding.GetCharCount(bytes);
Span<char> scratchBuffer = writer.GetSpan(charCount);
int actualCharsWritten = encoding.GetChars(bytes, scratchBuffer);
writer.Advance(actualCharsWritten);
return actualCharsWritten;
}
else
{
// Allocate a stateful Decoder instance and chunk this.
Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long totalCharsWritten, out bool completed);
return totalCharsWritten;
}
}
/// <summary>
/// Decodes the specified <see cref="ReadOnlySequence{Byte}"/> to <see langword="char"/>s using the specified <see cref="Encoding"/>
/// and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="bytes"/> should be decoded.</param>
/// <param name="bytes">The <see cref="ReadOnlySequence{Byte}"/> whose bytes should be decoded.</param>
/// <param name="writer">The buffer to which the decoded chars will be written.</param>
/// <returns>The number of chars written to <paramref name="writer"/>.</returns>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be decoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static long GetChars(this Encoding encoding, in ReadOnlySequence<byte> bytes, IBufferWriter<char> writer)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
// Delegate to the Span-based method if possible.
// If that doesn't work, allocate the Encoder instance and run a loop.
if (bytes.IsSingleSegment)
{
return GetChars(encoding, bytes.FirstSpan, writer);
}
else
{
Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long charsWritten, out bool completed);
return charsWritten;
}
}
/// <summary>
/// Decodes the specified <see cref="ReadOnlySequence{Byte}"/> to <see langword="char"/>s using the specified <see cref="Encoding"/>
/// and outputs the result to <paramref name="chars"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="bytes"/> is encoded.</param>
/// <param name="bytes">The <see cref="ReadOnlySequence{Byte}"/> to decode to characters.</param>
/// <param name="chars">The destination buffer to which the decoded characters will be written.</param>
/// <returns>The number of chars written to <paramref name="chars"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="chars"/> is not large enough to contain the encoded form of <paramref name="bytes"/>.</exception>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be decoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static int GetChars(this Encoding encoding, in ReadOnlySequence<byte> bytes, Span<char> chars)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (bytes.IsSingleSegment)
{
// If the incoming sequence is single-segment, one-shot this.
return encoding.GetChars(bytes.FirstSpan, chars);
}
else
{
// If the incoming sequence is multi-segment, create a stateful Decoder
// and use it as the workhorse. On the final iteration we'll pass flush=true.
ReadOnlySequence<byte> remainingBytes = bytes;
int originalCharsLength = chars.Length;
Decoder decoder = encoding.GetDecoder();
bool isFinalSegment;
do
{
remainingBytes.GetFirstSpan(out ReadOnlySpan<byte> firstSpan, out SequencePosition next);
isFinalSegment = remainingBytes.IsSingleSegment;
int charsWrittenJustNow = decoder.GetChars(firstSpan, chars, flush: isFinalSegment);
chars = chars.Slice(charsWrittenJustNow);
remainingBytes = remainingBytes.Slice(next);
} while (!isFinalSegment);
return originalCharsLength - chars.Length; // total number of chars we wrote
}
}
/// <summary>
/// Decodes the specified <see cref="ReadOnlySequence{Byte}"/> into a <see cref="string"/> using the specified <see cref="Encoding"/>.
/// </summary>
/// <param name="encoding">The <see cref="Encoding"/> which represents how the data in <paramref name="bytes"/> is encoded.</param>
/// <param name="bytes">The <see cref="ReadOnlySequence{Byte}"/> to decode into characters.</param>
/// <returns>A <see cref="string"/> which represents the decoded contents of <paramref name="bytes"/>.</returns>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be decoded and <paramref name="encoding"/> is configured
/// to throw an exception when such data is seen.</exception>
public static string GetString(this Encoding encoding, in ReadOnlySequence<byte> bytes)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (bytes.IsSingleSegment)
{
// If the incoming sequence is single-segment, one-shot this.
return encoding.GetString(bytes.FirstSpan);
}
else
{
// If the incoming sequence is multi-segment, create a stateful Decoder
// and use it as the workhorse. On the final iteration we'll pass flush=true.
Decoder decoder = encoding.GetDecoder();
// Maintain a list of all the segments we'll need to concat together.
// These will be released back to the pool at the end of the method.
List<(char[], int)> listOfSegments = new List<(char[], int)>();
int totalCharCount = 0;
ReadOnlySequence<byte> remainingBytes = bytes;
bool isFinalSegment;
do
{
remainingBytes.GetFirstSpan(out ReadOnlySpan<byte> firstSpan, out SequencePosition next);
isFinalSegment = remainingBytes.IsSingleSegment;
int charCountThisIteration = decoder.GetCharCount(firstSpan, flush: isFinalSegment); // could throw ArgumentException if overflow would occur
char[] rentedArray = ArrayPool<char>.Shared.Rent(charCountThisIteration);
int actualCharsWrittenThisIteration = decoder.GetChars(firstSpan, rentedArray, flush: isFinalSegment);
listOfSegments.Add((rentedArray, actualCharsWrittenThisIteration));
totalCharCount += actualCharsWrittenThisIteration;
if (totalCharCount < 0)
{
// If we overflowed, call string.Create, passing int.MaxValue.
// This will end up throwing the expected OutOfMemoryException
// since strings are limited to under int.MaxValue elements in length.
totalCharCount = int.MaxValue;
break;
}
remainingBytes = remainingBytes.Slice(next);
} while (!isFinalSegment);
// Now build up the string to return, then release all of our scratch buffers
// back to the shared pool.
return string.Create(totalCharCount, listOfSegments, (span, listOfSegments) =>
{
foreach ((char[] array, int length) in listOfSegments)
{
array.AsSpan(0, length).CopyTo(span);
ArrayPool<char>.Shared.Return(array);
span = span.Slice(length);
}
Debug.Assert(span.IsEmpty, "Over-allocated the string instance?");
});
}
}
/// <summary>
/// Converts a <see cref="ReadOnlySpan{Char}"/> to bytes using <paramref name="encoder"/> and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoder">The <see cref="Encoder"/> instance which can convert <see langword="char"/>s to <see langword="byte"/>s.</param>
/// <param name="chars">A sequence of characters to encode.</param>
/// <param name="writer">The buffer to which the encoded bytes will be written.</param>
/// <param name="flush"><see langword="true"/> to indicate no further data is to be converted; otherwise <see langword="false"/>.</param>
/// <param name="bytesUsed">When this method returns, contains the count of <see langword="byte"/>s which were written to <paramref name="writer"/>.</param>
/// <param name="completed">
/// When this method returns, contains <see langword="true"/> if <paramref name="encoder"/> contains no partial internal state; otherwise, <see langword="false"/>.
/// If <paramref name="flush"/> is <see langword="true"/>, this will always be set to <see langword="true"/> when the method returns.
/// </param>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoder"/> is configured
/// to throw an exception when such data is seen.</exception>
public static void Convert(this Encoder encoder, ReadOnlySpan<char> chars, IBufferWriter<byte> writer, bool flush, out long bytesUsed, out bool completed)
{
if (encoder is null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
// We need to perform at least one iteration of the loop since the encoder could have internal state.
long totalBytesWritten = 0;
do
{
// If our remaining input is very large, instead truncate it and tell the encoder
// that there'll be more data after this call. This truncation is only for the
// purposes of getting the required byte count. Since the writer may give us a span
// larger than what we asked for, we'll pass the entirety of the remaining data
// to the transcoding routine, since it may be able to make progress beyond what
// was initially computed for the truncated input data.
int byteCountForThisSlice = (chars.Length <= MaxInputElementsPerIteration)
? encoder.GetByteCount(chars, flush)
: encoder.GetByteCount(chars.Slice(0, MaxInputElementsPerIteration), flush: false /* this isn't the end of the data */);
Span<byte> scratchBuffer = writer.GetSpan(byteCountForThisSlice);
encoder.Convert(chars, scratchBuffer, flush, out int charsUsedJustNow, out int bytesWrittenJustNow, out completed);
chars = chars.Slice(charsUsedJustNow);
writer.Advance(bytesWrittenJustNow);
totalBytesWritten += bytesWrittenJustNow;
} while (!chars.IsEmpty);
bytesUsed = totalBytesWritten;
}
/// <summary>
/// Converts a <see cref="ReadOnlySequence{Char}"/> to encoded bytes and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="encoder">The <see cref="Encoder"/> instance which can convert <see langword="char"/>s to <see langword="byte"/>s.</param>
/// <param name="chars">A sequence of characters to encode.</param>
/// <param name="writer">The buffer to which the encoded bytes will be written.</param>
/// <param name="flush"><see langword="true"/> to indicate no further data is to be converted; otherwise <see langword="false"/>.</param>
/// <param name="bytesUsed">When this method returns, contains the count of <see langword="byte"/>s which were written to <paramref name="writer"/>.</param>
/// <param name="completed">When this method returns, contains <see langword="true"/> if all input up until <paramref name="bytesUsed"/> was
/// converted; otherwise, <see langword="false"/>. If <paramref name="flush"/> is <see langword="true"/>, this will always be set to
/// <see langword="true"/> when the method returns.</param>
/// <exception cref="EncoderFallbackException">Thrown if <paramref name="chars"/> contains data that cannot be encoded and <paramref name="encoder"/> is configured
/// to throw an exception when such data is seen.</exception>
public static void Convert(this Encoder encoder, in ReadOnlySequence<char> chars, IBufferWriter<byte> writer, bool flush, out long bytesUsed, out bool completed)
{
// Parameter null checks will be performed by the workhorse routine.
ReadOnlySequence<char> remainingChars = chars;
long totalBytesWritten = 0;
bool isFinalSegment;
do
{
// Process each segment individually. We need to run at least one iteration of the loop in case
// the Encoder has internal state.
remainingChars.GetFirstSpan(out ReadOnlySpan<char> firstSpan, out SequencePosition next);
isFinalSegment = remainingChars.IsSingleSegment;
Convert(encoder, firstSpan, writer, flush && isFinalSegment, out long bytesWrittenThisIteration, out completed);
totalBytesWritten += bytesWrittenThisIteration;
remainingChars = remainingChars.Slice(next);
} while (!isFinalSegment);
bytesUsed = totalBytesWritten;
}
/// <summary>
/// Converts a <see cref="ReadOnlySpan{Byte}"/> to chars using <paramref name="decoder"/> and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="decoder">The <see cref="Decoder"/> instance which can convert <see langword="byte"/>s to <see langword="char"/>s.</param>
/// <param name="bytes">A sequence of bytes to decode.</param>
/// <param name="writer">The buffer to which the decoded chars will be written.</param>
/// <param name="flush"><see langword="true"/> to indicate no further data is to be converted; otherwise <see langword="false"/>.</param>
/// <param name="charsUsed">When this method returns, contains the count of <see langword="char"/>s which were written to <paramref name="writer"/>.</param>
/// <param name="completed">
/// When this method returns, contains <see langword="true"/> if <paramref name="decoder"/> contains no partial internal state; otherwise, <see langword="false"/>.
/// If <paramref name="flush"/> is <see langword="true"/>, this will always be set to <see langword="true"/> when the method returns.
/// </param>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be encoded and <paramref name="decoder"/> is configured
/// to throw an exception when such data is seen.</exception>
public static void Convert(this Decoder decoder, ReadOnlySpan<byte> bytes, IBufferWriter<char> writer, bool flush, out long charsUsed, out bool completed)
{
if (decoder is null)
{
throw new ArgumentNullException(nameof(decoder));
}
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
// We need to perform at least one iteration of the loop since the decoder could have internal state.
long totalCharsWritten = 0;
do
{
// If our remaining input is very large, instead truncate it and tell the decoder
// that there'll be more data after this call. This truncation is only for the
// purposes of getting the required char count. Since the writer may give us a span
// larger than what we asked for, we'll pass the entirety of the remaining data
// to the transcoding routine, since it may be able to make progress beyond what
// was initially computed for the truncated input data.
int charCountForThisSlice = (bytes.Length <= MaxInputElementsPerIteration)
? decoder.GetCharCount(bytes, flush)
: decoder.GetCharCount(bytes.Slice(0, MaxInputElementsPerIteration), flush: false /* this isn't the end of the data */);
Span<char> scratchBuffer = writer.GetSpan(charCountForThisSlice);
decoder.Convert(bytes, scratchBuffer, flush, out int bytesUsedJustNow, out int charsWrittenJustNow, out completed);
bytes = bytes.Slice(bytesUsedJustNow);
writer.Advance(charsWrittenJustNow);
totalCharsWritten += charsWrittenJustNow;
} while (!bytes.IsEmpty);
charsUsed = totalCharsWritten;
}
/// <summary>
/// Converts a <see cref="ReadOnlySequence{Byte}"/> to UTF-16 encoded characters and writes the result to <paramref name="writer"/>.
/// </summary>
/// <param name="decoder">The <see cref="Decoder"/> instance which can convert <see langword="byte"/>s to <see langword="char"/>s.</param>
/// <param name="bytes">A sequence of bytes to decode.</param>
/// <param name="writer">The buffer to which the decoded characters will be written.</param>
/// <param name="flush"><see langword="true"/> to indicate no further data is to be converted; otherwise <see langword="false"/>.</param>
/// <param name="charsUsed">When this method returns, contains the count of <see langword="char"/>s which were written to <paramref name="writer"/>.</param>
/// <param name="completed">
/// When this method returns, contains <see langword="true"/> if <paramref name="decoder"/> contains no partial internal state; otherwise, <see langword="false"/>.
/// If <paramref name="flush"/> is <see langword="true"/>, this will always be set to <see langword="true"/> when the method returns.
/// </param>
/// <exception cref="DecoderFallbackException">Thrown if <paramref name="bytes"/> contains data that cannot be decoded and <paramref name="decoder"/> is configured
/// to throw an exception when such data is seen.</exception>
public static void Convert(this Decoder decoder, in ReadOnlySequence<byte> bytes, IBufferWriter<char> writer, bool flush, out long charsUsed, out bool completed)
{
// Parameter null checks will be performed by the workhorse routine.
ReadOnlySequence<byte> remainingBytes = bytes;
long totalCharsWritten = 0;
bool isFinalSegment;
do
{
// Process each segment individually. We need to run at least one iteration of the loop in case
// the Decoder has internal state.
remainingBytes.GetFirstSpan(out ReadOnlySpan<byte> firstSpan, out SequencePosition next);
isFinalSegment = remainingBytes.IsSingleSegment;
Convert(decoder, firstSpan, writer, flush && isFinalSegment, out long charsWrittenThisIteration, out completed);
totalCharsWritten += charsWrittenThisIteration;
remainingBytes = remainingBytes.Slice(next);
} while (!isFinalSegment);
charsUsed = totalCharsWritten;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: __Error
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Centralized error methods for the IO package.
** Mostly useful for translating Win32 HRESULTs into meaningful
** error strings & exceptions.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
[Pure]
internal static class __Error
{
internal static void EndOfFile() {
throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF"));
}
internal static void FileNotOpen() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed"));
}
internal static void StreamIsClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
}
internal static void MemoryStreamNotExpandable() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable"));
}
internal static void ReaderClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed"));
}
internal static void ReadNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
}
internal static void SeekNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
internal static void WrongAsyncResult() {
throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult"));
}
internal static void EndReadCalledTwice() {
// Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple"));
}
internal static void EndWriteCalledTwice() {
// Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple"));
}
// Given a possible fully qualified path, ensure that we have path
// discovery permission to that path. If we do not, return just the
// file name. If we know it is a directory, then don't return the
// directory name.
[System.Security.SecurityCritical] // auto-generated
internal static String GetDisplayablePath(String path, bool isInvalidPath)
{
if (String.IsNullOrEmpty(path))
return String.Empty;
// Is it a fully qualified path?
bool isFullyQualified = false;
if (path.Length < 2)
return path;
if (Path.IsDirectorySeparator(path[0]) && Path.IsDirectorySeparator(path[1]))
isFullyQualified = true;
else if (path[1] == Path.VolumeSeparatorChar) {
isFullyQualified = true;
}
if (!isFullyQualified && !isInvalidPath)
return path;
bool safeToReturn = false;
try {
if (!isInvalidPath) {
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand();
#endif
safeToReturn = true;
}
}
catch (SecurityException) {
}
catch (ArgumentException) {
// ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters
// inside FileIOPermission.AddPathList
}
catch (NotSupportedException) {
// paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown
// from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path
// beyond string index position 1.
}
if (!safeToReturn) {
if (Path.IsDirectorySeparator(path[path.Length - 1]))
path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName");
else
path = Path.GetFileName(path);
}
return path;
}
[System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIOError() {
int errorCode = Marshal.GetLastWin32Error();
WinIOError(errorCode, String.Empty);
}
// After calling GetLastWin32Error(), it clears the last error field,
// so you must save the HResult and pass it to this method. This method
// will determine the appropriate exception to throw dependent on your
// error, and depending on the error, insert a string into the message
// gotten from the ResourceManager.
[System.Security.SecurityCritical] // auto-generated
internal static void WinIOError(int errorCode, String maybeFullPath) {
// This doesn't have to be perfect, but is a perf optimization.
bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
String str = GetDisplayablePath(maybeFullPath, isInvalidPath);
switch (errorCode) {
case Win32Native.ERROR_FILE_NOT_FOUND:
if (str.Length == 0)
throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound"));
else
throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str);
case Win32Native.ERROR_PATH_NOT_FOUND:
if (str.Length == 0)
throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName"));
else
throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str));
case Win32Native.ERROR_ACCESS_DENIED:
if (str.Length == 0)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
else
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str));
case Win32Native.ERROR_ALREADY_EXISTS:
if (str.Length == 0)
goto default;
throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
case Win32Native.ERROR_INVALID_DRIVE:
throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str));
case Win32Native.ERROR_INVALID_PARAMETER:
throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_SHARING_VIOLATION:
if (str.Length == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
else
throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_FILE_EXISTS:
if (str.Length == 0)
goto default;
throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_OPERATION_ABORTED:
throw new OperationCanceledException();
default:
throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
}
}
// An alternative to WinIOError with friendlier messages for drives
[System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIODriveError(String driveName) {
int errorCode = Marshal.GetLastWin32Error();
WinIODriveError(driveName, errorCode);
}
[System.Security.SecurityCritical] // auto-generated
internal static void WinIODriveError(String driveName, int errorCode)
{
switch (errorCode) {
case Win32Native.ERROR_PATH_NOT_FOUND:
case Win32Native.ERROR_INVALID_DRIVE:
throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", driveName));
default:
WinIOError(errorCode, driveName);
break;
}
}
internal static void WriteNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
}
internal static void WriterClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_WriterClosed"));
}
// From WinError.h
internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER;
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 10/14/2008 8:52:08 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections.Generic;
using System.Drawing;
namespace DotSpatial.Data
{
/// <summary>
/// ImageData (not named Image because of conflicting with the Dot Net Image object)
/// </summary>
public class ImageData : RasterBoundDataSet, IImageData
{
#region Constructors
/// <summary>
/// Creates a new instance of ImageData
/// </summary>
public ImageData()
{
TypeName = "Image";
WorldFile = new WorldFile();
}
#endregion
#region Methods
/// <summary>
/// Copies the values from the specified source image.
/// </summary>
/// <param name="source">The source image to copy values from.</param>
public virtual void CopyValues(IImageData source)
{
}
/// <summary>
/// Attempts to create a bitmap for the entire image. This may cause memory exceptions.
/// </summary>
/// <returns>A Bitmap of the image.</returns>
public virtual Bitmap GetBitmap()
{
return null;
}
/// <summary>
/// The geographic envelope gives the region that the image should be created for.
/// The window gives the corresponding pixel dimensions for the image, so that
/// images matching the resolution of the screen can be used.
/// </summary>
/// <param name="envelope">The geographic extents to retrieve data for</param>
/// <param name="size">The rectangle that defines the size of the drawing area in pixels</param>
/// <returns>A bitmap captured from the main image </returns>
public Bitmap GetBitmap(Extent envelope, Size size)
{
return GetBitmap(envelope, new Rectangle(new Point(0, 0), size));
}
/// <summary>
/// The geographic envelope gives the region that the image should be created for.
/// The window gives the corresponding pixel dimensions for the image, so that
/// images matching the resolution of the screen can be used.
/// </summary>
/// <param name="envelope">The geographic extents to retrieve data for</param>
/// <param name="window">The rectangle that defines the size of the drawing area in pixels</param>
/// <returns>A bitmap captured from the main image </returns>
public virtual Bitmap GetBitmap(Extent envelope, Rectangle window)
{
return null;
}
/// <summary>
/// Opens the file, assuming that the fileName has already been specified
/// </summary>
public virtual void Open()
{
// todo: determine how this ImageData should wire itself to the returned value of OpenImage()
DataManager.DefaultDataManager.OpenImage(Filename);
}
/// <summary>
/// Forces the image to read values from the graphic image format to the byte array format
/// </summary>
public virtual void CopyBitmapToValues()
{
}
/// <summary>
/// Saves the image and associated world file to the current fileName.
/// </summary>
public virtual void Save()
{
}
/// <summary>
/// Saves the image to a new fileName.
/// </summary>
/// <param name="fileName">The string fileName to save the image to.</param>
public virtual void SaveAs(string fileName)
{
DataManager.DefaultDataManager.CreateImage(fileName, Height, Width, BandType);
}
/// <summary>
/// Forces the image to copy values from the byte array format to the image format.
/// </summary>
public virtual void CopyValuesToBitmap()
{
}
/// <summary>
/// Creates a new image and world file, placing the default bounds at the origin, with one pixel per unit.
/// </summary>
/// <param name="fileName">The string fileName</param>
/// <param name="width">The integer width</param>
/// <param name="height">The integer height</param>
/// <param name="bandType">The color band type</param>
public virtual IImageData Create(string fileName, int width, int height, ImageBandType bandType)
{
return DataManager.DefaultDataManager.CreateImage(fileName, height, width, bandType);
}
/// <summary>
/// Opens the file with the specified fileName
/// </summary>
/// <param name="fileName">The string fileName to open</param>
public static IImageData Open(string fileName)
{
return DataManager.DefaultDataManager.OpenImage(fileName);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the color palette
/// </summary>
protected IEnumerable<Color> ColorPalette { get; set; }
/// <summary>
/// Gets or sets an integer indicating how many bytes exist for each pixel.
/// Eg. 32 ARGB = 4, 24 RGB = 3, 16 bit GrayScale = 2
/// </summary>
public int BytesPerPixel { get; set; }
/// <summary>
/// Creates a color structure from the byte values in the values array that correspond to the
/// specified position.
/// </summary>
/// <param name="row">The integer row index for the pixel.</param>
/// <param name="column">The integer column index for the pixel.</param>
/// <returns>A Color.</returns>
public virtual Color GetColor(int row, int column)
{
int bpp = BytesPerPixel;
int strd = Stride;
int b = Values[row * strd + column * bpp];
int g = Values[row * strd + column * bpp + 1];
int r = Values[row * strd + column * bpp + 2];
int a = 255;
if (BytesPerPixel == 4)
{
a = Values[row * strd + column * bpp + 3];
}
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// Sets the color value into the byte array based on the row and column position of the pixel.
/// </summary>
/// <param name="row">The integer row index of the pixel to set the color of.</param>
/// <param name="column">The integer column index of the pixel to set the color of </param>
/// <param name="col">The color to copy values from</param>
public virtual void SetColor(int row, int column, Color col)
{
int bpp = BytesPerPixel;
int strd = Stride;
Values[row * strd + column * bpp] = col.B;
Values[row * strd + column * bpp + 1] = col.G;
Values[row * strd + column * bpp + 2] = col.R;
if (BytesPerPixel == 4)
{
Values[row * strd + column * bpp + 3] = col.A;
}
}
/// <summary>
/// Gets the image height in pixels
/// </summary>
public int Height { get; set; }
/// <summary>
/// Gets or sets the number of bands that are in the image. One band is a gray valued image, 3 bands for color RGB and 4 bands
/// for ARGB.
/// </summary>
public int NumBands { get; set; }
/// <summary>
/// Gets or sets the stride in bytes.
/// </summary>
public int Stride { get; set; }
/// <summary>
/// Gets a one dimensional array of byte values
/// </summary>
public virtual byte[] Values { get; set; }
/// <summary>
/// Gets the image width in pixels
/// </summary>
public int Width { get; set; }
/// <summary>
/// Gets or sets the world file that stores the georeferencing information for this image.
/// </summary>
public WorldFile WorldFile { get; set; }
/// <summary>
/// Gets a block of data directly, converted into a bitmap.
/// </summary>
/// <param name="xOffset">The zero based integer column offset from the left</param>
/// <param name="yOffset">The zero based integer row offset from the top</param>
/// <param name="xSize">The integer number of pixel columns in the block. </param>
/// <param name="ySize">The integer number of pixel rows in the block.</param>
/// <returns>A Bitmap that is xSize, ySize.</returns>
public virtual Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize)
{
// Implemented in sub-classes.
return null;
}
/// <summary>
/// Saves a bitmap of data as a continuous block into the specified location.
/// Be sure to call UpdateOverviews after writing all blocks in pyramid images.
/// </summary>
/// <param name="value">The bitmap value to save.</param>
/// <param name="xOffset">The zero based integer column offset from the left</param>
/// <param name="yOffset">The zero based integer row offset from the top</param>
public virtual void WriteBlock(Bitmap value, int xOffset, int yOffset)
{
// Implemented in subclasses.
}
/// <summary>
/// Finalizes the blocks. In the case of a pyramid image, this forces recalculation of the
/// various overlays. For GDAL images, this may do nothing, since the overlay recalculation
/// may be on the fly. For InRam images this does nothing.
/// </summary>
public virtual void UpdateOverviews()
{
}
/// <summary>
/// This is only used in the palette indexed band type.
/// </summary>
public virtual IEnumerable<Color> GetColorPalette()
{
return ColorPalette;
}
/// <summary>
/// This should update the palette cached and in the file.
/// </summary>
/// <param name="value"></param>
public virtual void SetColorPalette(IEnumerable<Color> value)
{
ColorPalette = value;
}
/// <summary>
/// Gets or sets the interpretation for the image bands. This currently is only for GDAL images.
/// </summary>
public ImageBandType BandType { get; set; }
/// <summary>
/// Occurs when the bounds have been set.
/// </summary>
/// <param name="bounds">The new bounds.</param>
protected override void OnBoundsChanged(IRasterBounds bounds)
{
// Bounds may be null when the image layer is being disposed.
// We could probably skip calling this event in that case, but at any rate, we don't want to crash.
if (WorldFile != null && bounds != null)
WorldFile.Affine = bounds.AffineCoefficients;
}
#endregion
/// <summary>
/// Disposes the managed memory objects in the ImageData class, and then forwards
/// the Dispose operation to the internal dataset in the base class, if any.
/// </summary>
/// <param name="disposeManagedResources">Boolean, true if both managed and unmanaged resources should be finalized.</param>
protected override void Dispose(bool disposeManagedResources)
{
if (disposeManagedResources)
{
WorldFile = null;
Filename = null;
Bounds = null;
Values = null;
}
base.Dispose(disposeManagedResources);
}
}
}
| |
// 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.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.ReplaceMethodWithProperty;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplaceMethodWithProperty
{
public class ReplaceMethodWithPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
{
return new ReplaceMethodWithPropertyCodeRefactoringProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithGetName()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
}
}",
@"class C
{
int Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutGetName()
{
await TestAsync(
@"class C
{
int [||]Foo()
{
}
}",
@"class C
{
int Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(6034, "https://github.com/dotnet/roslyn/issues/6034")]
public async Task TestMethodWithArrowBody()
{
await TestAsync(
@"class C
{
int [||]GetFoo() => 0;
}",
@"class C
{
int Foo => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutBody()
{
await TestAsync(
@"class C
{
int [||]GetFoo();
}",
@"class C
{
int Foo { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithModifiers()
{
await TestAsync(
@"class C
{
public static int [||]GetFoo()
{
}
}",
@"class C
{
public static int Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithAttributes()
{
await TestAsync(
@"class C
{
[A]
int [||]GetFoo()
{
}
}",
@"class C
{
[A]
int Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_1()
{
await TestAsync(
@"class C
{
// Foo
int [||]GetFoo()
{
}
}",
@"class C
{
// Foo
int Foo
{
get
{
}
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
@"class C
{
int Foo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod()
{
await TestAsync(
@"class C
{
#if true
int [||]GetFoo()
{
}
#endif
}",
@"class C
{
#if true
int Foo
{
get
{
}
}
#endif
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_2()
{
await TestAsync(
@"class C
{
// Foo
int [||]GetFoo()
{
}
// SetFoo
void SetFoo(int i)
{
}
}",
@"class C
{
// Foo
// SetFoo
int Foo
{
get
{
}
set
{
}
}
}",
index: 1,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_1()
{
await TestAsync(
@"class C
{
int [||]I.GetFoo()
{
}
}",
@"class C
{
int I.Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_2()
{
await TestAsync(
@"interface I
{
int GetFoo();
}
class C : I
{
int [||]I.GetFoo()
{
}
}",
@"interface I
{
int Foo { get; }
}
class C : I
{
int I.Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_3()
{
await TestAsync(
@"interface I
{
int [||]GetFoo();
}
class C : I
{
int I.GetFoo()
{
}
}",
@"interface I
{
int Foo { get; }
}
class C : I
{
int I.Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInAttribute()
{
await TestMissingAsync(
@"class C
{
[At[||]tr]
int GetFoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInMethod()
{
await TestMissingAsync(
@"class C
{
int GetFoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVoidMethod()
{
await TestMissingAsync(
@"class C
{
void [||]GetFoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestAsyncMethod()
{
await TestMissingAsync(
@"class C
{
async Task [||]GetFoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGenericMethod()
{
await TestMissingAsync(
@"class C
{
int [||]GetFoo<T>()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExtensionMethod()
{
await TestMissingAsync(
@"static class C
{
int [||]GetFoo(this int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_1()
{
await TestMissingAsync(
@"class C
{
int [||]GetFoo(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_2()
{
await TestMissingAsync(
@"class C
{
int [||]GetFoo(int i = 0)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_1()
{
await TestMissingAsync(
@"class C
{
[At[||]tr]
int GetFoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_2()
{
await TestMissingAsync(
@"class C
{
int GetFoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceNotInMethod()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
}
void Bar()
{
var x = GetFoo();
}
}",
@"class C
{
int Foo
{
get
{
}
}
void Bar()
{
var x = Foo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceSimpleInvocation()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
}
void Bar()
{
var x = GetFoo();
}
}",
@"class C
{
int Foo
{
get
{
}
}
void Bar()
{
var x = Foo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceMemberAccessInvocation()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
}
void Bar()
{
var x = this.GetFoo();
}
}",
@"class C
{
int Foo
{
get
{
}
}
void Bar()
{
var x = this.Foo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceBindingMemberInvocation()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
}
void Bar()
{
C x;
var v = x?.GetFoo();
}
}",
@"class C
{
int Foo
{
get
{
}
}
void Bar()
{
C x;
var v = x?.Foo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceInMethod()
{
await TestAsync(
@"class C
{
int [||]GetFoo()
{
return GetFoo();
}
}",
@"class C
{
int Foo
{
get
{
return Foo;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOverride()
{
await TestAsync(
@"class C
{
public virtual int [||]GetFoo()
{
}
}
class D : C
{
public override int GetFoo()
{
}
}",
@"class C
{
public virtual int Foo
{
get
{
}
}
}
class D : C
{
public override int Foo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_NonInvoked()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void Bar()
{
Action<int> i = GetFoo;
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Foo|};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_ImplicitReference()
{
await TestAsync(
@"using System.Collections;
class C
{
public IEnumerator [||]GetEnumerator()
{
}
void Bar()
{
foreach (var x in this)
{
}
}
}",
@"using System.Collections;
class C
{
public IEnumerator Enumerator
{
get
{
}
}
void Bar()
{
{|Conflict:foreach (var x in this)
{
}|}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int i)
{
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetReference_NonInvoked()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int i)
{
}
void Bar()
{
Action<int> i = SetFoo;
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Foo|};
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetterAccessibility()
{
await TestAsync(
@"using System;
class C
{
public int [||]GetFoo()
{
}
private void SetFoo(int i)
{
}
}",
@"using System;
class C
{
public int Foo
{
get
{
}
private set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_ExpressionBodies()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo() => 0;
void SetFoo(int i) => Bar();
}",
@"using System;
class C
{
int Foo
{
get
{
return 0;
}
set
{
Bar();
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_GetInSetReference()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int i)
{
}
void Bar()
{
SetFoo(GetFoo() + 1);
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
}
}
void Bar()
{
Foo = Foo + 1;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_1()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int i)
{
v = i;
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_2()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int value)
{
v = value;
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetReferenceInSetter()
{
await TestAsync(
@"using System;
class C
{
int [||]GetFoo()
{
}
void SetFoo(int i)
{
SetFoo(i - 1);
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
Foo = value - 1;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_1()
{
await TestAsync(
@"class C
{
protected virtual int [||]GetFoo()
{
}
}
class D : C
{
protected override int GetFoo()
{
}
}",
@"class C
{
protected virtual int Foo
{
get
{
}
}
}
class D : C
{
protected override int Foo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_2()
{
await TestAsync(
@"class C
{
protected virtual int [||]GetFoo()
{
}
}
class D : C
{
protected override int GetFoo()
{
base.GetFoo();
}
}",
@"class C
{
protected virtual int Foo
{
get
{
}
}
}
class D : C
{
protected override int Foo
{
get
{
base.Foo;
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGetWithInterface()
{
await TestAsync(
@"interface I
{
int [||]GetFoo();
}
class C : I
{
public int GetFoo()
{
}
}",
@"interface I
{
int Foo { get; }
}
class C : I
{
public int Foo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestWithPartialClasses()
{
await TestAsync(
@"partial class C
{
int [||]GetFoo()
{
}
}
partial class C
{
void SetFoo(int i)
{
}
}",
@"partial class C
{
int Foo
{
get
{
}
set
{
}
}
}
partial class C
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetCaseInsensitive()
{
await TestAsync(
@"using System;
class C
{
int [||]getFoo()
{
}
void setFoo(int i)
{
}
}",
@"using System;
class C
{
int Foo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple()
{
await TestAsync(
@"class C
{
(int, string) [||]GetFoo()
{
}
}",
@"class C
{
(int, string) Foo
{
get
{
}
}
}",
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple_GetAndSet()
{
await TestAsync(
@"using System;
class C
{
(int, string) [||]getFoo()
{
}
void setFoo((int, string) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int, string) Foo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1,
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithNames_GetAndSet()
{
await TestAsync(
@"using System;
class C
{
(int a, string b) [||]getFoo()
{
}
void setFoo((int a, string b) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int a, string b) Foo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1,
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithDifferentNames_GetAndSet()
{
// Cannot refactor tuples with different names together
await Assert.ThrowsAsync<Xunit.Sdk.InRangeException>(() =>
TestAsync(
@"using System;
class C
{
(int a, string b) [||]getFoo()
{
}
void setFoo((int c, string d) i)
{
}
}",
@"",
index: 1,
parseOptions: TestOptions.Regular,
withScriptOption: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_1()
{
await TestAsync(
@"class C
{
// Foo
int [||]GetFoo()
{
}
// SetFoo
void SetFoo(out int i)
{
}
void Test()
{
SetFoo(out int i);
}
}",
@"class C
{
// Foo
int Foo
{
get
{
}
}
// SetFoo
void SetFoo(out int i)
{
}
void Test()
{
SetFoo(out int i);
}
}",
index: 0,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_2()
{
await TestAsync(
@"class C
{
// Foo
int [||]GetFoo()
{
}
// SetFoo
void SetFoo(int i)
{
}
void Test()
{
SetFoo(out int i);
}
}",
@"class C
{
// Foo
// SetFoo
int Foo
{
get
{
}
set
{
}
}
void Test()
{
{|Conflict:Foo|}(out int i);
}
}",
index: 1,
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_3()
{
await TestMissingAsync(
@"class C
{
// Foo
int GetFoo()
{
}
// SetFoo
void [||]SetFoo(out int i)
{
}
void Test()
{
SetFoo(out int i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_4()
{
await TestMissingAsync(
@"class C
{
// Foo
int [||]GetFoo(out int i)
{
}
// SetFoo
void SetFoo(out int i, int j)
{
}
void Test()
{
var y = GetFoo(out int i);
}
}");
}
[WorkItem(14327, "https://github.com/dotnet/roslyn/issues/14327")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateChainedGet1()
{
await TestAsync(
@"public class Foo
{
public Foo()
{
Foo value = GetValue().GetValue();
}
public Foo [||]GetValue()
{
return this;
}
}",
@"public class Foo
{
public Foo()
{
Foo value = Value.Value;
}
public Foo Value
{
get
{
return this;
}
}
}");
}
}
}
| |
//
// CTFontDescriptor.cs: Implements the managed CTFontDescriptor
//
// Authors: Mono Team
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2010 Novell, Inc
// Copyright 2011, 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
using MonoMac.Foundation;
namespace MonoMac.CoreText {
[Since (3,2)]
public enum CTFontOrientation : uint {
Default = 0,
Horizontal = 1,
Vertical = 2,
}
[Since (3,2)]
public enum CTFontFormat : uint {
Unrecognized = 0,
OpenTypePostScript = 1,
OpenTypeTrueType = 2,
TrueType = 3,
PostScript = 4,
Bitmap = 5,
}
[Since (3,2)]
public enum CTFontPriority : uint {
System = 10000,
Network = 20000,
Computer = 30000,
User = 40000,
Dynamic = 50000,
Process = 60000,
}
public enum CTFontDescriptorMatchingState : uint {
Started,
Finished,
WillBeginQuerying,
Stalled,
WillBeginDownloading,
Downloading,
DownloadingFinished,
Matched,
FailedWithError
}
[Since (3,2)]
public static class CTFontDescriptorAttributeKey {
public static readonly NSString Url;
public static readonly NSString Name;
public static readonly NSString DisplayName;
public static readonly NSString FamilyName;
public static readonly NSString StyleName;
public static readonly NSString Traits;
public static readonly NSString Variation;
public static readonly NSString Size;
public static readonly NSString Matrix;
public static readonly NSString CascadeList;
public static readonly NSString CharacterSet;
public static readonly NSString Languages;
public static readonly NSString BaselineAdjust;
public static readonly NSString MacintoshEncodings;
public static readonly NSString Features;
public static readonly NSString FeatureSettings;
public static readonly NSString FixedAdvance;
public static readonly NSString FontOrientation;
public static readonly NSString FontFormat;
public static readonly NSString RegistrationScope;
public static readonly NSString Priority;
public static readonly NSString Enabled;
static CTFontDescriptorAttributeKey ()
{
var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Url = Dlfcn.GetStringConstant (handle, "kCTFontURLAttribute");
Name = Dlfcn.GetStringConstant (handle, "kCTFontNameAttribute");
DisplayName = Dlfcn.GetStringConstant (handle, "kCTFontDisplayNameAttribute");
FamilyName = Dlfcn.GetStringConstant (handle, "kCTFontFamilyNameAttribute");
StyleName = Dlfcn.GetStringConstant (handle, "kCTFontStyleNameAttribute");
Traits = Dlfcn.GetStringConstant (handle, "kCTFontTraitsAttribute");
Variation = Dlfcn.GetStringConstant (handle, "kCTFontVariationAttribute");
Size = Dlfcn.GetStringConstant (handle, "kCTFontSizeAttribute");
Matrix = Dlfcn.GetStringConstant (handle, "kCTFontMatrixAttribute");
CascadeList = Dlfcn.GetStringConstant (handle, "kCTFontCascadeListAttribute");
CharacterSet = Dlfcn.GetStringConstant (handle, "kCTFontCharacterSetAttribute");
Languages = Dlfcn.GetStringConstant (handle, "kCTFontLanguagesAttribute");
BaselineAdjust = Dlfcn.GetStringConstant (handle, "kCTFontBaselineAdjustAttribute");
MacintoshEncodings = Dlfcn.GetStringConstant (handle, "kCTFontMacintoshEncodingsAttribute");
Features = Dlfcn.GetStringConstant (handle, "kCTFontFeaturesAttribute");
FeatureSettings = Dlfcn.GetStringConstant (handle, "kCTFontFeatureSettingsAttribute");
FixedAdvance = Dlfcn.GetStringConstant (handle, "kCTFontFixedAdvanceAttribute");
FontOrientation = Dlfcn.GetStringConstant (handle, "kCTFontOrientationAttribute");
FontFormat = Dlfcn.GetStringConstant (handle, "kCTFontFormatAttribute");
RegistrationScope = Dlfcn.GetStringConstant (handle, "kCTFontRegistrationScopeAttribute");
Priority = Dlfcn.GetStringConstant (handle, "kCTFontPriorityAttribute");
Enabled = Dlfcn.GetStringConstant (handle, "kCTFontEnabledAttribute");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
[Since (3,2)]
public class CTFontDescriptorAttributes {
public CTFontDescriptorAttributes ()
: this (new NSMutableDictionary ())
{
}
public CTFontDescriptorAttributes (NSDictionary dictionary)
{
if (dictionary == null)
throw new ArgumentNullException ("dictionary");
Dictionary = dictionary;
}
public NSDictionary Dictionary {get; private set;}
public NSUrl Url {
get {return (NSUrl) Dictionary [CTFontDescriptorAttributeKey.Url];}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Url, value);}
}
public string Name {
get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.Name);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Name, value);}
}
public string DisplayName {
get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName, value);}
}
public string FamilyName {
get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName, value);}
}
public string StyleName {
get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.StyleName);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.StyleName, value);}
}
public CTFontTraits Traits {
get {
var traits = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Traits];
if (traits == null)
return null;
return new CTFontTraits (traits);
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Traits,
value == null ? null : value.Dictionary);
}
}
public CTFontVariation Variation {
get {
var variation = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Variation];
return variation == null ? null : new CTFontVariation (variation);
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Variation,
value == null ? null : value.Dictionary);
}
}
public float? Size {
get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.Size);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Size, value);}
}
public unsafe CGAffineTransform? Matrix {
get {
var d = (NSData) Dictionary [CTFontDescriptorAttributeKey.Matrix];
if (d == null)
return null;
return (CGAffineTransform) Marshal.PtrToStructure (d.Bytes, typeof (CGAffineTransform));
}
set {
if (!value.HasValue)
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, (NSObject) null);
else {
byte[] data = new byte [Marshal.SizeOf (typeof (CGAffineTransform))];
fixed (byte* p = data) {
Marshal.StructureToPtr (value.Value, (IntPtr) p, false);
}
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, NSData.FromArray (data));
}
}
}
public IEnumerable<CTFontDescriptor> CascadeList {
get {
return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.CascadeList,
d => new CTFontDescriptor (d, false));
}
set {Adapter.SetNativeValue (Dictionary, CTFontDescriptorAttributeKey.CascadeList, value);}
}
public NSCharacterSet CharacterSet {
get {return (NSCharacterSet) Dictionary [CTFontDescriptorAttributeKey.CharacterSet];}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.CharacterSet, value);}
}
public IEnumerable<string> Languages {
get {return Adapter.GetStringArray (Dictionary, CTFontDescriptorAttributeKey.Languages);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Languages, value);}
}
public float? BaselineAdjust {
get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust, value);}
}
public float? MacintoshEncodings {
get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings, value);}
}
public IEnumerable<CTFontFeatures> Features {
get {
return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features,
d => new CTFontFeatures ((NSDictionary) Runtime.GetNSObject (d)));
}
set {
List<CTFontFeatures> v;
if (value == null || (v = new List<CTFontFeatures> (value)).Count == 0) {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null);
return;
}
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features,
NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary)));
}
}
public IEnumerable<CTFontFeatureSettings> FeatureSettings {
get {
return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features,
d => new CTFontFeatureSettings ((NSDictionary) Runtime.GetNSObject (d)));
}
set {
List<CTFontFeatureSettings> v;
if (value == null || (v = new List<CTFontFeatureSettings> (value)).Count == 0) {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null);
return;
}
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FeatureSettings,
NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary)));
}
}
public float? FixedAdvance {
get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance);}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance, value);}
}
public CTFontOrientation? FontOrientation {
get {
var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontOrientation);
return !value.HasValue ? null : (CTFontOrientation?) value.Value;
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontOrientation,
value.HasValue ? (uint?) value.Value : null);
}
}
public CTFontFormat? FontFormat {
get {
var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontFormat);
return !value.HasValue ? null : (CTFontFormat?) value.Value;
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontFormat,
value.HasValue ? (uint?) value.Value : null);
}
}
// TODO: docs mention CTFontManagerScope values, but I don't see any such enumeration.
public NSNumber RegistrationScope {
get {return (NSNumber) Dictionary [CTFontDescriptorAttributeKey.RegistrationScope];}
set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.RegistrationScope, value);}
}
public CTFontPriority? Priority {
get {
var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.Priority);
return !value.HasValue ? null : (CTFontPriority?) value.Value;
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Priority,
value.HasValue ? (uint?) value.Value : null);
}
}
public bool Enabled {
get {
var value = (NSNumber) Dictionary [CTFontDescriptorAttributeKey.Enabled];
if (value == null)
return false;
return value.Int32Value != 0;
}
set {
Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Enabled,
value ? new NSNumber (1) : null);
}
}
}
[Since (3,2)]
public class CTFontDescriptor : INativeObject, IDisposable {
internal IntPtr handle;
internal CTFontDescriptor (IntPtr handle)
: this (handle, false)
{
}
internal CTFontDescriptor (IntPtr handle, bool owns)
{
if (handle == IntPtr.Zero)
throw ConstructorError.ArgumentNull (this, "handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
~CTFontDescriptor ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get {return handle;}
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
#region Descriptor Creation
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateWithNameAndSize (IntPtr name, float size);
public CTFontDescriptor (string name, float size)
{
if (name == null)
throw ConstructorError.ArgumentNull (this, "name");
using (CFString n = name)
handle = CTFontDescriptorCreateWithNameAndSize (n.Handle, size);
if (handle == IntPtr.Zero)
throw ConstructorError.Unknown (this);
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateWithAttributes (IntPtr attributes);
public CTFontDescriptor (CTFontDescriptorAttributes attributes)
{
if (attributes == null)
throw ConstructorError.ArgumentNull (this, "attributes");
handle = CTFontDescriptorCreateWithAttributes (attributes.Dictionary.Handle);
if (handle == IntPtr.Zero)
throw ConstructorError.Unknown (this);
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateCopyWithAttributes (IntPtr original, IntPtr attributes);
public CTFontDescriptor WithAttributes (NSDictionary attributes)
{
if (attributes == null)
throw new ArgumentNullException ("attributes");
return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Handle));
}
static CTFontDescriptor CreateDescriptor (IntPtr h)
{
if (h == IntPtr.Zero)
return null;
return new CTFontDescriptor (h, true);
}
public CTFontDescriptor WithAttributes (CTFontDescriptorAttributes attributes)
{
if (attributes == null)
throw new ArgumentNullException ("attributes");
return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Dictionary.Handle));
}
// TODO: is there a better type to use for variationIdentifier?
// uint perhaps? "This is the four character code of the variation axis"
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateCopyWithVariation (IntPtr original, IntPtr variationIdentifier, float variationValue);
public CTFontDescriptor WithVariation (uint variationIdentifier, float variationValue)
{
using (var id = new NSNumber (variationIdentifier))
return CreateDescriptor (CTFontDescriptorCreateCopyWithVariation (handle,
id.Handle, variationValue));
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateCopyWithFeature (IntPtr original, IntPtr featureTypeIdentifier, IntPtr featureSelectorIdentifier);
[Advice ("Use WithFeature with specific selector")]
public CTFontDescriptor WithFeature (NSNumber featureTypeIdentifier, NSNumber featureSelectorIdentifier)
{
if (featureTypeIdentifier == null)
throw new ArgumentNullException ("featureTypeIdentifier");
if (featureSelectorIdentifier == null)
throw new ArgumentNullException ("featureSelectorIdentifier");
return CreateDescriptor (CTFontDescriptorCreateCopyWithFeature (handle, featureTypeIdentifier.Handle, featureSelectorIdentifier.Handle));
}
public CTFontDescriptor WithFeature (CTFontFeatureAllTypographicFeatures.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.AllTypographicFeatures, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureLigatures.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.Ligatures, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCursiveConnection.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CursiveConnection, (int) featureSelector);
}
[Obsolete ("Deprecated")]
public CTFontDescriptor WithFeature (CTFontFeatureLetterCase.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.LetterCase, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureVerticalSubstitutionConnection.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.VerticalSubstitution, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureLinguisticRearrangementConnection.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.LinguisticRearrangement, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureNumberSpacing.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.NumberSpacing, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureSmartSwash.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.SmartSwash, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureDiacritics.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.Diacritics, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureVerticalPosition.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.VerticalPosition, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureFractions.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.Fractions, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureOverlappingCharacters.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.OverlappingCharacters, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureTypographicExtras.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.TypographicExtras, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureMathematicalExtras.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.MathematicalExtras, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureOrnamentSets.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.OrnamentSets, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCharacterAlternatives.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CharacterAlternatives, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureDesignComplexity.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.DesignComplexity, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureStyleOptions.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.StyleOptions, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCharacterShape.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CharacterShape, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureNumberCase.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.NumberCase, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureTextSpacing.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.TextSpacing, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureTransliteration.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.Transliteration, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureAnnotation.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.Annotation, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureKanaSpacing.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.KanaSpacing, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureIdeographicSpacing.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.IdeographicSpacing, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureUnicodeDecomposition.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.UnicodeDecomposition, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureRubyKana.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.RubyKana, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCJKSymbolAlternatives.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CJKSymbolAlternatives, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureIdeographicAlternatives.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.IdeographicAlternatives, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCJKVerticalRomanPlacement.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CJKVerticalRomanPlacement, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureItalicCJKRoman.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.ItalicCJKRoman, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCaseSensitiveLayout.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CaseSensitiveLayout, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureAlternateKana.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.AlternateKana, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureStylisticAlternatives.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.StylisticAlternatives, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureContextualAlternates.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.ContextualAlternates, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureLowerCase.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.LowerCase, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureUpperCase.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.UpperCase, (int) featureSelector);
}
public CTFontDescriptor WithFeature (CTFontFeatureCJKRomanSpacing.Selector featureSelector)
{
return WithFeature (FontFeatureGroup.CJKRomanSpacing, (int) featureSelector);
}
CTFontDescriptor WithFeature (FontFeatureGroup featureGroup, int featureSelector)
{
using (NSNumber t = new NSNumber ((int) featureGroup), f = new NSNumber (featureSelector)) {
return CreateDescriptor (CTFontDescriptorCreateCopyWithFeature (handle, t.Handle, f.Handle));
}
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptors (IntPtr descriptor, IntPtr mandatoryAttributes);
public CTFontDescriptor[] GetMatchingFontDescriptors (NSSet mandatoryAttributes)
{
var cfArrayRef = CTFontDescriptorCreateMatchingFontDescriptors (handle,
mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle);
if (cfArrayRef == IntPtr.Zero)
return new CTFontDescriptor [0];
var matches = NSArray.ArrayFromHandle (cfArrayRef,
fd => new CTFontDescriptor (cfArrayRef, false));
CFObject.CFRelease (cfArrayRef);
return matches;
}
public CTFontDescriptor[] GetMatchingFontDescriptors (params NSString[] mandatoryAttributes)
{
NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes);
return GetMatchingFontDescriptors (attrs);
}
public CTFontDescriptor[] GetMatchingFontDescriptors ()
{
NSSet attrs = null;
return GetMatchingFontDescriptors (attrs);
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptor (IntPtr descriptor, IntPtr mandatoryAttributes);
public CTFontDescriptor GetMatchingFontDescriptor (NSSet mandatoryAttributes)
{
return CreateDescriptor (CTFontDescriptorCreateMatchingFontDescriptors (handle,
mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle));
}
public CTFontDescriptor GetMatchingFontDescriptor (params NSString[] mandatoryAttributes)
{
NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes);
return GetMatchingFontDescriptor (attrs);
}
public CTFontDescriptor GetMatchingFontDescriptor ()
{
NSSet attrs = null;
return GetMatchingFontDescriptor (attrs);
}
#endregion
#region Descriptor Accessors
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCopyAttributes (IntPtr descriptor);
public CTFontDescriptorAttributes GetAttributes()
{
var cfDictRef = CTFontDescriptorCopyAttributes (handle);
if (cfDictRef == IntPtr.Zero)
return null;
var dict = (NSDictionary) Runtime.GetNSObject (cfDictRef);
dict.Release ();
return new CTFontDescriptorAttributes (dict);
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCopyAttribute (IntPtr descriptor, IntPtr attribute);
public NSObject GetAttribute (NSString attribute)
{
if (attribute == null)
throw new ArgumentNullException ("attribute");
return Runtime.GetNSObject (CTFontDescriptorCopyAttribute (handle, attribute.Handle));
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, IntPtr language);
public NSObject GetLocalizedAttribute (NSString attribute)
{
return Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, IntPtr.Zero));
}
[DllImport (Constants.CoreTextLibrary)]
static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, out IntPtr language);
public NSObject GetLocalizedAttribute (NSString attribute, out NSString language)
{
IntPtr lang;
var o = Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, out lang));
language = (NSString) Runtime.GetNSObject (lang);
if (lang != IntPtr.Zero)
CFObject.CFRelease (lang);
return o;
}
#endregion
[DllImport (Constants.CoreTextLibrary)]
static extern bool CTFontDescriptorMatchFontDescriptorsWithProgressHandler (IntPtr descriptors, IntPtr mandatoryAttributes,
Func<CTFontDescriptorMatchingState, IntPtr, bool> progressHandler);
[Since (6,0)]
public static bool MatchFontDescriptors (CTFontDescriptor[] descriptors, NSSet mandatoryAttributes, Func<CTFontDescriptorMatchingState, IntPtr, bool> progressHandler)
{
var ma = mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle;
// FIXME: SIGSEGV probably due to mandatoryAttributes mismatch
using (var ar = CFArray.FromNativeObjects (descriptors)) {
return CTFontDescriptorMatchFontDescriptorsWithProgressHandler (ar.Handle, ma, progressHandler);
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
[InitializeOnLoad]
class OVRPluginUpdater
{
enum PluginPlatform
{
Android,
AndroidUniversal,
OSXUniversal,
Win,
Win64,
}
class PluginPackage
{
public string RootPath;
public System.Version Version;
public Dictionary<PluginPlatform, string> Plugins = new Dictionary<PluginPlatform, string>();
public bool IsBundledPluginPackage()
{
return (RootPath == GetBundledPluginRootPath());
}
public bool IsEnabled()
{
// TODO: Check each individual platform rather than using the Win64 DLL status for the overall package status.
string path = "";
if (Plugins.TryGetValue(PluginPlatform.Win64, out path))
{
return File.Exists(path);
}
return false;
}
public bool IsAndroidUniversalEnabled()
{
string path = "";
if (Plugins.TryGetValue(PluginPlatform.AndroidUniversal, out path))
{
if (File.Exists(path))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
if (pi != null)
{
return pi.GetCompatibleWithPlatform(BuildTarget.Android);
}
}
}
return false;
}
public bool IsAndroidUniversalPresent()
{
string path = "";
if (Plugins.TryGetValue(PluginPlatform.AndroidUniversal, out path))
{
string disabledPath = path + GetDisabledPluginSuffix();
if (File.Exists(path) || File.Exists(disabledPath))
{
return true;
}
}
return false;
}
}
private static bool restartPending = false;
private static bool unityVersionSupportsAndroidUniversal = false;
private static bool enableAndroidUniversalSupport = true;
static OVRPluginUpdater()
{
EditorApplication.delayCall += OnDelayCall;
}
static void OnDelayCall()
{
if (enableAndroidUniversalSupport)
{
#if UNITY_2018_1_OR_NEWER
// Temporarily disable the AndroidUniversal plugin because of a plugin copying error in Unity
unityVersionSupportsAndroidUniversal = false;
#endif
}
if (ShouldAttemptPluginUpdate())
{
AttemptPluginUpdate(true);
}
}
private static PluginPackage GetPluginPackage(string rootPath)
{
return new PluginPackage()
{
RootPath = rootPath,
Version = GetPluginVersion(rootPath),
Plugins = new Dictionary<PluginPlatform, string>()
{
{ PluginPlatform.Android, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Android) },
{ PluginPlatform.AndroidUniversal, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.AndroidUniversal) },
{ PluginPlatform.OSXUniversal, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.OSXUniversal) },
{ PluginPlatform.Win, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Win) },
{ PluginPlatform.Win64, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Win64) },
}
};
}
private static PluginPackage GetBundledPluginPackage()
{
return GetPluginPackage(GetBundledPluginRootPath());
}
private static List<PluginPackage> GetAllUtilitiesPluginPackages()
{
string pluginRootPath = GetUtilitiesPluginRootPath();
List<PluginPackage> packages = new List<PluginPackage>();
if (Directory.Exists(pluginRootPath))
{
var dirs = Directory.GetDirectories(pluginRootPath);
foreach(string dir in dirs)
{
packages.Add(GetPluginPackage(dir));
}
}
return packages;
}
private static string GetCurrentProjectPath()
{
return Directory.GetParent(Application.dataPath).FullName;
}
private static string GetUtilitiesPluginRootPath()
{
return GetUtilitiesRootPath() + @"/Plugins";
}
private static string GetUtilitiesRootPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string assetPath = AssetDatabase.GetAssetPath(script);
string editorDir = Directory.GetParent(assetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
return ovrDir;
}
private static string GetBundledPluginRootPath()
{
string basePath = EditorApplication.applicationContentsPath;
string pluginPath = @"/UnityExtensions/Unity/VR";
return basePath + pluginPath;
}
private static string GetPluginBuildTargetSubPath(PluginPlatform target)
{
string path = string.Empty;
switch (target)
{
case PluginPlatform.Android:
path = @"/Android/OVRPlugin.aar";
break;
case PluginPlatform.AndroidUniversal:
path = @"/AndroidUniversal/OVRPlugin.aar";
break;
case PluginPlatform.OSXUniversal:
path = @"/OSXUniversal/OVRPlugin.bundle";
break;
case PluginPlatform.Win:
path = @"/Win/OVRPlugin.dll";
break;
case PluginPlatform.Win64:
path = @"/Win64/OVRPlugin.dll";
break;
default:
throw new ArgumentException("Attempted GetPluginBuildTargetSubPath() for unsupported BuildTarget: " + target);
}
return path;
}
private static string GetDisabledPluginSuffix()
{
return @".disabled";
}
private static System.Version GetPluginVersion(string path)
{
System.Version invalidVersion = new System.Version("0.0.0");
System.Version pluginVersion = invalidVersion;
try
{
pluginVersion = new System.Version(Path.GetFileName(path));
}
catch
{
pluginVersion = invalidVersion;
}
if (pluginVersion == invalidVersion)
{
//Unable to determine version from path, fallback to Win64 DLL meta data
path += GetPluginBuildTargetSubPath(PluginPlatform.Win64);
if (!File.Exists(path))
{
path += GetDisabledPluginSuffix();
if (!File.Exists(path))
{
return invalidVersion;
}
}
FileVersionInfo pluginVersionInfo = FileVersionInfo.GetVersionInfo(path);
if (pluginVersionInfo == null || pluginVersionInfo.ProductVersion == null || pluginVersionInfo.ProductVersion == "")
{
return invalidVersion;
}
pluginVersion = new System.Version(pluginVersionInfo.ProductVersion);
}
return pluginVersion;
}
private static bool ShouldAttemptPluginUpdate()
{
return !UnitySupportsEnabledAndroidPlugin() || (autoUpdateEnabled && !restartPending && !Application.isPlaying);
}
private static void DisableAllUtilitiesPluginPackages()
{
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
foreach(string path in pluginPkg.Plugins.Values)
{
if ((Directory.Exists(path)) || (File.Exists(path)))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
string relDisabledPath = relPath + GetDisabledPluginSuffix();
AssetDatabase.MoveAsset(relPath, relDisabledPath);
AssetDatabase.ImportAsset(relDisabledPath, ImportAssetOptions.ForceUpdate);
}
}
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
private static void EnablePluginPackage(PluginPackage pluginPkg)
{
foreach(var kvp in pluginPkg.Plugins)
{
PluginPlatform platform = kvp.Key;
string path = kvp.Value;
if ((Directory.Exists(path + GetDisabledPluginSuffix())) || (File.Exists(path + GetDisabledPluginSuffix())))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
string relDisabledPath = relPath + GetDisabledPluginSuffix();
AssetDatabase.MoveAsset(relDisabledPath, relPath);
AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate);
PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
if (pi == null)
{
continue;
}
// Disable support for all platforms, then conditionally enable desired support below
pi.SetCompatibleWithEditor(false);
pi.SetCompatibleWithAnyPlatform(false);
pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
switch (platform)
{
case PluginPlatform.Android:
pi.SetCompatibleWithPlatform(BuildTarget.Android, !unityVersionSupportsAndroidUniversal);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7");
break;
case PluginPlatform.AndroidUniversal:
pi.SetCompatibleWithPlatform(BuildTarget.Android, unityVersionSupportsAndroidUniversal);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARM64");
break;
case PluginPlatform.OSXUniversal:
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, true);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, true);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, true);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, true);
#endif
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "AnyCPU");
pi.SetEditorData("OS", "OSX");
pi.SetPlatformData("Editor", "CPU", "AnyCPU");
pi.SetPlatformData("Editor", "OS", "OSX");
break;
case PluginPlatform.Win:
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86");
pi.SetPlatformData("Editor", "OS", "Windows");
break;
case PluginPlatform.Win64:
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86_64");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86_64");
pi.SetPlatformData("Editor", "OS", "Windows");
break;
default:
throw new ArgumentException("Attempted EnablePluginPackage() for unsupported BuildTarget: " + platform);
}
AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate);
}
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
private static readonly string autoUpdateEnabledKey = "Oculus_Utilities_OVRPluginUpdater_AutoUpdate_" + OVRManager.utilitiesVersion;
private static bool autoUpdateEnabled
{
get {
return PlayerPrefs.GetInt(autoUpdateEnabledKey, 1) == 1;
}
set {
PlayerPrefs.SetInt(autoUpdateEnabledKey, value ? 1 : 0);
}
}
[MenuItem("Tools/Oculus/Disable OVR Utilities Plugin")]
private static void AttemptPluginDisable()
{
PluginPackage bundledPluginPkg = GetBundledPluginPackage();
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
PluginPackage enabledUtilsPluginPkg = null;
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if (pluginPkg.IsEnabled())
{
if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
{
enabledUtilsPluginPkg = pluginPkg;
}
}
}
if (enabledUtilsPluginPkg == null)
{
if (EditorUtility.DisplayDialog("Disable Oculus Utilities Plugin", "The OVRPlugin included with Oculus Utilities is already disabled. The OVRPlugin bundled with the Unity Editor will continue to be used.\n\nBundled version: " + bundledPluginPkg.Version, "Ok", ""))
{
return;
}
}
else
{
if (EditorUtility.DisplayDialog("Disable Oculus Utilities Plugin", "Do you want to disable the OVRPlugin included with Oculus Utilities and revert to the OVRPlugin bundled with the Unity Editor?\n\nCurrent version: " + enabledUtilsPluginPkg.Version + "\nBundled version: " + bundledPluginPkg.Version, "Yes", "No"))
{
DisableAllUtilitiesPluginPackages();
if (EditorUtility.DisplayDialog("Restart Unity", "OVRPlugin has been updated to " + bundledPluginPkg.Version + ".\n\nPlease restart the Unity Editor to complete the update process. You may need to manually relaunch Unity if you are using Unity 5.6 and higher.", "Restart", "Not Now"))
{
RestartUnityEditor();
}
}
}
}
[MenuItem("Tools/Oculus/Update OVR Utilities Plugin")]
private static void RunPluginUpdate()
{
AttemptPluginUpdate(false);
}
private static void AttemptPluginUpdate(bool triggeredByAutoUpdate)
{
OVRPlugin.SendEvent("attempt_plugin_update_auto", triggeredByAutoUpdate.ToString());
autoUpdateEnabled = true;
PluginPackage bundledPluginPkg = GetBundledPluginPackage();
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
PluginPackage enabledUtilsPluginPkg = null;
PluginPackage newestUtilsPluginPkg = null;
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if ((newestUtilsPluginPkg == null) || (pluginPkg.Version > newestUtilsPluginPkg.Version))
{
newestUtilsPluginPkg = pluginPkg;
}
if (pluginPkg.IsEnabled())
{
if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
{
enabledUtilsPluginPkg = pluginPkg;
}
}
}
bool reenableCurrentPluginPkg = false;
PluginPackage targetPluginPkg = null;
if ((newestUtilsPluginPkg != null) && (newestUtilsPluginPkg.Version > bundledPluginPkg.Version))
{
if ((enabledUtilsPluginPkg == null) || (enabledUtilsPluginPkg.Version != newestUtilsPluginPkg.Version))
{
targetPluginPkg = newestUtilsPluginPkg;
}
}
else if ((enabledUtilsPluginPkg != null) && (enabledUtilsPluginPkg.Version < bundledPluginPkg.Version))
{
targetPluginPkg = bundledPluginPkg;
}
PluginPackage currentPluginPkg = (enabledUtilsPluginPkg != null) ? enabledUtilsPluginPkg : bundledPluginPkg;
if ((targetPluginPkg == null) && !UnitySupportsEnabledAndroidPlugin())
{
// Force reenabling the current package to configure the correct android plugin for this unity version.
reenableCurrentPluginPkg = true;
targetPluginPkg = currentPluginPkg;
}
if (targetPluginPkg == null)
{
if (!triggeredByAutoUpdate)
{
EditorUtility.DisplayDialog("Update Oculus Utilities Plugin", "OVRPlugin is already up to date.\n\nCurrent version: " + currentPluginPkg.Version + "\nBundled version: " + bundledPluginPkg.Version, "Ok", "");
}
return; // No update necessary.
}
System.Version targetVersion = targetPluginPkg.Version;
string dialogBody = "Oculus Utilities has detected that a newer OVRPlugin is available. Using the newest version is recommended. Do you want to enable it?\n\nCurrent version: "
+ currentPluginPkg.Version
+ "\nAvailable version: "
+ targetVersion;
if (reenableCurrentPluginPkg)
{
dialogBody = "Oculus Utilities has detected a configuration change that requires re-enabling the current OVRPlugin. Do you want to proceed?\n\nCurrent version: "
+ currentPluginPkg.Version;
}
int dialogResult = EditorUtility.DisplayDialogComplex("Update Oculus Utilities Plugin", dialogBody, "Yes", "No, Don't Ask Again", "No");
bool userAcceptsUpdate = false;
switch (dialogResult)
{
case 0: // "Yes"
userAcceptsUpdate = true;
break;
case 1: // "No, Don't Ask Again"
autoUpdateEnabled = false;
EditorUtility.DisplayDialog("Oculus Utilities OVRPlugin", "To manually update in the future, use the following menu option:\n\n[Tools -> Oculus -> Update OVR Utilities Plugin]", "Ok", "");
return;
case 2: // "No"
return;
}
if (userAcceptsUpdate)
{
DisableAllUtilitiesPluginPackages();
if (!targetPluginPkg.IsBundledPluginPackage())
{
EnablePluginPackage(targetPluginPkg);
}
if (EditorUtility.DisplayDialog("Restart Unity", "OVRPlugin has been updated to " + targetPluginPkg.Version + ".\n\nPlease restart the Unity Editor to complete the update process. You may need to manually relaunch Unity if you are using Unity 5.6 and higher.", "Restart", "Not Now"))
{
RestartUnityEditor();
}
}
}
private static bool UnitySupportsEnabledAndroidPlugin()
{
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if (pluginPkg.IsEnabled())
{
if (pluginPkg.IsAndroidUniversalEnabled() && !unityVersionSupportsAndroidUniversal)
{
// Android Universal should only be enabled on supported Unity versions since it can prevent app launch.
return false;
}
else if (!pluginPkg.IsAndroidUniversalEnabled() && pluginPkg.IsAndroidUniversalPresent() && unityVersionSupportsAndroidUniversal)
{
// Android Universal is present and should be enabled on supported Unity versions since ARM64 config will fail otherwise.
return false;
}
}
}
return true;
}
private static void RestartUnityEditor()
{
restartPending = true;
EditorApplication.OpenProject(GetCurrentProjectPath());
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using TimePunchAPI.Models;
namespace TimePunchAPI.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160509113151_RemoveRemainingEstimateFromIssue")]
partial class RemoveRemainingEstimateFromIssue
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("RoleId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<long>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b =>
{
b.Property<long>("UserId");
b.Property<long>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("TimePunchAPI.Models.ApplicationRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
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("TimePunchAPI.Models.ApplicationUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
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("TimePunchAPI.Models.Issue", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<long>("OriginalEstimate");
b.Property<int>("Priority");
b.Property<long>("ProjectId");
b.Property<string>("Summary");
b.Property<string>("Tag");
b.Property<int>("Type");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.Project", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Key");
b.Property<long>("LeaderId");
b.Property<string>("Name");
b.Property<string>("Summary");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.Timespan", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("ApplicationUserId");
b.Property<long>("IssueId");
b.Property<DateTime>("StartTime");
b.Property<DateTime>("StopTime");
b.Property<string>("Tag");
b.Property<long>("TimeSpent");
b.Property<long>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.UserProject", b =>
{
b.Property<long>("UserId");
b.Property<long>("ProjectId");
b.HasKey("UserId", "ProjectId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("TimePunchAPI.Models.Issue", b =>
{
b.HasOne("TimePunchAPI.Models.Project")
.WithMany()
.HasForeignKey("ProjectId");
});
modelBuilder.Entity("TimePunchAPI.Models.Timespan", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("ApplicationUserId");
b.HasOne("TimePunchAPI.Models.Issue")
.WithMany()
.HasForeignKey("IssueId");
});
modelBuilder.Entity("TimePunchAPI.Models.UserProject", b =>
{
b.HasOne("TimePunchAPI.Models.Project")
.WithMany()
.HasForeignKey("ProjectId");
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
namespace Signum.Test.LinqProvider;
/// <summary>
/// Summary description for LinqProvider
/// </summary>
public class GroupByTest
{
public GroupByTest()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
}
[Fact]
public void GroupStringByEnum()
{
var list = Database.Query<ArtistEntity>().GroupBy(a => a.Sex, a => a.Name).ToList();
}
[Fact]
public void GroupStringByEnumSimilar()
{
var queryA = (from a in Database.Query<ArtistEntity>()
group a.Name by a.Sex into g
select g).QueryText();
var queryN = Database.Query<ArtistEntity>().GroupBy(a => a.Sex, a => a.Name).QueryText();
Assert.Equal(queryN, queryA);
}
[Fact]
public void GroupMultiAggregate()
{
var sexos = from a in Database.Query<ArtistEntity>()
group a.Name.Length by a.Sex into g
select new
{
g.Key,
Count = g.Count(),
Sum = g.Sum(),
Min = g.Min(),
Max = g.Max(),
Avg = g.Average(),
};
sexos.ToList();
}
[Fact]
public void GroupCountNull()
{
var sexes = from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new
{
g.Key,
Count = g.Count(), //Fast
CountNames = g.Count(a => a.Name != null), //Fast
CountNullFast = g.Count(a => (a.Name == null ? "hi" : null) != null), //Fast
CountNullFast1 = g.Where(a => a.Name == null).Count(), //Fast
CountNullFast2= g.Count(a => a.Name == null), //Fast
CountLastAward = g.Count(a => a.LastAward != null), //Fast
};
sexes.ToList();
}
[Fact]
public void GroupCountDistinctFast()
{
var sexes = from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new
{
g.Key,
Count1 = g.Select(a => a.Name).Where(a => a != null).Distinct().Count(), //Fast
Count2 = g.Where(a => a.Name != null).Select(a => a.Name).Distinct().Count(), //Fast
Count3 = g.Select(a => a.Name).Distinct().Where(a => a != null).Count(), //Fast
Count4 = g.Select(a => a.Name).Distinct().Count(a => a != null), //Fast
};
sexes.ToList();
}
[Fact]
public void RootCountDistinct()
{
var count = Database.Query<ArtistEntity>().Select(a => a.Name).Where(a => a != null).Distinct().Count();
}
[Fact]
public void GroupCountDistinctSlow()
{
var sexes = from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new
{
g.Key,
Count1 = g.Select(a => a.Name).Distinct().Count(), //Slow
Count2 = g.Distinct().Count(), //Slow
};
sexes.ToList();
}
[Fact]
public void GroupMultiAggregateNoKeys()
{
var sexos = from a in Database.Query<ArtistEntity>()
group a.Name.Length by new { } into g
select new
{
g.Key,
Count = g.Count(),
Sum = g.Sum(),
Min = g.Min(),
Max = g.Max(),
Avg = g.Average(),
};
sexos.ToList();
}
[Fact]
public void GroupStdDev()
{
var sexos = from a in Database.Query<ArtistEntity>()
group a.Name.Length by a.Sex into g
select new
{
g.Key,
StdDev = (double?)g.StdDev(),
StdDevInMemory = GetStdDev(g.ToList()),
StdDevP = (double?)g.StdDevP(),
StdDevPInMemory = GetStdDevP(g.ToList()),
};
var list = sexos.ToList();
list.ForEach(a => ExtensionsTest.AssertSimilar(a.StdDev, a.StdDevInMemory));
list.ForEach(a => ExtensionsTest.AssertSimilar(a.StdDevP, a.StdDevPInMemory));
}
static double? GetStdDev(List<int> list)
{
return list.StdDev();
}
static double? GetStdDevP(List<int> list)
{
return list.StdDevP();
}
[Fact]
public void GroupEntityByEnum()
{
var list = Database.Query<ArtistEntity>().GroupBy(a => a.Sex).ToList();
}
//[Fact]
//public void GroupEntityByTypeFie()
//{
// var list = Database.Query<AlbumEntity>().GroupBy(a => a.GetType()).ToList();
//}
[Fact]
public void GroupEntityByTypeIb()
{
var list = Database.Query<AwardNominationEntity>().GroupBy(a => a.Award.EntityType).ToList();
}
[Fact]
public void WhereGroup()
{
var list = Database.Query<ArtistEntity>().Where(a => a.Dead).GroupBy(a => a.Sex).ToList();
}
[Fact]
public void GroupWhere()
{
var list = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, DeadArtists = g.Where(a => a.Dead).ToList() }).ToList();
}
[Fact]
public void GroupCount()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, Count = g.Count() }).ToList();
}
[Fact]
public void GroupCountInterval()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Id < 10 ? 0 : 10 into g
select new { Id = g.Key, Count = g.Count() }).ToList();
}
[Fact]
public void GroupWhereCount()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, DeadArtists = (int?)g.Count(a => a.Dead) }).ToList();
}
[Fact]
public void GroupEntityByTypeFieCount()
{
var list = Database.Query<AlbumEntity>().GroupBy(a => a.GetType()).Select(gr => new { gr.Key, Count = gr.Count() }).ToList();
}
[Fact]
public void GroupEntityByTypeIbCount()
{
var list = Database.Query<AlbumEntity>().GroupBy(a => a.Author.GetType()).Select(gr => new { gr.Key, Count = gr.Count() }).ToList();
}
[Fact]
public void GroupExpandKey()
{
var songs = (from a in Database.Query<AlbumEntity>()
group a by a.Label.Name into g
select new { g.Key, Count = g.Count() }).ToList();
}
[Fact]
public void GroupExpandResult()
{
var songs = (from a in Database.Query<AlbumEntity>()
group a by a.Label into g
select new { g.Key.Name, Count = g.Count() }).ToList();
}
[Fact]
public void GroupSum()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, Sum = g.Sum(a => a.Name.Length) }).ToList();
}
[Fact]
public void GroupMax()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, Max = g.Max(a => a.Name.Length) }).ToList();
}
[Fact]
public void GroupMin()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, Min = g.Min(a => a.Name.Length) }).ToList();
}
[Fact]
public void GroupMaxBy()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, MaxBy = g.MaxBy(a => a.Name.Length) }).ToList();
}
[Fact]
public void GroupMinBy()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, MinBy = g.MinBy(a => a.Name.Length) }).ToList();
}
[Fact]
public void GroupAverage()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new { Sex = g.Key, Avg = g.Average(a => a.Name.Length) }).ToList();
}
[Fact]
public void RootCount()
{
var songsAlbum = Database.Query<ArtistEntity>().Count();
}
[Fact]
public void RootCountWhere()
{
var songsAlbum = Database.Query<ArtistEntity>().Count(a => a.Name.StartsWith("M"));
}
[Fact]
public void RootCountWhereZero()
{
Assert.Equal(0, Database.Query<ArtistEntity>().Count(a => false));
}
[Fact]
public void RootSum()
{
var songsAlbum = Database.Query<ArtistEntity>().Sum(a => a.Name.Length);
}
[Fact]
public void RootSumNoArgs()
{
var songsAlbum = Database.Query<ArtistEntity>().Select(a => a.Name.Length).Sum();
}
[Fact]
public void SumWhere()
{
var songsAlbum = Database.Query<BandEntity>().Where(a => a.Members.Sum(m => m.Name.Length) > 0).ToList();
}
[Fact]
public void SumSimplification()
{
var songsAlbum = Database.Query<BandEntity>().Select(a => new { a.Name, Sum = a.Members.Sum(m => m.Name.Length) }).Select(a => a.Name).ToList();
}
[Fact]
public void RootSumZero()
{
Assert.Equal(0, Database.Query<ArtistEntity>().Where(a => false).Sum(a => a.Name.Length));
}
[Fact]
public void RootSumNull()
{
Assert.Null(Database.Query<ArtistEntity>().Where(a => false).Sum(a => (int?)a.Name.Length));
}
[Fact]
public void RootSumSomeNull()
{
Assert.True(Database.Query<AwardNominationEntity>().Sum(a => (int)a.Award.Id.Object) > 0);
}
[Fact]
public void RootMax()
{
var songsAlbum = Database.Query<ArtistEntity>().Max(a => a.Name.Length);
}
[Fact]
public void RootMaxNoArgs()
{
var songsAlbum = Database.Query<ArtistEntity>().Select(a => a.Name.Length).Max();
}
[Fact]
public void RootMaxException()
{
Assert.Throws<FieldReaderException>(() => Database.Query<ArtistEntity>().Where(a => false).Max(a => a.Name.Length));
}
[Fact]
public void RootMin()
{
var songsAlbum = Database.Query<ArtistEntity>().Min(a => a.Name.Length);
}
[Fact]
public void RootMinBy()
{
var songsAlbum = Database.Query<ArtistEntity>().MinBy(a => a.Name.Length);
}
[Fact]
public void RootMaxBy()
{
var songsAlbum = Database.Query<ArtistEntity>().MaxBy(a => a.Name.Length);
}
[Fact]
public void MinEnum()
{
var list = Database.Query<ArtistEntity>().GroupBy(a => a.Sex).Select(gr => gr.Min(a => a.Status));
var list2 = Database.Query<ArtistEntity>().GroupBy(a => a.Sex).Select(gr => gr.Where(a => a.Id > 10).Min(a => a.Status));
var minSex = Database.Query<ArtistEntity>().Min(a => a.Sex);
}
[Fact]
public void MinEnumNullable()
{
var minSex = Database.Query<ArtistEntity>().Where(a => false).Min(a => (Sex?)a.Sex);
var minSexs = Database.Query<BandEntity>().Select(b => b.Members.Where(a => false).Min(a => (Sex?)a.Sex));
}
[Fact]
public void RootMinException()
{
Assert.Throws<FieldReaderException>(() => Database.Query<ArtistEntity>().Where(a => false).Min(a => a.Name.Length));
}
[Fact]
public void RootMinNullable()
{
var min = Database.Query<ArtistEntity>().Where(a => false).Min(a => (int?)a.Name.Length);
}
[Fact]
public void RootAverage()
{
var songsAlbum = Database.Query<ArtistEntity>().Average(a => a.Name.Length);
}
[Fact]
public void GroupBySelectSelect()
{
var artistsBySex =
Database.Query<ArtistEntity>()
.GroupBy(a => a.Sex)
.Select(g => g)
.Select(g => new { Sex = g.Key, Count = g.Count() }).ToList();
}
[Fact]
public void JoinGroupPair()
{
var list = (from a in Database.Query<AlbumEntity>()
group new { a, HasBonusTrack = a.BonusTrack != null } by a.Label into g
select new
{
Label = g.Key,
Albums = g.Count(),
BonusTracks = g.Count(a => a.HasBonusTrack)
}).ToList();
}
[Fact]
public void GroupByEntity()
{
var list = (from a in Database.Query<AlbumEntity>()
group a by a.Label into g
select g.Key.ToLite()).ToList();
}
[Fact]
public void GroupByEntityExpand()
{
var list = (from a in Database.Query<AlbumEntity>()
where a.Label.Name != "whatever"
group a by a.Label into g
select new
{
Label = g.Key.Name,
Albums = g.Count(),
}).ToList();
}
[Fact]
public void SelectExpansionCount()
{
var albums = (from b in Database.Query<BandEntity>()
from a in b.Members
let count = Database.Query<ArtistEntity>().Count(a2 => a2.Sex == a.Sex) //a should be expanded here
select new
{
Album = a.ToLite(),
Count = count
}).ToList();
}
[Fact]
public void GroupBySelectMany()
{
var songsAlbum = Database.Query<ArtistEntity>().GroupBy(a => a.Sex).SelectMany(a => a).ToList();
}
[Fact]
public void SumSum()
{
var first = Database.Query<BandEntity>().Sum(b => b.Members.Sum(m => (int)m.Id.Object));
}
[Fact]
public void SumGroupbySum()
{
var first = Database.Query<ArtistEntity>().GroupBy(a => a.Status).Select(gr => gr.Sum(b => b.Friends.Sum(m => (int)m.Id.Object)));
}
[Fact]
public void MinMax()
{
var first = Database.Query<BandEntity>().Min(b => b.Members.Max(m => m.Id));
}
[Fact]
public void MinGroupByMax()
{
var first = Database.Query<ArtistEntity>().GroupBy(a => a.Status).Select(gr => gr.Min(b => b.Friends.Max(m => m.Id)));
}
[Fact]
public void GroupbyAggregateImplicitJoin()
{
var first = Database.Query<AlbumEntity>().GroupBy(a => a.Year).Select(gr => gr.Max(a => a.Label.Name)).ToList();
}
[Fact]
public void GroupByTake()
{
var list = (from a in Database.Query<AlbumEntity>()
group a by new { Author = a.Author.ToLite(), Year = a.Year / 2 } into g
select new
{
g.Key.Author,
g.Key.Year,
Count = g.Count()
}).Take(10).ToList();
}
[Fact]
public void GroupByTakeSomeKeys()
{
var list = (from a in Database.Query<AlbumEntity>()
group a by new { Author = a.Author.ToLite(), Year = a.Year / 2 } into g
select new
{
g.Key.Author,
//Year = g.Key.Year,
Count = g.Count()
}).Take(10).ToList();
}
[Fact]
public void GroupByMaybeAuthorLite()
{
var query = (from a in Database.Query<AlbumEntity>()
let old = a.Year < 2000
group a by old ? a.Author.ToLite() : null into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByMaybeAuthor()
{
var query = (from a in Database.Query<AlbumEntity>()
let old = a.Year < 2000
group a by old ? a.Author : null into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByMaybeLabel()
{
var query = (from a in Database.Query<AlbumEntity>()
let old = a.Year < 2000
group a by old ? a.Label : null into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByMaybeLabelLite()
{
var query = (from a in Database.Query<AlbumEntity>()
let old = a.Year < 2000
group a by old ? a.Label.ToLite() : null into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByCoallesceAuthorLite()
{
var query = (from a in Database.Query<AlbumEntity>()
group a by a.Author.ToLite() ?? a.Author.ToLite() into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByCoallesceAuthor()
{
var query = (from a in Database.Query<AlbumEntity>()
let old = a.Year < 2000
group a by a.Author ?? a.Author into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByCoallesceLabel()
{
var query = (from a in Database.Query<AlbumEntity>()
group a by a.Label ?? a.Label into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByCoallesceLabelLite()
{
var query = (from a in Database.Query<AlbumEntity>()
group a by a.Label.ToLite() ?? a.Label.ToLite() into g
select new
{
Author = g.Key,
Count = g.Count()
}).Take(10);
query.ToList();
}
[Fact]
public void GroupByExpandGroupBy()
{
var list = (from a in Database.Query<ArtistEntity>()
group a by a.Sex into g
select new
{
g.Key,
MaxFriends = g.Max(a => a.Friends.Count),
}).ToList();
}
#pragma warning disable CA1829 // Use Length/Count property instead of Count() when available
[Fact]
public void LetTrick()
{
var list = (from a in Database.Query<ArtistEntity>()
let friend = a.Friends
select new
{
Artist = a.ToLite(),
Friends = friend.Count(), // will also be expanded but then simplified
FemaleFriends = friend.Count(f => f.Entity.Sex == Sex.Female)
}).ToList();
}
#pragma warning restore CA1829 // Use Length/Count property instead of Count() when available
[Fact]
public void DistinctGroupByForce()
{
var list = Database.Query<ArtistEntity>()
.Select(a => new { Initials = a.Name.Substring(0, 1), a.Sex })
.Distinct()
.GroupBy(a => a.Initials)
.Select(gr => new { gr.Key, Count = gr.Count() })
.ToList();
}
[Fact]
public void GroupByCount()
{
var list = Database.Query<AlbumEntity>()
.GroupBy(a => a.Songs.Count)
.Select(gr => new { NumSongs = gr.Key, Count = gr.Count() })
.ToList();
}
[Fact]
public void FirstLastMList()
{
var list = (from a in Database.Query<AlbumEntity>()
where a.Songs.Count > 1
select new
{
FirstName = a.Songs.OrderBy(s => s.Name).FirstOrDefault()!.Name,
FirstDuration = a.Songs.OrderBy(s => s.Name).FirstOrDefault()!.Duration,
Last = a.Songs.OrderByDescending(s => s.Name).FirstOrDefault()
}).ToList();
Assert.True(list.All(a => a.FirstName != a.Last.Name));
}
[Fact]
public void FirstLastGroup()
{
var list = (from mle in Database.MListQuery((AlbumEntity a)=>a.Songs)
group mle.Element by mle.Parent into g
where g.Count() > 1
select new
{
FirstName = g.OrderBy(s => s.Name).FirstOrDefault()!.Name,
FirstDuration = g.OrderBy(s => s.Name).FirstOrDefault()!.Duration,
Last = g.OrderByDescending(s => s.Name).FirstOrDefault()
}).ToList();
Assert.True(list.All(a => a.FirstName != a.Last!.Name));
}
[Fact]
public void FirstLastList()
{
var list = (from a in Database.Query<AlbumEntity>()
select a.Songs into songs
where songs.Count > 1
select new
{
FirstName = songs.OrderBy(s => s.Name).FirstOrDefault()!.Name,
FirstDuration = songs.OrderBy(s => s.Name).FirstOrDefault()!.Duration,
Last = songs.OrderByDescending(s => s.Name).FirstOrDefault()
}).ToList();
Assert.True(list.All(a => a.FirstName != a.Last!.Name));
}
[Fact]
public void GroupByOr()
{
var b = (from a in Database.Query<ArtistEntity>()
group a by a.Sex.IsDefined()
into g
select new {g.Key, count = g.Count()}).ToList();
}
}
| |
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A Job Release task to run on job completion on any compute node where the job has run.
/// </summary>
public partial class JobReleaseTask : ITransportObjectProvider<Models.JobReleaseTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<TimeSpan?> MaxWallClockTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<TimeSpan?> RetentionTimeProperty;
public readonly PropertyAccessor<bool?> RunElevatedProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.MaxWallClockTimeProperty = this.CreatePropertyAccessor<TimeSpan?>("MaxWallClockTime", BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.RetentionTimeProperty = this.CreatePropertyAccessor<TimeSpan?>("RetentionTime", BindingAccess.Read | BindingAccess.Write);
this.RunElevatedProperty = this.CreatePropertyAccessor<bool?>("RunElevated", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobReleaseTask protocolObject) : base(BindingState.Bound)
{
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read | BindingAccess.Write);
this.MaxWallClockTimeProperty = this.CreatePropertyAccessor(
protocolObject.MaxWallClockTime,
"MaxWallClockTime",
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read | BindingAccess.Write);
this.RetentionTimeProperty = this.CreatePropertyAccessor(
protocolObject.RetentionTime,
"RetentionTime",
BindingAccess.Read | BindingAccess.Write);
this.RunElevatedProperty = this.CreatePropertyAccessor(
protocolObject.RunElevated,
"RunElevated",
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobReleaseTask"/> class.
/// </summary>
/// <param name='commandLine'>The command line of the task.</param>
public JobReleaseTask(
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.CommandLine = commandLine;
}
internal JobReleaseTask(Models.JobReleaseTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobReleaseTask
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets the collection of EnvironmentSetting instances.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets the maximum duration of time for which a task is allowed to run from the time it is created.
/// </summary>
public TimeSpan? MaxWallClockTime
{
get { return this.propertyContainer.MaxWallClockTimeProperty.Value; }
set { this.propertyContainer.MaxWallClockTimeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the duration of time for which files in the task's working directory are retained, from the time
/// it completes execution. After this duration, the task's working directory is reclaimed.
/// </summary>
public TimeSpan? RetentionTime
{
get { return this.propertyContainer.RetentionTimeProperty.Value; }
set { this.propertyContainer.RetentionTimeProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether to run the task in elevated mode.
/// </summary>
public bool? RunElevated
{
get { return this.propertyContainer.RunElevatedProperty.Value; }
set { this.propertyContainer.RunElevatedProperty.Value = value; }
}
#endregion // JobReleaseTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobReleaseTask ITransportObjectProvider<Models.JobReleaseTask>.GetTransportObject()
{
Models.JobReleaseTask result = new Models.JobReleaseTask()
{
CommandLine = this.CommandLine,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
Id = this.Id,
MaxWallClockTime = this.MaxWallClockTime,
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RetentionTime = this.RetentionTime,
RunElevated = this.RunElevated,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
namespace NetworkUtility
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public class UriPathSegmentList : IList<string>, IList, INotifyPropertyChanged, INotifyCollectionChanged, IEquatable<UriPathSegmentList>, IComparable<UriPathSegmentList>, IComparable
{
private static StringComparer _comparer = StringComparer.InvariantCultureIgnoreCase;
private object _syncRoot = new object();
private List<string> _segments = null;
private List<char> _separators = new List<char>();
private int _count = 0;
private string _fullPath = "";
private string _encodedFullPath = "";
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public string FullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _fullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public string EncodedFullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _encodedFullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsEmpty
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments == null; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsPathRooted
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments != null && _separators.Count == _segments.Count; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
Monitor.Enter(_syncRoot);
try
{
if (value)
{
if (_separators == null)
_separators = new List<char>();
else if (_separators.Count < _segments.Count)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
}
else if (_separators != null)
{
if (_separators.Count == 0)
_separators = null;
else
_separators.RemoveAt(0);
}
}
finally { Monitor.Exit(_syncRoot); }
}
}
public string this[int index]
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments[index]; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
string oldValue;
Monitor.Enter(_syncRoot);
try
{
if (value == null)
throw new ArgumentNullException();
if (_segments[index] == value)
return;
oldValue = _segments[index];
_segments[index] = value;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath(() => RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldValue, index)));
}
}
object IList.this[int index]
{
get { return this[index]; }
set
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
this[index] = (string)obj;
}
}
public int Count
{
get
{
Monitor.Enter(_syncRoot);
try { return _count; }
finally { Monitor.Exit(_syncRoot); }
}
}
bool ICollection<string>.IsReadOnly { get { return false; } }
bool IList.IsReadOnly { get { return false; } }
bool IList.IsFixedSize { get { return false; } }
object ICollection.SyncRoot { get { return _syncRoot; } }
bool ICollection.IsSynchronized { get { return true; } }
public static string EscapePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case '%':
sb.Append("%25");
break;
case '\\':
sb.Append("%5C");
break;
case '#':
sb.Append("%23");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
public static string EncodePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case ' ':
sb.Append("%20");
break;
case '"':
sb.Append("%22");
break;
case '%':
sb.Append("%25");
break;
case '<':
sb.Append("%3C");
break;
case '>':
sb.Append("%3E");
break;
case '\\':
sb.Append("%5C");
break;
case '^':
sb.Append("%5E");
break;
case '`':
sb.Append("%60");
break;
case '{':
sb.Append("%7B");
break;
case '|':
sb.Append("%7C");
break;
case '}':
sb.Append("%7D");
break;
case '#':
sb.Append("%23");
break;
case '+':
sb.Append("%2B");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
private void EnsureCount(Action action)
{
try { action(); }
finally { EnsureCount(); }
}
private void EnsureCount()
{
Monitor.Enter(_syncRoot);
try
{
if (_count == _segments.Count)
return;
_count = _segments.Count;
}
finally { Monitor.Exit(_syncRoot); }
RaisePropertyChanged("Count");
}
private void UpdateFullPath(Action action)
{
try { action(); }
finally { UpdateFullPath(); }
}
private void UpdateFullPath()
{
string encodedFullPath, escapedFullPath;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
{
encodedFullPath = "";
escapedFullPath = "";
}
else
{
StringBuilder encoded = new StringBuilder();
StringBuilder escaped = new StringBuilder();
if (_segments.Count == _separators.Count)
{
for (int i = 0; i < _segments.Count; i++)
{
char c = _separators[i];
encoded.Append(c);
escaped.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
else
{
encoded.Append(EncodePathSegment(_segments[0]));
for (int i = 1; i < _segments.Count; i++)
{
char c = _separators[i - 1];
encoded.Append(c);
encoded.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
encodedFullPath = encoded.ToString();
escapedFullPath = escaped.ToString();
}
if (_encodedFullPath == encodedFullPath)
encodedFullPath = null;
else
_encodedFullPath = encodedFullPath;
if (_fullPath == escapedFullPath)
escapedFullPath = null;
else
_fullPath = escapedFullPath;
}
finally { Monitor.Exit(_syncRoot); }
if (escapedFullPath != null)
RaisePropertyChanged("FullPath");
if (encodedFullPath != null)
RaisePropertyChanged("EncodedFullPath");
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { }
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
try { OnPropertyChanged(args); }
finally
{
PropertyChangedEventHandler propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, args);
}
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { }
private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args)
{
try { OnCollectionChanged(args); }
finally
{
NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;
if (collectionChanged != null)
collectionChanged(this, args);
}
}
public int Add(string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
int index;
try
{
index = _segments.Count;
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
_segments.Add(item);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return index;
}
void ICollection<string>.Add(string item) { Add(item); }
int IList.Add(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Add((string)obj);
}
public void Clear()
{
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return;
if (_separators.Count == _segments.Count)
_separators.Clear();
else
_separators = null;
_segments.Clear();
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public bool Contains(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return false;
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return true;
}
}
finally { Monitor.Exit(_syncRoot); }
return false;
}
bool IList.Contains(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Contains(obj as string);
}
public void CopyTo(string[] array, int arrayIndex)
{
Monitor.Enter(_syncRoot);
try { _segments.CopyTo(array, arrayIndex); }
finally { Monitor.Exit(_syncRoot); }
}
void ICollection.CopyTo(Array array, int index)
{
Monitor.Enter(_syncRoot);
try { _segments.ToArray().CopyTo(array, index); }
finally { Monitor.Exit(_syncRoot); }
}
public IEnumerator<string> GetEnumerator() { return _segments.GetEnumerator(); }
public char? GetSeparator(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators != null && _separators.Count == _segments.Count)
return _separators[index];
if (index == 0)
return null;
return _separators[index - 1];
}
finally { Monitor.Exit(_syncRoot); }
}
public int IndexOf(string item)
{
if (item == null)
return -1;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return -1;
int index = _segments.IndexOf(item);
if (index < 0)
{
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return i;
}
}
return index;
}
finally { Monitor.Exit(_syncRoot); }
}
int IList.IndexOf(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return IndexOf(obj as string);
}
public void Insert(int index, string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index > _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (index == _segments.Count)
{
_segments.Add(item);
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
}
else
{
if (_separators.Count == _segments.Count)
_separators.Insert(index, _separators[index]);
else if (index == _separators.Count)
_separators.Add(_separators.DefaultIfEmpty('/').Last());
else if (index == 0)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
else
_separators.Insert(index - 1, _separators[index - 1]);
_segments.Insert(index, item);
}
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
void IList.Insert(int index, object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Insert(index, (string)obj);
}
public bool Remove(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
int index = IndexOf(item);
if (index < 0)
return false;
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return true;
}
void IList.Remove(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Remove(obj as string);
}
public void RemoveAt(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public void SetSeparator(int index, char separator)
{
if (!(separator == ':' || separator == '/' || separator == '\\'))
throw new ArgumentException("Invalid separator character", "separator");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators.Count == _segments.Count)
_separators[index] = separator;
else if (index == 0)
_separators.Insert(0, separator);
else
_separators[index - 1] = separator;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath();
}
IEnumerator IEnumerable.GetEnumerator() { return _segments.ToArray().GetEnumerator(); }
#warning Not implemented
public int CompareTo(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public int CompareTo(object obj) { return CompareTo(obj as UriPathSegmentList); }
public bool Equals(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public override bool Equals(object obj) { return Equals(obj as UriPathSegmentList); }
public override int GetHashCode() { return ToString().GetHashCode(); }
public override string ToString()
{
Monitor.Enter(_syncRoot);
try
{
throw new NotImplementedException();
}
finally { Monitor.Exit(_syncRoot); }
}
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
| |
//------------------------------------------------------------------------------
// <copyright file="PathDescriptorParser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
namespace Microsoft.XmlDiffPatch
{
internal class PathDescriptorParser
{
static char[] Delimiters = new char[] {'|','-','/'};
static char[] MultiNodesDelimiters = new char[] {'|','-'};
internal static XmlNodeList SelectNodes( XmlNode rootNode, XmlNode currentParentNode, string pathDescriptor )
{
switch ( pathDescriptor[0] )
{
case '/':
return SelectAbsoluteNodes( rootNode, pathDescriptor );
case '@':
if ( pathDescriptor.Length < 2 )
OnInvalidExpression( pathDescriptor );
if ( pathDescriptor[1] == '*' )
return SelectAllAttributes( currentParentNode );
else
return SelectAttributes( currentParentNode, pathDescriptor );
case '*':
if ( pathDescriptor.Length == 1 )
return SelectAllChildren( currentParentNode );
else
{
OnInvalidExpression( pathDescriptor );
return null;
}
default:
return SelectChildNodes( currentParentNode, pathDescriptor, 0 );
}
}
private static XmlNodeList SelectAbsoluteNodes( XmlNode rootNode, string path )
{
Debug.Assert( path[0] == '/' );
int pos = 1;
XmlNode node = rootNode;
for (;;)
{
int startPos = pos;
XmlNodeList childNodes = node.ChildNodes;
int nodePos = ReadPosition( path, ref pos );
if ( pos == path.Length || path[pos] == '/' ) {
if ( childNodes.Count == 0 || nodePos < 0 || nodePos > childNodes.Count )
OnNoMatchingNode( path );
node = childNodes.Item( nodePos - 1 );
if ( pos == path.Length ) {
XmlPatchNodeList list = new SingleNodeList();
list.AddNode( node );
return list;
}
pos++;
}
else {
if ( path[pos] == '-' || path[pos] == '|' ) {
return SelectChildNodes( node, path, startPos );
}
OnInvalidExpression( path );
}
}
}
private static XmlNodeList SelectAllAttributes( XmlNode parentNode )
{
XmlAttributeCollection attributes = parentNode.Attributes;
if ( attributes.Count == 0 )
{
OnNoMatchingNode( "@*" );
return null;
}
else if ( attributes.Count == 1 )
{
XmlPatchNodeList nodeList = new SingleNodeList();
nodeList.AddNode( attributes.Item( 0 ) );
return nodeList;
}
else
{
IEnumerator enumerator = attributes.GetEnumerator();
XmlPatchNodeList nodeList = new MultiNodeList();
while ( enumerator.MoveNext() )
nodeList.AddNode( (XmlNode) enumerator.Current );
return nodeList;
}
}
private static XmlNodeList SelectAttributes( XmlNode parentNode, string path )
{
Debug.Assert( path[0] == '@' );
int pos = 1;
XmlAttributeCollection attributes = parentNode.Attributes;
XmlPatchNodeList nodeList = null;
for (;;)
{
string name = ReadAttrName( path, ref pos );
if ( nodeList == null )
{
if ( pos == path.Length )
nodeList = new SingleNodeList();
else
nodeList = new MultiNodeList();
}
XmlNode attr = attributes.GetNamedItem( name );
if ( attr == null )
OnNoMatchingNode( path );
nodeList.AddNode( attr );
if ( pos == path.Length )
break;
else if ( path[pos] == '|' ) {
pos++;
if ( path[pos] != '@' )
OnInvalidExpression( path );
pos++;
}
else
OnInvalidExpression( path );
}
return nodeList;
}
private static XmlNodeList SelectAllChildren( XmlNode parentNode )
{
XmlNodeList children = parentNode.ChildNodes;
if ( children.Count == 0 )
{
OnNoMatchingNode( "*" );
return null;
}
else if ( children.Count == 1 )
{
XmlPatchNodeList nodeList = new SingleNodeList();
nodeList.AddNode( children.Item( 0 ) );
return nodeList;
}
else
{
IEnumerator enumerator = children.GetEnumerator();
XmlPatchNodeList nodeList = new MultiNodeList();
while ( enumerator.MoveNext() )
nodeList.AddNode( (XmlNode) enumerator.Current );
return nodeList;
}
}
private static XmlNodeList SelectChildNodes( XmlNode parentNode, string path, int startPos )
{
int pos = startPos;
XmlPatchNodeList nodeList = null;
XmlNodeList children = parentNode.ChildNodes;
int nodePos = ReadPosition( path, ref pos );
if ( pos == path.Length )
nodeList = new SingleNodeList();
else
nodeList = new MultiNodeList();
for (;;)
{
if ( nodePos <= 0 || nodePos > children.Count )
OnNoMatchingNode( path );
XmlNode node = children.Item( nodePos - 1 );
nodeList.AddNode( node );
if ( pos == path.Length )
break;
else if ( path[pos] == '|' )
pos++;
else if ( path[pos] == '-' )
{
pos++;
int endNodePos = ReadPosition( path, ref pos );
if ( endNodePos <= 0 || endNodePos > children.Count )
OnNoMatchingNode( path );
while ( nodePos < endNodePos )
{
nodePos++;
node = node.NextSibling;
nodeList.AddNode( node );
}
Debug.Assert( (object)node == (object)children.Item( endNodePos - 1 ) );
if ( pos == path.Length )
break;
else if ( path[pos] == '|' )
pos++;
else
OnInvalidExpression( path );
}
nodePos = ReadPosition( path, ref pos );
}
return nodeList;
}
private static int ReadPosition( string str, ref int pos )
{
int end = str.IndexOfAny( Delimiters, pos );
if ( end < 0 )
end = str.Length;
// TODO: better error handling if this should be shipped
int nodePos = int.Parse( str.Substring( pos, end - pos ) );
pos = end;
return nodePos;
}
private static string ReadAttrName( string str, ref int pos )
{
int end = str.IndexOf( '|', pos );
if ( end < 0 )
end = str.Length;
// TODO: better error handling if this should be shipped
string name = str.Substring( pos, end - pos );
pos = end;
return name;
}
private static void OnInvalidExpression( string path )
{
XmlPatchError.Error( XmlPatchError.InvalidPathDescriptor, path );
}
private static void OnNoMatchingNode( string path )
{
XmlPatchError.Error( XmlPatchError.NoMatchingNode, path );
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Reflection;
using Awesomium.Core;
using AwesomiumUiLib;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO;
#endregion
namespace Inspire.GameEngine.ScreenManager
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
protected GameScreen()
{
}
public void Initialize()
{
InjectLibraries();
}
private void InjectLibraries()
{
}
/// <summary>
/// The UI manager helps create windows and the basic HTML chrome for pages that require it
/// </summary>
public AwesomiumUI UiManager
{
get { return _uiManager; }
set { _uiManager = value; }
}
#region Properties
/// <summary>
/// The camera for this particular screen
/// </summary>
public Camera2D Camera2D { get; set; }
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup = false;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 1 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionAlpha
{
get { return 1f - TransitionPosition; }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
bool isExiting = false;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
ScreenManager screenManager;
/// <summary>
/// Gets the index of the player who is currently controlling this screen,
/// or null if it is accepting input from any player. This is used to lock
/// the game to a specific player profile. The main menu responds to input
/// from any connected gamepad, but whichever player makes a selection from
/// this menu is given control over all subsequent screens, so other gamepads
/// are inactive until the controlling player returns to the main menu.
/// </summary>
public PlayerIndex? ControllingPlayer
{
get { return controllingPlayer; }
internal set { controllingPlayer = value; }
}
PlayerIndex? controllingPlayer;
/// <summary>
/// Gets the gestures the screen is interested in. Screens should be as specific
/// as possible with gestures to increase the accuracy of the gesture engine.
/// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate.
/// These gestures are handled by the ScreenManager when screens change and
/// all gestures are placed in the InputState passed to the HandleInput method.
/// </summary>
public GestureType EnabledGestures
{
get { return enabledGestures; }
protected set
{
enabledGestures = value;
// the screen manager handles this during screen changes, but
// if this screen is active and the gesture types are changing,
// we have to update the TouchPanel ourself.
if (ScreenState == ScreenState.Active)
{
TouchPanel.EnabledGestures = value;
}
}
}
GestureType enabledGestures = GestureType.None;
private AwesomiumUI _uiManager;
#endregion
#region Initialization
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (!UiManager.webView.IsLoading)
UiManager.Update();
if (isExiting)
{
// If the screen is going away to die, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if (((direction < 0) && (transitionPosition <= 0)) ||
((direction > 0) && (transitionPosition >= 1)))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputState input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime)
{
var spriteBatch = ScreenManager.SpriteBatch;
var width = ScreenManager.GraphicsDevice.PresentationParameters.BackBufferWidth;
var height = ScreenManager.GraphicsDevice.PresentationParameters.BackBufferHeight;
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
if (_uiManager.webTexture != null)
spriteBatch.Draw(_uiManager.webTexture, new Rectangle(0, 0, width, height), Color.White);
spriteBatch.End();
_uiManager.RenderWebView();
}
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
#endregion
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger 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 from this software.
*/
using System;
using System.Text;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using PHP.Core;
using PHP.Core.Reflection;
using System.Collections.Generic;
#if !SILVERLIGHT
using System.Web;
#else
using System.Windows.Browser;
#endif
namespace PHP.Core
{
/// <summary>
/// Manages displaying of information about Phalanger and external PHP modules.
/// </summary>
public static class PhpNetInfo
{
/// <summary>
/// Sections of Phalanger information.
/// </summary>
[Flags]
public enum Sections
{
General = 1,
Credits = 2,
Configuration = 4,
Extensions = 8,
Environment = 16,
Variables = 32,
License = 64,
All = -1
}
/// <summary>
/// Writes all information about Phalanger and external PHP modules to output.
/// </summary>
/// <param name="output">An output where to write information.</param>
/// <param name="sections">A mask of sections which to write.</param>
public static void Write(Sections/*!*/ sections, TextWriter/*!*/ output)
{
output.Write(htmlPrologue);
output.Write(htmlStyle, htmlCss);
if ((sections & Sections.General) != 0)
{
WriteLogo(output);
}
if ((sections & (Sections.Configuration | Sections.General)) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_config"));
output.Write("</h2>");
WriteConfiguration(output);
}
if ((sections & Sections.Credits) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_credits"));
output.Write("</h2>");
WriteCredits(output);
}
if ((sections & Sections.Extensions) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_loaded_extensions"));
output.Write("</h2>");
// TODO: loaded extensions
}
if ((sections & Sections.Environment) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_environment_variables"));
output.Write("</h2>");
WriteEnvironmentVariables(output);
}
if ((sections & Sections.Variables) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_global_variables"));
output.Write("</h2>");
WriteGlobalVariables(output);
}
if ((sections & Sections.License) != 0)
{
output.Write("<h2>");
output.Write(CoreResources.GetString("info_license"));
output.Write("</h2>");
WriteLicense(output);
}
output.Write(htmlEpilogue);
}
#region Private HTML constructs
private const string htmlTableStart = "<table cellpadding='3' align='center'>";
private const string htmlTableEnd = "</table>";
private const string htmlTableBoxStart = "<tr><td>";
private const string htmlTableHeaderBoxStart = "<tr class='header'><td>";
private const string htmlTableBoxEnd = "</tr></td>";
private const string htmlHorizontalLine = "<hr/>";
private const string htmlTableColspanHeader = "<tr><td class='colHeader' colspan={0}>{1}</td></tr>";
private const string htmlSectionCaption = "<h3>{0}</h3>";
private const string htmlPrologue = "<div class='PhpNetInfo' align='center'>";
private const string htmlEpilogue = "</div>";
private const string htmlStyle = "<style type='text/css'>\n {0} \n</style>";
private const string htmlCss =
"div.PhpNetInfo { font-family:sans-serif; background-color:white; color:black; text-align:center; }\n" +
"div.PhpNetInfo pre { margin:0px; font-family:monospace; }\n" +
"div.PhpNetInfo a:link { color:#000099; text-decoration:none; }\n" +
"div.PhpNetInfo a:hover { text-decoration: underline; }\n" +
"div.PhpNetInfo table { width:600px; border-collapse:collapse; text-align:left; }\n" +
"div.PhpNetInfo th { text-align: center; !important }\n" +
"div.PhpNetInfo td, div.PhpNetInfo th { border:1px solid black; font-size:75%; vertical-align:baseline; }\n" +
"div.PhpNetInfo td { background-color:#cccccc; }\n" +
"div.PhpNetInfo td.rowHeader { background-color:#ccccff; font-weight:bold; }\n" +
"div.PhpNetInfo tr.colHeader { background-color:#9999cc; font-weight:bold; }\n" +
"div.PhpNetInfo i { color:#666666; }\n" +
"div.PhpNetInfo img { float: right; border:0px; }\n" +
"div.PhpNetInfo hr { width:600px; align:center; background-color:#cccccc; border:0px; height:1px; }\n";
/// <summary>
/// Makes a table row containing given <c>cells</c>.
/// </summary>
/// <param name="doEscape">Do escape HTML entities (tag markers etc.)?</param>
/// <param name="cells">The content of cells of the written row.</param>
/// <returns>The row in HTML.</returns>
private static string HtmlRow(bool doEscape, params string[] cells)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("<tr><td class='rowHeader'>{0}</td>", cells[0]);
for (int i = 1; i < cells.Length; i++)
{
string cell = cells[i];
if (cell == null || cell == "") cell = "<i>no value</i>";
else
if (doEscape) cell = HttpUtility.HtmlEncode(cell);
result.AppendFormat("<td>{0}</td>", cell);
}
result.AppendFormat("</tr>");
return result.ToString();
}
/// <summary>
/// Outputs a table row containing a variable dump.
/// </summary>
private static void HtmlVarRow(TextWriter output, string array, object name, object variable)
{
string s;
output.Write("<tr><td class='rowHeader'>{0}[\"", array);
// name:
if ((s = name as string) != null)
output.Write((string)StringUtils.AddCSlashes(s, false, true));
else
output.Write((int)name);
// printed value:
output.Write("\"]</td><td>");
IPhpPrintable printable;
if (variable == null || (variable as string) == String.Empty)
{
output.Write("<i>no value</i>");
}
else
if ((printable = variable as IPhpPrintable) != null)
{
output.Write("<pre>");
StringWriter str_output = new StringWriter();
printable.Print(str_output);
output.Write(HttpUtility.HtmlEncode(str_output.ToString()));
output.Write("</pre>");
}
else
{
output.Write(Convert.ObjectToString(variable));
}
output.Write("</td></tr>");
}
/// <summary>
/// Makes a table header row containing given <c>cells</c>.
/// </summary>
/// <param name="cells">The content of cells of the written row.</param>
/// <returns>The row in HTML.</returns>
private static string HtmlHeaderRow(params string[] cells)
{
StringBuilder result = new StringBuilder("<tr class='colHeader'>");
foreach (string cell in cells)
result.AppendFormat("<th>{0}</th>", (cell == null || cell == "") ? " " : cell);
result.Append("</tr>");
return result.ToString();
}
private static string HtmlEntireRowHeader(string text, int count)
{
StringBuilder result = new StringBuilder("<tr class='colHeader'>");
result.AppendFormat("<th colspan='{0}' align='center'>{1}</th>", count, text);
result.Append("</tr>");
return result.ToString();
}
/// <summary>
/// Converts option's value to string to be displayed.
/// </summary>
/// <param name="value">The value of the option.</param>
/// <returns>String representation of the option's value.</returns>
private static string OptionValueToString(object value)
{
// lists:
IList list = value as IList;
if (list != null)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
if (list[i] != null)
{
if (i > 0) sb.Append("; ");
sb.Append(list[i].ToString());
}
}
return sb.ToString();
}
// convertible:
IPhpConvertible conv = value as IPhpConvertible;
if (conv != null)
return conv.ToString();
Encoding encoding = value as Encoding;
if (encoding != null)
return encoding.WebName;
// others:
return (value == null) ? String.Empty : value.ToString();
}
#endregion
#region Info Writers
private static void WriteLogo(TextWriter output)
{
output.Write("<h1>Phalanger {0}{1} {2}</h1>",
PhalangerVersion.Current,
#if DEBUG
", DEBUG,",
#else
null,
#endif
(Environment.Is64BitProcess ? "x64" : "x86"));
output.Write("<h4>The PHP language compiler for .NET Framework</h4>");
}
private static void WriteLicense(TextWriter output)
{
output.Write(htmlTableStart);
output.Write("<tr><td>");
output.Write(
"<p align='center'>" +
"<b>Copyright (c) Jan Benda, Miloslav Beno, Martin Maly, Tomas Matousek, Jakub Misek, Pavel Novak, Vaclav Novak, and Ladislav Prosek.</b>" +
"</p>");
output.Write(CoreResources.GetString("info_license_text"));
output.Write("</td></tr>");
output.Write(htmlTableEnd);
}
private static void WriteCredits(TextWriter output)
{
string contribution = CoreResources.GetString("credits_contribution");
string authors = CoreResources.GetString("credits_authors");
output.Write(htmlSectionCaption, CoreResources.GetString("credits_design"));
output.Write(htmlTableStart);
output.Write(HtmlHeaderRow(contribution, authors));
ScriptContext context = ScriptContext.CurrentContext;
output.Write(HtmlRow(false, CoreResources.GetString("credits_overall_concept"), "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_specific_features_compilation"), "Tomas Matousek, Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_oo_features_compilation"), "Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_php_clr"), "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_overall_compiler_design"), "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_code_analysis"), "Tomas Matousek, Vaclav Novak"));
output.Write(HtmlRow(false, "Core", "Tomas Matousek, Ladislav Prosek"));
output.Write(HtmlRow(false, "Class Library", "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_extmgr_wrappers"), "Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_ast"), "Vaclav Novak, Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_compiler_tables"), "Tomas Matousek, Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_code_generator"), "Tomas Matousek, Ladislav Prosek, Martin Maly"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_configuration"), "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_aspnet"), "Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_automatic_tests"), "Pavel Novak"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_interactive_tests"), "Jan Benda, Jakub Misek"));
output.Write(htmlTableEnd);
output.Write(htmlSectionCaption, CoreResources.GetString("credits_implementation"));
output.Write(htmlTableStart);
output.Write(HtmlHeaderRow(contribution, authors));
output.Write(HtmlRow(false, CoreResources.GetString("credits_core_functionality"), "Tomas Matousek, Ladislav Prosek, Tomas Petricek, Daniel Balas, Jakub Misek, Miloslav Beno"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_lexical_syntactic_analysis"), "Tomas Matousek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_semantic_analysis"), "Tomas Matousek, Vaclav Novak"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_code_generation"), "Tomas Matousek, Ladislav Prosek, Martin Maly, Jakub Misek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_clr_features"), "Ladislav Prosek, Tomas Matousek"));
output.Write(HtmlRow(false, "Class Library", "Tomas Matousek, Ladislav Prosek, Jan Benda, Pavel Novak, Tomas Petricek, Daniel Balas, Miloslav Beno, Jakub Misek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_extensions_management"), "Ladislav Prosek, Daniel Balas, Jakub Misek"));
output.Write(HtmlRow(false, "SHM Channel", "Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_aspnet"), "Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_vsnet"), "Tomas Matousek, Tomas Petricek, Jakub Misek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_streams"), "Jan Benda"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_interactive_tests"), "Jan Benda"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_automatic_tester"), "Pavel Novak, Jakub Misek, Miloslav Beno"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_utilities"), "Tomas Matousek, Ladislav Prosek"));
output.Write(HtmlRow(false, CoreResources.GetString("credits_installation"), "Ladislav Prosek, Jakub Misek"));
output.Write(htmlTableEnd);
}
private const BindingFlags ConfigBindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
private static void ReflectConfigSection(TextWriter output, string prefix, Type type, object config1, object config2)
{
FieldInfo[] fields = type.GetFields(ConfigBindingFlags);
PropertyInfo[] properties = type.GetProperties(ConfigBindingFlags);
string[] cells = new string[(config2 != null) ? 3 : 2];
// fields which contains sections:
for (int i = 0; i < fields.Length; i++)
{
if (fields[i].IsDefined(typeof(NoPhpInfoAttribute), false))
{
fields[i] = null;
}
else if (typeof(IPhpConfigurationSection).IsAssignableFrom(fields[i].FieldType))
{
ReflectConfigSection(output, prefix + fields[i].Name + ".", fields[i].FieldType,
fields[i].GetValue(config1), (config2 != null) ? fields[i].GetValue(config2) : null);
fields[i] = null;
}
}
// remaining fields:
for (int i = 0; i < fields.Length; i++)
{
if (fields[i] != null)
{
try
{
cells[0] = prefix + fields[i].Name;
cells[1] = OptionValueToString(fields[i].GetValue(config1));
if (config2 != null) cells[2] = OptionValueToString(fields[i].GetValue(config2));
output.Write(HtmlRow(true, cells));
}
catch (Exception e)
{
cells[1] = e.Message;
if (config2 != null) cells[2] = null;
output.Write(HtmlRow(true, cells));
}
}
}
// properties:
foreach (PropertyInfo property in properties)
{
if (!property.IsDefined(typeof(NoPhpInfoAttribute), false))
{
try
{
cells[0] = prefix + property.Name;
cells[1] = OptionValueToString(property.GetValue(config1, null));
if (config2 != null) cells[2] = OptionValueToString(property.GetValue(config2, null));
output.Write(HtmlRow(true, cells));
}
catch (Exception e)
{
cells[1] = e.Message;
if (config2 != null) cells[2] = null;
output.Write(HtmlRow(true, cells));
}
}
}
}
/// <summary>
/// Writes core configuration to given output.
/// </summary>
/// <param name="output">The output.</param>
/// <remarks>
/// Configuration is traversed by reflection methods and all fields and its values are formatted to table.
/// </remarks>
private static void WriteConfiguration(TextWriter/*!*/ output)
{
ApplicationContext app_context = ScriptContext.CurrentContext.ApplicationContext;
Debug.Assert(!app_context.AssemblyLoader.ReflectionOnly);
string directive = CoreResources.GetString("info_directive");
// script dependent configuration //
output.Write(htmlSectionCaption, CoreResources.GetString("info_script_dependent"));
output.Write(htmlTableStart);
output.Write(HtmlEntireRowHeader("Core", 3));
output.Write(HtmlHeaderRow(directive, CoreResources.GetString("info_script_value"), CoreResources.GetString("info_master_value")));
// core:
ReflectConfigSection(output, "", typeof(LocalConfiguration), Configuration.Local, Configuration.DefaultLocal);
// libraries:
foreach (PhpLibraryAssembly lib_assembly in app_context.GetLoadedLibraries())
{
IPhpConfiguration local = Configuration.Local.GetLibraryConfig(lib_assembly.Descriptor);
IPhpConfiguration @default = Configuration.DefaultLocal.GetLibraryConfig(lib_assembly.Descriptor);
if (local != null)
{
if (!local.GetType().IsDefined(typeof(NoPhpInfoAttribute), false))
{
output.Write(HtmlEntireRowHeader(HttpUtility.HtmlEncode(lib_assembly.Properties.Name), 3));
output.Write(HtmlHeaderRow(directive, CoreResources.GetString("info_script_value"), CoreResources.GetString("info_master_value")));
ReflectConfigSection(output, "", local.GetType(), local, @default);
}
}
}
output.Write(htmlTableEnd);
// script independent configuration //
output.Write(htmlSectionCaption, CoreResources.GetString("info_shared"));
output.Write(htmlTableStart);
output.Write(HtmlEntireRowHeader("Core", 2));
output.Write(HtmlHeaderRow(directive, CoreResources.GetString("info_value")));
// core:
ReflectConfigSection(output, "", typeof(GlobalConfiguration), Configuration.Global, null);
// libraries:
foreach (PhpLibraryAssembly lib_assembly in app_context.GetLoadedLibraries())
{
object config = Configuration.Global.GetLibraryConfig(lib_assembly.Descriptor);
if (config != null)
{
if (!config.GetType().IsDefined(typeof(NoPhpInfoAttribute), false))
{
output.Write(HtmlEntireRowHeader(HttpUtility.HtmlEncode(lib_assembly.Properties.Name), 2));
output.Write(HtmlHeaderRow(directive, CoreResources.GetString("info_value")));
ReflectConfigSection(output, "", config.GetType(), config, null);
}
}
}
output.Write(htmlTableEnd);
}
private static void WriteAutoGlobal(TextWriter output, ScriptContext context, string name, PhpReference autoglobal)
{
PhpArray array;
if ((array = autoglobal.Value as PhpArray) != null)
{
foreach (KeyValuePair<IntStringKey, object> entry in array)
HtmlVarRow(output, name, entry.Key.Object, entry.Value);
}
}
private static void WriteGlobalVariables(TextWriter output)
{
output.Write(htmlTableStart);
output.Write(HtmlHeaderRow(CoreResources.GetString("info_variable"), CoreResources.GetString("info_value")));
ScriptContext context = ScriptContext.CurrentContext;
#if !SILVERLIGHT
WriteAutoGlobal(output, context, VariableName.GetName, context.AutoGlobals.Get);
WriteAutoGlobal(output, context, VariableName.PostName, context.AutoGlobals.Post);
WriteAutoGlobal(output, context, VariableName.CookieName, context.AutoGlobals.Cookie);
WriteAutoGlobal(output, context, VariableName.FilesName, context.AutoGlobals.Files);
WriteAutoGlobal(output, context, VariableName.SessionName, context.AutoGlobals.Session);
WriteAutoGlobal(output, context, VariableName.ServerName, context.AutoGlobals.Server);
WriteAutoGlobal(output, context, VariableName.EnvName, context.AutoGlobals.Env);
#endif
output.Write(htmlTableEnd);
}
private static void WriteEnvironmentVariables(TextWriter output)
{
#if !SILVERLIGHT
output.Write(htmlTableStart);
output.Write(HtmlHeaderRow(CoreResources.GetString("info_variable"), CoreResources.GetString("info_value")));
IDictionary env_vars = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry entry in env_vars)
output.Write(HtmlRow(true, entry.Key as string, entry.Value as string));
output.Write(htmlTableEnd);
#endif
}
#endregion
#region External callbacks
/// <summary>
/// Prints the section caption.
/// </summary>
/// <param name="print">If true, the section caption is sent to output and returned, if false,
/// the section caption is returned.</param>
/// <param name="caption">The caption.</param>
/// <returns>The section caption.</returns>
[ExternalCallback("SECTION")]
public static string PrintSectionCaption(bool print, string caption)
{
string ret = String.Format(htmlSectionCaption, caption);
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
/// <summary>
/// Prints the table starting tag.
/// </summary>
/// <param name="print"> If true, the tag is sent to output and returned, if false, the tag
/// is returned.</param>
/// <returns>The table starting tag.</returns>
[ExternalCallback("php_info_print_table_start")]
public static string PrintTableStart(bool print)
{
if (print) ScriptContext.CurrentContext.Output.Write(htmlTableStart);
return htmlTableStart;
}
/// <summary>
/// Prints the table ending tag.
/// </summary>
/// <param name="print"> If true, the tag is sent to output and returned, if false, the tag
/// is returned.</param>
/// <returns>The table ending tag.</returns>
[ExternalCallback("php_info_print_table_end")]
public static string PrintTableEnd(bool print)
{
if (print) ScriptContext.CurrentContext.Output.Write(htmlTableEnd);
return htmlTableEnd;
}
/// <summary>
/// Prints table row (tr) starting tag and the first column starting tag (td).
/// </summary>
/// <param name="print"> If true, the tags are sent to output and returned, if false,
/// the tags are returned.</param>
/// <param name="isHeader">Nonzero if the row is a header row.</param>
/// <returns>Table row (tr) starting tag and the first column starting tag (td).</returns>
[ExternalCallback("php_info_box_start")]
public static string PrintBoxStart(bool print, int isHeader)
{
string ret = (isHeader == 0) ? htmlTableBoxStart : htmlTableHeaderBoxStart;
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
/// <summary>
/// Prints td and tr ending tags.
/// </summary>
/// <param name="print"> If true, the tags are sent to output and returned, if false,
/// the tags are returned.</param>
/// <returns>Td and tr ending tags.</returns>
[ExternalCallback("php_info_box_end")]
public static string PrintBoxEnd(bool print)
{
if (print) ScriptContext.CurrentContext.Output.Write(htmlTableBoxEnd);
return htmlTableBoxEnd;
}
/// <summary>
/// Prints horizontal line (hr) tag.
/// </summary>
/// <param name="print"> If true, the tag is sent to output and returned, if false, the tag
/// is returned.</param>
/// <returns>Horizontal line (hr) tag.</returns>
[ExternalCallback("php_info_hr")]
public static string PrintHr(bool print)
{
if (print) ScriptContext.CurrentContext.Output.Write(htmlHorizontalLine);
return htmlHorizontalLine;
}
/// <summary>
/// Prints table header occupying given number of columns.
/// </summary>
/// <param name="print">If true, the header is sent to output and returned, if false, the
/// header is returned.</param>
/// <param name="columnCount">The number of columns.</param>
/// <param name="caption">The caption printed.</param>
/// <returns>The table header.</returns>
[ExternalCallback("php_info_print_table_colspan_header")]
public static string PrintTableColspanHeader(bool print, int columnCount, string caption)
{
string ret = String.Format(htmlTableColspanHeader, columnCount, caption);
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
/// <summary>
/// Prints table header having several columns.
/// </summary>
/// <param name="print">If true, the header is sent to output and returned, if false, the
/// header is returned.</param>
/// <param name="cells">Captions of columns.</param>
/// <returns>The table header.</returns>
[ExternalCallback("php_info_print_table_header")]
public static string PrintTableHeader(bool print, params string[] cells)
{
string ret = HtmlHeaderRow(cells);
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
/// <summary>
/// Prints table row having several columns.
/// </summary>
/// <param name="print">If true, the row is sent to output and returned, if false, the
/// row is returned.</param>
/// <param name="cells">Cells' content.</param>
/// <returns>The table row.</returns>
[ExternalCallback("php_info_print_table_row")]
public static string PrintTableRow(bool print, params string[] cells)
{
string ret = HtmlRow(true, cells);
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
[ExternalCallback("php_info_print_css")]
public static string PrintCss(bool print)
{
if (print) ScriptContext.CurrentContext.Output.Write(htmlCss);
return htmlCss;
}
[ExternalCallback("php_info_print_style")]
public static string PrintStyle(bool print)
{
string ret = String.Format(htmlStyle, htmlCss);
if (print) ScriptContext.CurrentContext.Output.Write(ret);
return ret;
}
#endregion
}
#region Version
/// <summary>
/// Provides version information of Phalanger runtime.
/// </summary>
public static class PhalangerVersion
{
/// <summary>
/// Current Phalanger version obtained from <see cref="AssemblyFileVersionAttribute"/> or version of this assembly.
/// </summary>
public static readonly string/*!*/Current;
/// <summary>
/// Phalanger name obtained from <see cref="AssemblyProductAttribute"/>.
/// </summary>
public static readonly string/*!*/ProductName;
static PhalangerVersion()
{
var/*!*/ass = typeof(PhalangerVersion).Assembly;
object[] attrsPhalangerVer = ass.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
Current = attrsPhalangerVer.Length > 0
? ((AssemblyFileVersionAttribute)attrsPhalangerVer[0]).Version
: ass.GetName().Version.ToString(4);
object[] attrsPhalangerProduct = ass.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
Debug.Assert(attrsPhalangerProduct.Length > 0);
ProductName = ((AssemblyProductAttribute)attrsPhalangerProduct[0]).Product;
}
}
/// <summary>
/// Provides means for working with PHP version as well as the currently supported version.
/// </summary>
public sealed class PhpVersion
{
/// <summary>
/// Currently supported PHP major version.
/// </summary>
public const int Major = 5;
/// <summary>
/// Currently supported PHP minor version.
/// </summary>
public const int Minor = 3;
/// <summary>
/// Currently supported PHP release version.
/// </summary>
public const int Release = 10;
/// <summary>
/// Currently supported PHP version.
/// </summary>
public static readonly string Current = Major + "." + Minor + "." + Release;
/// <summary>
/// Extra version string.
/// </summary>
public const string Extra = "phalanger";
/// <summary>
/// Currently supported Zend Engine version.
/// </summary>
public const string Zend = "2.0.0";
/// <summary>
/// Compares parts of varsions delimited by '.'.
/// </summary>
/// <param name="part1">A part of the first version.</param>
/// <param name="part2">A part of the second version.</param>
/// <returns>The result of parts comparison (-1,0,+1).</returns>
private static int CompareParts(string part1, string part2)
{
string[] parts = { "dev", "alpha", "a", "beta", "b", "RC", " ", "#", "pl", "p" };
int[] order = { -1, 0, 1, 1, 2, 2, 3, 4, 5, 6, 6 };
// GENERICS:
int i = Array.IndexOf(parts, part1);
int j = Array.IndexOf(parts, part2);
return Math.Sign(order[i + 1] - order[j + 1]);
}
/// <summary>
/// Parses a version and splits it into an array of parts.
/// </summary>
/// <param name="version">The version to be parsed (can be a <B>null</B> reference).</param>
/// <returns>An array of parts.</returns>
/// <remarks>
/// Non-alphanumeric characters are eliminated.
/// The version is split in between a digit following a non-digit and by
/// characters '.', '-', '+', '_'.
/// </remarks>
private static string[] VersionToArray(string version)
{
if (version == null || version.Length == 0)
return ArrayUtils.EmptyStrings;
StringBuilder sb = new StringBuilder(version.Length);
char last = '\0';
for (int i = 0; i < version.Length; i++)
{
if (version[i] == '-' || version[i] == '+' || version[i] == '_' || version[i] == '.')
{
if (last != '.') sb.Append(last = '.');
}
else if (i > 0 && (Char.IsDigit(version[i]) ^ Char.IsDigit(version[i - 1])))
{
if (last != '.') sb.Append('.');
sb.Append(last = version[i]);
}
else if (Char.IsLetterOrDigit(version[i]))
{
sb.Append(last = version[i]);
}
else
{
if (last != '.') sb.Append(last = '.');
}
}
if (last == '.') sb.Length--;
return sb.ToString().Split('.');
}
/// <summary>
/// Compares two PHP versions.
/// </summary>
/// <param name="ver1">The first version.</param>
/// <param name="ver2">The second version.</param>
/// <returns>The result of comparison (-1,0,+1).</returns>
public static int Compare(string ver1, string ver2)
{
string[] v1 = VersionToArray(ver1);
string[] v2 = VersionToArray(ver2);
int result;
for (int i = 0; i < Math.Max(v1.Length, v2.Length); i++)
{
string item1 = (i < v1.Length) ? v1[i] : " ";
string item2 = (i < v2.Length) ? v2[i] : " ";
if (Char.IsDigit(item1[0]) && Char.IsDigit(item2[0]))
{
result = PhpComparer.CompareInteger(Convert.StringToInteger(v1[i]), Convert.StringToInteger(item2));
}
else
{
result = CompareParts(Char.IsDigit(item1[0]) ? "#" : item1, Char.IsDigit(item2[0]) ? "#" : item2);
}
if (result != 0)
return result;
}
return 0;
}
/// <summary>
/// Compares two PHP versions using a specified operator.
/// </summary>
/// <param name="ver1">The first version.</param>
/// <param name="ver2">The second version.</param>
/// <param name="op">
/// The operator (supported are: "<","lt";"<=","le";">","gt";">=","ge";"==","=","eq";"!=","<>","ne").
/// </param>
/// <returns>The result of the comparison.</returns>
public static object Compare(string ver1, string ver2, string op) // GENERICS: return value: bool?
{
switch (op)
{
case "<":
case "lt": return Compare(ver1, ver2) < 0;
case "<=":
case "le": return Compare(ver1, ver2) <= 0;
case ">":
case "gt": return Compare(ver1, ver2) > 0;
case ">=":
case "ge": return Compare(ver1, ver2) >= 0;
case "==":
case "=":
case "eq": return Compare(ver1, ver2) == 0;
case "!=":
case "<>":
case "ne": return Compare(ver1, ver2) != 0;
}
return null;
}
#region Unit Testing
#if DEBUG
public static void Test()
{
Console.WriteLine("Version to array:");
string[] vers = { "4.0.4", "5.0-1RC", "abc099sdf2-+........3...", "4.3.2RC1" };
foreach (string ver in vers)
Console.WriteLine(String.Join(";", VersionToArray(ver)));
Console.WriteLine("\nComparation of Parts:");
string[] parts = { "#", "RC", "p", "dev", "devxxx", "ssss" };
foreach (string part1 in parts)
foreach (string part2 in parts)
{
int r = CompareParts(part1, part2);
Console.WriteLine("{0}{1}{2}", part1, (r < 0) ? "<" : (r > 0) ? ">" : "==", part2);
}
Console.WriteLine("\nComparation of Versions:");
vers = new string[] { "4.0.4", "5.0.1RC", "3", "5.0.1beta", "5.0.1", "5.0.1.0.0.0.0" };
foreach (string ver1 in vers)
foreach (string ver2 in vers)
{
int r = CompareParts(ver1, ver2);
Console.WriteLine("{0}{1}{2}", ver1, (r < 0) ? "<" : (r > 0) ? ">" : "==", ver2);
}
}
#endif
#endregion
}
#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.Buffers.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.JsonLab.Tests.Resources;
using Xunit;
namespace System.Text.JsonLab.Tests
{
public class JsonParserTests
{
[Fact]
public void ParseBasicJson()
{
var json = ReadJson(TestJson.ParseJson);
var person = json[0];
var age = (double)person["age"];
var first = (string)person["first"];
var last = (string)person["last"];
var phoneNums = person["phoneNumbers"];
var phoneNum1 = (string)phoneNums[0];
var phoneNum2 = (string)phoneNums[1];
var address = person["address"];
var street = (string)address["street"];
var city = (string)address["city"];
var zipCode = (double)address["zip"];
// Exceptional use case
//var a = json[1]; // IndexOutOfRangeException
//var b = json["age"]; // NullReferenceException
//var c = person[0]; // NullReferenceException
//var d = address["cit"]; // KeyNotFoundException
//var e = address[0]; // NullReferenceException
//var f = (double)address["city"]; // InvalidCastException
//var g = (bool)address["city"]; // InvalidCastException
//var h = (string)address["zip"]; // InvalidCastException
//var i = (string)person["phoneNumbers"]; // NullReferenceException
//var j = (string)person; // NullReferenceException
Assert.Equal(age, 30);
Assert.Equal(first, "John");
Assert.Equal(last, "Smith");
Assert.Equal(phoneNum1, "425-000-1212");
Assert.Equal(phoneNum2, "425-000-1213");
Assert.Equal(street, "1 Microsoft Way");
Assert.Equal(city, "Redmond");
Assert.Equal(zipCode, 98052);
}
[Fact]
public void ReadBasicJson()
{
var testJson = CreateJson();
Assert.Equal(testJson.ToString(), TestJson.ExpectedCreateJson);
var readJson = ReadJson(TestJson.BasicJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedBasicJson);
}
[Fact]
public void ReadBasicJsonWithLongInt()
{
var readJson = ReadJson(TestJson.BasicJsonWithLargeNum);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedBasicJsonWithLargeNum);
}
[Fact]
public void ReadFullJsonSchema()
{
var readJson = ReadJson(TestJson.FullJsonSchema1);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedFullJsonSchema1);
}
[Fact]
public void ReadFullJsonSchemaAndGetValue()
{
var readJson = ReadJson(TestJson.FullJsonSchema2);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedFullJsonSchema2);
Assert.Equal(readJson.GetValueFromPropertyName("long")[0].NumberValue, 9.2233720368547758E+18);
var emptyObject = readJson.GetValueFromPropertyName("emptyObject");
Assert.Equal(emptyObject[0].ObjectValue.Pairs.Count, 0);
var arrayString = readJson.GetValueFromPropertyName("arrayString");
Assert.Equal(arrayString[0].ArrayValue.Values.Count, 2);
Assert.Equal(readJson.GetValueFromPropertyName("firstName").Count, 4);
Assert.Equal(readJson.GetValueFromPropertyName("propertyDNE").Count, 0);
}
[Fact(Skip = "This test is injecting invalid characters into the stream and needs to be re-visited")]
public void ReadJsonSpecialStrings()
{
var readJson = ReadJson(TestJson.JsonWithSpecialStrings);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedJsonWithSpecialStrings);
}
[Fact(Skip = "The current primitive parsers do not support E-notation for numbers.")]
public void ReadJsonSpecialNumbers()
{
var readJson = ReadJson(TestJson.JsonWithSpecialNumFormat);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedJsonWithSpecialNumFormat);
}
[Fact]
public void ReadProjectLockJson()
{
var readJson = ReadJson(TestJson.ProjectLockJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedProjectLockJson);
}
[Fact]
public void ReadHeavyNestedJson()
{
var readJson = ReadJson(TestJson.HeavyNestedJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedHeavyNestedJson);
}
[Fact]
public void ReadHeavyNestedJsonWithArray()
{
var readJson = ReadJson(TestJson.HeavyNestedJsonWithArray);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedHeavyNestedJsonWithArray);
}
[Fact]
public void ReadLargeJson()
{
var readJson = ReadJson(TestJson.LargeJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedLargeJson);
}
private static TestDom CreateJson()
{
var valueAge = new Value
{
Type = Value.ValueType.Number,
NumberValue = 30
};
var pairAge = new Pair
{
Name = "age",
Value = valueAge
};
var valueFirst = new Value
{
Type = Value.ValueType.String,
StringValue = "John"
};
var pairFirst = new Pair
{
Name = "first",
Value = valueFirst
};
var valueLast = new Value
{
Type = Value.ValueType.String,
StringValue = "Smith"
};
var pairLast = new Pair
{
Name = "last",
Value = valueLast
};
var value1 = new Value
{
Type = Value.ValueType.String,
StringValue = "425-000-1212"
};
var value2 = new Value
{
Type = Value.ValueType.String,
StringValue = "425-000-1213"
};
var values = new List<Value> { value1, value2 };
var arrInner = new Array { Values = values };
var valuePhone = new Value
{
Type = Value.ValueType.Array,
ArrayValue = arrInner
};
var pairPhone = new Pair
{
Name = "phoneNumbers",
Value = valuePhone
};
var valueStreet = new Value
{
Type = Value.ValueType.String,
StringValue = "1 Microsoft Way"
};
var pairStreet = new Pair
{
Name = "street",
Value = valueStreet
};
var valueCity = new Value
{
Type = Value.ValueType.String,
StringValue = "Redmond"
};
var pairCity = new Pair
{
Name = "city",
Value = valueCity
};
var valueZip = new Value
{
Type = Value.ValueType.Number,
NumberValue = 98052
};
var pairZip = new Pair
{
Name = "zip",
Value = valueZip
};
var pairsInner = new List<Pair> { pairStreet, pairCity, pairZip };
var objInner = new Object { Pairs = pairsInner };
var valueAddress = new Value
{
Type = Value.ValueType.Object,
ObjectValue = objInner
};
var pairAddress = new Pair
{
Name = "address",
Value = valueAddress
};
var pairs = new List<Pair> { pairAge, pairFirst, pairLast, pairPhone, pairAddress };
var obj = new Object { Pairs = pairs };
var json = new TestDom { Object = obj };
return json;
}
private static TestDom ReadJson(string jsonString)
{
var json = new TestDom();
if (string.IsNullOrEmpty(jsonString))
{
return json;
}
var jsonReader = new JsonReader(MemoryMarshal.AsBytes(jsonString.AsSpan()), SymbolTable.InvariantUtf16);
jsonReader.Read();
switch (jsonReader.TokenType)
{
case JsonTokenType.StartArray:
json.Array = ReadArray(ref jsonReader);
break;
case JsonTokenType.StartObject:
json.Object = ReadObject(ref jsonReader);
break;
default:
Assert.True(false, "The test JSON does not start with an array or object token");
break;
}
return json;
}
private static Value GetValue(ref JsonReader jsonReader)
{
var value = new Value { Type = MapValueType(jsonReader.ValueType) };
switch (value.Type)
{
case Value.ValueType.String:
value.StringValue = ReadString(ref jsonReader);
break;
case Value.ValueType.Number:
CustomParser.TryParseDecimal(jsonReader.Value, out decimal num, out int consumed, jsonReader.SymbolTable);
value.NumberValue = Convert.ToDouble(num);
break;
case Value.ValueType.True:
break;
case Value.ValueType.False:
break;
case Value.ValueType.Null:
break;
case Value.ValueType.Object:
value.ObjectValue = ReadObject(ref jsonReader);
break;
case Value.ValueType.Array:
value.ArrayValue = ReadArray(ref jsonReader);
break;
default:
throw new ArgumentOutOfRangeException();
}
return value;
}
private static Value.ValueType MapValueType(JsonValueType type)
{
switch (type)
{
case JsonValueType.False:
return Value.ValueType.False;
case JsonValueType.True:
return Value.ValueType.True;
case JsonValueType.Null:
return Value.ValueType.Null;
case JsonValueType.Number:
return Value.ValueType.Number;
case JsonValueType.String:
return Value.ValueType.String;
case JsonValueType.Array:
return Value.ValueType.Array;
case JsonValueType.Object:
return Value.ValueType.Object;
default:
throw new ArgumentException();
}
}
private static Object ReadObject(ref JsonReader jsonReader)
{
// NOTE: We should be sitting on a StartObject token.
Assert.Equal(JsonTokenType.StartObject, jsonReader.TokenType);
var jsonObject = new Object();
List<Pair> jsonPairs = new List<Pair>();
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonTokenType.EndObject:
jsonObject.Pairs = jsonPairs;
return jsonObject;
case JsonTokenType.PropertyName:
string name = ReadString(ref jsonReader);
jsonReader.Read(); // Move to value token
var pair = new Pair
{
Name = name,
Value = GetValue(ref jsonReader)
};
if (jsonPairs != null) jsonPairs.Add(pair);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
throw new FormatException("Json object was started but never ended.");
}
private static Array ReadArray(ref JsonReader jsonReader)
{
// NOTE: We should be sitting on a StartArray token.
Assert.Equal(JsonTokenType.StartArray, jsonReader.TokenType);
Array jsonArray = new Array();
List<Value> jsonValues = new List<Value>();
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonTokenType.EndArray:
jsonArray.Values = jsonValues;
return jsonArray;
case JsonTokenType.StartArray:
case JsonTokenType.StartObject:
case JsonTokenType.Value:
jsonValues.Add(GetValue(ref jsonReader));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
throw new FormatException("Json array was started but never ended.");
}
private static string ReadString(ref JsonReader jsonReader)
{
if (jsonReader.SymbolTable == SymbolTable.InvariantUtf8)
{
var status = Encodings.Utf8.ToUtf16Length(jsonReader.Value, out int needed);
Assert.Equal(Buffers.OperationStatus.Done, status);
var text = new string(' ', needed);
unsafe
{
fixed (char* pChars = text)
{
var dst = new Span<byte>((byte*)pChars, needed);
status = Encodings.Utf8.ToUtf16(jsonReader.Value, dst, out int consumed, out int written);
Assert.Equal(Buffers.OperationStatus.Done, status);
}
}
return text;
}
else if (jsonReader.SymbolTable == SymbolTable.InvariantUtf16)
{
var utf16 = MemoryMarshal.Cast<byte, char>(jsonReader.Value);
var chars = utf16.ToArray();
return new string(chars);
}
else
throw new NotImplementedException();
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
using System;
using System.Collections.Generic;
using System.Text;
/**********************************************************************
*
* The Microsoft.Zelig.MetaData.Importer.Signature* classes represent the signatures read
* from the Blob heap of the input file(s).
*
* Since the signatures have references to MetaData* objects, the
* signatures are initially just an array of bytes. When all the
* MetaData objects have been created, the array of bytes is processed
* and the references resolved.
*
**********************************************************************/
namespace Microsoft.Zelig.MetaData.Importer
{
public abstract class SignatureType : Signature
{
//
// State
//
protected readonly ElementTypes m_elementType;
protected Modifier m_modifierChain;
//
// Constructor Methods
//
protected SignatureType( ElementTypes elementType )
{
m_elementType = elementType;
}
//--//
internal void SetModifierChain( Modifier modifierChain )
{
m_modifierChain = modifierChain;
}
//--//
internal Normalized.MetaDataSignature ApplyModifiers( Normalized.MetaDataTypeDefinitionAbstract obj ,
MetaDataNormalizationContext context )
{
Normalized.SignatureType sig = Normalized.SignatureType.Create( obj );
if(m_modifierChain != null)
{
m_modifierChain.Apply( sig, context );
}
return (Normalized.MetaDataSignature)sig.MakeUnique();
}
//
// Access Methods
//
public ElementTypes ElementType
{
get
{
return m_elementType;
}
}
public Modifier ModifierChain
{
get
{
return m_modifierChain;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append( m_elementType );
if(m_modifierChain != null)
{
sb.Append( "," );
sb.Append( m_modifierChain );
}
return sb.ToString();
}
//--//--//
public class BuiltIn : SignatureType,
IMetaDataNormalizeSignature
{
//
// Constructor Methods
//
public BuiltIn( ElementTypes elementType ) : base( elementType )
{
}
//--//
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.MetaDataTypeDefinitionAbstract res = context.LookupBuiltIn( m_elementType );
return ApplyModifiers( res, context );
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append( base.ToString() );
return sb.ToString();
}
}
public class ClassOrStruct : SignatureType,
IMetaDataNormalizeSignature
{
//
// State
//
protected IMetaDataTypeDefOrRef m_classObject;
//
// Constructor Methods
//
public ClassOrStruct( ElementTypes elementType ,
IMetaDataTypeDefOrRef classObject ) : base( elementType )
{
m_classObject = classObject;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.MetaDataTypeDefinitionAbstract res;
context.GetNormalizedObject( m_classObject, out res, MetaDataNormalizationMode.LookupExisting );
return ApplyModifiers( res, context );
}
//
// Access Methods
//
public IMetaDataTypeDefOrRef ClassObject
{
get
{
return m_classObject;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "ClassOrStruct(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_classObject );
sb.Append( ")" );
return sb.ToString();
}
}
public class Prefix : SignatureType,
IMetaDataNormalizeSignature
{
//
// State
//
protected readonly SignatureType m_type;
//
// Constructor Methods
//
public Prefix( ElementTypes elementType ,
SignatureType type ) : base( elementType )
{
m_type = type;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.SignatureType sig;
context.GetNormalizedSignature( m_type, out sig, MetaDataNormalizationMode.Default );
//--//
Normalized.MetaDataTypeDefinitionByRef byref = new Normalized.MetaDataTypeDefinitionByRef( context.GetAssemblyFromContext(), 0, m_elementType );
byref.m_type = sig.Type;
return ApplyModifiers( byref, context );
}
//
// Access Methods
//
public SignatureType InnerType
{
get
{
return m_type;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "Prefix(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_type );
sb.Append( ")" );
return sb.ToString();
}
}
public class Method : SignatureType,
IMetaDataNormalizeSignature
{
//
// State
//
protected readonly SignatureMethod m_method;
//
// Constructor Methods
//
public Method( SignatureMethod method ) : base( ElementTypes.FNPTR )
{
m_method = method;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
throw IllegalMetaDataFormatException.Create( "FNPTR elements in signatures not supported" );
}
//
// Access Methods
//
public SignatureMethod Signature
{
get
{
return m_method;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "Method(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_method );
sb.Append( ")" );
return sb.ToString();
}
}
public abstract class BaseArray : SignatureType
{
//
// Constructor Methods
//
protected BaseArray( ElementTypes elementType ) : base( elementType )
{
}
}
public class SzArray : BaseArray,
IMetaDataNormalizeSignature
{
//
// State
//
protected readonly SignatureType m_typeObject;
//
// Constructor Methods
//
public SzArray( SignatureType typeObject ) : base( ElementTypes.SZARRAY )
{
m_typeObject = typeObject;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.SignatureType sigTypeObject;
context.GetNormalizedSignature( m_typeObject, out sigTypeObject, MetaDataNormalizationMode.Default );
//--//
Normalized.MetaDataTypeDefinitionArraySz arrayNew = new Normalized.MetaDataTypeDefinitionArraySz( context.GetAssemblyFromContext(), 0 );
arrayNew.m_elementType = m_elementType;
arrayNew.m_extends = context.LookupBuiltIn( ElementTypes.SZARRAY );
arrayNew.m_objectType = sigTypeObject.Type;
return ApplyModifiers( arrayNew, context );
}
//
// Access Methods
//
public SignatureType TypeObject
{
get
{
return m_typeObject;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "SzArray(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_typeObject );
sb.Append( ")" );
return sb.ToString();
}
}
public class Array : BaseArray,
IMetaDataNormalizeSignature
{
public struct Dimension
{
//
// State
//
public uint m_lowerBound;
public uint m_upperBound;
}
//
// State
//
protected readonly SignatureType m_type;
protected readonly uint m_rank;
protected readonly Dimension[] m_dimensions;
//
// Constructor Methods
//
public Array( SignatureType type ,
uint rank ,
Dimension[] dimensions ) : base( ElementTypes.ARRAY )
{
m_type = type;
m_rank = rank;
m_dimensions = dimensions;
}
//
// IMetaDataNoIMetaDataNormalizeSignaturermalize methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.SignatureType sigTypeObject;
context.GetNormalizedSignature( m_type, out sigTypeObject, MetaDataNormalizationMode.Default );
//--//
Normalized.MetaDataTypeDefinitionArrayMulti arrayNew = new Normalized.MetaDataTypeDefinitionArrayMulti( context.GetAssemblyFromContext(), 0 );
arrayNew.m_extends = context.LookupBuiltIn( ElementTypes.SZARRAY );
arrayNew.m_objectType = sigTypeObject.Type;
arrayNew.m_rank = m_rank;
arrayNew.m_dimensions = new Normalized.MetaDataTypeDefinitionArrayMulti.Dimension[m_dimensions.Length];
for(int i = 0; i < m_dimensions.Length; i++)
{
arrayNew.m_dimensions[i].m_lowerBound = m_dimensions[i].m_lowerBound;
arrayNew.m_dimensions[i].m_upperBound = m_dimensions[i].m_upperBound;
}
return ApplyModifiers( arrayNew, context );
}
//
// Access Methods
//
public SignatureType BaseType
{
get
{
return m_type;
}
}
public uint Rank
{
get
{
return m_rank;
}
}
public Dimension[] Dimensions
{
get
{
return m_dimensions;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "Array(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_type );
sb.Append( "[" );
for(int i = 0; i < m_rank; i++)
{
uint lower = m_dimensions[i].m_lowerBound;
uint upper = m_dimensions[i].m_upperBound;
if(i != 0)
{
sb.Append( "," );
}
if(lower != 0 || upper != 0)
{
sb.Append( lower );
if(upper > lower)
{
sb.Append( ".." );
sb.Append( upper );
}
}
}
sb.Append( "]" );
sb.Append( ")" );
return sb.ToString();
}
}
public class GenericParameter : SignatureType,
IMetaDataNormalizeSignature
{
//
// State
//
private readonly uint m_number;
//
// Constructor Methods
//
public GenericParameter( ElementTypes elementType ,
uint number ) : base( elementType )
{
m_number = number;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
switch(m_elementType)
{
case ElementTypes.VAR:
{
Normalized.MetaDataTypeDefinitionDelayed tdNew = new Normalized.MetaDataTypeDefinitionDelayed( context.GetAssemblyForDelayedParameters(), 0 );
tdNew.m_elementType = ElementTypes.VAR;
tdNew.m_parameterNumber = (int)m_number;
tdNew.m_isMethodParam = false;
return ApplyModifiers( tdNew, context );
}
case ElementTypes.MVAR:
{
Normalized.MetaDataTypeDefinitionDelayed tdNew = new Normalized.MetaDataTypeDefinitionDelayed( context.GetAssemblyForDelayedParameters(), 0 );
tdNew.m_elementType = ElementTypes.MVAR;
tdNew.m_parameterNumber = (int)m_number;
tdNew.m_isMethodParam = true;
return ApplyModifiers( tdNew, context );
}
}
throw IllegalMetaDataFormatException.Create( "'{0}' cannot be resolved in the context of '{1}'", this, context );
}
//
// Access Methods
//
public uint Number
{
get
{
return m_number;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "GenParam(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_number );
sb.Append( ")" );
return sb.ToString();
}
}
public class GenericInstantiation : SignatureType,
IMetaDataNormalizeSignature
{
//
// State
//
private readonly SignatureType m_type;
private readonly SignatureType[] m_parameters;
//
// Constructor Methods
//
public GenericInstantiation( SignatureType type ,
SignatureType[] parameters ) : base( ElementTypes.GENERICINST )
{
m_type = type;
m_parameters = parameters;
}
//
// IMetaDataNormalizeSignature methods
//
Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
Normalized.SignatureType baseType;
Normalized.SignatureType[] parameters;
context.GetNormalizedSignature ( m_type , out baseType , MetaDataNormalizationMode.Default );
context.GetNormalizedSignatureArray( m_parameters, out parameters, MetaDataNormalizationMode.Default );
Normalized.MetaDataTypeDefinitionGenericInstantiation tdNew = new Normalized.MetaDataTypeDefinitionGenericInstantiation( context.GetAssemblyFromContext(), 0 );
tdNew.m_baseType = (Normalized.MetaDataTypeDefinitionGeneric)baseType.Type;
tdNew.m_parameters = parameters;
return ApplyModifiers( tdNew, context );
}
//
// Access Methods
//
public SignatureType Type
{
get
{
return m_type;
}
}
public SignatureType[] Parameters
{
get
{
return m_parameters;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder( "GenInst(" );
sb.Append( base.ToString() );
sb.Append( "," );
sb.Append( m_type );
sb.Append( "<" );
for(int i = 0; i < m_parameters.Length; i++)
{
if(i != 0)
{
sb.Append( "," );
}
sb.Append( m_parameters[i] );
}
sb.Append( ">" );
sb.Append( ")" );
return sb.ToString();
}
}
//--//
public class Modifier
{
//
// State
//
private ElementTypes m_mod;
private IMetaDataTypeDefOrRef m_classObject;
private Modifier m_next;
//
// Constructor Methods
//
public Modifier( ElementTypes mod ,
IMetaDataTypeDefOrRef classObject ,
Modifier next )
{
m_mod = mod;
m_classObject = classObject;
m_next = next;
}
internal void Apply( Normalized.SignatureType sig ,
MetaDataNormalizationContext context )
{
Normalized.MetaDataTypeDefinitionAbstract classObject;
context.GetNormalizedObject( m_classObject, out classObject, MetaDataNormalizationMode.Default );
sig.m_modifiers = ArrayUtility.AppendToArray( sig.m_modifiers, classObject );
if(m_next != null)
{
m_next.Apply( sig, context );
}
}
//
// Access Methods
//
public ElementTypes Kind
{
get
{
return m_mod;
}
}
public IMetaDataTypeDefOrRef ClassObject
{
get
{
return m_classObject;
}
}
public Modifier Next
{
get
{
return m_next;
}
}
//
// Debug Methods
//
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append( m_mod );
sb.Append( "(" );
sb.Append( m_classObject );
sb.Append( ")" );
if(m_next != null)
{
sb.Append( " " );
sb.Append( m_next );
}
return sb.ToString();
}
}
}
//--//
public abstract class Signature
{
[Flags]
internal enum ParseFlags
{
Default = 0x00,
AllowCustomModifiers = 0x01,
AllowPinned = 0x02,
AllowByRef = 0x04,
AllowTypedByRef = 0x08,
AllowVoid = 0x10,
MustBeWholeSignature = 0x20,
}
public enum CallingConventions : byte
{
Default = 0x00,
Unmanaged_cdecl = 0x01,
Unmanaged_sdtcall = 0x02,
Unmanaged_thiscall = 0x03,
Unmanaged_fastcall = 0x04,
VarArg = 0x05,
Field = 0x06,
LocalVar = 0x07,
Property = 0x08,
Unmanaged = 0x09,
GenericInst = 0x0A,
Mask = 0x0F,
Generic = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40
}
//
// Helper Methods
//
internal static void CheckEndOfSignature( ArrayReader reader )
{
if(reader.IsEOF == false)
{
throw IllegalMetaDataFormatException.Create( "Only read {0} bytes of signature {1}", reader.Position, reader );
}
}
internal static Signature ParseUnknown( Parser parser ,
ArrayReader reader )
{
return Signature.ParseUnknown( parser, reader, ParseFlags.MustBeWholeSignature );
}
internal static Signature ParseUnknown( Parser parser ,
ArrayReader reader ,
ParseFlags flags )
{
if((flags & ParseFlags.MustBeWholeSignature) != 0)
{
flags &= ~ParseFlags.MustBeWholeSignature;
Signature type = ParseUnknown( parser, reader, flags );
Signature.CheckEndOfSignature( reader );
//Console.Out.WriteLine( "{0}", type );
return type;
}
//--//
uint unmaskedCallingConvention = reader.ReadCompressedUInt32();
CallingConventions callingConvention = (CallingConventions)(unmaskedCallingConvention & (uint)CallingConventions.Mask);
switch(callingConvention)
{
case CallingConventions.Field:
{
//
// Section 23.2.4 of ECMA spec, Partition II
//
//
// ParseFlags.AllowByRef is added to allow parsing of managed C++ assemblies.
//
SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef );
return new SignatureField( type );
}
case CallingConventions.LocalVar:
{
//
// Section 23.2.6 of ECMA spec, Partition II
//
uint count = reader.ReadCompressedUInt32();
SignatureType[] locals = new SignatureType[count];
for(int i = 0; i < count; i++)
{
locals[i] = Signature.ParseSignatureLocal( parser, reader );
}
return new SignatureLocalVar( locals );
}
case CallingConventions.Property:
{
//
// Section 23.2.5 of ECMA spec, Partition II
//
uint paramCount = reader.ReadCompressedUInt32();
SignatureType returnType = Signature.ParseReturnType( parser, reader );
SignatureType[] parameters = new SignatureType[paramCount];
for(int i = 0; i < paramCount; i++)
{
parameters[i] = Signature.ParseParam( parser, reader );
}
return new SignatureProperty( returnType, parameters );
}
case CallingConventions.GenericInst:
{
//
// Section 22.29, 23.2.15 of ECMA spec, Partition II
//
uint genericParamCount = reader.ReadCompressedUInt32();
SignatureType[] genericParameters = new SignatureType[genericParamCount];
for(int i = 0; i < genericParamCount; i++)
{
genericParameters[i] = Signature.ParseParam( parser, reader );
}
return new SignatureMethodSpec( genericParameters );
}
default:
{
//
// Section 23.2.1, 23.2.2, and 23.2.3 of ECMA spec, Partition II
//
uint genericParamCount = 0;
if((unmaskedCallingConvention & (uint)CallingConventions.Generic) != 0)
{
genericParamCount = reader.ReadCompressedUInt32();
}
uint paramCount = reader.ReadCompressedUInt32();
SignatureType returnType = Signature.ParseReturnType( parser, reader );
int sentinelLocation = -1;
SignatureType[] parameters = new SignatureType[paramCount];
for(int i = 0; i < paramCount; i++)
{
byte first = reader.PeekUInt8();
if(first == (byte)ElementTypes.SENTINEL)
{
reader.Seek( 1 );
sentinelLocation = i;
}
parameters[i] = Signature.ParseParam( parser, reader );
}
return new SignatureMethod( (CallingConventions)unmaskedCallingConvention, genericParamCount, sentinelLocation, returnType, parameters );
}
}
}
internal static Signature ParseMemberRef( Parser parser ,
ArrayReader reader )
{
Signature sig = Signature.ParseUnknown( parser, reader );
if(sig is SignatureField)
{
}
else if(sig is SignatureMethod)
{
}
else
{
throw IllegalMetaDataFormatException.Create( "Not a member ref signature: {0}", sig );
}
return sig;
}
internal static SignatureType ParseType( Parser parser ,
ArrayReader reader ,
ParseFlags flags )
{
if((flags & ParseFlags.AllowCustomModifiers) != 0)
{
//
// The flag is not reset to allow parsing of managed C++ assemblies,
// where a type can have multiple custom modifiers throughout the signature.
//
SignatureType.Modifier modifier = ParseOptionalModifier( parser, reader );
if(modifier != null)
{
SignatureType type = Signature.ParseType( parser, reader, flags );
type.SetModifierChain( modifier );
return type;
}
}
ElementTypes elementType = (ElementTypes)reader.ReadUInt8();
switch(elementType)
{
case ElementTypes.VOID:
{
if((flags & ParseFlags.AllowVoid) == 0)
{
throw IllegalMetaDataFormatException.Create( "Unexpected VOID element at {0} in {1}", reader.Position, reader );
}
goto case ElementTypes.BOOLEAN;
}
case ElementTypes.TYPEDBYREF:
{
// APPCOMPACT: Although not allowed, v1.1 mscorlib.dll contains a TYPEDBYREF field...
//if((flags & ParseFlags.AllowTypedByRef) == 0)
//{
// throw new IllegalMetaDataFormatException( "Unexpected TYPEDBYREF element at " + reader.Position + " in " + reader );
//}
goto case ElementTypes.BOOLEAN;
}
case ElementTypes.BOOLEAN:
case ElementTypes.CHAR :
case ElementTypes.I1 :
case ElementTypes.U1 :
case ElementTypes.I2 :
case ElementTypes.U2 :
case ElementTypes.I4 :
case ElementTypes.U4 :
case ElementTypes.I8 :
case ElementTypes.U8 :
case ElementTypes.R4 :
case ElementTypes.R8 :
case ElementTypes.U :
case ElementTypes.I :
case ElementTypes.OBJECT :
case ElementTypes.STRING :
{
return new SignatureType.BuiltIn( elementType );
}
case ElementTypes.VALUETYPE:
case ElementTypes.CLASS :
{
// Followed by: TypeDefOrRefEncoded
int typeEncoded = reader.ReadCompressedToken();
return new SignatureType.ClassOrStruct( elementType, (IMetaDataTypeDefOrRef)parser.getObjectFromToken( typeEncoded ) );
}
case ElementTypes.SZARRAY:
{
// Followed by: CustomMod* Type
SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers );
return new SignatureType.SzArray( type );
}
case ElementTypes.ARRAY:
{
// Followed by: Type ArrayShape
SignatureType type = Signature.ParseType( parser, reader, ParseFlags.Default );
uint rank = reader.ReadCompressedUInt32();
if(rank == 0)
{
throw IllegalMetaDataFormatException.Create( "ARRAY with rank 0" );
}
SignatureType.Array.Dimension[] dimensions = new SignatureType.Array.Dimension[rank];
uint numUpperBounds = reader.ReadCompressedUInt32();
if(numUpperBounds > rank)
{
throw IllegalMetaDataFormatException.Create( "ARRAY with upper bounds > rank" );
}
for(int i = 0; i < numUpperBounds; i++)
{
dimensions[i].m_upperBound = reader.ReadCompressedUInt32();
}
uint numLowerBounds = reader.ReadCompressedUInt32();
if(numLowerBounds > rank)
{
throw IllegalMetaDataFormatException.Create( "ARRAY with lower bounds > rank" );
}
for(int i = 0; i < numLowerBounds; i++)
{
dimensions[i].m_lowerBound = reader.ReadCompressedUInt32();
}
return new SignatureType.Array( type, rank, dimensions );
}
case ElementTypes.FNPTR:
{
// Followed by: MethodDefSig or MethodRefSig
SignatureMethod signature = SignatureMethod.Parse( parser, reader, ParseFlags.Default );
return new SignatureType.Method( signature );
}
case ElementTypes.VAR :
case ElementTypes.MVAR:
{
// Generic type variables
uint number = reader.ReadCompressedUInt32();
return new SignatureType.GenericParameter( elementType, number );
}
case ElementTypes.GENERICINST:
{
// Generic type instantiation
SignatureType type = Signature.ParseType( parser, reader, ParseFlags.Default );
uint typeCount = reader.ReadCompressedUInt32();
SignatureType[] typeParams = new SignatureType[typeCount];
for(int i = 0; i < typeCount; i++)
{
SignatureType paramType =
typeParams[i] = Signature.ParseType( parser, reader, ParseFlags.Default );
}
return new SignatureType.GenericInstantiation( type, typeParams );
}
case ElementTypes.CMOD_REQD:
case ElementTypes.CMOD_OPT :
throw IllegalMetaDataFormatException.Create( "Unexpected custom modifier: 0x{0:X2} at {1} in {2}", (byte)elementType, reader.Position, reader );
case ElementTypes.PINNED:
{
// APPCOMPACT: Although not allowed, v1.1 mscorlib.dll contains a PINNED field...
//if((flags & ParseFlags.AllowPinned) == 0)
//{
// throw new IllegalMetaDataFormatException( "Unexpected PINNED prefix at " + reader.Position + " in " + reader );
//}
flags &= ~ParseFlags.AllowPinned;
// APPCOMPACT: fixed (void* pBuffer) gets encoded as PINNED BYREF VOID.
if((flags & ParseFlags.AllowByRef) != 0)
{
flags |= ParseFlags.AllowVoid;
}
SignatureType type = Signature.ParseType( parser, reader, flags );
return new SignatureType.Prefix( elementType, type );
}
case ElementTypes.PTR:
{
// Modifiers
SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowVoid );
return new SignatureType.Prefix( elementType, type );
}
case ElementTypes.BYREF:
{
if((flags & ParseFlags.AllowByRef) == 0)
{
throw IllegalMetaDataFormatException.Create( "Unexpected BYREF prefix at {0} in {1}", reader.Position, reader );
}
flags &= ~ParseFlags.AllowByRef;
SignatureType type = Signature.ParseType( parser, reader, flags );
return new SignatureType.Prefix( elementType, type );
}
default:
{
throw IllegalMetaDataFormatException.Create( "Unknown signature type: 0x{0:X2} at {1} in {2}", (byte)elementType, reader.Position, reader );
}
}
}
protected static SignatureType.Modifier ParseOptionalModifier( Parser parser ,
ArrayReader reader )
{
SignatureType.Modifier result = null;
while(reader.IsEOF == false)
{
ElementTypes mod = (ElementTypes)reader.PeekUInt8();
if(mod == ElementTypes.CMOD_REQD ||
mod == ElementTypes.CMOD_OPT )
{
reader.Seek( 1 );
int typeEncoded = reader.ReadCompressedToken();
result = new SignatureType.Modifier( mod, (IMetaDataTypeDefOrRef)parser.getObjectFromToken( typeEncoded ), result );
}
else
{
break;
}
}
return result;
}
protected static SignatureType ParseParam( Parser parser ,
ArrayReader reader )
{
return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef );
}
protected static SignatureType ParseReturnType( Parser parser ,
ArrayReader reader )
{
return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef | ParseFlags.AllowVoid );
}
protected static SignatureType ParseSignatureLocal( Parser parser ,
ArrayReader reader )
{
return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowPinned | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef );
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.HttpResponseWrapper.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web
{
public partial class HttpResponseWrapper : HttpResponseBase
{
#region Methods and constructors
public override void AddCacheDependency(System.Web.Caching.CacheDependency[] dependencies)
{
}
public override void AddCacheItemDependencies(string[] cacheKeys)
{
}
public override void AddCacheItemDependencies(System.Collections.ArrayList cacheKeys)
{
}
public override void AddCacheItemDependency(string cacheKey)
{
}
public override void AddFileDependencies(string[] filenames)
{
}
public override void AddFileDependencies(System.Collections.ArrayList filenames)
{
}
public override void AddFileDependency(string filename)
{
}
public override void AddHeader(string name, string value)
{
}
public override void AppendCookie(HttpCookie cookie)
{
}
public override void AppendHeader(string name, string value)
{
}
public override void AppendToLog(string param)
{
}
public override string ApplyAppPathModifier(string virtualPath)
{
return default(string);
}
public override void BinaryWrite(byte[] buffer)
{
}
public override void Clear()
{
}
public override void ClearContent()
{
}
public override void ClearHeaders()
{
}
public override void Close()
{
}
public override void DisableKernelCache()
{
}
public override void End()
{
}
public override void Flush()
{
}
public HttpResponseWrapper(HttpResponse httpResponse)
{
}
public override void Pics(string value)
{
}
public override void Redirect(string url)
{
}
public override void Redirect(string url, bool endResponse)
{
}
public override void RedirectPermanent(string url, bool endResponse)
{
}
public override void RedirectPermanent(string url)
{
}
public override void RemoveOutputCacheItem(string path, string providerName)
{
}
public override void RemoveOutputCacheItem(string path)
{
}
public override void SetCookie(HttpCookie cookie)
{
}
public override void TransmitFile(string filename, long offset, long length)
{
}
public override void TransmitFile(string filename)
{
}
public override void Write(char[] buffer, int index, int count)
{
}
public override void Write(Object obj)
{
}
public override void Write(string s)
{
}
public override void Write(char ch)
{
}
public override void WriteFile(string filename, long offset, long size)
{
}
public override void WriteFile(IntPtr fileHandle, long offset, long size)
{
}
public override void WriteFile(string filename)
{
}
public override void WriteFile(string filename, bool readIntoMemory)
{
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback)
{
}
#endregion
#region Properties and indexers
public override bool Buffer
{
get
{
return default(bool);
}
set
{
}
}
public override bool BufferOutput
{
get
{
return default(bool);
}
set
{
}
}
public override HttpCachePolicyBase Cache
{
get
{
return default(HttpCachePolicyBase);
}
}
public override string CacheControl
{
get
{
return default(string);
}
set
{
}
}
public override string Charset
{
get
{
return default(string);
}
set
{
}
}
public override Encoding ContentEncoding
{
get
{
return default(Encoding);
}
set
{
}
}
public override string ContentType
{
get
{
return default(string);
}
set
{
}
}
public override HttpCookieCollection Cookies
{
get
{
return default(HttpCookieCollection);
}
}
public override int Expires
{
get
{
return default(int);
}
set
{
}
}
public override DateTime ExpiresAbsolute
{
get
{
return default(DateTime);
}
set
{
}
}
public override Stream Filter
{
get
{
return default(Stream);
}
set
{
}
}
public override Encoding HeaderEncoding
{
get
{
return default(Encoding);
}
set
{
}
}
public override System.Collections.Specialized.NameValueCollection Headers
{
get
{
return default(System.Collections.Specialized.NameValueCollection);
}
}
public override bool IsClientConnected
{
get
{
return default(bool);
}
}
public override bool IsRequestBeingRedirected
{
get
{
return default(bool);
}
}
public override TextWriter Output
{
get
{
return default(TextWriter);
}
}
public override Stream OutputStream
{
get
{
return default(Stream);
}
}
public override string RedirectLocation
{
get
{
return default(string);
}
set
{
}
}
public override string Status
{
get
{
return default(string);
}
set
{
}
}
public override int StatusCode
{
get
{
return default(int);
}
set
{
}
}
public override string StatusDescription
{
get
{
return default(string);
}
set
{
}
}
public override int SubStatusCode
{
get
{
return default(int);
}
set
{
}
}
public override bool SuppressContent
{
get
{
return default(bool);
}
set
{
}
}
public override bool TrySkipIisCustomErrors
{
get
{
return default(bool);
}
set
{
}
}
#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.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl
{
public interface ICategorySelector
{
void LoadCategories();
void Filter(string criteria);
void SelectCategory(BlogPostCategory category);
void UpArrow();
void DownArrow();
void Enter();
void CtrlEnter();
}
internal partial class CategoryDisplayFormW3M1 : MiniForm
{
private readonly CategoryContext ctx;
private ICategorySelector selector;
private bool selfDispose = false;
private Point? anchor;
public CategoryDisplayFormW3M1(CategoryContext ctx, Point? anchor)
{
this.ctx = ctx;
this.anchor = anchor;
InitializeComponent();
if (ctx.MaxCategoryNameLength > 0)
txtNewCategory.MaxLength = ctx.MaxCategoryNameLength;
/* TODO: Whoops, missed UI Freeze... do this later
txtFilter.AccessibleName = Res.Get(StringId.CategoryCategoryFilter);
cbParent.AccessibleName = Res.Get(StringId.CategoryNewCategoryParent);
*/
txtNewCategory.AccessibleName = Res.Get(StringId.CategoryCategoryName);
btnRefresh.AccessibleName = Res.Get(StringId.CategoryRefreshList);
grpAdd.Enter += delegate { AcceptButton = btnDoAdd; };
grpAdd.Leave += delegate { AcceptButton = null; };
grpAdd.Text = Res.Get(StringId.CategoryAdd);
btnDoAdd.Text = Res.Get(StringId.AddButton2);
toolTip.SetToolTip(btnRefresh, Res.Get(StringId.CategoryRefreshList));
ControlHelper.SetCueBanner(txtNewCategory, Res.Get(StringId.CategoryCategoryName));
lblNone.Text = Res.Get(StringId.CategoryControlNoCategories2);
RefreshParentCombo();
btnRefresh.Image = ResourceHelper.LoadAssemblyResourceBitmap("OpenPost.Images.RefreshPostListEnabled.png");
btnRefresh.ImageAlign = ContentAlignment.MiddleCenter;
pictureBox1.Image = ResourceHelper.LoadAssemblyResourceBitmap("PostPropertyEditing.CategoryControl.Images.Search.png");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
DismissOnDeactivate = true;
Control selectorControl;
if (ctx.SelectionMode == CategoryContext.SelectionModes.SingleSelect)
selectorControl = new RadioCategorySelector(ctx);
else if (ctx.SelectionMode == CategoryContext.SelectionModes.MultiSelect)
selectorControl = new TreeCategorySelector(ctx);
else
throw new ArgumentException("Unexpected selection mode: " + ctx.SelectionMode);
lblNone.BringToFront();
lblNone.Visible = ctx.Categories.Length == 0;
selector = (ICategorySelector) selectorControl;
AdaptAddCategories();
ctx.Changed += ctx_Changed;
Disposed += delegate { ctx.Changed -= ctx_Changed; };
selectorControl.Dock = DockStyle.Fill;
selectorContainer.Controls.Add(selectorControl);
txtFilter.AccessibleName = Res.Get(StringId.FindCategory);
cbParent.AccessibleName = ControlHelper.ToAccessibleName(Res.Get(StringId.CategoryParentAccessible));
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
// Tree control has weird first-time paint issues in RTL builds
if (BidiHelper.IsRightToLeft)
Invalidate(true);
}
private void AdaptAddCategories()
{
if (!ctx.SupportsAddingCategories)
{
int deltaY = ClientSize.Height - grpAdd.Top;
grpAdd.Visible = false;
using (LayoutHelper.SuspendAnchoring(selectorContainer, grpAdd))
{
Height -= deltaY;
Top += deltaY;
}
}
else
{
if (!ctx.SupportsHierarchicalCategories)
{
txtNewCategory.Width = cbParent.Width;
int deltaY = cbParent.Top - txtNewCategory.Top;
btnDoAdd.Top -= deltaY;
cbParent.Visible = false;
using (LayoutHelper.SuspendAnchoring(txtNewCategory, cbParent, btnDoAdd, selectorContainer, grpAdd))
{
grpAdd.Height -= deltaY;
Height -= deltaY;
Top += deltaY;
}
}
}
}
private void ctx_Changed(object sender, CategoryContext.CategoryChangedEventArgs eventArgs)
{
switch (eventArgs.ChangeType)
{
case CategoryContext.ChangeType.Category:
lblNone.Visible = ctx.Categories.Length == 0;
selector.LoadCategories();
// Fix bug 611888: Funny grey box in category control when adding a category to an empty category list
// Yes, this does need to happen in a BeginInvoke--invalidating doesn't work
// properly until some other (unknown) message gets consumed
BeginInvoke(new System.Threading.ThreadStart(delegate { ((Control) selector).Invalidate(true); }));
break;
case CategoryContext.ChangeType.SelectionMode:
Close();
break;
}
}
private void RefreshParentCombo()
{
object selectedItem = cbParent.SelectedItem;
cbParent.Items.Clear();
cbParent.Items.Add(new ParentCategoryComboItemNone(cbParent));
BlogPostCategoryListItem[] categoryListItems = BlogPostCategoryListItem.BuildList(ctx.BlogCategories, true);
foreach (BlogPostCategoryListItem categoryListItem in categoryListItems)
cbParent.Items.Add(new ParentCategoryComboItem(cbParent, categoryListItem.Category, categoryListItem.IndentLevel));
if (selectedItem != null && cbParent.Items.Contains(selectedItem))
cbParent.SelectedItem = selectedItem;
else
cbParent.SelectedIndex = 0;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
int growth = (-btnDoAdd.Width) + DisplayHelper.AutoFitSystemButton(btnDoAdd, btnDoAdd.Width, int.MaxValue);
if (cbParent.Visible)
growth += (-cbParent.Width) + DisplayHelper.AutoFitSystemCombo(cbParent, cbParent.Width, int.MaxValue, true);
Width += growth;
MinimumSize = new Size(MinimumSize.Width + growth, MinimumSize.Height);
if (cbParent.Visible)
cbParent.Width -= growth;
else
txtNewCategory.Width -= growth;
Size preferredSize = selectorContainer.Controls[0].GetPreferredSize(Size.Empty);
// Fix bug 611894: Category control exhibits unexpected scrolling behavior with long category names
if (preferredSize.Width > (selectorContainer.Width + (MaximumSize.Width - Width)))
preferredSize.Height += SystemInformation.HorizontalScrollBarHeight;
preferredSize.Width += SystemInformation.VerticalScrollBarWidth;
int deltaY = preferredSize.Height - selectorContainer.Height;
int deltaX = preferredSize.Width - selectorContainer.Width;
Bounds = new Rectangle(
Left - deltaX,
Top - deltaY,
Width + deltaX,
Height + deltaY
);
txtFilter.Select();
}
/// <summary>
/// Indicates whether this form should dispose itself after closing.
/// </summary>
public bool SelfDispose
{
get { return selfDispose; }
set { selfDispose = value; }
}
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (anchor != null)
{
if (RightToLeft == RightToLeft.Yes)
Location = (Point) anchor;
else
Location = (Point) anchor - new Size(Width, 0);
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
// I don't know why this is necessary, but when RightToLeft and RightToLeftLayout
// are both true, the rightmost column or two of pixels get clipped unless we
// explicitly reset the clip.
e.Graphics.ResetClip();
// draw border around form
e.Graphics.DrawRectangle(SystemPens.ControlDarkDark, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
// draw border around filter textbox
Rectangle filterRect = new Rectangle(
selectorContainer.Left,
txtFilter.Top - ScaleY(3),
selectorContainer.Width - btnRefresh.Width - ScaleX(4),
txtFilter.Height + ScaleY(5)
);
e.Graphics.FillRectangle(SystemBrushes.Window, filterRect);
filterRect.Inflate(1, 1);
e.Graphics.DrawRectangle(SystemPens.ControlDarkDark, filterRect);
// draw border around category control
Rectangle categoryRect = selectorContainer.Bounds;
categoryRect.Inflate(1, 1);
e.Graphics.DrawRectangle(SystemPens.ControlDarkDark, categoryRect);
}
int ScaleX(int x)
{
return (int) Math.Round(DisplayHelper.ScaleX(x));
}
int ScaleY(int y)
{
return (int) Math.Round(DisplayHelper.ScaleY(y));
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (SelfDispose)
Dispose();
}
private string lastFilterValue = "";
private void txtFilter_TextChanged(object sender, EventArgs e)
{
selector.Filter(txtFilter.Text.TrimStart(' ').ToLower(CultureInfo.CurrentCulture));
if (txtNewCategory.Visible)
{
if (txtNewCategory.ForeColor != SystemColors.WindowText
|| txtNewCategory.Text == ""
|| txtNewCategory.Text == lastFilterValue)
{
txtNewCategory.Text = txtFilter.Text;
}
}
lastFilterValue = txtFilter.Text;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
Close();
return true;
}
if (!grpAdd.ContainsFocus)
{
switch (keyData)
{
case Keys.Down:
selector.DownArrow();
return true;
case Keys.Up:
selector.UpArrow();
return true;
case Keys.Enter:
selector.Enter();
return true;
case Keys.Enter | Keys.Control:
selector.CtrlEnter();
return true;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void btnRefresh_Click(object sender, EventArgs e)
{
using (new WaitCursor())
{
ctx.Refresh();
}
}
private void btnDoAdd_Click(object sender, EventArgs e)
{
AddCategory();
}
private void AddCategory()
{
BlogPostCategory cat = CreateNewOrFetchExistingCategory();
if (cat != null)
{
txtNewCategory.Text = "";
cbParent.SelectedIndex = 0;
txtFilter.Text = "";
selector.SelectCategory(cat);
txtNewCategory.Focus();
}
}
private BlogPostCategory CreateNewOrFetchExistingCategory()
{
BlogPostCategory newCategory = GetNewCategory();
if (newCategory == null)
return null;
foreach (BlogPostCategory existingCat in ctx.Categories)
{
if (BlogPostCategory.Equals(existingCat, newCategory, true))
{
return existingCat;
}
}
// create category
ctx.AddNewCategory(newCategory);
return newCategory;
}
private BlogPostCategory GetNewCategory()
{
if (txtNewCategory.ForeColor == SystemColors.WindowText)
{
string categoryName = txtNewCategory.Text.Trim();
if (categoryName != String.Empty)
{
// see if we have a parent
BlogPostCategory parentCategory = cbParent.Category;
if (parentCategory != null)
return new BlogPostCategory(categoryName, categoryName, parentCategory.Id);
else
return new BlogPostCategory(categoryName);
}
else
{
return null;
}
}
else
{
return null;
}
}
private class ParentCategoryComboBox : ComboBox
{
public ParentCategoryComboBox()
{
// prevent editing and showing of drop down
DropDownStyle = ComboBoxStyle.DropDownList;
// fully cusotm painting
DrawMode = DrawMode.OwnerDrawFixed;
IntegralHeight = false;
}
public BlogPostCategory Category
{
get
{
if (!Visible)
return null;
ParentCategoryComboItem parentComboItem = SelectedItem as ParentCategoryComboItem;
if (parentComboItem != null)
{
if (!BlogPostCategoryNone.IsCategoryNone(parentComboItem.Category))
return parentComboItem.Category;
else
return null;
}
else
{
return null;
}
}
}
protected override void OnDropDown(EventArgs e)
{
DisplayHelper.AutoFitSystemComboDropDown(this);
base.OnDropDown(e);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index != -1)
{
ParentCategoryComboItem comboItem = Items[e.Index] as ParentCategoryComboItem;
e.DrawBackground();
// don't indent for main display of category
string text = comboItem != null ? comboItem.ToString() : "";
if (e.Bounds.Width < Width)
text = text.Trim();
Color textColor = ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
? SystemColors.HighlightText
: comboItem.TextColor;
BidiGraphics bg = new BidiGraphics(e.Graphics, e.Bounds);
bg.DrawText(text, e.Font, e.Bounds, textColor, TextFormatFlags.NoPrefix);
e.DrawFocusRectangle();
}
}
}
private class ParentCategoryComboItem
{
public ParentCategoryComboItem(ComboBox parentCombo, BlogPostCategory category, int indentLevel)
{
_parentCombo = parentCombo;
_category = category;
_indentLevel = indentLevel;
}
public BlogPostCategory Category
{
get { return _category; }
}
private BlogPostCategory _category;
public virtual Color TextColor { get { return _parentCombo.ForeColor; } }
public override bool Equals(object obj)
{
ParentCategoryComboItem item = obj as ParentCategoryComboItem;
if (item == null)
return false;
return item.Category.Equals(Category);
}
public override int GetHashCode()
{
return Category.GetHashCode();
}
public override string ToString()
{
// default padding
string padding = new String(' ', _indentLevel * 3);
// override if we are selected
if (!_parentCombo.DroppedDown && (_parentCombo.SelectedItem != null) && this.Equals(_parentCombo.SelectedItem))
padding = String.Empty;
string categoryName = HtmlUtils.UnEscapeEntities(Category.Name, HtmlUtils.UnEscapeMode.Default);
string stringRepresentation = padding + categoryName;
return stringRepresentation;
}
private int _indentLevel;
private ComboBox _parentCombo;
}
private class ParentCategoryComboItemNone : ParentCategoryComboItem
{
public ParentCategoryComboItemNone(ComboBox parentCombo)
: base(parentCombo, new BlogPostCategoryNone(), 0)
{
}
public override Color TextColor { get { return SystemColors.GrayText; } }
public override string ToString()
{
return Res.Get(StringId.CategoryNoParent);
}
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using dnlib.IO;
namespace dnlib.PE {
/// <summary>
/// Represents the IMAGE_OPTIONAL_HEADER (32-bit) PE section
/// </summary>
public sealed class ImageOptionalHeader32 : FileSection, IImageOptionalHeader {
readonly ushort magic;
readonly byte majorLinkerVersion;
readonly byte minorLinkerVersion;
readonly uint sizeOfCode;
readonly uint sizeOfInitializedData;
readonly uint sizeOfUninitializedData;
readonly RVA addressOfEntryPoint;
readonly RVA baseOfCode;
readonly RVA baseOfData;
readonly uint imageBase;
readonly uint sectionAlignment;
readonly uint fileAlignment;
readonly ushort majorOperatingSystemVersion;
readonly ushort minorOperatingSystemVersion;
readonly ushort majorImageVersion;
readonly ushort minorImageVersion;
readonly ushort majorSubsystemVersion;
readonly ushort minorSubsystemVersion;
readonly uint win32VersionValue;
readonly uint sizeOfImage;
readonly uint sizeOfHeaders;
readonly uint checkSum;
readonly Subsystem subsystem;
readonly DllCharacteristics dllCharacteristics;
readonly uint sizeOfStackReserve;
readonly uint sizeOfStackCommit;
readonly uint sizeOfHeapReserve;
readonly uint sizeOfHeapCommit;
readonly uint loaderFlags;
readonly uint numberOfRvaAndSizes;
readonly ImageDataDirectory[] dataDirectories = new ImageDataDirectory[16];
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.Magic field
/// </summary>
public ushort Magic => magic;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MajorLinkerVersion field
/// </summary>
public byte MajorLinkerVersion => majorLinkerVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MinorLinkerVersion field
/// </summary>
public byte MinorLinkerVersion => minorLinkerVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfCode field
/// </summary>
public uint SizeOfCode => sizeOfCode;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfInitializedData field
/// </summary>
public uint SizeOfInitializedData => sizeOfInitializedData;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfUninitializedData field
/// </summary>
public uint SizeOfUninitializedData => sizeOfUninitializedData;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.AddressOfEntryPoint field
/// </summary>
public RVA AddressOfEntryPoint => addressOfEntryPoint;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.BaseOfCode field
/// </summary>
public RVA BaseOfCode => baseOfCode;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.BaseOfData field
/// </summary>
public RVA BaseOfData => baseOfData;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.ImageBase field
/// </summary>
public ulong ImageBase => imageBase;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SectionAlignment field
/// </summary>
public uint SectionAlignment => sectionAlignment;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.FileAlignment field
/// </summary>
public uint FileAlignment => fileAlignment;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MajorOperatingSystemVersion field
/// </summary>
public ushort MajorOperatingSystemVersion => majorOperatingSystemVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MinorOperatingSystemVersion field
/// </summary>
public ushort MinorOperatingSystemVersion => minorOperatingSystemVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MajorImageVersion field
/// </summary>
public ushort MajorImageVersion => majorImageVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MinorImageVersion field
/// </summary>
public ushort MinorImageVersion => minorImageVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MajorSubsystemVersion field
/// </summary>
public ushort MajorSubsystemVersion => majorSubsystemVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.MinorSubsystemVersion field
/// </summary>
public ushort MinorSubsystemVersion => minorSubsystemVersion;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.Win32VersionValue field
/// </summary>
public uint Win32VersionValue => win32VersionValue;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfImage field
/// </summary>
public uint SizeOfImage => sizeOfImage;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfHeaders field
/// </summary>
public uint SizeOfHeaders => sizeOfHeaders;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.CheckSum field
/// </summary>
public uint CheckSum => checkSum;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.Subsystem field
/// </summary>
public Subsystem Subsystem => subsystem;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.DllCharacteristics field
/// </summary>
public DllCharacteristics DllCharacteristics => dllCharacteristics;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfStackReserve field
/// </summary>
public ulong SizeOfStackReserve => sizeOfStackReserve;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfStackCommit field
/// </summary>
public ulong SizeOfStackCommit => sizeOfStackCommit;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfHeapReserve field
/// </summary>
public ulong SizeOfHeapReserve => sizeOfHeapReserve;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.SizeOfHeapCommit field
/// </summary>
public ulong SizeOfHeapCommit => sizeOfHeapCommit;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.LoaderFlags field
/// </summary>
public uint LoaderFlags => loaderFlags;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.NumberOfRvaAndSizes field
/// </summary>
public uint NumberOfRvaAndSizes => numberOfRvaAndSizes;
/// <summary>
/// Returns the IMAGE_OPTIONAL_HEADER.DataDirectories field
/// </summary>
public ImageDataDirectory[] DataDirectories => dataDirectories;
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">PE file reader pointing to the start of this section</param>
/// <param name="totalSize">Total size of this optional header (from the file header)</param>
/// <param name="verify">Verify section</param>
/// <exception cref="BadImageFormatException">Thrown if verification fails</exception>
public ImageOptionalHeader32(ref DataReader reader, uint totalSize, bool verify) {
if (totalSize < 0x60)
throw new BadImageFormatException("Invalid optional header size");
if (verify && (ulong)reader.Position + totalSize > reader.Length)
throw new BadImageFormatException("Invalid optional header size");
SetStartOffset(ref reader);
magic = reader.ReadUInt16();
majorLinkerVersion = reader.ReadByte();
minorLinkerVersion = reader.ReadByte();
sizeOfCode = reader.ReadUInt32();
sizeOfInitializedData = reader.ReadUInt32();
sizeOfUninitializedData = reader.ReadUInt32();
addressOfEntryPoint = (RVA)reader.ReadUInt32();
baseOfCode = (RVA)reader.ReadUInt32();
baseOfData = (RVA)reader.ReadUInt32();
imageBase = reader.ReadUInt32();
sectionAlignment = reader.ReadUInt32();
fileAlignment = reader.ReadUInt32();
majorOperatingSystemVersion = reader.ReadUInt16();
minorOperatingSystemVersion = reader.ReadUInt16();
majorImageVersion = reader.ReadUInt16();
minorImageVersion = reader.ReadUInt16();
majorSubsystemVersion = reader.ReadUInt16();
minorSubsystemVersion = reader.ReadUInt16();
win32VersionValue = reader.ReadUInt32();
sizeOfImage = reader.ReadUInt32();
sizeOfHeaders = reader.ReadUInt32();
checkSum = reader.ReadUInt32();
subsystem = (Subsystem)reader.ReadUInt16();
dllCharacteristics = (DllCharacteristics)reader.ReadUInt16();
sizeOfStackReserve = reader.ReadUInt32();
sizeOfStackCommit = reader.ReadUInt32();
sizeOfHeapReserve = reader.ReadUInt32();
sizeOfHeapCommit = reader.ReadUInt32();
loaderFlags = reader.ReadUInt32();
numberOfRvaAndSizes = reader.ReadUInt32();
for (int i = 0; i < dataDirectories.Length; i++) {
uint len = reader.Position - (uint)startOffset;
if (len + 8 <= totalSize)
dataDirectories[i] = new ImageDataDirectory(ref reader, verify);
else
dataDirectories[i] = new ImageDataDirectory();
}
reader.Position = (uint)startOffset + totalSize;
SetEndoffset(ref reader);
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Reflection;
using System.Text;
using ALinq;
using ALinq.Mapping;
using System.Data.OracleClient;
using ALinq.Oracle;
namespace NorthwindDemo
{
//[License("ansiboy", "AV7D47FBDE5376DFA5")]
[Provider(typeof(OracleProvider))]
[Database(Name = "Northwind")]
public class OracleNorthwind : NorthwindDatabase
{
#region Constrouctor
public OracleNorthwind(string conn)
: base(conn)
{
}
public OracleNorthwind(string databaseName, string systemPassword)
: base(CreateConnection(databaseName, systemPassword, DB_HOST))
{
}
public OracleNorthwind(string databaseName, string systemPassword, string server)
: base(CreateConnection(databaseName, systemPassword, server))
{
}
public OracleNorthwind(IDbConnection connection)
: base(connection)
{
}
public OracleNorthwind(IDbConnection connection, MappingSource mapping)
: base(connection, mapping)
{
}
public static DbConnection CreateConnection(string databaseName, string systemPassword, string server)
{
var builder = new OracleConnectionStringBuilder()
{
DataSource = server,
UserID = databaseName,
Password = systemPassword,
PersistSecurityInfo = true,
};
return new OracleConnection(builder.ToString());
}
protected override void ImportData()
{
var builder = new OracleConnectionStringBuilder()
{
UserID = "Northwind",
Password = "Test",
DataSource = DB_HOST,
};
var instance = new OracleNorthwind(new OracleConnection(builder.ToString()), this.Mapping.MappingSource) { Log = Log };
var data = new NorthwindData();
instance.Regions.InsertAllOnSubmit(data.regions);
instance.Employees.InsertAllOnSubmit(data.employees);
instance.Territories.InsertAllOnSubmit(data.territories);
instance.EmployeeTerritories.InsertAllOnSubmit(data.employeeTerritories);
instance.Customers.InsertAllOnSubmit(data.customers);
instance.Shippers.InsertAllOnSubmit(data.shippers);
instance.Categories.InsertAllOnSubmit(data.categories);
instance.Suppliers.InsertAllOnSubmit(data.suppliers);
instance.Products.InsertAllOnSubmit(data.products);
instance.Orders.InsertAllOnSubmit(data.orders);
instance.OrderDetails.InsertAllOnSubmit(data.orderDetails);
instance.SubmitChanges();
}
#endregion
public override void CreateDatabase()
{
base.CreateDatabase();
var conn = CreateConnection("Northwind", "Test", DB_HOST);
var command = conn.CreateCommand();
command.Connection.Open();
try
{
var sb = new StringBuilder();
#region PROCEDURE AddCategory
sb.AppendLine("create or replace procedure add_category(category_id in int, category_name in VarChar, ");
sb.AppendLine("category_description in VarChar,RETURN_VALUE out int) is");
sb.AppendLine("begin");
sb.AppendLine("Insert Into Categories");
sb.AppendLine("(CategoryID,CategoryName, Description)");
sb.AppendLine("Values (category_id, category_name, category_description);");
sb.AppendLine("Select category_id into RETURN_VALUE From Dual;");
sb.AppendLine("end add_category;");
command.CommandText = @"
create or replace procedure add_category(category_id in int, category_name in VarChar,
category_description in VarChar,RETURN_VALUE out int) is
begin
Insert Into Categories
(CategoryID,CategoryName, Description)
Values (category_id, category_name, category_description);
Select category_id into RETURN_VALUE From Dual;
end add_category;";
command.CommandText = sb.ToString();
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
#endregion
#region PROCEDURE GetCustomersCountByRegion
command.CommandText = @"
create or replace procedure get_customers_count_by_region (
region in VarChar, RETURN_VALUE out int) is
begin
select Count(*) into RETURN_VALUE
from Customers
where Region = region;
end get_customers_count_by_region;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
#endregion
#region PROCEDURE GetCustomersByCity
command.CommandText = @"
create or replace package pkg1 is
type mytype is ref cursor;
procedure get_customers_by_city(city in VarChar, mycs out mytype, RETURN_VALUE out number);
end pkg1 ;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
command.CommandText = @"
create or replace package body pkg1 is
procedure get_customers_by_city(city in VarChar, mycs out mytype, RETURN_VALUE out number) is
begin
open mycs for select CustomerID, ContactName, CompanyName
from Customers
where City = city;
RETURN_VALUE := 1;
end get_customers_by_city;
end pkg1;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
#endregion
#region PROCEDURE SingleRowsetMultiShape
command.CommandText = @"
create or replace package pkg2 is
type mytype is ref cursor;
procedure single_rowset_multi_shape(param in number,mycs out mytype,RETURN_VALUE out number);
end pkg2;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
command.CommandText = @"
create or replace package body pkg2 is
procedure single_rowset_multi_shape(param in number,mycs out mytype,RETURN_VALUE out number) is
begin
if param = 1 then
open mycs for select *
from Customers
where Region = 'WA';
end if;
if param = 2 then
open mycs for select CustomerID, ContactName, CompanyName
from Customers
where City = 'WA';
end if;
RETURN_VALUE := 1;
end single_rowset_multi_shape;
end pkg2;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
#endregion
#region PROCEDURE GetCustomerAndOrders
command.CommandText = @"
create or replace package pkg3 is
type mytype1 is ref cursor;
type mytype2 is ref cursor;
procedure get_customer_and_orders(CustomerID in VarChar, mycs1 out mytype1, mycs2 out mytype2, RETURN_VALUE out numeric);
end pkg3;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
command.CommandText = @"
create or replace package body pkg3 is
procedure get_customer_and_orders(customerID in VarChar, mycs1 out mytype1, mycs2 out mytype2, RETURN_VALUE out numeric) is
begin
open mycs1 for select *
from Customers
where CustomerID = customerID;
open mycs2 for select *
from Orders
where CustomerID = customerID;
RETURN_VALUE := 1;
end get_customer_and_orders;
end pkg3;";
if (Log != null)
{
Log.WriteLine(command.CommandText);
Log.WriteLine();
}
command.ExecuteNonQuery();
#endregion
}
finally
{
command.Connection.Close();
}
}
[Function(Name = "northwind.add_category")]
public new int AddCategory(
[Parameter(Name = "category_id")]
int categoryID,
[Parameter(Name = "category_name")]
string categoryName,
[Parameter(Name = "category_description")]
string categoryDescription
)
{
var result = ExecuteMethodCall(this, (MethodInfo)MethodBase.GetCurrentMethod(),
categoryID, categoryName, categoryDescription).ReturnValue;
return (int)result;
}
[Function(Name = "northwind.get_customers_count_by_region")]
public int GetCustomersCountByRegion(
[Parameter]
string region)
{
var result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), region);
return ((int)(result.ReturnValue));
}
[Function(Name = "pkg_customers_by_city.get")]
public ISingleResult<PartialCustomersSetResult> GetCustomersByCity(
[Parameter(DbType = "NVarChar(20)")]
string city,
[Parameter(DbType = "Cursor")]
object mycs)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), city, null);
return ((ISingleResult<PartialCustomersSetResult>)(result.ReturnValue));
}
[Function(Name = "northwind.pkg_Single_Rowset_Multi_Shape.get")]
[ResultType(typeof(Customer))]
[ResultType(typeof(PartialCustomersSetResult))]
public IMultipleResults SingleRowset_MultiShape(
[Parameter] int? param,
[Parameter(DbType = "Cursor")] object mycs)
{
IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), param, mycs);
return ((IMultipleResults)(result.ReturnValue));
}
[Function(Name = "northwind.pkg_customer_and_orders.get")]
[ResultType(typeof(Customer))]
[ResultType(typeof(Order))]
public IMultipleResults GetCustomerAndOrders(
[Parameter] string customerID,
[Parameter(DbType = "Cursor")] object mycs1,
[Parameter(DbType = "Cursor")] object mycs2)
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(),
customerID, mycs1, mycs2);
return ((IMultipleResults)(result.ReturnValue));
}
public class PartialCustomersSetResult
{
[Column]
public string CustomerID;
[Column]
public string ContactName;
[Column]
public string CompanyName;
}
[Function(Name = "sysdate", IsComposable = true)]
public override DateTime Now()
{
throw new NotImplementedException();
}
}
}
| |
// 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.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml;
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
namespace XmlReaderTest.Common
{
////////////////////////////////////////////////////////////////
// TestFiles
//
////////////////////////////////////////////////////////////////
public class TestFiles
{
//Data
private const string _AllNodeTypeDTD = "AllNodeTypes.dtd";
private const string _AllNodeTypeENT = "AllNodeTypes.ent";
private const string _GenericXml = "Generic.xml";
private const string _BigFileXml = "Big.xml";
private const string _JunkFileXml = "Junk.xml";
private const string _NamespaceXml = "XmlNamespace.xml";
private const string _InvNamespaceXml = "InvNamespace.xml";
private const string _LangFileXml = "XmlLang.xml";
private const string _SpaceFileXml = "XmlSpace.xml";
private const string _WellFormedDTD = "WellDtdFile.xml";
private const string _NonWellFormedDTD = "NonWellDtdFile.xml";
private const string _InvWellFormedDTD = "InvWellDtdFile.xml";
private const string _ValidDTD = "DtdFile.xml";
private const string _InvDTD = "InvDtdFile.xml";
private const string _InvXmlWithXDR = "InvXdrXmlFile.xml";
private const string _ValidXDR = "XdrFile.xml";
private const string _ValidXmlWithXDR = "XdrXmlFile.xml";
private const string _XsltCopyStylesheet = "XsltCtest.xsl";
private const string _XsltCopyDoc = "XsltCtest.xml";
private const string _WhitespaceXML = "Whitespace.xml";
private const string _Base64Xml = "Base64.xml";
private const string _BinHexXml = "BinHex.xml";
private const string _UnicodeXml = "Unicode.xml";
private const string _UTF8Xml = "UTF8.xml";
private const string _ByteXml = "Byte.xml";
private const string _BigEndianXml = "BigEndian.xml";
private const string _ConstructorXml = "Constructor.xml";
private const string _LineNumberXml = "LineNumber.xml";
private const string _LineNumberEnt = "LineNumber.ent";
private const string _LbNormalization = "LbNormalization.xml";
private const string _LbNormEnt1 = "se3_1.ent";
private const string _LbNormEnt2 = "se3_2.ent";
private const string _SchemaTypeXml = "SchemaType.xml";
private const string _SchemaTypeXsd = "SchemaType.xsd";
private const string _BinaryXml = "Binary.bin";
private const string strBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private const string strBinHex = "0123456789ABCDEF";
public static void RemoveDataReader(EREADER_TYPE eReaderType)
{
switch (eReaderType)
{
case EREADER_TYPE.UNICODE:
DeleteTestFile(_UnicodeXml);
break;
case EREADER_TYPE.UTF8:
DeleteTestFile(_UTF8Xml);
break;
case EREADER_TYPE.BIGENDIAN:
DeleteTestFile(_BigEndianXml);
break;
case EREADER_TYPE.BYTE:
DeleteTestFile(_ByteXml);
break;
case EREADER_TYPE.GENERIC:
DeleteTestFile(_AllNodeTypeDTD);
DeleteTestFile(_AllNodeTypeENT);
DeleteTestFile(_GenericXml);
break;
case EREADER_TYPE.BIG_ELEMENT_SIZE:
DeleteTestFile(_BigFileXml);
break;
case EREADER_TYPE.JUNK:
DeleteTestFile(_JunkFileXml);
break;
case EREADER_TYPE.INVALID_NAMESPACE:
DeleteTestFile(_InvNamespaceXml);
break;
case EREADER_TYPE.XMLNAMESPACE_TEST:
DeleteTestFile(_NamespaceXml);
break;
case EREADER_TYPE.XMLLANG_TEST:
DeleteTestFile(_LangFileXml);
break;
case EREADER_TYPE.XMLSPACE_TEST:
DeleteTestFile(_SpaceFileXml);
break;
case EREADER_TYPE.WELLFORMED_DTD:
DeleteTestFile(_WellFormedDTD);
break;
case EREADER_TYPE.NONWELLFORMED_DTD:
DeleteTestFile(_NonWellFormedDTD);
break;
case EREADER_TYPE.INVWELLFORMED_DTD:
DeleteTestFile(_InvWellFormedDTD);
break;
case EREADER_TYPE.VALID_DTD:
DeleteTestFile(_ValidDTD);
break;
case EREADER_TYPE.INVALID_DTD:
DeleteTestFile(_InvDTD);
break;
case EREADER_TYPE.INVALID_SCHEMA:
DeleteTestFile(_ValidXDR);
DeleteTestFile(_InvXmlWithXDR);
break;
case EREADER_TYPE.XMLSCHEMA:
DeleteTestFile(_ValidXDR);
DeleteTestFile(_ValidXmlWithXDR);
break;
case EREADER_TYPE.XSLT_COPY:
DeleteTestFile(_AllNodeTypeDTD);
DeleteTestFile(_AllNodeTypeENT);
DeleteTestFile(_XsltCopyStylesheet);
DeleteTestFile(_XsltCopyDoc);
break;
case EREADER_TYPE.WHITESPACE_TEST:
DeleteTestFile(_WhitespaceXML);
break;
case EREADER_TYPE.BASE64_TEST:
DeleteTestFile(_Base64Xml);
break;
case EREADER_TYPE.BINHEX_TEST:
DeleteTestFile(_BinHexXml);
break;
case EREADER_TYPE.CONSTRUCTOR:
DeleteTestFile(_ConstructorXml);
break;
case EREADER_TYPE.LINENUMBER:
break;
case EREADER_TYPE.LBNORMALIZATION:
DeleteTestFile(_LbNormalization);
break;
case EREADER_TYPE.BINARY:
DeleteTestFile(_BinaryXml);
break;
default:
throw new Exception();
}
}
private static Dictionary<EREADER_TYPE, string> s_fileNameMap = null;
public static string GetTestFileName(EREADER_TYPE eReaderType)
{
if (s_fileNameMap == null)
InitFileNameMap();
return s_fileNameMap[eReaderType];
}
private static void InitFileNameMap()
{
if (s_fileNameMap == null)
{
s_fileNameMap = new Dictionary<EREADER_TYPE, string>();
}
s_fileNameMap.Add(EREADER_TYPE.UNICODE, _UnicodeXml);
s_fileNameMap.Add(EREADER_TYPE.UTF8, _UTF8Xml);
s_fileNameMap.Add(EREADER_TYPE.BIGENDIAN, _BigEndianXml);
s_fileNameMap.Add(EREADER_TYPE.BYTE, _ByteXml);
s_fileNameMap.Add(EREADER_TYPE.GENERIC, _GenericXml);
s_fileNameMap.Add(EREADER_TYPE.STRING_ONLY, String.Empty);
s_fileNameMap.Add(EREADER_TYPE.BIG_ELEMENT_SIZE, _BigFileXml);
s_fileNameMap.Add(EREADER_TYPE.JUNK, _JunkFileXml);
s_fileNameMap.Add(EREADER_TYPE.INVALID_NAMESPACE, _InvNamespaceXml);
s_fileNameMap.Add(EREADER_TYPE.XMLNAMESPACE_TEST, _NamespaceXml);
s_fileNameMap.Add(EREADER_TYPE.XMLLANG_TEST, _LangFileXml);
s_fileNameMap.Add(EREADER_TYPE.XMLSPACE_TEST, _SpaceFileXml);
s_fileNameMap.Add(EREADER_TYPE.WELLFORMED_DTD, _WellFormedDTD);
s_fileNameMap.Add(EREADER_TYPE.NONWELLFORMED_DTD, _NonWellFormedDTD);
s_fileNameMap.Add(EREADER_TYPE.INVWELLFORMED_DTD, _InvWellFormedDTD);
s_fileNameMap.Add(EREADER_TYPE.VALID_DTD, _ValidDTD);
s_fileNameMap.Add(EREADER_TYPE.INVALID_DTD, _InvDTD);
s_fileNameMap.Add(EREADER_TYPE.INVALID_SCHEMA, _InvXmlWithXDR);
s_fileNameMap.Add(EREADER_TYPE.XMLSCHEMA, _ValidXmlWithXDR);
s_fileNameMap.Add(EREADER_TYPE.XSLT_COPY, _XsltCopyDoc);
s_fileNameMap.Add(EREADER_TYPE.WHITESPACE_TEST, _WhitespaceXML);
s_fileNameMap.Add(EREADER_TYPE.BASE64_TEST, _Base64Xml);
s_fileNameMap.Add(EREADER_TYPE.BINHEX_TEST, _BinHexXml);
s_fileNameMap.Add(EREADER_TYPE.CONSTRUCTOR, _ConstructorXml);
s_fileNameMap.Add(EREADER_TYPE.LINENUMBER, _LineNumberXml);
s_fileNameMap.Add(EREADER_TYPE.LBNORMALIZATION, _LbNormalization);
s_fileNameMap.Add(EREADER_TYPE.BINARY, _BinaryXml);
}
public static void CreateTestFile(ref string strFileName, EREADER_TYPE eReaderType)
{
strFileName = GetTestFileName(eReaderType);
switch (eReaderType)
{
case EREADER_TYPE.UNICODE:
CreateEncodedTestFile(strFileName, Encoding.Unicode);
break;
case EREADER_TYPE.UTF8:
CreateUTF8EncodedTestFile(strFileName, Encoding.UTF8);
break;
case EREADER_TYPE.BIGENDIAN:
CreateEncodedTestFile(strFileName, Encoding.BigEndianUnicode);
break;
case EREADER_TYPE.BYTE:
CreateByteTestFile(strFileName);
break;
case EREADER_TYPE.GENERIC:
CreateGenericTestFile(strFileName);
break;
case EREADER_TYPE.BIG_ELEMENT_SIZE:
CreateBigElementTestFile(strFileName);
break;
case EREADER_TYPE.JUNK:
CreateJunkTestFile(strFileName);
break;
case EREADER_TYPE.XMLNAMESPACE_TEST:
CreateNamespaceTestFile(strFileName);
break;
case EREADER_TYPE.XMLLANG_TEST:
CreateXmlLangTestFile(strFileName);
break;
case EREADER_TYPE.INVALID_NAMESPACE:
CreateInvalidNamespaceTestFile(strFileName);
break;
case EREADER_TYPE.XMLSPACE_TEST:
CreateXmlSpaceTestFile(strFileName);
break;
case EREADER_TYPE.VALID_DTD:
CreateValidDTDTestFile(strFileName);
break;
case EREADER_TYPE.INVALID_DTD:
CreateInvalidDTDTestFile(strFileName);
break;
case EREADER_TYPE.WELLFORMED_DTD:
CreateWellFormedDTDTestFile(strFileName);
break;
case EREADER_TYPE.NONWELLFORMED_DTD:
CreateNonWellFormedDTDTestFile(strFileName);
break;
case EREADER_TYPE.INVWELLFORMED_DTD:
CreateInvWellFormedDTDTestFile(strFileName);
break;
case EREADER_TYPE.INVALID_SCHEMA:
CreateXDRTestFile(strFileName);
CreateInvalidXMLXDRTestFile(strFileName);
break;
case EREADER_TYPE.XMLSCHEMA:
CreateXDRTestFile(strFileName);
CreateXDRXMLTestFile(strFileName);
break;
case EREADER_TYPE.XSLT_COPY:
CreateXSLTStyleSheetWCopyTestFile(strFileName);
CreateGenericXsltTestFile(strFileName);
break;
case EREADER_TYPE.WHITESPACE_TEST:
CreateWhitespaceHandlingTestFile(strFileName);
break;
case EREADER_TYPE.BASE64_TEST:
CreateBase64TestFile(strFileName);
break;
case EREADER_TYPE.BINHEX_TEST:
CreateBinHexTestFile(strFileName);
break;
case EREADER_TYPE.CONSTRUCTOR:
CreateConstructorTestFile(strFileName);
break;
case EREADER_TYPE.LINENUMBER:
CreateLineNumberTestFile(strFileName);
break;
case EREADER_TYPE.LBNORMALIZATION:
CreateLbNormalizationTestFile(strFileName);
break;
case EREADER_TYPE.BINARY:
CreateBinaryTestFile(strFileName);
break;
default:
break;
}
}
protected static void DeleteTestFile(string strFileName)
{
}
public static void CreateByteTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("x");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateUTF8EncodedTestFile(string strFileName, Encoding encode)
{
Stream strm = new MemoryStream();
TextWriter tw = new StreamWriter(strm, encode);
tw.WriteLine("<root>");
tw.Write("\u00A9");
tw.WriteLine("</root>");
tw.Flush();
FilePathUtil.addStream(strFileName, strm);
}
public static void CreateEncodedTestFile(string strFileName, Encoding encode)
{
Stream strm = new MemoryStream();
TextWriter tw = new StreamWriter(strm, encode);
tw.WriteLine("<root>");
tw.WriteLine("</root>");
tw.Flush();
FilePathUtil.addStream(strFileName, strm);
}
public static void CreateWhitespaceHandlingTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<!DOCTYPE dt [");
tw.WriteLine("<!ELEMENT WHITESPACE1 (#PCDATA)*>");
tw.WriteLine("<!ELEMENT WHITESPACE2 (#PCDATA)*>");
tw.WriteLine("<!ELEMENT WHITESPACE3 (#PCDATA)*>");
tw.WriteLine("]>");
tw.WriteLine("<doc>");
tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>");
tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>");
tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>");
tw.WriteLine("</doc>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateGenericXsltTestFile(string strFileName)
{
// Create stylesheet
CreateXSLTStyleSheetWCopyTestFile(_XsltCopyStylesheet);
CreateGenericTestFile(strFileName);
}
public static void CreateGenericTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
tw.WriteLine("<!-- comment1 -->");
tw.WriteLine("<?PI1_First processing instruction?>");
tw.WriteLine("<?PI1a?>");
tw.WriteLine("<?PI1b?>");
tw.WriteLine("<?PI1c?>");
tw.WriteLine("<PLAY>");
tw.WriteLine("<root xmlns:something=\"something\" xmlns:my=\"my\" xmlns:dt=\"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">");
tw.WriteLine("<elem1 child1=\"\" child2=\"NO_REFERENCEe2;\" child3=\"something\">");
tw.WriteLine("text node two NO_REFERENCEe1; text node three");
tw.WriteLine("</elem1>");
tw.WriteLine("NO_REFERENCEe2;");
tw.WriteLine("<![CDATA[ This section contains characters that should not be interpreted as markup. For example, characters ', \",");
tw.WriteLine("<, >, and & are all fine here.]]>");
tw.WriteLine("<elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"> ");
tw.WriteLine("<a />");
tw.WriteLine("</elem2>");
tw.WriteLine("<elem2> ");
tw.WriteLine("elem2-text1");
tw.WriteLine("<a refs=\"id2\"> ");
tw.WriteLine("this-is-a ");
tw.WriteLine("</a> ");
tw.WriteLine("elem2-text2");
tw.WriteLine("<!-- elem2-comment1-->");
tw.WriteLine("elem2-text3");
tw.WriteLine("<b> ");
tw.WriteLine("this-is-b");
tw.WriteLine("</b>");
tw.WriteLine("elem2-text4");
tw.WriteLine("<?elem2_PI elem2-PI?>");
tw.WriteLine("elem2-text5");
tw.WriteLine("</elem2>");
tw.WriteLine("<elem2 att1=\"id2\"></elem2>");
tw.WriteLine("</root>");
tw.Write("<ENTITY1 att1='xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx'>xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY1>");
tw.WriteLine("<ENTITY2 att1='xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx'>xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY2>");
tw.WriteLine("<ENTITY3 att1='xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx'>xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY3>");
tw.WriteLine("<ENTITY4 att1='xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx'>xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY4>");
tw.WriteLine("<ENTITY5>NO_REFERENCEext3;</ENTITY5>");
tw.WriteLine("<ATTRIBUTE1 />");
tw.WriteLine("<ATTRIBUTE2 a1='a1value' />");
tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />");
tw.WriteLine("<ATTRIBUTE4 a1='' />");
tw.WriteLine("<ATTRIBUTE5 CRLF='x\r\nx' CR='x\rx' LF='x\nx' MS='x x' TAB='x\tx' />");
tw.WriteLine("<?PI1a a\r\n\rb ?>");
tw.WriteLine("<!--comm\r\n\rent-->");
tw.WriteLine("<![CDATA[cd\r\n\rata]]>");
tw.WriteLine("<ENDOFLINE1>x\r\nx</ENDOFLINE1>");
tw.WriteLine("<ENDOFLINE2>x\rx</ENDOFLINE2>");
tw.WriteLine("<ENDOFLINE3>x\nx</ENDOFLINE3>");
tw.WriteLine("<WHITESPACE1>\r\n<ELEM />\r\n</WHITESPACE1>");
tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>");
tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>");
tw.WriteLine("<SKIP1 /><AFTERSKIP1 />");
tw.WriteLine("<SKIP2></SKIP2><AFTERSKIP2 />");
tw.WriteLine("<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3><AFTERSKIP3></AFTERSKIP3>");
tw.WriteLine("<SKIP4><ELEM1 /><ELEM2>xxx<ELEM3 /></ELEM2></SKIP4>");
tw.WriteLine("<CHARS1>0123456789</CHARS1>");
tw.WriteLine("<CHARS2>xxx<MARKUP />yyy</CHARS2>");
tw.WriteLine("<CHARS_ELEM1>xxx<MARKUP />yyy</CHARS_ELEM1>");
tw.WriteLine("<CHARS_ELEM2><MARKUP />yyy</CHARS_ELEM2>");
tw.WriteLine("<CHARS_ELEM3>xxx<MARKUP /></CHARS_ELEM3>");
tw.WriteLine("<CHARS_CDATA1>xxx<![CDATA[yyy]]>zzz</CHARS_CDATA1>");
tw.WriteLine("<CHARS_CDATA2><![CDATA[yyy]]>zzz</CHARS_CDATA2>");
tw.WriteLine("<CHARS_CDATA3>xxx<![CDATA[yyy]]></CHARS_CDATA3>");
tw.WriteLine("<CHARS_PI1>xxx<?PI_CHAR1 yyy?>zzz</CHARS_PI1>");
tw.WriteLine("<CHARS_PI2><?PI_CHAR2?>zzz</CHARS_PI2>");
tw.WriteLine("<CHARS_PI3>xxx<?PI_CHAR3 yyy?></CHARS_PI3>");
tw.WriteLine("<CHARS_COMMENT1>xxx<!-- comment1-->zzz</CHARS_COMMENT1>");
tw.WriteLine("<CHARS_COMMENT2><!-- comment1-->zzz</CHARS_COMMENT2>");
tw.WriteLine("<CHARS_COMMENT3>xxx<!-- comment1--></CHARS_COMMENT3>");
tw.Flush();
tw.WriteLine("<ISDEFAULT />");
tw.WriteLine("<ISDEFAULT a1='a1value' />");
tw.WriteLine("<BOOLEAN1>true</BOOLEAN1>");
tw.WriteLine("<BOOLEAN2>false</BOOLEAN2>");
tw.WriteLine("<BOOLEAN3>1</BOOLEAN3>");
tw.WriteLine("<BOOLEAN4>tRue</BOOLEAN4>");
tw.WriteLine("<DATETIME>1999-02-22T11:11:11</DATETIME>");
tw.WriteLine("<DATE>1999-02-22</DATE>");
tw.WriteLine("<TIME>11:11:11</TIME>");
tw.WriteLine("<INTEGER>9999</INTEGER>");
tw.WriteLine("<FLOAT>99.99</FLOAT>");
tw.WriteLine("<DECIMAL>.09</DECIMAL>");
tw.WriteLine("<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>");
tw.WriteLine("<TITLE><!-- this is a comment--></TITLE>");
tw.WriteLine("<PGROUP>");
tw.WriteLine("<ACT0 xmlns:foo=\"http://www.foo.com\" foo:Attr0=\"0\" foo:Attr1=\"1111111101\" foo:Attr2=\"222222202\" foo:Attr3=\"333333303\" foo:Attr4=\"444444404\" foo:Attr5=\"555555505\" foo:Attr6=\"666666606\" foo:Attr7=\"777777707\" foo:Attr8=\"888888808\" foo:Attr9=\"999999909\" />");
tw.WriteLine("<ACT1 Attr0=\'0\' Attr1=\'1111111101\' Attr2=\'222222202\' Attr3=\'333333303\' Attr4=\'444444404\' Attr5=\'555555505\' Attr6=\'666666606\' Attr7=\'777777707\' Attr8=\'888888808\' Attr9=\'999999909\' />");
tw.WriteLine("<QUOTE1 Attr0=\"0\" Attr1=\'1111111101\' Attr2=\"222222202\" Attr3=\'333333303\' />");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<QUOTE2 Attr0=\"0\" Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\'333333303\' />");
tw.WriteLine("<QUOTE3 Attr0=\'0\' Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\"333333303\" />");
tw.WriteLine("<EMPTY1 />");
tw.WriteLine("<EMPTY2 val=\"abc\" />");
tw.WriteLine("<EMPTY3></EMPTY3>");
tw.WriteLine("<NONEMPTY0></NONEMPTY0>");
tw.WriteLine("<NONEMPTY1>ABCDE</NONEMPTY1>");
tw.WriteLine("<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>");
tw.WriteLine("<ACT2 Attr0=\"10\" Attr1=\"1111111011\" Attr2=\"222222012\" Attr3=\"333333013\" Attr4=\"444444014\" Attr5=\"555555015\" Attr6=\"666666016\" Attr7=\"777777017\" Attr8=\"888888018\" Attr9=\"999999019\" />");
tw.WriteLine("<GRPDESCR>twin brothers, and sons to Aegeon and Aemilia.</GRPDESCR>");
tw.WriteLine("</PGROUP>");
tw.WriteLine("<PGROUP>");
tw.Flush();
tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color NO_REFERENCEe1; is it?</XMLLANG0>");
tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>");
tw.WriteLine("<NOXMLLANG />");
tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />");
tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>");
tw.WriteLine("<DONEXMLLANG />");
tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>< ></XMLSPACE1>");
tw.Write("<XMLSPACE2 xml:space=\'preserve\'>< ><a><!-- comment--><b><?PI1a?><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>");
tw.WriteLine("<NOSPACE />");
tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />");
tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>< <XMLSPACE3 xml:space=\'preserve\'> < > <XMLSPACE4 xml:space=\'default\'> < > </XMLSPACE4> test </XMLSPACE3> ></XMLSPACE2A>");
tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>");
tw.WriteLine("<DOCNAMESPACE>");
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>");
tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check><bar:check2></bar:check2></d></c></b></a></NAMESPACE1>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />");
tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />");
tw.WriteLine("<EMPTY_NAMESPACE2 Attr0=\"0\" xmlns=\"14\"></EMPTY_NAMESPACE2>");
tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>");
tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">");
tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><empty100 /><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>");
tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<NONAMESPACE1 Attr1=\"one\" xmlns=\"1000\">Namespace=\"\"</NONAMESPACE1>");
tw.WriteLine("</DOCNAMESPACE>");
tw.WriteLine("</PGROUP>");
tw.WriteLine("<GOTOCONTENT>some text<![CDATA[cdata info]]></GOTOCONTENT>");
tw.WriteLine("<SKIPCONTENT att1=\"\"> <!-- comment1--> \n <?PI_SkipContent instruction?></SKIPCONTENT>");
tw.WriteLine("<MIXCONTENT> <!-- comment1-->some text<?PI_SkipContent instruction?><![CDATA[cdata info]]></MIXCONTENT>");
tw.WriteLine("<A att=\"123\">1<B>2<C>3<D>4<E>5<F>6<G>7<H>8<I>9<J>10");
tw.WriteLine("<A1 att=\"456\">11<B1>12<C1>13<D1>14<E1>15<F1>16<G1>17<H1>18<I1>19<J1>20");
tw.WriteLine("<A2 att=\"789\">21<B2>22<C2>23<D2>24<E2>25<F2>26<G2>27<H2>28<I2>29<J2>30");
tw.WriteLine("<A3 att=\"123\">31<B3>32<C3>33<D3>34<E3>35<F3>36<G3>37<H3>38<I3>39<J3>40");
tw.WriteLine("<A4 att=\"456\">41<B4>42<C4>43<D4>44<E4>45<F4>46<G4>47<H4>48<I4>49<J4>50");
tw.WriteLine("<A5 att=\"789\">51<B5>52<C5>53<D5>54<E5>55<F5>56<G5>57<H5>58<I5>59<J5>60");
tw.WriteLine("<A6 att=\"123\">61<B6>62<C6>63<D6>64<E6>65<F6>66<G6>67<H6>68<I6>69<J6>70");
tw.WriteLine("<A7 att=\"456\">71<B7>72<C7>73<D7>74<E7>75<F7>76<G7>77<H7>78<I7>79<J7>80");
tw.WriteLine("<A8 att=\"789\">81<B8>82<C8>83<D8>84<E8>85<F8>86<G8>87<H8>88<I8>89<J8>90");
tw.WriteLine("<A9 att=\"123\">91<B9>92<C9>93<D9>94<E9>95<F9>96<G9>97<H9>98<I9>99<J9>100");
tw.WriteLine("<A10 att=\"123\">101<B10>102<C10>103<D10>104<E10>105<F10>106<G10>107<H10>108<I10>109<J10>110");
tw.WriteLine("</J10>109</I10>108</H10>107</G10>106</F10>105</E10>104</D10>103</C10>102</B10>101</A10>");
tw.WriteLine("</J9>99</I9>98</H9>97</G9>96</F9>95</E9>94</D9>93</C9>92</B9>91</A9>");
tw.WriteLine("</J8>89</I8>88</H8>87</G8>86</F8>85</E8>84</D8>83</C8>82</B8>81</A8>");
tw.WriteLine("</J7>79</I7>78</H7>77</G7>76</F7>75</E7>74</D7>73</C7>72</B7>71</A7>");
tw.WriteLine("</J6>69</I6>68</H6>67</G6>66</F6>65</E6>64</D6>63</C6>62</B6>61</A6>");
tw.WriteLine("</J5>59</I5>58</H5>57</G5>56</F5>55</E5>54</D5>53</C5>52</B5>51</A5>");
tw.WriteLine("</J4>49</I4>48</H4>47</G4>46</F4>45</E4>44</D4>43</C4>42</B4>41</A4>");
tw.WriteLine("</J3>39</I3>38</H3>37</G3>36</F3>35</E3>34</D3>33</C3>32</B3>31</A3>");
tw.WriteLine("</J2>29</I2>28</H2>27</G2>26</F2>25</E2>24</D2>23</C2>22</B2>21</A2>");
tw.WriteLine("</J1>19</I1>18</H1>17</G1>16</F1>15</E1>14</D1>13</C1>12</B1>11</A1>");
tw.Write("</J>9</I>8</H>7</G>6</F>5</E>4</D>3</C>2</B>1</A>");
tw.WriteLine("<EMPTY4 val=\"abc\"></EMPTY4>");
tw.WriteLine("<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>");
tw.WriteLine("<DUMMY />");
tw.WriteLine("<MULTISPACES att=' \r\n \t \r\r\n n1 \r\n \t \r\r\n n2 \r\n \t \r\r\n ' />");
tw.WriteLine("<CAT>AB<![CDATA[CD]]> </CAT>");
tw.WriteLine("<CATMIXED>AB<![CDATA[CD]]> </CATMIXED>");
tw.WriteLine("<VALIDXMLLANG0 xml:lang=\"a\" />");
tw.WriteLine("<VALIDXMLLANG1 xml:lang=\"\" />");
tw.WriteLine("<VALIDXMLLANG2 xml:lang=\"ab-cd-\" />");
tw.WriteLine("<VALIDXMLLANG3 xml:lang=\"a b-cd\" />");
tw.Write("</PLAY>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateInvalidDTDTestFile(string strFileName)
{
}
public static void CreateValidDTDTestFile(string strFileName)
{
}
public static void CreateWellFormedDTDTestFile(string strFileName)
{
}
public static void CreateNonWellFormedDTDTestFile(string strFileName)
{
}
public static void CreateInvWellFormedDTDTestFile(string strFileName)
{
}
public static void CreateInvalidXMLXDRTestFile(string strFileName)
{
}
public static void CreateXDRXMLTestFile(string strFileName)
{
}
public static void CreateXDRTestFile(string strFileName)
{
}
public static void CreateInvalidNamespaceTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar1:check>Namespace=1</bar1:check></NAMESPACE0>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateNamespaceTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<DOCNAMESPACE>");
tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>");
tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check></d></c></b></a></NAMESPACE1>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />");
tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />");
tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>");
tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">");
tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>");
tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>");
tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>");
tw.WriteLine("</DOCNAMESPACE>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateXmlLangTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<PGROUP>");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<PERSONA>DROMIO OF SYRACUSE</PERSONA>");
tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>");
tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>");
tw.WriteLine("<NOXMLLANG />");
tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />");
tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>");
tw.WriteLine("<DONEXMLLANG />");
tw.WriteLine("</PGROUP>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateXmlSpaceTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<PGROUP>");
tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>");
tw.WriteLine("<PERSONA>DROMIO OF SYRACUSE</PERSONA>");
tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>< ></XMLSPACE1>");
tw.Write("<XMLSPACE2 xml:space=\'preserve\'>< ><a><b><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>");
tw.WriteLine("<NOSPACE />");
tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />");
tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>< <XMLSPACE3 xml:space=\'preserve\'> < > <XMLSPACE4 xml:space=\'default\'> < > </XMLSPACE4> test </XMLSPACE3> ></XMLSPACE2A>");
tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>");
tw.WriteLine("</PGROUP>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateJunkTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
string str = new String('Z', (1 << 20) - 1);
tw.Write(str);
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateBase64TestFile(string strFileName)
{
byte[] Wbase64 = new byte[2048];
int Wbase64len = 0;
byte[] WNumOnly = new byte[1024];
int WNumOnlylen = 0;
byte[] WTextOnly = new byte[1024];
int WTextOnlylen = 0;
int i = 0;
for (i = 0; i < strBase64.Length; i++)
{
WriteToBuffer(ref Wbase64, ref Wbase64len, System.BitConverter.GetBytes(strBase64[i]));
}
for (i = 52; i < strBase64.Length; i++)
{
WriteToBuffer(ref WNumOnly, ref WNumOnlylen, System.BitConverter.GetBytes(strBase64[i]));
}
for (i = 0; i < strBase64.Length - 12; i++)
{
WriteToBuffer(ref WTextOnly, ref WTextOnlylen, System.BitConverter.GetBytes(strBase64[i]));
}
MemoryStream mems = new MemoryStream();
XmlWriter w = XmlWriter.Create(mems, null);
w.WriteStartDocument();
w.WriteStartElement("Root");
w.WriteStartElement("ElemAll");
w.WriteBase64(Wbase64, 0, (int)Wbase64len);
w.WriteEndElement();
w.WriteStartElement("ElemEmpty");
w.WriteString(String.Empty);
w.WriteEndElement();
w.WriteStartElement("ElemNum");
w.WriteBase64(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemText");
w.WriteBase64(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemNumText");
w.WriteBase64(WTextOnly, 0, (int)WTextOnlylen);
w.WriteBase64(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemLong");
for (i = 0; i < 10; i++)
w.WriteBase64(Wbase64, 0, (int)Wbase64len);
w.WriteEndElement();
w.WriteElementString("ElemErr", "a&AQID");
w.WriteStartElement("ElemMixed");
w.WriteRaw("D2BAa<MIX></MIX>AQID");
w.WriteEndElement();
w.WriteEndElement();
w.Flush();
FilePathUtil.addStream(strFileName, mems);
}
public static void CreateBinHexTestFile(string strFileName)
{
byte[] Wbinhex = new byte[2000];
int Wbinhexlen = 0;
byte[] WNumOnly = new byte[2000];
int WNumOnlylen = 0;
byte[] WTextOnly = new byte[2000];
int WTextOnlylen = 0;
int i = 0;
for (i = 0; i < strBinHex.Length; i++)
{
WriteToBuffer(ref Wbinhex, ref Wbinhexlen, System.BitConverter.GetBytes(strBinHex[i]));
}
for (i = 0; i < 10; i++)
{
WriteToBuffer(ref WNumOnly, ref WNumOnlylen, System.BitConverter.GetBytes(strBinHex[i]));
}
for (i = 10; i < strBinHex.Length; i++)
{
WriteToBuffer(ref WTextOnly, ref WTextOnlylen, System.BitConverter.GetBytes(strBinHex[i]));
}
MemoryStream mems = new MemoryStream();
XmlWriter w = XmlWriter.Create(mems);
w.WriteStartElement("Root");
w.WriteStartElement("ElemAll");
w.WriteBinHex(Wbinhex, 0, (int)Wbinhexlen);
w.WriteEndElement();
w.Flush();
w.WriteStartElement("ElemEmpty");
w.WriteString(String.Empty);
w.WriteEndElement();
w.WriteStartElement("ElemNum");
w.WriteBinHex(WNumOnly, 0, (int)WNumOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemText");
w.WriteBinHex(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemNumText");
w.WriteBinHex(WNumOnly, 0, (int)WNumOnlylen);
w.WriteBinHex(WTextOnly, 0, (int)WTextOnlylen);
w.WriteEndElement();
w.WriteStartElement("ElemLong");
for (i = 0; i < 10; i++)
w.WriteBinHex(Wbinhex, 0, (int)Wbinhexlen);
w.WriteEndElement();
w.WriteElementString("ElemErr", "a&A2A3");
w.WriteEndElement();
w.Flush();
FilePathUtil.addStream(strFileName, mems);
}
public static void CreateBigElementTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
string str = new String('Z', (1 << 20) - 1);
tw.WriteLine("<Root>");
tw.Write("<");
tw.Write(str);
tw.WriteLine("X />");
tw.Flush();
tw.Write("<");
tw.Write(str);
tw.WriteLine("Y />");
tw.WriteLine("</Root>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateXSLTStyleSheetWCopyTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
tw.WriteLine("<xsl:template match=\"/\">");
tw.WriteLine("<xsl:copy-of select=\"/\" />");
tw.WriteLine("</xsl:template>");
tw.WriteLine("</xsl:stylesheet>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateConstructorTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
tw.WriteLine("<?xml version=\"1.0\"?>");
tw.WriteLine("<ROOT>");
tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />");
tw.Write("</ROOT>");
tw.Flush();
FilePathUtil.addStream(strFileName, s);
}
public static void CreateLineNumberTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
FilePathUtil.addStream(strFileName, s);
}
public static void CreateLbNormalizationTestFile(string strFileName)
{
Stream s = new MemoryStream();
TextWriter tw = new StreamWriter(s);
FilePathUtil.addStream(strFileName, s);
}
public static void CreateBinaryTestFile(string strFileName)
{
}
public static void ensureSpace(ref byte[] buffer, int len)
{
if (len >= buffer.Length)
{
int originalLen = buffer.Length;
byte[] newBuffer = new byte[(len * 2)];
for (uint i = 0; i < originalLen; newBuffer[i] = buffer[i++])
{
// Intentionally Empty
}
buffer = newBuffer;
}
}
public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte srcByte)
{
ensureSpace(ref destBuff, len);
destBuff[len++] = srcByte;
return;
}
public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte[] srcBuff)
{
int srcArrayLen = srcBuff.Length;
WriteToBuffer(ref destBuff, ref len, srcBuff, 0, srcArrayLen);
return;
}
public static void WriteToBuffer(ref byte[] destBuff, ref int destStart, byte[] srcBuff, int srcStart, int count)
{
ensureSpace(ref destBuff, destStart + count - 1);
for (int i = srcStart; i < srcStart + count; i++)
{
destBuff[destStart++] = srcBuff[i];
}
}
public static void WriteToBuffer(ref byte[] destBuffer, ref int destBuffLen, String strValue)
{
for (int i = 0; i < strValue.Length; i++)
{
WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes(strValue[i]));
}
WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes('\0'));
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Parallel\Testing\Tcl\TestExtrudePiece.tcl
// output file is AVTestExtrudePiece.cs
/// <summary>
/// The testing class derived from AVTestExtrudePiece
/// </summary>
public class AVTestExtrudePieceClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTestExtrudePiece(String [] argv)
{
//Prefix Content is: ""
disk = new vtkDiskSource();
disk.SetRadialResolution((int)2);
disk.SetCircumferentialResolution((int)9);
clean = new vtkCleanPolyData();
clean.SetInputConnection((vtkAlgorithmOutput)disk.GetOutputPort());
clean.SetTolerance((double)0.01);
piece = new vtkExtractPolyDataPiece();
piece.SetInputConnection((vtkAlgorithmOutput)clean.GetOutputPort());
extrude = new vtkPLinearExtrusionFilter();
extrude.SetInputConnection((vtkAlgorithmOutput)piece.GetOutputPort());
extrude.PieceInvariantOn();
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection((vtkAlgorithmOutput)extrude.GetOutputPort());
mapper.SetNumberOfPieces((int)2);
mapper.SetPiece((int)1);
bf = new vtkProperty();
bf.SetColor((double)1,(double)0,(double)0);
actor = new vtkActor();
actor.SetMapper((vtkMapper)mapper);
actor.GetProperty().SetColor((double)1,(double)1,(double)0.8);
actor.SetBackfaceProperty((vtkProperty)bf);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)actor);
ren1.SetBackground((double)0.1,(double)0.2,(double)0.4);
renWin.SetSize((int)300,(int)300);
// render the image[]
//[]
cam1 = ren1.GetActiveCamera();
cam1.Azimuth((double)20);
cam1.Elevation((double)40);
ren1.ResetCamera();
cam1.Zoom((double)1.2);
iren.Initialize();
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkDiskSource disk;
static vtkCleanPolyData clean;
static vtkExtractPolyDataPiece piece;
static vtkPLinearExtrusionFilter extrude;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkPolyDataMapper mapper;
static vtkProperty bf;
static vtkActor actor;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDiskSource Getdisk()
{
return disk;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdisk(vtkDiskSource toSet)
{
disk = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCleanPolyData Getclean()
{
return clean;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setclean(vtkCleanPolyData toSet)
{
clean = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractPolyDataPiece Getpiece()
{
return piece;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpiece(vtkExtractPolyDataPiece toSet)
{
piece = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPLinearExtrusionFilter Getextrude()
{
return extrude;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setextrude(vtkPLinearExtrusionFilter toSet)
{
extrude = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkProperty Getbf()
{
return bf;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setbf(vtkProperty toSet)
{
bf = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getactor()
{
return actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor(vtkActor toSet)
{
actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(disk!= null){disk.Dispose();}
if(clean!= null){clean.Dispose();}
if(piece!= null){piece.Dispose();}
if(extrude!= null){extrude.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(mapper!= null){mapper.Dispose();}
if(bf!= null){bf.Dispose();}
if(actor!= null){actor.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
namespace NLog.UnitTests.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NLog.Common;
using Xunit;
using Xunit.Extensions;
public class InternalLoggerTests_Trace : NLogTestBase
{
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Equal(0, mockTraceListener.Messages.Count);
}
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Equal(0, mockTraceListener.Messages.Count);
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace);
InternalLogger.Debug("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace);
InternalLogger.Info("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace);
InternalLogger.Warn("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace);
InternalLogger.Error("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace);
InternalLogger.Fatal("Logger1 Hello");
Assert.Equal(1, mockTraceListener.Messages.Count);
Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")]
public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener()
{
SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null);
Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException"));
}
/// <summary>
/// Helper method to setup tests configuration
/// </summary>
/// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param>
/// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param>
/// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param>
/// <returns><see cref="TraceListener"/> instance.</returns>
private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener
{
var internalLogToTraceAttribute = "";
if (internalLogToTrace.HasValue)
{
internalLogToTraceAttribute = string.Format(" internalLogToTrace='{0}'", internalLogToTrace.Value);
}
var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute);
LogManager.Configuration = CreateConfigurationFromString(xmlConfiguration);
InternalLogger.IncludeTimestamp = false;
if (logToTrace.HasValue)
{
InternalLogger.LogToTrace = logToTrace.Value;
}
T traceListener;
if (typeof (T) == typeof (MockTraceListener))
{
traceListener = CreateMockTraceListener() as T;
}
else
{
traceListener = CreateNLogTraceListener() as T;
}
Trace.Listeners.Clear();
if (traceListener == null)
{
return null;
}
Trace.Listeners.Add(traceListener);
return traceListener;
}
private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}>
<targets>
<target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/>
</targets>
<rules>
<logger name='*' level='{0}' writeTo='debug'/>
</rules>
</nlog>";
/// <summary>
/// Creates <see cref="MockTraceListener"/> instance.
/// </summary>
/// <returns><see cref="MockTraceListener"/> instance.</returns>
private static MockTraceListener CreateMockTraceListener()
{
return new MockTraceListener();
}
/// <summary>
/// Creates <see cref="NLogTraceListener"/> instance.
/// </summary>
/// <returns><see cref="NLogTraceListener"/> instance.</returns>
private static NLogTraceListener CreateNLogTraceListener()
{
return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace};
}
private class MockTraceListener : TraceListener
{
internal readonly List<string> Messages = new List<string>();
/// <summary>
/// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
/// </summary>
/// <param name="message">A message to write. </param>
public override void Write(string message)
{
Messages.Add(message);
}
/// <summary>
/// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
/// </summary>
/// <param name="message">A message to write. </param>
public override void WriteLine(string message)
{
Messages.Add(message + Environment.NewLine);
}
}
}
}
#endif
| |
#region Copyright
// Copyright 2016 Patrice Thivierge F.
//
// 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.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace NewApp.Core.SettingsMgmt
{
/// <summary>
/// Provides methods for reading and writing to an INI file.
/// <see cref="http://www.codeproject.com/Articles/20053/A-Complete-Win-INI-File-Utility-Class"/>
/// License:
/// The Code Project Open License (CPOL) 1.02
/// <see cref="http://www.codeproject.com/info/cpol10.aspx"/>
/// </summary>
public class IniFile
{
/// <summary>
/// The maximum size of a section in an ini file.
/// </summary>
/// <remarks>
/// This property defines the maximum size of the buffers
/// used to retreive data from an ini file. This value is
/// the maximum allowed by the win32 functions
/// GetPrivateProfileSectionNames() or
/// GetPrivateProfileString().
/// </remarks>
public const int MaxSectionSize = 32767; // 32 KB
//The path of the file we are operating on.
private readonly string m_path;
#region P/Invoke declares
/// <summary>
/// A static class that provides the win32 P/Invoke signatures
/// used by this class.
/// </summary>
/// <remarks>
/// Note: In each of the declarations below, we explicitly set CharSet to
/// Auto. By default in C#, CharSet is set to Ansi, which reduces
/// performance on windows 2000 and above due to needing to convert strings
/// from Unicode (the native format for all .Net strings) to Ansi before
/// marshalling. Using Auto lets the marshaller select the Unicode version of
/// these functions when available.
/// </remarks>
[SuppressUnmanagedCodeSecurity]
private static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer,
uint nSize,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern uint GetPrivateProfileString(string lpAppName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
int nSize,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern uint GetPrivateProfileString(string lpAppName,
string lpKeyName,
string lpDefault,
[In, Out] char[] lpReturnedString,
int nSize,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileString(string lpAppName,
string lpKeyName,
string lpDefault,
IntPtr lpReturnedString,
uint nSize,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileInt(string lpAppName,
string lpKeyName,
int lpDefault,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileSection(string lpAppName,
IntPtr lpReturnedString,
uint nSize,
string lpFileName);
//We explicitly enable the SetLastError attribute here because
// WritePrivateProfileString returns errors via SetLastError.
// Failure to set this can result in errors being lost during
// the marshal back to managed code.
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool WritePrivateProfileString(string lpAppName,
string lpKeyName,
string lpString,
string lpFileName);
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="IniFile" /> class.
/// </summary>
/// <param name="path">The ini file to read and write from.</param>
public IniFile(string path)
{
//Convert to the full path. Because of backward compatibility,
// the win32 functions tend to assume the path should be the
// root Windows directory if it is not specified. By calling
// GetFullPath, we make sure we are always passing the full path
// the win32 functions.
m_path = System.IO.Path.GetFullPath(path);
}
/// <summary>
/// Gets the full path of ini file this object instance is operating on.
/// </summary>
/// <value>A file path.</value>
public string Path
{
get { return m_path; }
}
#region Get Value Methods
/// <summary>
/// Gets the value of a setting in an ini file as a <see cref="T:System.String" />.
/// </summary>
/// <param name="sectionName">The name of the section to read from.</param>
/// <param name="keyName">The name of the key in section to read.</param>
/// <param name="defaultValue">
/// The default value to return if the key
/// cannot be found.
/// </param>
/// <returns>
/// The value of the key, if found. Otherwise, returns
/// <paramref name="defaultValue" />
/// </returns>
/// <remarks>
/// The retreived value must be less than 32KB in length.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public string GetString(string sectionName,
string keyName,
string defaultValue)
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
if (keyName == null)
throw new ArgumentNullException("keyName");
var retval = new StringBuilder(MaxSectionSize);
NativeMethods.GetPrivateProfileString(sectionName,
keyName,
defaultValue,
retval,
MaxSectionSize,
m_path);
return retval.ToString();
}
/// <summary>
/// Gets the value of a setting in an ini file as a <see cref="T:System.Int16" />.
/// </summary>
/// <param name="sectionName">The name of the section to read from.</param>
/// <param name="keyName">The name of the key in section to read.</param>
/// <param name="defaultValue">
/// The default value to return if the key
/// cannot be found.
/// </param>
/// <returns>
/// The value of the key, if found. Otherwise, returns
/// <paramref name="defaultValue" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public int GetInt16(string sectionName,
string keyName,
short defaultValue)
{
int retval = GetInt32(sectionName, keyName, defaultValue);
return Convert.ToInt16(retval);
}
/// <summary>
/// Gets the value of a setting in an ini file as a <see cref="T:System.Int32" />.
/// </summary>
/// <param name="sectionName">The name of the section to read from.</param>
/// <param name="keyName">The name of the key in section to read.</param>
/// <param name="defaultValue">
/// The default value to return if the key
/// cannot be found.
/// </param>
/// <returns>
/// The value of the key, if found. Otherwise, returns
/// <paramref name="defaultValue" />
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public int GetInt32(string sectionName,
string keyName,
int defaultValue)
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
if (keyName == null)
throw new ArgumentNullException("keyName");
return NativeMethods.GetPrivateProfileInt(sectionName, keyName, defaultValue, m_path);
}
/// <summary>
/// Gets the value of a setting in an ini file as a <see cref="T:System.Double" />.
/// </summary>
/// <param name="sectionName">The name of the section to read from.</param>
/// <param name="keyName">The name of the key in section to read.</param>
/// <param name="defaultValue">
/// The default value to return if the key
/// cannot be found.
/// </param>
/// <returns>
/// The value of the key, if found. Otherwise, returns
/// <paramref name="defaultValue" />
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public double GetDouble(string sectionName,
string keyName,
double defaultValue)
{
string retval = GetString(sectionName, keyName, "");
if (retval == null || retval.Length == 0)
{
return defaultValue;
}
return Convert.ToDouble(retval, CultureInfo.InvariantCulture);
}
#endregion
#region GetSectionValues Methods
/// <summary>
/// Gets all of the values in a section as a list.
/// </summary>
/// <param name="sectionName">
/// Name of the section to retrieve values from.
/// </param>
/// <returns>
/// A <see cref="List{T}" /> containing <see cref="KeyValuePair{T1, T2}" /> objects
/// that describe this section. Use this verison if a section may contain
/// multiple items with the same key value. If you know that a section
/// cannot contain multiple values with the same key name or you don't
/// care about the duplicates, use the more convenient
/// <see cref="GetSectionValues" /> function.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> is a null reference (Nothing in VB)
/// </exception>
public List<KeyValuePair<string, string>> GetSectionValuesAsList(string sectionName)
{
List<KeyValuePair<string, string>> retval;
string[] keyValuePairs;
string key, value;
int equalSignPos;
if (sectionName == null)
throw new ArgumentNullException("sectionName");
//Allocate a buffer for the returned section names.
IntPtr ptr = Marshal.AllocCoTaskMem(MaxSectionSize);
try
{
//Get the section key/value pairs into the buffer.
int len = NativeMethods.GetPrivateProfileSection(sectionName,
ptr,
MaxSectionSize,
m_path);
keyValuePairs = ConvertNullSeperatedStringToStringArray(ptr, len);
}
finally
{
//Free the buffer
Marshal.FreeCoTaskMem(ptr);
}
//Parse keyValue pairs and add them to the list.
retval = new List<KeyValuePair<string, string>>(keyValuePairs.Length);
for (int i = 0; i < keyValuePairs.Length; ++i)
{
//Parse the "key=value" string into its constituent parts
equalSignPos = keyValuePairs[i].IndexOf('=');
key = keyValuePairs[i].Substring(0, equalSignPos);
value = keyValuePairs[i].Substring(equalSignPos + 1,
keyValuePairs[i].Length - equalSignPos - 1);
retval.Add(new KeyValuePair<string, string>(key, value));
}
return retval;
}
/// <summary>
/// Gets all of the values in a section as a dictionary.
/// </summary>
/// <param name="sectionName">
/// Name of the section to retrieve values from.
/// </param>
/// <returns>
/// A <see cref="Dictionary{T, T}" /> containing the key/value
/// pairs found in this section.
/// </returns>
/// <remarks>
/// If a section contains more than one key with the same name,
/// this function only returns the first instance. If you need to
/// get all key/value pairs within a section even when keys have the
/// same name, use <see cref="GetSectionValuesAsList" />.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> is a null reference (Nothing in VB)
/// </exception>
public Dictionary<string, string> GetSectionValues(string sectionName)
{
List<KeyValuePair<string, string>> keyValuePairs;
Dictionary<string, string> retval;
keyValuePairs = GetSectionValuesAsList(sectionName);
//Convert list into a dictionary.
retval = new Dictionary<string, string>(keyValuePairs.Count);
foreach (var keyValuePair in keyValuePairs)
{
//Skip any key we have already seen.
if (!retval.ContainsKey(keyValuePair.Key))
{
retval.Add(keyValuePair.Key, keyValuePair.Value);
}
}
return retval;
}
#endregion
#region Get Key/Section Names
/// <summary>
/// Gets the names of all keys under a specific section in the ini file.
/// </summary>
/// <param name="sectionName">
/// The name of the section to read key names from.
/// </param>
/// <returns>An array of key names.</returns>
/// <remarks>
/// The total length of all key names in the section must be
/// less than 32KB in length.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> is a null reference (Nothing in VB)
/// </exception>
public string[] GetKeyNames(string sectionName)
{
int len;
string[] retval;
if (sectionName == null)
throw new ArgumentNullException("sectionName");
//Allocate a buffer for the returned section names.
IntPtr ptr = Marshal.AllocCoTaskMem(MaxSectionSize);
try
{
//Get the section names into the buffer.
len = NativeMethods.GetPrivateProfileString(sectionName,
null,
null,
ptr,
MaxSectionSize,
m_path);
retval = ConvertNullSeperatedStringToStringArray(ptr, len);
}
finally
{
//Free the buffer
Marshal.FreeCoTaskMem(ptr);
}
return retval;
}
/// <summary>
/// Gets the names of all sections in the ini file.
/// </summary>
/// <returns>An array of section names.</returns>
/// <remarks>
/// The total length of all section names in the section must be
/// less than 32KB in length.
/// </remarks>
public string[] GetSectionNames()
{
string[] retval;
int len;
//Allocate a buffer for the returned section names.
IntPtr ptr = Marshal.AllocCoTaskMem(MaxSectionSize);
try
{
//Get the section names into the buffer.
len = NativeMethods.GetPrivateProfileSectionNames(ptr,
MaxSectionSize, m_path);
retval = ConvertNullSeperatedStringToStringArray(ptr, len);
}
finally
{
//Free the buffer
Marshal.FreeCoTaskMem(ptr);
}
return retval;
}
/// <summary>
/// Converts the null seperated pointer to a string into a string array.
/// </summary>
/// <param name="ptr">A pointer to string data.</param>
/// <param name="valLength">
/// Length of the data pointed to by <paramref name="ptr" />.
/// </param>
/// <returns>
/// An array of strings; one for each null found in the array of characters pointed
/// at by <paramref name="ptr" />.
/// </returns>
private static string[] ConvertNullSeperatedStringToStringArray(IntPtr ptr, int valLength)
{
string[] retval;
if (valLength == 0)
{
//Return an empty array.
retval = new string[0];
}
else
{
//Convert the buffer into a string. Decrease the length
//by 1 so that we remove the second null off the end.
string buff = Marshal.PtrToStringAuto(ptr, valLength - 1);
//Parse the buffer into an array of strings by searching for nulls.
retval = buff.Split('\0');
}
return retval;
}
#endregion
#region Write Methods
/// <summary>
/// Writes a <see cref="T:System.String" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The string value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
private void WriteValueInternal(string sectionName, string keyName, string value)
{
if (!NativeMethods.WritePrivateProfileString(sectionName, keyName, value, m_path))
{
throw new Win32Exception();
}
}
/// <summary>
/// Writes a <see cref="T:System.String" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The string value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> or
/// <paramref name="value" /> are a null reference (Nothing in VB)
/// </exception>
public void WriteValue(string sectionName, string keyName, string value)
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
if (keyName == null)
throw new ArgumentNullException("keyName");
if (value == null)
throw new ArgumentNullException("value");
WriteValueInternal(sectionName, keyName, value);
}
/// <summary>
/// Writes an <see cref="T:System.Int16" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
public void WriteValue(string sectionName, string keyName, short value)
{
WriteValue(sectionName, keyName, (int) value);
}
/// <summary>
/// Writes an <see cref="T:System.Int32" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public void WriteValue(string sectionName, string keyName, int value)
{
WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an <see cref="T:System.Single" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public void WriteValue(string sectionName, string keyName, float value)
{
WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Writes an <see cref="T:System.Double" /> value to the ini file.
/// </summary>
/// <param name="sectionName">The name of the section to write to .</param>
/// <param name="keyName">The name of the key to write to.</param>
/// <param name="value">The value to write</param>
/// <exception cref="T:System.ComponentModel.Win32Exception">
/// The write failed.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public void WriteValue(string sectionName, string keyName, double value)
{
WriteValue(sectionName, keyName, value.ToString(CultureInfo.InvariantCulture));
}
#endregion
#region Delete Methods
/// <summary>
/// Deletes the specified key from the specified section.
/// </summary>
/// <param name="sectionName">
/// Name of the section to remove the key from.
/// </param>
/// <param name="keyName">
/// Name of the key to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> or <paramref name="keyName" /> are
/// a null reference (Nothing in VB)
/// </exception>
public void DeleteKey(string sectionName, string keyName)
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
if (keyName == null)
throw new ArgumentNullException("keyName");
WriteValueInternal(sectionName, keyName, null);
}
/// <summary>
/// Deletes a section from the ini file.
/// </summary>
/// <param name="sectionName">
/// Name of the section to delete.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="sectionName" /> is a null reference (Nothing in VB)
/// </exception>
public void DeleteSection(string sectionName)
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
WriteValueInternal(sectionName, null, null);
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - 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 Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.Generic;
using System.Text;
namespace WebsitePanel.Providers.HostedSolution
{
public class ExchangeContact
{
string displayName;
string accountName;
string emailAddress;
bool hideFromAddressBook;
string firstName;
string initials;
string lastName;
string jobTitle;
string company;
string department;
string office;
ExchangeAccount managerAccount;
string businessPhone;
string fax;
string homePhone;
string mobilePhone;
string pager;
string webPage;
string address;
string city;
string state;
string zip;
string country;
string notes;
string sAMAccountName;
private int useMapiRichTextFormat;
ExchangeAccount[] acceptAccounts;
ExchangeAccount[] rejectAccounts;
bool requireSenderAuthentication;
[LogProperty]
public string DisplayName
{
get { return this.displayName; }
set { this.displayName = value; }
}
[LogProperty]
public string AccountName
{
get { return this.accountName; }
set { this.accountName = value; }
}
[LogProperty]
public string EmailAddress
{
get { return this.emailAddress; }
set { this.emailAddress = value; }
}
public bool HideFromAddressBook
{
get { return this.hideFromAddressBook; }
set { this.hideFromAddressBook = value; }
}
public string FirstName
{
get { return this.firstName; }
set { this.firstName = value; }
}
public string Initials
{
get { return this.initials; }
set { this.initials = value; }
}
public string LastName
{
get { return this.lastName; }
set { this.lastName = value; }
}
public string JobTitle
{
get { return this.jobTitle; }
set { this.jobTitle = value; }
}
public string Company
{
get { return this.company; }
set { this.company = value; }
}
public string Department
{
get { return this.department; }
set { this.department = value; }
}
public string Office
{
get { return this.office; }
set { this.office = value; }
}
public ExchangeAccount ManagerAccount
{
get { return this.managerAccount; }
set { this.managerAccount = value; }
}
public string BusinessPhone
{
get { return this.businessPhone; }
set { this.businessPhone = value; }
}
public string Fax
{
get { return this.fax; }
set { this.fax = value; }
}
public string HomePhone
{
get { return this.homePhone; }
set { this.homePhone = value; }
}
public string MobilePhone
{
get { return this.mobilePhone; }
set { this.mobilePhone = value; }
}
public string Pager
{
get { return this.pager; }
set { this.pager = value; }
}
public string WebPage
{
get { return this.webPage; }
set { this.webPage = value; }
}
public string Address
{
get { return this.address; }
set { this.address = value; }
}
public string City
{
get { return this.city; }
set { this.city = value; }
}
public string State
{
get { return this.state; }
set { this.state = value; }
}
public string Zip
{
get { return this.zip; }
set { this.zip = value; }
}
public string Country
{
get { return this.country; }
set { this.country = value; }
}
public string Notes
{
get { return this.notes; }
set { this.notes = value; }
}
public ExchangeAccount[] AcceptAccounts
{
get { return this.acceptAccounts; }
set { this.acceptAccounts = value; }
}
public ExchangeAccount[] RejectAccounts
{
get { return this.rejectAccounts; }
set { this.rejectAccounts = value; }
}
public bool RequireSenderAuthentication
{
get { return requireSenderAuthentication; }
set { requireSenderAuthentication = value; }
}
public int UseMapiRichTextFormat
{
get { return useMapiRichTextFormat; }
set { useMapiRichTextFormat = value; }
}
[LogProperty]
public string SAMAccountName
{
get { return sAMAccountName; }
set { sAMAccountName = value; }
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs
{
partial class RelatedFormDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RelatedFormDialog));
this.Button19 = new System.Windows.Forms.Button();
this.Button18 = new System.Windows.Forms.Button();
this.Button17 = new System.Windows.Forms.Button();
this.Button16 = new System.Windows.Forms.Button();
this.Button15 = new System.Windows.Forms.Button();
this.Button14 = new System.Windows.Forms.Button();
this.Button13 = new System.Windows.Forms.Button();
this.Button12 = new System.Windows.Forms.Button();
this.Button11 = new System.Windows.Forms.Button();
this.Button10 = new System.Windows.Forms.Button();
this.Button9 = new System.Windows.Forms.Button();
this.Button8 = new System.Windows.Forms.Button();
this.Button7 = new System.Windows.Forms.Button();
this.Button6 = new System.Windows.Forms.Button();
this.Button5 = new System.Windows.Forms.Button();
this.Button4 = new System.Windows.Forms.Button();
this.ComboBox1 = new System.Windows.Forms.ComboBox();
this.Label2 = new System.Windows.Forms.Label();
this.TextBox1 = new System.Windows.Forms.TextBox();
this.Label1 = new System.Windows.Forms.Label();
this.CheckBox2 = new System.Windows.Forms.CheckBox();
this.CheckBox1 = new System.Windows.Forms.CheckBox();
this.Button3 = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.Button1 = new System.Windows.Forms.Button();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.RadioButton2 = new System.Windows.Forms.RadioButton();
this.RadioButton1 = new System.Windows.Forms.RadioButton();
this.GroupBox1.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
//
// Button19
//
resources.ApplyResources(this.Button19, "Button19");
this.Button19.Name = "Button19";
//
// Button18
//
resources.ApplyResources(this.Button18, "Button18");
this.Button18.Name = "Button18";
//
// Button17
//
resources.ApplyResources(this.Button17, "Button17");
this.Button17.Name = "Button17";
//
// Button16
//
resources.ApplyResources(this.Button16, "Button16");
this.Button16.Name = "Button16";
//
// Button15
//
resources.ApplyResources(this.Button15, "Button15");
this.Button15.Name = "Button15";
//
// Button14
//
resources.ApplyResources(this.Button14, "Button14");
this.Button14.Name = "Button14";
//
// Button13
//
resources.ApplyResources(this.Button13, "Button13");
this.Button13.Name = "Button13";
//
// Button12
//
resources.ApplyResources(this.Button12, "Button12");
this.Button12.Name = "Button12";
//
// Button11
//
resources.ApplyResources(this.Button11, "Button11");
this.Button11.Name = "Button11";
//
// Button10
//
resources.ApplyResources(this.Button10, "Button10");
this.Button10.Name = "Button10";
//
// Button9
//
resources.ApplyResources(this.Button9, "Button9");
this.Button9.Name = "Button9";
//
// Button8
//
resources.ApplyResources(this.Button8, "Button8");
this.Button8.Name = "Button8";
//
// Button7
//
resources.ApplyResources(this.Button7, "Button7");
this.Button7.Name = "Button7";
//
// Button6
//
resources.ApplyResources(this.Button6, "Button6");
this.Button6.Name = "Button6";
//
// Button5
//
resources.ApplyResources(this.Button5, "Button5");
this.Button5.Name = "Button5";
//
// Button4
//
resources.ApplyResources(this.Button4, "Button4");
this.Button4.Name = "Button4";
//
// ComboBox1
//
resources.ApplyResources(this.ComboBox1, "ComboBox1");
this.ComboBox1.Name = "ComboBox1";
//
// Label2
//
resources.ApplyResources(this.Label2, "Label2");
this.Label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.Label2.Name = "Label2";
//
// TextBox1
//
resources.ApplyResources(this.TextBox1, "TextBox1");
this.TextBox1.Name = "TextBox1";
//
// Label1
//
resources.ApplyResources(this.Label1, "Label1");
this.Label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.Label1.Name = "Label1";
//
// CheckBox2
//
resources.ApplyResources(this.CheckBox2, "CheckBox2");
this.CheckBox2.Name = "CheckBox2";
//
// CheckBox1
//
resources.ApplyResources(this.CheckBox1, "CheckBox1");
this.CheckBox1.Name = "CheckBox1";
//
// Button3
//
resources.ApplyResources(this.Button3, "Button3");
this.Button3.Name = "Button3";
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// Button1
//
resources.ApplyResources(this.Button1, "Button1");
this.Button1.Name = "Button1";
//
// GroupBox1
//
this.GroupBox1.Controls.Add(this.RadioButton2);
this.GroupBox1.Controls.Add(this.RadioButton1);
this.GroupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.GroupBox1, "GroupBox1");
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.TabStop = false;
//
// RadioButton2
//
resources.ApplyResources(this.RadioButton2, "RadioButton2");
this.RadioButton2.Name = "RadioButton2";
//
// RadioButton1
//
this.RadioButton1.Checked = true;
resources.ApplyResources(this.RadioButton1, "RadioButton1");
this.RadioButton1.Name = "RadioButton1";
this.RadioButton1.TabStop = true;
//
// RelatedFormDialog
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.Button19);
this.Controls.Add(this.Button18);
this.Controls.Add(this.Button17);
this.Controls.Add(this.Button16);
this.Controls.Add(this.Button15);
this.Controls.Add(this.Button14);
this.Controls.Add(this.Button13);
this.Controls.Add(this.Button12);
this.Controls.Add(this.Button11);
this.Controls.Add(this.Button10);
this.Controls.Add(this.Button9);
this.Controls.Add(this.Button8);
this.Controls.Add(this.Button7);
this.Controls.Add(this.Button6);
this.Controls.Add(this.Button5);
this.Controls.Add(this.Button4);
this.Controls.Add(this.ComboBox1);
this.Controls.Add(this.Label2);
this.Controls.Add(this.TextBox1);
this.Controls.Add(this.Label1);
this.Controls.Add(this.CheckBox2);
this.Controls.Add(this.CheckBox1);
this.Controls.Add(this.Button3);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.Button1);
this.Controls.Add(this.GroupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "RelatedFormDialog";
this.ShowInTaskbar = false;
this.GroupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Button19;
private System.Windows.Forms.Button Button18;
private System.Windows.Forms.Button Button17;
private System.Windows.Forms.Button Button16;
private System.Windows.Forms.Button Button15;
private System.Windows.Forms.Button Button14;
private System.Windows.Forms.Button Button13;
private System.Windows.Forms.Button Button12;
private System.Windows.Forms.Button Button11;
private System.Windows.Forms.Button Button10;
private System.Windows.Forms.Button Button9;
private System.Windows.Forms.Button Button8;
private System.Windows.Forms.Button Button7;
private System.Windows.Forms.Button Button6;
private System.Windows.Forms.Button Button5;
private System.Windows.Forms.Button Button4;
private System.Windows.Forms.ComboBox ComboBox1;
private System.Windows.Forms.Label Label2;
private System.Windows.Forms.TextBox TextBox1;
private System.Windows.Forms.Label Label1;
private System.Windows.Forms.CheckBox CheckBox2;
private System.Windows.Forms.CheckBox CheckBox1;
private System.Windows.Forms.Button Button3;
private System.Windows.Forms.Button Button1;
private System.Windows.Forms.GroupBox GroupBox1;
private System.Windows.Forms.RadioButton RadioButton2;
private System.Windows.Forms.RadioButton RadioButton1;
private System.Windows.Forms.Button btnCancel;
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MirrorSharp.Advanced;
using Mono.Cecil;
using Mono.Cecil.Cil;
using SharpLab.Runtime.Internal;
using SharpLab.Server.Common;
namespace SharpLab.Server.Execution.Internal {
public class FlowReportingRewriter : IAssemblyRewriter {
private const int HiddenLine = 0xFEEFEE;
private static readonly MethodInfo ReportLineStartMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportLineStart))!;
private static readonly MethodInfo ReportValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportValue))!;
private static readonly MethodInfo ReportRefValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportRefValue))!;
private static readonly MethodInfo ReportSpanValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportSpanValue))!;
private static readonly MethodInfo ReportRefSpanValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportRefSpanValue))!;
private static readonly MethodInfo ReportReadOnlySpanValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportReadOnlySpanValue))!;
private static readonly MethodInfo ReportRefReadOnlySpanValueMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportRefReadOnlySpanValue))!;
private static readonly MethodInfo ReportExceptionMethod =
typeof(Flow).GetMethod(nameof(Flow.ReportException))!;
private readonly IReadOnlyDictionary<string, ILanguageAdapter> _languages;
public FlowReportingRewriter(IReadOnlyList<ILanguageAdapter> languages) {
_languages = languages.ToDictionary(l => l.LanguageName);
}
public void Rewrite(AssemblyDefinition assembly, IWorkSession session) {
foreach (var module in assembly.Modules) {
foreach (var type in module.Types) {
if (HasFlowSupressingCalls(type))
return;
}
}
foreach (var module in assembly.Modules) {
var flow = new ReportMethods {
ReportLineStart = module.ImportReference(ReportLineStartMethod),
ReportValue = module.ImportReference(ReportValueMethod),
ReportRefValue = module.ImportReference(ReportRefValueMethod),
ReportSpanValue = module.ImportReference(ReportSpanValueMethod),
ReportRefSpanValue = module.ImportReference(ReportRefSpanValueMethod),
ReportReadOnlySpanValue = module.ImportReference(ReportReadOnlySpanValueMethod),
ReportRefReadOnlySpanValue = module.ImportReference(ReportRefReadOnlySpanValueMethod),
ReportException = module.ImportReference(ReportExceptionMethod),
};
foreach (var type in module.Types) {
Rewrite(type, flow, session);
}
}
}
private bool HasFlowSupressingCalls(TypeDefinition type) {
foreach (var method in type.Methods) {
if (!method.HasBody || method.Body.Instructions.Count == 0)
continue;
foreach (var instruction in method.Body.Instructions) {
if (instruction.OpCode.FlowControl == FlowControl.Call && IsFlowSuppressing((MethodReference)instruction.Operand))
return true;
}
}
foreach (var nested in type.NestedTypes) {
if (HasFlowSupressingCalls(nested))
return true;
}
return false;
}
private bool IsFlowSuppressing(MethodReference callee) {
return callee.Name == nameof(Inspect.Allocations)
&& callee.DeclaringType.Name == nameof(Inspect);
}
private void Rewrite(TypeDefinition type, ReportMethods flow, IWorkSession session) {
foreach (var method in type.Methods) {
Rewrite(method, flow, session);
}
foreach (var nested in type.NestedTypes) {
Rewrite(nested, flow, session);
}
}
private void Rewrite(MethodDefinition method, ReportMethods flow, IWorkSession session) {
if (!method.HasBody || method.Body.Instructions.Count == 0)
return;
var il = method.Body.GetILProcessor();
var instructions = il.Body.Instructions;
var lastLine = (int?)null;
for (var i = 0; i < instructions.Count; i++) {
var instruction = instructions[i];
var sequencePoint = method.DebugInformation?.GetSequencePoint(instruction);
var hasSequencePoint = sequencePoint != null && sequencePoint.StartLine != HiddenLine;
if (!hasSequencePoint && lastLine == null)
continue;
if (hasSequencePoint && sequencePoint!.StartLine != lastLine) {
if (i == 0)
TryInsertReportMethodArguments(il, instruction, sequencePoint, method, flow, session, ref i);
il.InsertBeforeAndRetargetAll(instruction, il.CreateLdcI4Best(sequencePoint.StartLine));
il.InsertBefore(instruction, il.CreateCall(flow.ReportLineStart));
i += 2;
lastLine = sequencePoint.StartLine;
}
var valueOrNull = GetValueToReport(instruction, il, session);
if (valueOrNull == null)
continue;
var value = valueOrNull.Value;
InsertReportValue(
il, instruction,
il.Create(OpCodes.Dup), value.type, value.name,
sequencePoint?.StartLine ?? lastLine ?? Flow.UnknownLineNumber,
flow, ref i
);
}
RewriteExceptionHandlers(il, flow);
}
private void TryInsertReportMethodArguments(ILProcessor il, Instruction instruction, SequencePoint sequencePoint, MethodDefinition method, ReportMethods flow, IWorkSession session, ref int index) {
if (!method.HasParameters)
return;
var parameterLines = _languages[session.LanguageName]
.GetMethodParameterLines(session, sequencePoint.StartLine, sequencePoint.StartColumn);
if (parameterLines.Length == 0)
return;
// Note: method parameter lines are unreliable and can potentially return
// wrong lines if nested method syntax is unrecognized and code matches it
// to the containing method. That is acceptable, as long as parameter count
// mismatch does not crash things -> so check length here.
if (parameterLines.Length != method.Parameters.Count)
return;
foreach (var parameter in method.Parameters) {
if (parameter.IsOut)
continue;
InsertReportValue(
il, instruction,
il.CreateLdargBest(parameter), parameter.ParameterType, parameter.Name,
parameterLines[parameter.Index], flow,
ref index
);
}
}
private (string name, TypeReference type)? GetValueToReport(Instruction instruction, ILProcessor il, IWorkSession session) {
var localIndex = GetIndexIfStloc(instruction);
if (localIndex != null) {
var variable = il.Body.Variables[localIndex.Value];
var symbols = il.Body.Method.DebugInformation;
if (symbols == null || !symbols.TryGetName(variable, out var variableName))
return null;
return (variableName, variable.VariableType);
}
if (instruction.OpCode.Code == Code.Ret) {
if (instruction.Previous?.Previous?.OpCode.Code == Code.Tail)
return null;
var returnType = il.Body.Method.ReturnType;
if (returnType.IsVoid())
return null;
return ("return", returnType);
}
return null;
}
private void InsertReportValue(
ILProcessor il,
Instruction instruction,
Instruction getValue,
TypeReference valueType,
string valueName,
int line,
ReportMethods flow,
ref int index
) {
il.InsertBefore(instruction, getValue);
il.InsertBefore(instruction, valueName != null ? il.Create(OpCodes.Ldstr, valueName) : il.Create(OpCodes.Ldnull));
il.InsertBefore(instruction, il.CreateLdcI4Best(line));
if (valueType is RequiredModifierType requiredType)
valueType = requiredType.ElementType; // not the same as GetElementType() which unwraps nested ref-types etc
var report = PrepareReportValue(valueType, flow.ReportValue, flow.ReportSpanValue, flow.ReportReadOnlySpanValue);
if (valueType is ByReferenceType byRef)
report = PrepareReportValue(byRef.ElementType, flow.ReportRefValue, flow.ReportRefSpanValue, flow.ReportRefReadOnlySpanValue);
il.InsertBefore(instruction, il.CreateCall(report));
index += 4;
}
private GenericInstanceMethod PrepareReportValue(TypeReference valueType, MethodReference reportAnyNonSpan, MethodReference reportSpan, MethodReference reportReadOnlySpan) {
if (valueType is GenericInstanceType generic) {
if (generic.ElementType.FullName == "System.Span`1")
return new GenericInstanceMethod(reportSpan) { GenericArguments = { generic.GenericArguments[0] } };
if (generic.ElementType.FullName == "System.ReadOnlySpan`1")
return new GenericInstanceMethod(reportReadOnlySpan) { GenericArguments = { generic.GenericArguments[0] } };
}
return new GenericInstanceMethod(reportAnyNonSpan) { GenericArguments = { valueType } };
}
private void RewriteExceptionHandlers(ILProcessor il, ReportMethods flow) {
if (!il.Body.HasExceptionHandlers)
return;
var handlers = il.Body.ExceptionHandlers;
for (var i = 0; i < handlers.Count; i++) {
switch (handlers[i].HandlerType) {
case ExceptionHandlerType.Catch:
RewriteCatch(handlers[i].HandlerStart, il, flow);
break;
case ExceptionHandlerType.Filter:
RewriteCatch(handlers[i].FilterStart, il, flow);
break;
case ExceptionHandlerType.Finally:
RewriteFinally(handlers[i], ref i, il, flow);
break;
}
}
}
private void RewriteCatch(Instruction start, ILProcessor il, ReportMethods flow) {
il.InsertBeforeAndRetargetAll(start, il.Create(OpCodes.Dup));
il.InsertBefore(start, il.CreateCall(flow.ReportException));
}
private void RewriteFinally(ExceptionHandler handler, ref int handlerIndex, ILProcessor il, ReportMethods flow) {
// for try/finally, the only thing we can do is to
// wrap internals of try into a new try+filter+catch
var outerTryLeave = handler.TryEnd.Previous;
if (!outerTryLeave.OpCode.Code.IsLeave()) {
// in some cases (e.g. exception throw) outer handler does
// not end with `leave` -- but we do need it once we wrap
// that throw
// if the handler is the last thing in the method
if (handler.HandlerEnd == null)
{
var finalReturn = il.Create(OpCodes.Ret);
il.Append(finalReturn);
handler.HandlerEnd = finalReturn;
}
outerTryLeave = il.Create(OpCodes.Leave, handler.HandlerEnd);
il.InsertBefore(handler.TryEnd, outerTryLeave);
}
var innerTryLeave = il.Create(OpCodes.Leave_S, outerTryLeave);
var reportCall = il.CreateCall(flow.ReportException);
var catchHandler = il.Create(OpCodes.Pop);
il.InsertBeforeAndRetargetAll(outerTryLeave, innerTryLeave);
il.InsertBefore(outerTryLeave, reportCall);
il.InsertBefore(outerTryLeave, il.Create(OpCodes.Ldc_I4_0));
il.InsertBefore(outerTryLeave, il.Create(OpCodes.Endfilter));
il.InsertBefore(outerTryLeave, catchHandler);
il.InsertBefore(outerTryLeave, il.Create(OpCodes.Leave_S, outerTryLeave));
for (var i = 0; i < handlerIndex; i++) {
il.Body.ExceptionHandlers[i].RetargetAll(outerTryLeave.Next, innerTryLeave.Next);
}
il.Body.ExceptionHandlers.Insert(handlerIndex, new ExceptionHandler(ExceptionHandlerType.Filter) {
TryStart = handler.TryStart,
TryEnd = reportCall,
FilterStart = reportCall,
HandlerStart = catchHandler,
HandlerEnd = outerTryLeave
});
handlerIndex += 1;
}
private void InsertAfter(ILProcessor il, ref Instruction target, ref int index, Instruction instruction) {
il.InsertAfter(target, instruction);
target = instruction;
index += 1;
}
private int? GetIndexIfStloc(Instruction instruction) {
switch (instruction.OpCode.Code) {
case Code.Stloc_0: return 0;
case Code.Stloc_1: return 1;
case Code.Stloc_2: return 2;
case Code.Stloc_3: return 3;
case Code.Stloc_S:
case Code.Stloc:
return ((VariableReference)instruction.Operand).Index;
default: return null;
}
}
private struct ReportMethods {
public MethodReference ReportLineStart { get; set; }
public MethodReference ReportValue { get; set; }
public MethodReference ReportRefValue { get; set; }
public MethodReference ReportSpanValue { get; set; }
public MethodReference ReportRefSpanValue { get; set; }
public MethodReference ReportReadOnlySpanValue { get; set; }
public MethodReference ReportRefReadOnlySpanValue { get; set; }
public MethodReference ReportException { get; set; }
}
}
}
| |
namespace Snippets5.UpgradeGuides._4to5
{
using System;
using System.Security.Principal;
using System.Threading;
using NServiceBus;
using NServiceBus.MessageMutator;
using NServiceBus.Persistence;
using Raven.Client.Document;
public class Upgrade
{
#region 4to5RemovePrincipalHack
public class PrincipalMutator : IMutateIncomingTransportMessages
{
public void MutateIncoming(TransportMessage message)
{
string windowsIdentityName = message.Headers[Headers.WindowsIdentityName];
GenericIdentity identity = new GenericIdentity(windowsIdentityName);
GenericPrincipal principal = new GenericPrincipal(identity, new string[0]);
Thread.CurrentPrincipal = principal;
}
}
#endregion
public void MessageConventions()
{
#region 4to5MessageConventions
BusConfiguration busConfiguration = new BusConfiguration();
ConventionsBuilder conventions = busConfiguration.Conventions();
conventions.DefiningCommandsAs(t => t.Namespace != null && t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Commands"));
conventions.DefiningEventsAs(t => t.Namespace != null && t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Events"));
conventions.DefiningMessagesAs(t => t.Namespace != null && t.Namespace == "Messages");
conventions.DefiningEncryptedPropertiesAs(p => p.Name.StartsWith("Encrypted"));
conventions.DefiningDataBusPropertiesAs(p => p.Name.EndsWith("DataBus"));
conventions.DefiningExpressMessagesAs(t => t.Name.EndsWith("Express"));
conventions.DefiningTimeToBeReceivedAs(t => t.Name.EndsWith("Expires") ? TimeSpan.FromSeconds(30) : TimeSpan.MaxValue);
#endregion
}
public void CustomConfigOverrides()
{
#region 4to5CustomConfigOverrides
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.AssembliesToScan(AllAssemblies.Except("NotThis.dll"));
busConfiguration.Conventions().DefiningEventsAs(type => type.Name.EndsWith("Event"));
busConfiguration.EndpointName("MyEndpointName");
#endregion
}
public void UseTransport()
{
BusConfiguration busConfiguration = new BusConfiguration();
#region 4to5UseTransport
//Choose one of the following
busConfiguration.UseTransport<MsmqTransport>();
busConfiguration.UseTransport<RabbitMQTransport>();
busConfiguration.UseTransport<SqlServerTransport>();
busConfiguration.UseTransport<AzureStorageQueueTransport>();
busConfiguration.UseTransport<AzureServiceBusTransport>();
#endregion
}
public void InterfaceMessageCreation()
{
IBus Bus = null;
#region 4to5InterfaceMessageCreation
Bus.Publish<MyInterfaceMessage>(o =>
{
o.OrderNumber = 1234;
});
#endregion
IMessageCreator messageCreator = null;
#region 4to5ReflectionInterfaceMessageCreation
//This type would be derived from some other runtime information
Type messageType = typeof(MyInterfaceMessage);
object instance = messageCreator.CreateInstance(messageType);
//use reflection to set properties on the constructed instance
Bus.Publish(instance);
#endregion
}
public interface MyInterfaceMessage
{
int OrderNumber { get; set; }
}
public void CustomRavenConfig()
{
#region 4to5CustomRavenConfig
DocumentStore documentStore = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "MyDatabase",
};
documentStore.Initialize();
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.UsePersistence<RavenDBPersistence>()
.SetDefaultDocumentStore(documentStore);
#endregion
}
public void StartupAction()
{
#region 4to5StartupAction
IStartableBus bus = Bus.Create(new BusConfiguration());
MyCustomAction();
bus.Start();
#endregion
}
public void MyCustomAction()
{
}
public void Installers()
{
#region 4to5Installers
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EnableInstallers();
Bus.Create(busConfiguration); //this will run the installers
#endregion
}
public void AllThePersistence()
{
#pragma warning disable 618
#region 4to5ConfigurePersistence
BusConfiguration busConfiguration = new BusConfiguration();
// Configure to use InMemory for all persistence types
busConfiguration.UsePersistence<InMemoryPersistence>();
// Configure to use InMemory for specific persistence types
busConfiguration.UsePersistence<InMemoryPersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
// Configure to use NHibernate for all persistence types
busConfiguration.UsePersistence<NHibernatePersistence>();
// Configure to use NHibernate for specific persistence types
busConfiguration.UsePersistence<NHibernatePersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
// Configure to use RavenDB for all persistence types
busConfiguration.UsePersistence<RavenDBPersistence>();
// Configure to use RavenDB for specific persistence types
busConfiguration.UsePersistence<RavenDBPersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
#endregion
#pragma warning restore 618
}
#region 4to5BusExtensionMethodForHandler
public class MyHandler : IHandleMessages<MyMessage>
{
IBus bus;
public MyHandler(IBus bus)
{
this.bus = bus;
}
public void Handle(MyMessage message)
{
bus.Reply(new OtherMessage());
}
}
#endregion
public class MyMessage
{
}
public class OtherMessage
{
}
public void RunCustomAction()
{
#region 4to5RunCustomAction
IStartableBus bus = Bus.Create(new BusConfiguration());
MyCustomAction();
bus.Start();
#endregion
}
public void DefineCriticalErrorAction()
{
#region 4to5DefineCriticalErrorAction
BusConfiguration busConfiguration = new BusConfiguration();
// Configuring how NServicebus handles critical errors
busConfiguration.DefineCriticalErrorAction((message, exception) =>
{
string output = string.Format("We got a critical exception: '{0}'\r\n{1}", message, exception);
Console.WriteLine(output);
// Perhaps end the process??
});
#endregion
}
public void FileShareDataBus()
{
string databusPath = null;
#region 4to5FileShareDataBus
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.UseDataBus<FileShareDataBus>()
.BasePath(databusPath);
#endregion
}
public void PurgeOnStartup()
{
#region 4to5PurgeOnStartup
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.PurgeOnStartup(true);
#endregion
}
public void EncryptionServiceSimple()
{
#region 4to5EncryptionServiceSimple
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.RijndaelEncryptionService();
#endregion
}
public void License()
{
#region 4to5License
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.LicensePath("PathToLicense");
//or
busConfiguration.License("YourCustomLicenseText");
#endregion
}
public void TransactionConfig()
{
#region 4to5TransactionConfig
BusConfiguration busConfiguration = new BusConfiguration();
//Enable
busConfiguration.Transactions().Enable();
// Disable
busConfiguration.Transactions().Disable();
#endregion
}
public void StaticConfigureEndpoint()
{
#region 4to5StaticConfigureEndpoint
BusConfiguration busConfiguration = new BusConfiguration();
// SendOnly
Bus.CreateSendOnly(busConfiguration);
// AsVolatile
busConfiguration.Transactions().Disable();
busConfiguration.DisableDurableMessages();
busConfiguration.UsePersistence<InMemoryPersistence>();
// DisableDurableMessages
busConfiguration.DisableDurableMessages();
// EnableDurableMessages
busConfiguration.EnableDurableMessages();
#endregion
}
public void PerformanceMonitoring()
{
#region 4to5PerformanceMonitoring
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EnableSLAPerformanceCounter();
//or
busConfiguration.EnableSLAPerformanceCounter(TimeSpan.FromMinutes(3));
#endregion
}
public void DoNotCreateQueues()
{
#region 4to5DoNotCreateQueues
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.DoNotCreateQueues();
#endregion
}
public void EndpointName()
{
#region 4to5EndpointName
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("MyEndpoint");
#endregion
}
public void SendOnly()
{
#region 4to5SendOnly
BusConfiguration busConfiguration = new BusConfiguration();
ISendOnlyBus bus = Bus.CreateSendOnly(busConfiguration);
#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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using CURLAUTH = Interop.libcurl.CURLAUTH;
using CURLcode = Interop.libcurl.CURLcode;
using CurlFeatures = Interop.libcurl.CURL_VERSION_Features;
using CURLMcode = Interop.libcurl.CURLMcode;
using CURLoption = Interop.libcurl.CURLoption;
using CurlVersionInfoData = Interop.libcurl.curl_version_info_data;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE";
private const string HttpPrefix = "HTTP/";
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes
private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic };
private readonly static CurlVersionInfoData s_curlVersionInfoData;
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.libcurl's cctor
// Verify the version of curl we're using is new enough
s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge));
if (s_curlVersionInfoData.age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
// Feature detection
s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0;
s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0;
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool SupportsRedirectConfiguration
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy;
}
set
{
CheckDisposedOrStarted();
_proxyPolicy = value ?
ProxyUsePolicy.UseCustomProxy :
ProxyUsePolicy.DoNotUseProxy;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return ClientCertificateOption.Manual;
}
set
{
if (ClientCertificateOption.Manual != value)
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option);
}
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
/// <summary>
/// <b> UseDefaultCredentials is a no op on Unix </b>
/// </summary>
internal bool UseDefaultCredentials
{
get
{
return false;
}
set
{
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps))
{
throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required);
}
if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
// TODO: Check that SendAsync is not being called again for same request object.
// Probably fix is needed in WinHttpHandler as well
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
// Submit the easy request to the multi agent.
if (request.Content != null)
{
// If there is request content to be sent, preload the stream
// and submit the request to the multi agent. This is separated
// out into a separate async method to avoid associated overheads
// in the case where there is no request content stream.
return QueueOperationWithRequestContentAsync(easy);
}
else
{
// Otherwise, just submit the request.
ConfigureAndQueue(easy);
return easy.Task;
}
}
private void ConfigureAndQueue(EasyRequest easy)
{
try
{
easy.InitializeCurl();
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
}
/// <summary>
/// Loads the request's request content stream asynchronously and
/// then submits the request to the multi agent.
/// </summary>
private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy)
{
Debug.Assert(easy._requestMessage.Content != null, "Expected request to have non-null request content");
easy._requestContentStream = await easy._requestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
ConfigureAndQueue(easy);
}
return await easy.Task.ConfigureAwait(false);
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri)
{
if (_preAuthenticate)
{
NetworkCredential nc = null;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
nc = GetCredentials(_credentialCache, requestUri);
}
if (nc != null)
{
return nc;
}
}
return GetCredentials(credentials, requestUri);
}
private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc)
{
lock (LockObject)
{
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
if ((authAvail & s_authSchemePriorityOrder[i]) != 0)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
_credentialCache.Add(serverUri, s_authenticationSchemes[i], nc);
}
}
}
}
private void AddResponseCookies(Uri serverUri, HttpResponseMessage response)
{
if (!_useCookie)
{
return;
}
if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
_cookieContainer.SetCookies(serverUri, cookieHeader);
}
catch (CookieException e)
{
string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}",
e.Message,
serverUri.OriginalString,
cookieHeader);
VerboseTrace(msg);
}
}
}
}
private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri)
{
if (credentials == null)
{
return null;
}
foreach (var authScheme in s_authenticationSchemes)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme);
if (networkCredential != null)
{
return networkCredential;
}
}
return null;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(int error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException(error, isMulti: false);
VerboseTrace(inner.Message);
throw CreateHttpRequestException(inner);
}
}
private static void ThrowIfCURLMError(int error)
{
if (error != CURLMcode.CURLM_OK)
{
string msg = CurlException.GetCurlErrorString(error, true);
VerboseTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw CreateHttpRequestException(new CurlException(error, msg));
}
}
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null && easy._associatedMultiAgent != null)
{
agent = easy._associatedMultiAgent;
}
int? agentId = agent != null ? agent.RunningWorkerId : null;
// Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about
string ids = "";
if (agentId != null || easy != null)
{
ids = "(" +
(agentId != null ? "M#" + agentId : "") +
(agentId != null && easy != null ? ", " : "") +
(easy != null ? "E#" + easy.Task.Id : "") +
")";
}
// Create the message and trace it out
string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text);
Interop.Sys.PrintF("%s\n", msg);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
VerboseTrace(text, memberName, easy, agent: null);
}
}
private static Exception CreateHttpRequestException(Exception inner = null)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
int responseHeaderLength = responseHeader.Length;
// Check if line begins with HTTP/1.1 or HTTP/1.0
int prefixLength = HttpPrefix.Length;
int versionIndex = prefixLength + 2;
if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
{
response.Version =
responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
new Version(0, 0);
}
else
{
response.Version = new Version(0, 0);
}
// TODO: Parsing errors are treated as fatal. Find right behaviour
int spaceIndex = responseHeader.IndexOf(SpaceChar);
if (spaceIndex > -1)
{
int codeStartIndex = spaceIndex + 1;
int statusCode = 0;
// Parse first 3 characters after a space as status code
if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
{
response.StatusCode = (HttpStatusCode)statusCode;
int codeEndIndex = codeStartIndex + StatusCodeLength;
int reasonPhraseIndex = codeEndIndex + 1;
if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
{
int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
}
state._isRedirect = state._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
response.StatusCode == HttpStatusCode.RedirectMethod) ;
}
}
return true;
}
private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode)
{
if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length)
{
statusCode = 0;
return false;
}
char c100 = responseHeader[statusCodeStartIndex];
char c10 = responseHeader[statusCodeStartIndex + 1];
char c1 = responseHeader[statusCodeStartIndex + 2];
if (c100 < '0' || c100 > '9' ||
c10 < '0' || c10 > '9' ||
c1 < '0' || c1 > '9')
{
statusCode = 0;
return false;
}
statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0');
return true;
}
private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue)
{
Debug.Assert(state._isRedirect);
Debug.Assert(state._handler.AutomaticRedirection);
string location = locationValue.Trim();
//only for absolute redirects
Uri forwardUri;
if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri)
{
NetworkCredential newCredential = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri);
if (newCredential != null)
{
state.SetCredentialsOptions(newCredential);
}
else
{
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
}
// reset proxy - it is possible that the proxy has different credentials for the new URI
state.SetProxyOptions(forwardUri);
if (state._handler._useCookie)
{
// reset cookies.
state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
// set cookies again
state.SetCookieOption(forwardUri);
}
}
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
private enum ProxyUsePolicy
{
DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment.
UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any.
UseCustomProxy = 2 // Use The proxy specified by the user.
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmBarcodePerson
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmBarcodePerson() : base()
{
Load += frmBarcodePerson_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
public System.Windows.Forms.CheckedListBox lstPerson;
private System.Windows.Forms.Button withEventsField_cndExit;
public System.Windows.Forms.Button cndExit {
get { return withEventsField_cndExit; }
set {
if (withEventsField_cndExit != null) {
withEventsField_cndExit.Click -= cndExit_Click;
}
withEventsField_cndExit = value;
if (withEventsField_cndExit != null) {
withEventsField_cndExit.Click += cndExit_Click;
}
}
}
public System.Windows.Forms.Label _Label2_1;
public System.Windows.Forms.Label lblPrinterType;
public System.Windows.Forms.Label lblPrinter;
public System.Windows.Forms.Label _Label2_0;
public System.Windows.Forms.Label Label1;
//Public WithEvents Label2 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmBarcodePerson));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdPrint = new System.Windows.Forms.Button();
this.lstPerson = new System.Windows.Forms.CheckedListBox();
this.cndExit = new System.Windows.Forms.Button();
this._Label2_1 = new System.Windows.Forms.Label();
this.lblPrinterType = new System.Windows.Forms.Label();
this.lblPrinter = new System.Windows.Forms.Label();
this._Label2_0 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
//Me.Label2 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Security Barcode Printing";
this.ClientSize = new System.Drawing.Size(394, 449);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.Icon = (System.Drawing.Icon)resources.GetObject("frmBarcodePerson.Icon");
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmBarcodePerson";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(106, 49);
this.cmdPrint.Location = new System.Drawing.Point(21, 381);
this.cmdPrint.TabIndex = 7;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.TabStop = true;
this.cmdPrint.Name = "cmdPrint";
this.lstPerson.Size = new System.Drawing.Size(361, 244);
this.lstPerson.Location = new System.Drawing.Point(15, 93);
this.lstPerson.TabIndex = 6;
this.lstPerson.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstPerson.BackColor = System.Drawing.SystemColors.Window;
this.lstPerson.CausesValidation = true;
this.lstPerson.Enabled = true;
this.lstPerson.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstPerson.IntegralHeight = true;
this.lstPerson.Cursor = System.Windows.Forms.Cursors.Default;
this.lstPerson.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstPerson.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstPerson.Sorted = false;
this.lstPerson.TabStop = true;
this.lstPerson.Visible = true;
this.lstPerson.MultiColumn = false;
this.lstPerson.Name = "lstPerson";
this.cndExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cndExit.Text = "E&xit";
this.cndExit.Size = new System.Drawing.Size(106, 49);
this.cndExit.Location = new System.Drawing.Point(267, 381);
this.cndExit.TabIndex = 5;
this.cndExit.BackColor = System.Drawing.SystemColors.Control;
this.cndExit.CausesValidation = true;
this.cndExit.Enabled = true;
this.cndExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cndExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cndExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cndExit.TabStop = true;
this.cndExit.Name = "cndExit";
this._Label2_1.Text = "Printer Type:";
this._Label2_1.Size = new System.Drawing.Size(90, 16);
this._Label2_1.Location = new System.Drawing.Point(6, 24);
this._Label2_1.TabIndex = 4;
this._Label2_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label2_1.BackColor = System.Drawing.Color.Transparent;
this._Label2_1.Enabled = true;
this._Label2_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_1.UseMnemonic = true;
this._Label2_1.Visible = true;
this._Label2_1.AutoSize = true;
this._Label2_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_1.Name = "_Label2_1";
this.lblPrinterType.Text = "Label1";
this.lblPrinterType.Size = new System.Drawing.Size(41, 16);
this.lblPrinterType.Location = new System.Drawing.Point(102, 24);
this.lblPrinterType.TabIndex = 3;
this.lblPrinterType.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblPrinterType.BackColor = System.Drawing.Color.Transparent;
this.lblPrinterType.Enabled = true;
this.lblPrinterType.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPrinterType.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPrinterType.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPrinterType.UseMnemonic = true;
this.lblPrinterType.Visible = true;
this.lblPrinterType.AutoSize = true;
this.lblPrinterType.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblPrinterType.Name = "lblPrinterType";
this.lblPrinter.Text = "Label1";
this.lblPrinter.Size = new System.Drawing.Size(41, 16);
this.lblPrinter.Location = new System.Drawing.Point(102, 6);
this.lblPrinter.TabIndex = 2;
this.lblPrinter.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblPrinter.BackColor = System.Drawing.Color.Transparent;
this.lblPrinter.Enabled = true;
this.lblPrinter.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPrinter.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPrinter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPrinter.UseMnemonic = true;
this.lblPrinter.Visible = true;
this.lblPrinter.AutoSize = true;
this.lblPrinter.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblPrinter.Name = "lblPrinter";
this._Label2_0.Text = "Printer:";
this._Label2_0.Size = new System.Drawing.Size(50, 16);
this._Label2_0.Location = new System.Drawing.Point(45, 6);
this._Label2_0.TabIndex = 1;
this._Label2_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label2_0.BackColor = System.Drawing.Color.Transparent;
this._Label2_0.Enabled = true;
this._Label2_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_0.UseMnemonic = true;
this._Label2_0.Visible = true;
this._Label2_0.AutoSize = true;
this._Label2_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_0.Name = "_Label2_0";
this.Label1.Text = "Tick the check boxes for the Persons you require access barcodes for from the list below.";
this.Label1.Size = new System.Drawing.Size(357, 37);
this.Label1.Location = new System.Drawing.Point(12, 45);
this.Label1.TabIndex = 0;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(cmdPrint);
this.Controls.Add(lstPerson);
this.Controls.Add(cndExit);
this.Controls.Add(_Label2_1);
this.Controls.Add(lblPrinterType);
this.Controls.Add(lblPrinter);
this.Controls.Add(_Label2_0);
this.Controls.Add(Label1);
//Me.Label2.SetIndex(_Label2_1, CType(1, Short))
//Me.Label2.SetIndex(_Label2_0, CType(0, Short))
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).EndInit()
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections;
namespace Tutor.Structure
{
/// <summary>
/// Summary description for EquationStructure.
/// </summary>
public interface Equation
{
bool Equal(Equation E);
string str();
int order();
void cycle();
bool simple();
}
public class EquConstant : Equation
{
public long Value;
public EquConstant(long v)
{
Value = v;
}
public bool Equal(Equation E)
{
if(E is EquConstant)
{
EquConstant V = (EquConstant) E;
return V.Value == Value;
}
return false;
}
public string str()
{
if(Value < 0)
{
return "\\left(" + Value + "\\right)";
}
return "" + Value + "";
}
public string lisp()
{
return "(n " + Value + ")";
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
};
public class EquVariable : Equation
{
public string Variable;
public EquVariable(string var)
{
Variable = var;
}
public bool Equal(Equation E)
{
if(E is EquVariable)
{
EquVariable V = (EquVariable) E;
return V.Variable.Equals(Variable);
}
return false;
}
public string str()
{
return "" + Variable + "";
}
public string lisp()
{
return Variable;
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
};
public class EquRoot : Equation
{
public Equation Term;
public Equation Root;
public EquRoot(Equation t, Equation r)
{
Term = t;
Root = r;
}
public bool Equal(Equation E)
{
if(E is EquRoot)
{
EquRoot V = (EquRoot) E;
return V.Term.Equal(Term) && V.Root.Equal(Root);
}
return false;
}
public string str()
{
if(Root.str().Equals("2"))
return "\\sqrt{" + Term.str() + "}";
return "\\sqrt["+Root.str()+"]{" + Term.str() + "}";
}
/*
public string lisp()
{
if(Root.str().Equals("2"))
return "(sqrt " + Term.lisp() + ")";
return "(root " + Term.lisp() + ";
}
*/
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
};
public class EquPower : Equation
{
public Equation Base;
public Equation Power;
public EquPower(Equation b, Equation p)
{
Base = b;
Power = p;
}
public bool Equal(Equation E)
{
if(E is EquPower)
{
EquPower V = (EquPower) E;
return V.Base.Equal(Base) && V.Power.Equal(Power);
}
return false;
}
public string str()
{
string b = Base.str();
if(!Base.simple())
{
b = "\\left(" + b + "\\right)";
}
return b+"^{" + Power.str() + "}";
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return false; }
}
public class EquDivide : Equation
{
public Equation Numerator;
public Equation Denominator;
private int customCycle;
public EquDivide(Equation n, Equation d)
{
Numerator = n;
Denominator = d;
customCycle = 0;
}
public bool Equal(Equation E)
{
if(E is EquDivide)
{
EquDivide V = (EquDivide) E;
return V.Numerator.Equal(Numerator) && V.Denominator.Equal(Denominator);
}
return false;
}
public string str()
{
return "\\frac{" + Numerator.str() + "}{" + Denominator.str() + "}";
}
public int order() { return Numerator.order() * Denominator.order(); }
public void cycle() {
customCycle ++;
Numerator.cycle();
if(customCycle % Numerator.order() == 0)
{
Denominator.cycle();
}
}
public bool simple() { return false; }
}
public class EquEquality : Equation
{
public Equation Left;
public Equation Right;
public EquEquality(Equation l, Equation r)
{
Left = l;
Right = r;
}
public string str()
{
return "" + Left.str() + "=" + Right.str() + "";
}
public bool Equal(Equation E)
{
if(E is EquEquality)
{
EquEquality V = (EquEquality) E;
return V.Left.Equal(Left) && V.Right.Equal(Right);
}
return false;
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
};
public class EquNegation : Equation
{
public Equation Term;
public EquNegation(Equation t)
{
Term = t;
}
public bool Equal(Equation E)
{
if(E is EquNegation)
{
EquNegation V = (EquNegation) E;
return V.Term.Equal(Term);
}
return false;
}
public string str()
{
if(Term.simple()) return "-" + Term.str() + "";
return "-\\left(" + Term.str() + "\\right)";
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
}
public class EquAbsoluteValue : Equation
{
public Equation Term;
public EquAbsoluteValue(Equation t)
{
Term = t;
}
public bool Equal(Equation E)
{
if(E is EquAbsoluteValue)
{
EquAbsoluteValue V = (EquAbsoluteValue) E;
return V.Term.Equal(Term);
}
return false;
}
public string str()
{
return "\\abs{" + Term.str() + "}";
}
public int order() { return 1; }
public void cycle() {}
public bool simple() { return true; }
}
public class EquAddition : Equation
{
public ArrayList _Terms;
public EquAddition()
{
_Terms = new ArrayList();
}
public EquAddition(Equation a)
{
_Terms = new ArrayList();
_Terms.Add(a);
CollectSums();
}
public EquAddition(Equation a, Equation b)
{
_Terms = new ArrayList();
_Terms.Add(a);
_Terms.Add(b);
CollectSums();
}
public EquAddition(Equation [] A)
{
_Terms = new ArrayList();
foreach(Equation E in A)
_Terms.Add(E);
CollectSums();
}
public void CollectSums()
{
ArrayList NewTerms = new ArrayList();
foreach(Equation E in _Terms)
{
if(E is EquAddition)
{
EquAddition V = (EquAddition) E;
V.CollectSums();
foreach(Equation F in V._Terms)
NewTerms.Add(F);
}
else
{
NewTerms.Add(E);
}
}
_Terms = NewTerms;
_Terms.Sort(new CompareEquations());
}
public bool Equal(Equation E)
{
if(E is EquAddition)
{
EquAddition V = (EquAddition) E;
bool res = SubEquality.TestEquality(V._Terms, _Terms);
Console.WriteLine("Testing Equality between:" + this.str() + " and " + E.str() + ":" + res);
return res;
}
return false;
}
public string str()
{
string interior = "";
bool first = true;
foreach(Equation E in _Terms)
{
if(E is EquNegation)
{
if(!first)
{
interior += "-";
interior += ((EquNegation)E).Term.str();
}
else
{
interior += E.str();
}
}
else
{
if(!first) interior += "+";
interior += E.str();
}
first = false;
}
return "" +interior + "";
}
public int order() { return _Terms.Count; }
public void cycle()
{
Object F = _Terms[0];
_Terms.RemoveAt(0);
_Terms.Add(F);
}
public bool simple() { return false; }
};
public class EquMultiplication : Equation
{
public ArrayList _Factors;
public EquMultiplication()
{
_Factors = new ArrayList();
}
public EquMultiplication(Equation a)
{
_Factors = new ArrayList();
_Factors.Add(a);
CollectFactors();
}
public EquMultiplication(Equation a, Equation b)
{
_Factors = new ArrayList();
_Factors.Add(a);
_Factors.Add(b);
CollectFactors();
}
public EquMultiplication(Equation [] A)
{
_Factors = new ArrayList();
foreach(Equation E in A)
_Factors.Add(E);
CollectFactors();
}
public void CollectFactors()
{
ArrayList NewFactors = new ArrayList();
foreach(Equation E in _Factors)
{
if(E is EquMultiplication)
{
EquMultiplication V = (EquMultiplication) E;
V.CollectFactors();
foreach(Equation F in V._Factors)
NewFactors.Add(F);
}
else
{
NewFactors.Add(E);
}
}
_Factors = NewFactors;
_Factors.Sort(new CompareEquations());
}
public bool Equal(Equation E)
{
if(E is EquMultiplication)
{
EquMultiplication V = (EquMultiplication) E;
return SubEquality.TestEquality(V._Factors, _Factors);
}
return false;
}
public string str()
{
string interior = "";
bool first = true;
foreach(Equation E in _Factors)
{
if(!first) interior += "*";
if(!E.simple()) interior += "(";
interior += E.str();
if(!E.simple()) interior += ")";
first = false;
}
return "" + interior + "";
}
public int order() { return _Factors.Count; }
public void cycle()
{
Object F = _Factors[0];
_Factors.RemoveAt(0);
_Factors.Add(F);
}
public bool simple() { return true; }
}
public class SubEquality
{
public static bool TestEquality(ArrayList Left, ArrayList Right)
{
// quick rejection test
if(Left.Count != Right.Count) return false;
// the right side
Equation [] EqR = new Equation[Right.Count];
// copy from list to array
int idx = 0;
foreach(Equation E in Right) { EqR[idx] = E; idx++; }
foreach(Equation L in Left)
{
bool found = false;
for(int k = 0; k < EqR.Length && !found; k++)
{
if(EqR[k] != null)
{
if(EqR[k].Equal(L))
{
EqR[k] = null;
found = true;
}
}
}
if(!found) return false;
}
return true;
}
}
public class CompareEquations : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return ((Equation) x).str().CompareTo( ((Equation) y).str());
}
#endregion
}
public class UnknownEquNode : Exception
{
};
public class EquationParser
{
public static Equation Interpret(SimpleParser.SimpleParseTree SPL)
{
if(SPL.node.Equals("+"))
{
EquAddition add = new EquAddition();
foreach(SimpleParser.SimpleParseTree sub in SPL.children)
{
add._Terms.Add( Interpret(sub) );
}
add.CollectSums();
return add;
}
if(SPL.node.Equals("*"))
{
EquMultiplication mult = new EquMultiplication();
foreach(SimpleParser.SimpleParseTree sub in SPL.children)
{
mult._Factors.Add( Interpret(sub) );
}
mult.CollectFactors();
return mult;
}
if(SPL.node.Equals("var"))
{
return new EquVariable(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node);
}
if(SPL.node.Equals("^"))
{
return new EquPower(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("-"))
{
Equation Sub;
if(SPL.children.Count == 2)
{
Sub = Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) );
if(Sub is EquConstant)
{
EquConstant Eq = (EquConstant) Sub;
Eq.Value *= -1;
Sub = Eq;
}
else
{
Sub = new EquNegation( Sub );
}
return new EquAddition( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ),
Sub );
}
Sub = Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) );
if(Sub is EquConstant)
{
EquConstant Eq = (EquConstant) Sub;
Eq.Value *= -1;
return Eq;
}
return new EquNegation(Sub);
}
if(SPL.node.Equals("abs"))
{
return new EquAbsoluteValue( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) );
}
if(SPL.node.Equals("="))
{
return new EquEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) );
}
if(SPL.node.Equals("/"))
{
return new EquDivide(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("root"))
{
return new EquRoot(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("sqrt"))
{
return new EquRoot(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), new EquConstant(2) );
}
if(SPL.node.Equals("n"))
{
return new EquConstant( Int32.Parse(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node) );
}
throw new UnknownEquNode();
}
public static Equation Parse(string source)
{
SimpleParser.SimpleLexer SL = new SimpleParser.SimpleLexer(source);
SimpleParser.SimpleParseTree SPL = SimpleParser.SimpleParseTree.Parse(SL);
return Interpret(SPL);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Android.Animation;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.Widget;
using Android.Support.V7.Graphics.Drawable;
using Android.Util;
using Android.Views;
using Xamarin.Forms.Internals;
using ActionBarDrawerToggle = Android.Support.V7.App.ActionBarDrawerToggle;
using AView = Android.Views.View;
using AToolbar = Android.Support.V7.Widget.Toolbar;
using Fragment = Android.Support.V4.App.Fragment;
using FragmentManager = Android.Support.V4.App.FragmentManager;
using FragmentTransaction = Android.Support.V4.App.FragmentTransaction;
using Object = Java.Lang.Object;
using static Android.Views.View;
namespace Xamarin.Forms.Platform.Android.AppCompat
{
public class NavigationPageRenderer : VisualElementRenderer<NavigationPage>, IManageFragments, IOnClickListener
{
readonly List<Fragment> _fragmentStack = new List<Fragment>();
Drawable _backgroundDrawable;
Page _current;
bool _disposed;
ActionBarDrawerToggle _drawerToggle;
FragmentManager _fragmentManager;
int _lastActionBarHeight = -1;
AToolbar _toolbar;
ToolbarTracker _toolbarTracker;
DrawerMultiplexedListener _drawerListener;
DrawerLayout _drawerLayout;
bool _toolbarVisible;
// The following is based on https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/app/FragmentManager.java#849
const int TransitionDuration = 220;
public NavigationPageRenderer()
{
AutoPackage = false;
Id = FormsAppCompatActivity.GetUniqueId();
Device.Info.PropertyChanged += DeviceInfoPropertyChanged;
}
internal int ContainerPadding { get; set; }
Page Current
{
get { return _current; }
set
{
if (_current == value)
return;
if (_current != null)
_current.PropertyChanged -= CurrentOnPropertyChanged;
_current = value;
if (_current != null)
{
_current.PropertyChanged += CurrentOnPropertyChanged;
ToolbarVisible = NavigationPage.GetHasNavigationBar(_current);
}
}
}
FragmentManager FragmentManager => _fragmentManager ?? (_fragmentManager = ((FormsAppCompatActivity)Context).SupportFragmentManager);
IPageController PageController => Element as IPageController;
bool ToolbarVisible
{
get { return _toolbarVisible; }
set
{
if (_toolbarVisible == value)
return;
_toolbarVisible = value;
RequestLayout();
}
}
void IManageFragments.SetFragmentManager(FragmentManager childFragmentManager)
{
if (_fragmentManager == null)
_fragmentManager = childFragmentManager;
}
public Task<bool> PopToRootAsync(Page page, bool animated = true)
{
return OnPopToRootAsync(page, animated);
}
public Task<bool> PopViewAsync(Page page, bool animated = true)
{
return OnPopViewAsync(page, animated);
}
public Task<bool> PushViewAsync(Page page, bool animated = true)
{
return OnPushAsync(page, animated);
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
var activity = (FormsAppCompatActivity)Context;
// API only exists on newer android YAY
if ((int)Build.VERSION.SdkInt >= 17)
{
if (!activity.IsDestroyed)
{
FragmentManager fm = FragmentManager;
FragmentTransaction trans = fm.BeginTransaction();
foreach (Fragment fragment in _fragmentStack)
trans.Remove(fragment);
trans.CommitAllowingStateLoss();
fm.ExecutePendingTransactions();
}
}
if (_toolbarTracker != null)
{
_toolbarTracker.CollectionChanged -= ToolbarTrackerOnCollectionChanged;
_toolbarTracker.Target = null;
_toolbarTracker = null;
}
if (_toolbar != null)
{
_toolbar.SetNavigationOnClickListener(null);
_toolbar.Dispose();
_toolbar = null;
}
if (_drawerLayout != null && _drawerListener != null)
{
_drawerLayout.RemoveDrawerListener(_drawerListener);
}
if (_drawerListener != null)
{
_drawerListener.Dispose();
_drawerListener = null;
}
if (_drawerToggle != null)
{
_drawerToggle.Dispose();
_drawerToggle = null;
}
if (_backgroundDrawable != null)
{
_backgroundDrawable.Dispose();
_backgroundDrawable = null;
}
Current = null;
// We dispose the child renderers after cleaning up everything related to DrawerLayout in case
// one of the children is a MasterDetailPage (which may dispose of the DrawerLayout).
if (Element != null)
{
foreach (Element element in PageController.InternalChildren)
{
var child = element as VisualElement;
if (child == null)
continue;
IVisualElementRenderer renderer = Android.Platform.GetRenderer(child);
renderer?.Dispose();
}
var navController = (INavigationPageController)Element;
navController.PushRequested -= OnPushed;
navController.PopRequested -= OnPopped;
navController.PopToRootRequested -= OnPoppedToRoot;
navController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested;
navController.RemovePageRequested -= OnRemovePageRequested;
}
Device.Info.PropertyChanged -= DeviceInfoPropertyChanged;
}
base.Dispose(disposing);
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
PageController.SendAppearing();
_fragmentStack.Last().UserVisibleHint = true;
RegisterToolbar();
UpdateToolbar();
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
PageController.SendDisappearing();
}
protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
var oldNavController = (INavigationPageController)e.OldElement;
oldNavController.PushRequested -= OnPushed;
oldNavController.PopRequested -= OnPopped;
oldNavController.PopToRootRequested -= OnPoppedToRoot;
oldNavController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested;
oldNavController.RemovePageRequested -= OnRemovePageRequested;
RemoveAllViews();
if (_toolbar != null)
AddView(_toolbar);
}
if (e.NewElement != null)
{
if (_toolbarTracker == null)
{
SetupToolbar();
_toolbarTracker = new ToolbarTracker();
_toolbarTracker.CollectionChanged += ToolbarTrackerOnCollectionChanged;
}
var parents = new List<Page>();
Page root = Element;
while (!Application.IsApplicationOrNull(root.RealParent))
{
root = (Page)root.RealParent;
parents.Add(root);
}
_toolbarTracker.Target = e.NewElement;
_toolbarTracker.AdditionalTargets = parents;
UpdateMenu();
var navController = (INavigationPageController)e.NewElement;
navController.PushRequested += OnPushed;
navController.PopRequested += OnPopped;
navController.PopToRootRequested += OnPoppedToRoot;
navController.InsertPageBeforeRequested += OnInsertPageBeforeRequested;
navController.RemovePageRequested += OnRemovePageRequested;
// If there is already stuff on the stack we need to push it
foreach (Page page in navController.StackCopy.Reverse())
{
PushViewAsync(page, false);
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName)
UpdateToolbar();
else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName)
UpdateToolbar();
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
AToolbar bar = _toolbar;
// make sure bar stays on top of everything
bar.BringToFront();
base.OnLayout(changed, l, t, r, b);
int barHeight = ActionBarHeight();
if (barHeight != _lastActionBarHeight && _lastActionBarHeight > 0)
{
ResetToolbar();
bar = _toolbar;
}
_lastActionBarHeight = barHeight;
bar.Measure(MeasureSpecFactory.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(barHeight, MeasureSpecMode.Exactly));
int internalHeight = b - t - barHeight;
int containerHeight = ToolbarVisible ? internalHeight : b - t;
containerHeight -= ContainerPadding;
PageController.ContainerArea = new Rectangle(0, 0, Context.FromPixels(r - l), Context.FromPixels(containerHeight));
// Potential for optimization here, the exact conditions by which you don't need to do this are complex
// and the cost of doing when it's not needed is moderate to low since the layout will short circuit pretty fast
Element.ForceLayout();
for (var i = 0; i < ChildCount; i++)
{
AView child = GetChildAt(i);
bool isBar = JNIEnv.IsSameObject(child.Handle, bar.Handle);
if (ToolbarVisible)
{
if (isBar)
bar.Layout(0, 0, r - l, barHeight);
else
child.Layout(0, barHeight + ContainerPadding, r, b);
}
else
{
if (isBar)
bar.Layout(0, -1000, r, barHeight - 1000);
else
child.Layout(0, ContainerPadding, r, b);
}
}
}
protected virtual void SetupPageTransition(FragmentTransaction transaction, bool isPush)
{
if (isPush)
transaction.SetTransition((int)FragmentTransit.FragmentOpen);
else
transaction.SetTransition((int)FragmentTransit.FragmentClose);
}
internal int GetNavBarHeight()
{
if (!ToolbarVisible)
return 0;
return ActionBarHeight();
}
int ActionBarHeight()
{
int attr = Resource.Attribute.actionBarSize;
int actionBarHeight;
using (var tv = new TypedValue())
{
actionBarHeight = 0;
if (Context.Theme.ResolveAttribute(attr, tv, true))
actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, Resources.DisplayMetrics);
}
if (actionBarHeight <= 0)
return Device.Info.CurrentOrientation.IsPortrait() ? (int)Context.ToPixels(56) : (int)Context.ToPixels(48);
return actionBarHeight;
}
void AnimateArrowIn()
{
var icon = _toolbar.NavigationIcon as DrawerArrowDrawable;
if (icon == null)
return;
ValueAnimator valueAnim = ValueAnimator.OfFloat(0, 1);
valueAnim.SetDuration(200);
valueAnim.Update += (s, a) => icon.Progress = (float)a.Animation.AnimatedValue;
valueAnim.Start();
}
void AnimateArrowOut()
{
var icon = _toolbar.NavigationIcon as DrawerArrowDrawable;
if (icon == null)
return;
ValueAnimator valueAnim = ValueAnimator.OfFloat(1, 0);
valueAnim.SetDuration(200);
valueAnim.Update += (s, a) => icon.Progress = (float)a.Animation.AnimatedValue;
valueAnim.Start();
}
public void OnClick(AView v)
{
Element?.PopAsync();
}
void CurrentOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == NavigationPage.HasNavigationBarProperty.PropertyName)
ToolbarVisible = NavigationPage.GetHasNavigationBar(Current);
else if (e.PropertyName == Page.TitleProperty.PropertyName)
UpdateToolbar();
else if (e.PropertyName == NavigationPage.HasBackButtonProperty.PropertyName)
UpdateToolbar();
}
#pragma warning disable 1998 // considered for removal
async void DeviceInfoPropertyChanged(object sender, PropertyChangedEventArgs e)
#pragma warning restore 1998
{
if (nameof(Device.Info.CurrentOrientation) == e.PropertyName)
ResetToolbar();
}
void FilterPageFragment(Page page)
{
_fragmentStack.RemoveAll(f => ((FragmentContainer)f).Page == page);
}
void HandleToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == MenuItem.IsEnabledProperty.PropertyName || e.PropertyName == MenuItem.TextProperty.PropertyName || e.PropertyName == MenuItem.IconProperty.PropertyName)
UpdateMenu();
}
void InsertPageBefore(Page page, Page before)
{
UpdateToolbar();
int index = PageController.InternalChildren.IndexOf(before);
if (index == -1)
throw new InvalidOperationException("This should never happen, please file a bug");
Fragment fragment = FragmentContainer.CreateInstance(page);
_fragmentStack.Insert(index, fragment);
}
void OnInsertPageBeforeRequested(object sender, NavigationRequestedEventArgs e)
{
InsertPageBefore(e.Page, e.BeforePage);
}
void OnPopped(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopViewAsync(e.Page, e.Animated);
}
void OnPoppedToRoot(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopToRootAsync(e.Page, e.Animated);
}
Task<bool> OnPopToRootAsync(Page page, bool animated)
{
return SwitchContentAsync(page, animated, true, true);
}
Task<bool> OnPopViewAsync(Page page, bool animated)
{
Page pageToShow = ((INavigationPageController)Element).StackCopy.Skip(1).FirstOrDefault();
if (pageToShow == null)
return Task.FromResult(false);
return SwitchContentAsync(pageToShow, animated, true);
}
Task<bool> OnPushAsync(Page view, bool animated)
{
return SwitchContentAsync(view, animated);
}
void OnPushed(object sender, NavigationRequestedEventArgs e)
{
e.Task = PushViewAsync(e.Page, e.Animated);
}
void OnRemovePageRequested(object sender, NavigationRequestedEventArgs e)
{
RemovePage(e.Page);
}
void RegisterToolbar()
{
Context context = Context;
AToolbar bar = _toolbar;
Element page = Element.RealParent;
MasterDetailPage masterDetailPage = null;
while (page != null)
{
if (page is MasterDetailPage)
{
masterDetailPage = page as MasterDetailPage;
break;
}
page = page.RealParent;
}
if (masterDetailPage == null)
{
masterDetailPage = PageController.InternalChildren[0] as MasterDetailPage;
if (masterDetailPage == null)
return;
}
if (((IMasterDetailPageController)masterDetailPage).ShouldShowSplitMode)
return;
var renderer = Android.Platform.GetRenderer(masterDetailPage) as MasterDetailPageRenderer;
if (renderer == null)
return;
_drawerLayout = renderer;
_drawerToggle = new ActionBarDrawerToggle((Activity)context, _drawerLayout, bar, global::Android.Resource.String.Ok, global::Android.Resource.String.Ok)
{
ToolbarNavigationClickListener = new ClickListener(Element)
};
if (_drawerListener != null)
{
_drawerLayout.RemoveDrawerListener(_drawerListener);
}
_drawerListener = new DrawerMultiplexedListener { Listeners = { _drawerToggle, renderer } };
_drawerLayout.AddDrawerListener(_drawerListener);
_drawerToggle.DrawerIndicatorEnabled = true;
}
void RemovePage(Page page)
{
IVisualElementRenderer rendererToRemove = Android.Platform.GetRenderer(page);
var containerToRemove = (PageContainer)rendererToRemove?.ViewGroup.Parent;
// Also remove this page from the fragmentStack
FilterPageFragment(page);
containerToRemove.RemoveFromParent();
if (rendererToRemove != null)
{
rendererToRemove.ViewGroup.RemoveFromParent();
rendererToRemove.Dispose();
}
containerToRemove?.Dispose();
Device.StartTimer(TimeSpan.FromMilliseconds(10), () =>
{
UpdateToolbar();
return false;
});
}
void ResetToolbar()
{
AToolbar oldToolbar = _toolbar;
_toolbar.RemoveFromParent();
_toolbar.SetNavigationOnClickListener(null);
_toolbar = null;
SetupToolbar();
RegisterToolbar();
UpdateToolbar();
UpdateMenu();
// Preserve old values that can't be replicated by calling methods above
if (_toolbar != null)
_toolbar.Subtitle = oldToolbar.Subtitle;
}
void SetupToolbar()
{
Context context = Context;
var activity = (FormsAppCompatActivity)context;
AToolbar bar;
if (FormsAppCompatActivity.ToolbarResource != 0)
bar = activity.LayoutInflater.Inflate(FormsAppCompatActivity.ToolbarResource, null).JavaCast<AToolbar>();
else
bar = new AToolbar(context);
bar.SetNavigationOnClickListener(this);
AddView(bar);
_toolbar = bar;
}
Task<bool> SwitchContentAsync(Page page, bool animated, bool removed = false, bool popToRoot = false)
{
var tcs = new TaskCompletionSource<bool>();
Fragment fragment = GetFragment(page, removed, popToRoot);
#if DEBUG
// Enables logging of moveToState operations to logcat
FragmentManager.EnableDebugLogging(true);
#endif
Current = page;
((Platform)Element.Platform).NavAnimationInProgress = true;
FragmentTransaction transaction = FragmentManager.BeginTransaction();
if (animated)
SetupPageTransition(transaction, !removed);
transaction.DisallowAddToBackStack();
if (_fragmentStack.Count == 0)
{
transaction.Add(Id, fragment);
_fragmentStack.Add(fragment);
}
else
{
if (removed)
{
// pop only one page, or pop everything to the root
var popPage = true;
while (_fragmentStack.Count > 1 && popPage)
{
Fragment currentToRemove = _fragmentStack.Last();
_fragmentStack.RemoveAt(_fragmentStack.Count - 1);
transaction.Remove(currentToRemove);
popPage = popToRoot;
}
Fragment toShow = _fragmentStack.Last();
// Execute pending transactions so that we can be sure the fragment list is accurate.
FragmentManager.ExecutePendingTransactions();
if (FragmentManager.Fragments.Contains(toShow))
transaction.Show(toShow);
else
transaction.Add(Id, toShow);
}
else
{
// push
Fragment currentToHide = _fragmentStack.Last();
transaction.Hide(currentToHide);
transaction.Add(Id, fragment);
_fragmentStack.Add(fragment);
}
}
// We don't currently support fragment restoration, so we don't need to worry about
// whether the commit loses state
transaction.CommitAllowingStateLoss();
// The fragment transitions don't really SUPPORT telling you when they end
// There are some hacks you can do, but they actually are worse than just doing this:
if (animated)
{
if (!removed)
{
UpdateToolbar();
if (_drawerToggle != null && ((INavigationPageController)Element).StackDepth == 2)
AnimateArrowIn();
}
else if (_drawerToggle != null && ((INavigationPageController)Element).StackDepth == 2)
AnimateArrowOut();
Device.StartTimer(TimeSpan.FromMilliseconds(TransitionDuration), () =>
{
tcs.TrySetResult(true);
fragment.UserVisibleHint = true;
if (removed)
{
UpdateToolbar();
}
return false;
});
}
else
{
Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
{
tcs.TrySetResult(true);
fragment.UserVisibleHint = true;
UpdateToolbar();
return false;
});
}
Context.HideKeyboard(this);
((Platform)Element.Platform).NavAnimationInProgress = false;
// TransitionDuration is how long the built-in animations are, and they are "reversible" in the sense that starting another one slightly before it's done is fine
return tcs.Task;
}
Fragment GetFragment(Page page, bool removed, bool popToRoot)
{
// pop
if (removed)
return _fragmentStack[_fragmentStack.Count - 2];
// pop to root
if(popToRoot)
return _fragmentStack[0];
// push
return FragmentContainer.CreateInstance(page);
}
void ToolbarTrackerOnCollectionChanged(object sender, EventArgs eventArgs)
{
UpdateMenu();
}
void UpdateMenu()
{
if (_disposed)
return;
AToolbar bar = _toolbar;
Context context = Context;
IMenu menu = bar.Menu;
foreach (ToolbarItem item in _toolbarTracker.ToolbarItems)
item.PropertyChanged -= HandleToolbarItemPropertyChanged;
menu.Clear();
foreach (ToolbarItem item in _toolbarTracker.ToolbarItems)
{
IMenuItemController controller = item;
item.PropertyChanged += HandleToolbarItemPropertyChanged;
if (item.Order == ToolbarItemOrder.Secondary)
{
IMenuItem menuItem = menu.Add(item.Text);
menuItem.SetEnabled(controller.IsEnabled);
menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(controller.Activate));
}
else
{
IMenuItem menuItem = menu.Add(item.Text);
FileImageSource icon = item.Icon;
if (!string.IsNullOrEmpty(icon))
{
var iconBitmap = new BitmapDrawable(context.Resources, ResourceManager.GetBitmap(context.Resources, icon));
if (iconBitmap != null && iconBitmap.Bitmap != null)
menuItem.SetIcon(iconBitmap);
}
menuItem.SetEnabled(controller.IsEnabled);
menuItem.SetShowAsAction(ShowAsAction.Always);
menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(controller.Activate));
}
}
}
void UpdateToolbar()
{
if (_disposed)
return;
Context context = Context;
var activity = (FormsAppCompatActivity)context;
AToolbar bar = _toolbar;
ActionBarDrawerToggle toggle = _drawerToggle;
if (bar == null)
return;
bool isNavigated = ((INavigationPageController)Element).StackDepth > 1;
bar.NavigationIcon = null;
if (isNavigated)
{
if (toggle != null)
{
toggle.DrawerIndicatorEnabled = false;
toggle.SyncState();
}
if (NavigationPage.GetHasBackButton(Element.CurrentPage))
{
var icon = new DrawerArrowDrawable(activity.SupportActionBar.ThemedContext);
icon.Progress = 1;
bar.NavigationIcon = icon;
}
}
else
{
if (toggle != null)
{
toggle.DrawerIndicatorEnabled = true;
toggle.SyncState();
}
}
Color tintColor = Element.BarBackgroundColor;
if (Forms.IsLollipopOrNewer)
{
if (tintColor.IsDefault)
bar.BackgroundTintMode = null;
else
{
bar.BackgroundTintMode = PorterDuff.Mode.Src;
bar.BackgroundTintList = ColorStateList.ValueOf(tintColor.ToAndroid());
}
}
else
{
if (tintColor.IsDefault && _backgroundDrawable != null)
bar.SetBackground(_backgroundDrawable);
else if (!tintColor.IsDefault)
{
if (_backgroundDrawable == null)
_backgroundDrawable = bar.Background;
bar.SetBackgroundColor(tintColor.ToAndroid());
}
}
Color textColor = Element.BarTextColor;
if (!textColor.IsDefault)
bar.SetTitleTextColor(textColor.ToAndroid().ToArgb());
bar.Title = Element.CurrentPage.Title ?? "";
}
class ClickListener : Object, IOnClickListener
{
readonly NavigationPage _element;
public ClickListener(NavigationPage element)
{
_element = element;
}
public void OnClick(AView v)
{
_element?.PopAsync();
}
}
class DrawerMultiplexedListener : Object, DrawerLayout.IDrawerListener
{
public List<DrawerLayout.IDrawerListener> Listeners { get; } = new List<DrawerLayout.IDrawerListener>(2);
public void OnDrawerClosed(AView drawerView)
{
foreach (DrawerLayout.IDrawerListener listener in Listeners)
listener.OnDrawerClosed(drawerView);
}
public void OnDrawerOpened(AView drawerView)
{
foreach (DrawerLayout.IDrawerListener listener in Listeners)
listener.OnDrawerOpened(drawerView);
}
public void OnDrawerSlide(AView drawerView, float slideOffset)
{
foreach (DrawerLayout.IDrawerListener listener in Listeners)
listener.OnDrawerSlide(drawerView, slideOffset);
}
public void OnDrawerStateChanged(int newState)
{
foreach (DrawerLayout.IDrawerListener listener in Listeners)
listener.OnDrawerStateChanged(newState);
}
}
}
}
| |
/**
* Copyright 2016 Dartmouth-Hitchcock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Xml;
using Legion.Core.Caching;
using Legion.Core.DataStructures;
using Legion.Core.Exceptions;
using Legion.Core.Modules;
using Legion.Core.Services;
namespace Legion.Core {
/// <summary>
/// Manages requests to the Legion API
/// </summary>
public static class Manager {
private static Dictionary<string, Method> _systemMethods = new Dictionary<string, Method>() {
{ "__status", null }
};
/// <summary>
/// Start manager system tasks
/// </summary>
public static void SpinUp() {
LoggingBuffer.Start();
}
/// <summary>
/// Stop manager system tasks
/// </summary>
public static void SpinDown() {
LoggingBuffer.Stop();
}
/// <summary>
/// Processes the Legion request utilizing the Service cache
/// </summary>
/// <param name="page">The current Page object</param>
public static void Process(Page page){
if (page.Cache[Cache.CACHE_KEYS.Services] != null) {
Dictionary<string, Service> services = (Dictionary<string, Service>)HttpRuntime.Cache[Cache.CACHE_KEYS.Services];
Reply reply = GetReply(new Request(page), services);
page.Response.Clear();
page.Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
page.Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
page.Response.AppendHeader("Expires", "0"); // Proxies.
page.Response.ContentType = reply.ContentType;
page.Response.Write(reply);
}
else {
Logging.Module.WriteException(new LoggedException() {
Type = "CacheNotFound",
Message = Settings.GetString("ExceptionMessageCacheNotFound")
});
}
}
/// <summary>
/// Processes a pre-generated Legion Request
/// </summary>
/// <param name="request">The LegionRequest object to process</param>
/// <returns>The LegionReply from the service</returns>
internal static Reply Process(Request request) {
System.Web.Caching.Cache cache = HttpRuntime.Cache;
if (cache[Cache.CACHE_KEYS.Services] != null) {
Reply reply = GetReply(request, (Dictionary<string, Service>)cache[Cache.CACHE_KEYS.Services]);
return reply;
}
else {
Logging.Module.WriteException(new LoggedException() {
Type = "CacheNotFound",
Message = "Cache not found"
});
return null;
}
}
/// <summary>
/// Gets the result from the requested handler
/// </summary>
/// <param name="request">The LegionRequest object to process</param>
/// <param name="services">Dictionary of the available Services</param>
/// <returns>A string representation of the XML result</returns>
private static Reply GetReply(Request request, Dictionary<string, Service> services) {
Cache.Refresh();
ResultCache.TryExpire();
Reply reply = new Reply(request);
Service service = null; Method method = null;
DateTime dtprocessed = DateTime.Now;
TimeSpan executionTime = TimeSpan.Zero;
try {
if (!request.RateLimit.IsExceeded) {
request.RateLimit.BitchSlap();
//identify service.method call
if (request.APIKey.Key != null) {
if (!request.APIKey.IsRevoked) {
if (request.APIKey.IsValid) {
if (request.IsServiceToService || request.Application.HasValidSourceIP(request.Requestor.HostIPAddress)) {
if (request.ServiceKey != null) {
if (services.ContainsKey(request.ServiceKey)) {
service = services[request.ServiceKey];
if (request.IsServiceToService || service.HasValidSourceIP(request.Requestor.HostIPAddress)) {
if (request.MethodKey != null) {
if (service.Open != null && service.Open.ContainsKey(request.MethodKey))
method = service.Open[request.MethodKey];
else if (service.Restricted != null && service.Restricted.ContainsKey(request.MethodKey)) {
if (request.IsServiceToService || request.Application.HasPermissionTo(request.ServiceKey, request.MethodKey))
method = service.Restricted[request.MethodKey];
else //application does not have access to this method
LogFault(request, reply, "InsufficientPermissions", Settings.GetString("FaultMessageInsufficientPermissions", new Dictionary<string, string>(){
{"ApplicationName", request.Application.Name},
{"ServiceKey", request.ServiceKey},
{"MethodKey", request.MethodKey}
}));
}
else if (service.Special.ContainsKey(request.MethodKey)) { //special method
method = service.Special[request.MethodKey];
}
else //method not found
LogFault(request, reply, "MethodNotFound", Settings.GetString("FaultMessageMethodNotFound", new Dictionary<string, string>(){
{"ServiceKey", request.ServiceKey},
{"MethodKey", request.MethodKey}
}));
}
else //method not specified
LogFault(request, reply, "MethodNotSpecified", Settings.GetString("FaultMessageMethodNotSpecified", new Dictionary<string, string>(){
{"ServiceKey", request.ServiceKey}
}));
}
else //invalid service source ip
LogFault(request, reply, "ServiceSourceIpInvalid", Settings.GetString("FaultMessageServiceSourceIpInvalid", new Dictionary<string, string>(){
{"HostIpAddress", request.Requestor.HostIPAddress},
{"ServiceKey", request.ServiceKey}
}));
}
else //service not found
LogFault(request, reply, "ServiceNotFound", Settings.GetString("FaultMessageServiceNotFound", new Dictionary<string, string>(){
{"ServiceKey", request.ServiceKey}
}));
}
else //no service specified
LogFault(request, reply, "ServiceNotSpecified", Settings.GetString("FaultMessageServiceNotSpecified", new Dictionary<string, string>() {
}));
}
else //invalid application source ip
LogFault(request, reply, "ApplicationSourceIpInvalid", Settings.GetString("FaultMessageApplicationSourceIpInvalid", new Dictionary<string, string>(){
{"HostIpAddress", request.Requestor.HostIPAddress},
{"ApiKey", request.APIKey.Key}
}));
}
else //api key not found
LogFault(request, reply, "ApiKeyInvalid", Settings.GetString("FaultMessageApiKeyInvalid", new Dictionary<string, string>(){
{"ApiKey", request.APIKey.Key}
}));
}
else //api key revoked
LogFault(request, reply, "ApiKeyRevoked", Settings.GetString("FaultMessageApiKeyRevoked", new Dictionary<string, string>(){
{"ApiKey", request.APIKey.Key}
}));
}
else //no api key specified
LogFault(request, reply, "ApiKeyNotSpecified", Settings.GetString("FaultMessageApiKeyNotSpecified", new Dictionary<string, string>() {
}));
}
else //rate limit exceeded
LogFault(request, reply, "RateLimitExceeded", Settings.GetString("FaultMessageRateLimitExceeded", new Dictionary<string, string>(){
{"RateLimit", request.RateLimit.ToString()}
}));
//restrict public proxied requests
if (method != null && request.IsProxied) {
if (!request.Application.IsPublic) {
method = null;
LogFault(request, reply, "ApplicationNotPublic", Settings.GetString("FaultMessageApplicationNotPublic", new Dictionary<string, string>(){
{"ApiKey", request.APIKey.Key}
}));
}
else if (!(service.IsPublic || method.IsPublic)) {
method = null;
LogFault(request, reply, "MethodNotPublic", Settings.GetString("FaultMessageMethodNotPublic", new Dictionary<string, string>(){
{"MethodKey", request.MethodKey}
}));
}
}
if (method != null) {
if (request.Requestor.Account == null) { //check for auth token if required
if (method.IsAuthenticatedUserRequired) {
method = null;
LogFault(request, reply, "AuthenticatedUserRequiredForMethod", Settings.GetString("FaultMessageMethodAuthenticatedUserRequired", new Dictionary<string, string>(){
{"MethodKey", request.MethodKey}
}));
}
else if (service.IsAuthenticatedUserRequired) {
method = null;
LogFault(request, reply, "AuthenticatedUserRequiredForService", Settings.GetString("FaultMessageServiceAuthenticatedUserRequired", new Dictionary<string, string>(){
{"ServiceKey", request.ServiceKey}
}));
}
}
else { //check for authorization if required
if (method.IsAuthorizedUserRequired) {
bool hasPermission = Permissions.Module.Check(
request.Requestor.Account.AccountType,
request.Requestor.Account.IdentifierType,
request.Requestor.Account.Identifier,
string.Format("Method/{0}.{1}", request.ServiceKey, request.MethodKey)
);
if (!hasPermission) {
method = null;
LogFault(request, reply, "AuthorizedUserRequiredForMethod", Settings.GetString("FaultMessageMethodAuthorizedUserRequired", new Dictionary<string, string>(){
{"MethodKey", request.MethodKey}
}));
}
}
else if (service.IsAuthorizedUserRequired) {
bool hasPermission = Permissions.Module.Check(
request.Requestor.Account.AccountType,
request.Requestor.Account.IdentifierType,
request.Requestor.Account.Identifier,
string.Format("Service/{0}", request.ServiceKey, request.MethodKey)
);
if (!hasPermission) {
method = null;
LogFault(request, reply, "AuthorizedUserRequiredForService", Settings.GetString("FaultMessageServiceAuthorizedUserRequired", new Dictionary<string, string>(){
{"ServiceKey", request.ServiceKey}
}));
}
}
}
}
//service and method were found and are valid, process request
if (method != null) {
//is permanent logging required
if (request.Application.IsLogged || service.IsLogged || method.IsLogged) {
if (request.Requestor.ClientIPAddress != null)
executionTime = InvokeMethod(method, request, reply, dtprocessed, true);
else
LogFault(request, reply, "UserIpRequired", Settings.GetString("FaultMessageUserIpRequired", new Dictionary<string, string>(){
{"ServiceName", service.Name},
{"MethodName", method.Name}
}));
}
else
executionTime = InvokeMethod(method, request, reply, dtprocessed, false);
}
//add application details
if (request.Application != null && !request.IsProxied) {
XmlElement app = reply.Response.AddElement(Settings.GetString("NodeNameApplication"));
reply.Response.AddElement(app, Settings.GetString("NodeNameApplicationApiKey"), (request.APIKey.Key == null ? Settings.GetString("SymbolNotSpecified") : request.APIKey.Key));
reply.Response.AddElement(app, Settings.GetString("NodeNameApplicationName"), (request.Application == null ? string.Empty : request.Application.Name));
}
//add service details
if (service != null) {
XmlElement xService;
xService = reply.Response.AddElement(Settings.GetString("NodeNameService"), request.ServiceKey);
xService.SetAttribute(Settings.GetString("NodeAttributeServiceCompiledOn"), service.CompiledOn);
xService.SetAttribute(Settings.GetString("NodeAttributeServiceVersion"), service.Version);
//add method details
if (request.MethodKey != null)
reply.Response.AddElement(Settings.GetString("NodeNameMethod"), request.MethodKey);
}
//add host details
reply.Response.AddElement(Settings.GetString("NodeNameLegionHost"), string.Format("{0}:{1}", System.Environment.MachineName, System.Diagnostics.Process.GetCurrentProcess().Id));
reply.Response.AddElement(Settings.GetString("NodeNameProcessedOn"), Settings.FormatDateTime(dtprocessed));
//add time diagnostics
reply.Response.AddElement(Settings.GetString("NodeNameElapsedTime"), string.Format("{0} ms", (executionTime.TotalMilliseconds == 0 ? "less than 1" : string.Empty + executionTime.TotalMilliseconds)));
}
catch (HandlingError e) {
LogFault(request, reply, e.GetType().ToString(), e.Message);
}
finally {
//mark the request as complete and clean up the request stack
request.Complete();
}
return reply;
}
/// <summary>
/// Invokes a Method
/// </summary>
/// <param name="method">the method to invoke</param>
/// <param name="request">the Request object to pass to the Method</param>
/// <param name="reply">the Reply object to be used by the Method</param>
/// <param name="dtProcessingStart">the time the Legion request was recieved</param>
/// <param name="permLog">Log this call to the permenant log</param>
/// <returns>the time taken to invoke the method</returns>
private static TimeSpan InvokeMethod(Method method, Request request, Reply reply, DateTime dtProcessingStart, bool permLog) {
DateTime dtExecutionStart = DateTime.MinValue, dtExecutionEnd = DateTime.MinValue;
try {
request.Method = method;
dtExecutionStart = DateTime.Now;
method.Invoke(request, reply); //call it
dtExecutionEnd = DateTime.Now;
}
catch (Exception e) {
dtExecutionEnd = DateTime.Now; //this line is duplicated here to ensure that the excecution end time is set if there is a fault
if (e is TargetInvocationException && e.InnerException is ServiceError)
reply.Error.Friendly = e.InnerException.Message;
else
LogFault(request, reply, method, "InvocationException", e);
}
finally {
method.LogCall(dtProcessingStart, dtExecutionStart, dtExecutionEnd, request.Application, request.ServiceKey, request.ParameterSet, request.Requestor.HostIPAddress, request.Requestor.ClientIPAddress, permLog);
}
return (dtExecutionStart == DateTime.MinValue ? TimeSpan.Zero : dtExecutionEnd - dtExecutionStart);
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="reply"></param>
/// <param name="method"></param>
/// <param name="type"></param>
/// <param name="e"></param>
internal static void LogFault(Request request, Reply reply, Method method, string type, Exception e) {
if (e is TargetInvocationException)
e = e.InnerException;
int eventid = Logging.Module.WriteException(new LoggedException() {
Request = request,
Exception = e
});
reply.Result.Clear();
XmlElement exception = reply.Result.AddElement(Settings.GetString("NodeNameException"));
exception.SetAttribute(Settings.GetString("NodeAttributeExceptionId"), eventid.ToString());
reply.Result.AddElement(exception, Settings.GetString("NodeNameExceptionName"), e.GetType().Name);
reply.Result.AddElement(exception, Settings.GetString("NodeNameExceptionMessage"), e.Message);
reply.Result.AddElement(exception, Settings.GetString("NodeNameExceptionStacktrace"), e.StackTrace, true);
if (method != null && method.IsLogReplayDetailsOnException)
ReplayLog.LogException(eventid, method.Id, request.ParameterSet.ToXml(), e.GetType().Name, e.Message, e.StackTrace);
LogFault(
request,
reply,
type,
Settings.GetString("LogFormatExceptionFriendly", new Dictionary<string, string>(){
{"EventId", eventid.ToString()},
{"MethodKey", request.MethodKey},
{"MethodName", method.Name}
}),
Settings.GetString("LogFormatExceptionDetailed", new Dictionary<string, string>(){
{"EventId", eventid.ToString()},
{"MethodKey", request.MethodKey},
{"MethodName", method.Name}
})
);
}
/// <summary>
/// Logs an fault to Lumberjack and to the client
/// </summary>
/// <param name="request">The original Request object</param>
/// <param name="reply">The Reply object to be sent to the client</param>
/// <param name="type">The type of fault</param>
/// <param name="fault">The message to send to the client</param>
internal static void LogFault(Request request, Reply reply, string type, string fault) {
LogFault(request, reply, type, fault, fault);
}
/// <summary>
/// Logs an fault to Lumberjack and to the client
/// </summary>
/// <param name="request">The original Request object</param>
/// <param name="reply">The Reply object to be sent to the client</param>
/// <param name="type">The type of fault</param>
/// <param name="faultClient">The fault to send to the client</param>
/// <param name="faultLog">The detailed fault to log to file</param>
private static void LogFault(Request request, Reply reply, string type, string faultClient, string faultLog) {
XmlElement xFault = reply.Response.AddElement(Settings.GetString("NodeNameFault"), faultClient);
xFault.SetAttribute("type", type);
string apikey = (request.APIKey == null ? Settings.GetString("SymbolNotApplicable") : request.APIKey.Key);
string applicationid = (request.Application == null ? Settings.GetString("SymbolNotApplicable") : request.Application.Id.ToString());
string applicationname = (request.Application == null ? Settings.GetString("SymbolNotApplicable") : request.Application.Name);
string details = Settings.GetString("LogFormatFault", new Dictionary<string, string>(){
{"ApiKey", apikey},
{"ApplicationId", applicationid},
{"ApplicationName", applicationname},
{"ServiceKey", request.ServiceKey},
{"MethodKey", request.MethodKey},
{"Fault", faultLog}
});
Logging.Module.WriteEvent(new LoggedEvent(EventLevel.Fatal, type, details) {
ClientIp = request.Requestor.ClientIPAddress,
HostIp = request.Requestor.HostIPAddress
});
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define CONTRACTS_FULL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace ExamplesPurity
{
public class Simple
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=27,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=27,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=13,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=27,MethodILOffset=0)]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter untouched")]
public void ChangeFirstElementNoPure([Pure] int[] arr, object[] untouched)
{
Contract.Requires(arr != null);
Contract.Requires(arr.Length > 0);
arr[0] = 123;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=27,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=27,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=13,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=27,MethodILOffset=0)]
// Nothing to suggest
public void ChangeFirstElement([Pure] int[] arr, [Pure] object[] untouched)
{
Contract.Requires(arr != null);
Contract.Requires(arr.Length > 0);
arr[0] = 123;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=23,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=23,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=30,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=23,MethodILOffset=0)]
// Nothing to suggest
public void ChangeAllTheElements([Pure] int[] arr)
{
Contract.Requires(arr != null);
for (var i = 0; i < arr.Length; i++)
{
arr[i] = 1234;
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 'arr'",PrimaryILOffset=18,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(arr != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter arr")]
public int Unchanged(int[] arr)
{
var sum = 0;
for (var i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
return sum;
}
}
}
namespace ForAllPreconditionInference
{
public class Tests
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=24,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=13,MethodILOffset=0)]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public void TestAllElements(string[] s)
{
for (var i = 0; i < s.Length; i++)
{
Contract.Assert(s[i] != null);
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=28,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=13,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public void TestAllElementsAndChangeThem(string[] s)
{
for (var i = 0; i < s.Length; i++)
{
Contract.Assert(s[i] != null);
s[i] = null;
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=24,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public void AssumeAllElements(string[] s)
{
for (var i = 0; i < s.Length; i++)
{
Contract.Assume(s[i] != null);
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=28,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public void AssumeAllElementsAndChangeThem(string[] s)
{
for (var i = 0; i < s.Length; i++)
{
Contract.Assume(s[i] != null);
s[i] = null;
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=2,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be above the upper bound",PrimaryILOffset=2,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=2,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(3 < s.Length);")]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 3, 4, s[i] != null));")]
public void AssertOneElement(string[] s)
{
Contract.Assert(s[3] != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=3,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be above the upper bound",PrimaryILOffset=3,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=3,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(12 < s.Length);")]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
public int DoNotTestOneElement(string[] s)
{
int v;
if (s[12] == null)
{
v = 0;
}
else
{
v = 1;
}
return v;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=23,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference",PrimaryILOffset=10,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public int Sum(string[] s)
{
var sum = 0;
for (var i = 0; i < s.Length; i++)
{
sum += s[i].Length;
}
return sum;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=23,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly accessing a field on a null reference",PrimaryILOffset=10,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
[RegressionOutcome("Contract.Requires(Contract.Forall(s, 0, s.Length, s[i] != null));")]
public int Sum(Dummy[] s)
{
var sum = 0;
for (var i = 0; i < s.Length; i++)
{
sum += s[i].f;
}
return sum;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be above the upper bound",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 's'",PrimaryILOffset=9,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly accessing a field on a null reference",PrimaryILOffset=10,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter s")]
public int Sum(Dummy[] s, int end)
{
var sum = 0;
for (var i = 0; i < end; i++)
{
sum += s[i].f;
}
return sum;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=15,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=15,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=30,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=15,MethodILOffset=0)]
[RegressionOutcome("Consider adding the [Pure] attribute to the parameter genericArguments")]
[RegressionOutcome("Contract.Requires(Contract.Forall(genericArguments, 0, genericArguments.Length, genericArguments[i] != null));")]
static void SanityCheckArguments(object[] genericArguments)
{
if (genericArguments == null)
{
throw new ArgumentNullException();
}
for (int i = 0; i < genericArguments.Length; i++)
{
if (genericArguments[i] == null)
{
throw new ArgumentNullException();
}
}
}
public class Dummy
{
public int f;
}
}
public class ExamplesWithControlFlow
{
[ClousotRegressionTest]
public void NotAllThePaths(int x, string[] s)
{
if (x > 10)
return;
for (var i = 0; i < s.Length; i++)
{
Contract.Assert(s[i] != null);
}
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using MatterHackers.Agg.Image;
namespace MatterHackers.Agg
{
public interface IImageBufferAccessor
{
byte[] span(int x, int y, int len, out int bufferIndex);
byte[] next_x(out int bufferByteOffset);
byte[] next_y(out int bufferByteOffset);
IImageByte SourceImage
{
get;
}
};
public class ImageBufferAccessorCommon : IImageBufferAccessor
{
protected IImageByte m_SourceImage;
protected int m_x, m_x0, m_y, m_DistanceBetweenPixelsInclusive;
protected byte[] m_Buffer;
protected int m_CurrentBufferOffset = -1;
private int m_Width;
public ImageBufferAccessorCommon(IImageByte pixf)
{
attach(pixf);
}
private void attach(IImageByte pixf)
{
m_SourceImage = pixf;
m_Buffer = m_SourceImage.GetBuffer();
m_Width = m_SourceImage.Width;
m_DistanceBetweenPixelsInclusive = m_SourceImage.GetBytesBetweenPixelsInclusive();
}
public IImageByte SourceImage
{
get
{
return m_SourceImage;
}
}
private byte[] pixel(out int bufferByteOffset)
{
int x = m_x;
int y = m_y;
unchecked
{
if ((uint)x >= (uint)m_SourceImage.Width)
{
if (x < 0)
{
x = 0;
}
else
{
x = (int)m_SourceImage.Width - 1;
}
}
if ((uint)y >= (uint)m_SourceImage.Height)
{
if (y < 0)
{
y = 0;
}
else
{
y = (int)m_SourceImage.Height - 1;
}
}
}
bufferByteOffset = m_SourceImage.GetBufferOffsetXY(x, y);
return m_SourceImage.GetBuffer();
}
public byte[] span(int x, int y, int len, out int bufferOffset)
{
m_x = m_x0 = x;
m_y = y;
unchecked
{
if ((uint)y < (uint)m_SourceImage.Height
&& x >= 0 && x + len <= (int)m_SourceImage.Width)
{
bufferOffset = m_SourceImage.GetBufferOffsetXY(x, y);
m_Buffer = m_SourceImage.GetBuffer();
m_CurrentBufferOffset = bufferOffset;
return m_Buffer;
}
}
m_CurrentBufferOffset = -1;
return pixel(out bufferOffset);
}
public byte[] next_x(out int bufferOffset)
{
// this is the code (managed) that the original agg used.
// It looks like it doesn't check x but, It should be a bit faster and is valid
// because "span" checked the whole length for good x.
if (m_CurrentBufferOffset != -1)
{
m_CurrentBufferOffset += m_DistanceBetweenPixelsInclusive;
bufferOffset = m_CurrentBufferOffset;
return m_Buffer;
}
++m_x;
return pixel(out bufferOffset);
}
public byte[] next_y(out int bufferOffset)
{
++m_y;
m_x = m_x0;
if (m_CurrentBufferOffset != -1
&& (uint)m_y < (uint)m_SourceImage.Height)
{
m_CurrentBufferOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y);
m_SourceImage.GetBuffer();
bufferOffset = m_CurrentBufferOffset;
return m_Buffer;
}
m_CurrentBufferOffset = -1;
return pixel(out bufferOffset);
}
};
public sealed class ImageBufferAccessorClip : ImageBufferAccessorCommon
{
private byte[] m_OutsideBufferColor;
public ImageBufferAccessorClip(IImageByte sourceImage, Color bk)
: base(sourceImage)
{
m_OutsideBufferColor = new byte[4];
m_OutsideBufferColor[0] = bk.red;
m_OutsideBufferColor[1] = bk.green;
m_OutsideBufferColor[2] = bk.blue;
m_OutsideBufferColor[3] = bk.alpha;
}
private byte[] pixel(out int bufferByteOffset)
{
unchecked
{
if (((uint)m_x < (uint)m_SourceImage.Width)
&& ((uint)m_y < (uint)m_SourceImage.Height))
{
bufferByteOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y);
return m_SourceImage.GetBuffer();
}
}
bufferByteOffset = 0;
return m_OutsideBufferColor;
}
};
/*
//--------------------------------------------------image_accessor_no_clip
template<class PixFmt> class image_accessor_no_clip
{
public:
typedef PixFmt pixfmt_type;
typedef typename pixfmt_type::color_type color_type;
typedef typename pixfmt_type::order_type order_type;
typedef typename pixfmt_type::value_type value_type;
enum pix_width_e { pix_width = pixfmt_type::pix_width };
image_accessor_no_clip() {}
explicit image_accessor_no_clip(pixfmt_type& pixf) :
m_pixf(&pixf)
{}
void attach(pixfmt_type& pixf)
{
m_pixf = &pixf;
}
byte* span(int x, int y, int)
{
m_x = x;
m_y = y;
return m_pix_ptr = m_pixf->pix_ptr(x, y);
}
byte* next_x()
{
return m_pix_ptr += pix_width;
}
byte* next_y()
{
++m_y;
return m_pix_ptr = m_pixf->pix_ptr(m_x, m_y);
}
private:
pixfmt_type* m_pixf;
int m_x, m_y;
byte* m_pix_ptr;
};
*/
public sealed class ImageBufferAccessorClamp : ImageBufferAccessorCommon
{
public ImageBufferAccessorClamp(IImageByte pixf)
: base(pixf)
{
}
private byte[] pixel(out int bufferByteOffset)
{
int x = m_x;
int y = m_y;
unchecked
{
if ((uint)x >= (uint)m_SourceImage.Width)
{
if (x < 0)
{
x = 0;
}
else
{
x = (int)m_SourceImage.Width - 1;
}
}
if ((uint)y >= (uint)m_SourceImage.Height)
{
if (y < 0)
{
y = 0;
}
else
{
y = (int)m_SourceImage.Height - 1;
}
}
}
bufferByteOffset = m_SourceImage.GetBufferOffsetXY(x, y);
return m_SourceImage.GetBuffer();
}
};
/*
//-----------------------------------------------------image_accessor_wrap
template<class PixFmt, class WrapX, class WrapY> class image_accessor_wrap
{
public:
typedef PixFmt pixfmt_type;
typedef typename pixfmt_type::color_type color_type;
typedef typename pixfmt_type::order_type order_type;
typedef typename pixfmt_type::value_type value_type;
enum pix_width_e { pix_width = pixfmt_type::pix_width };
image_accessor_wrap() {}
explicit image_accessor_wrap(pixfmt_type& pixf) :
m_pixf(&pixf),
m_wrap_x(pixf.Width),
m_wrap_y(pixf.Height)
{}
void attach(pixfmt_type& pixf)
{
m_pixf = &pixf;
}
byte* span(int x, int y, int)
{
m_x = x;
m_row_ptr = m_pixf->row_ptr(m_wrap_y(y));
return m_row_ptr + m_wrap_x(x) * pix_width;
}
byte* next_x()
{
int x = ++m_wrap_x;
return m_row_ptr + x * pix_width;
}
byte* next_y()
{
m_row_ptr = m_pixf->row_ptr(++m_wrap_y);
return m_row_ptr + m_wrap_x(m_x) * pix_width;
}
private:
pixfmt_type* m_pixf;
byte* m_row_ptr;
int m_x;
WrapX m_wrap_x;
WrapY m_wrap_y;
};
//--------------------------------------------------------wrap_mode_repeat
class wrap_mode_repeat
{
public:
wrap_mode_repeat() {}
wrap_mode_repeat(int size) :
m_size(size),
m_add(size * (0x3FFFFFFF / size)),
m_value(0)
{}
int operator() (int v)
{
return m_value = (int(v) + m_add) % m_size;
}
int operator++ ()
{
++m_value;
if(m_value >= m_size) m_value = 0;
return m_value;
}
private:
int m_size;
int m_add;
int m_value;
};
//---------------------------------------------------wrap_mode_repeat_pow2
class wrap_mode_repeat_pow2
{
public:
wrap_mode_repeat_pow2() {}
wrap_mode_repeat_pow2(int size) : m_value(0)
{
m_mask = 1;
while(m_mask < size) m_mask = (m_mask << 1) | 1;
m_mask >>= 1;
}
int operator() (int v)
{
return m_value = int(v) & m_mask;
}
int operator++ ()
{
++m_value;
if(m_value > m_mask) m_value = 0;
return m_value;
}
private:
int m_mask;
int m_value;
};
//----------------------------------------------wrap_mode_repeat_auto_pow2
class wrap_mode_repeat_auto_pow2
{
public:
wrap_mode_repeat_auto_pow2() {}
wrap_mode_repeat_auto_pow2(int size) :
m_size(size),
m_add(size * (0x3FFFFFFF / size)),
m_mask((m_size & (m_size-1)) ? 0 : m_size-1),
m_value(0)
{}
int operator() (int v)
{
if(m_mask) return m_value = int(v) & m_mask;
return m_value = (int(v) + m_add) % m_size;
}
int operator++ ()
{
++m_value;
if(m_value >= m_size) m_value = 0;
return m_value;
}
private:
int m_size;
int m_add;
int m_mask;
int m_value;
};
//-------------------------------------------------------wrap_mode_reflect
class wrap_mode_reflect
{
public:
wrap_mode_reflect() {}
wrap_mode_reflect(int size) :
m_size(size),
m_size2(size * 2),
m_add(m_size2 * (0x3FFFFFFF / m_size2)),
m_value(0)
{}
int operator() (int v)
{
m_value = (int(v) + m_add) % m_size2;
if(m_value >= m_size) return m_size2 - m_value - 1;
return m_value;
}
int operator++ ()
{
++m_value;
if(m_value >= m_size2) m_value = 0;
if(m_value >= m_size) return m_size2 - m_value - 1;
return m_value;
}
private:
int m_size;
int m_size2;
int m_add;
int m_value;
};
//--------------------------------------------------wrap_mode_reflect_pow2
class wrap_mode_reflect_pow2
{
public:
wrap_mode_reflect_pow2() {}
wrap_mode_reflect_pow2(int size) : m_value(0)
{
m_mask = 1;
m_size = 1;
while(m_mask < size)
{
m_mask = (m_mask << 1) | 1;
m_size <<= 1;
}
}
int operator() (int v)
{
m_value = int(v) & m_mask;
if(m_value >= m_size) return m_mask - m_value;
return m_value;
}
int operator++ ()
{
++m_value;
m_value &= m_mask;
if(m_value >= m_size) return m_mask - m_value;
return m_value;
}
private:
int m_size;
int m_mask;
int m_value;
};
//---------------------------------------------wrap_mode_reflect_auto_pow2
class wrap_mode_reflect_auto_pow2
{
public:
wrap_mode_reflect_auto_pow2() {}
wrap_mode_reflect_auto_pow2(int size) :
m_size(size),
m_size2(size * 2),
m_add(m_size2 * (0x3FFFFFFF / m_size2)),
m_mask((m_size2 & (m_size2-1)) ? 0 : m_size2-1),
m_value(0)
{}
int operator() (int v)
{
m_value = m_mask ? int(v) & m_mask :
(int(v) + m_add) % m_size2;
if(m_value >= m_size) return m_size2 - m_value - 1;
return m_value;
}
int operator++ ()
{
++m_value;
if(m_value >= m_size2) m_value = 0;
if(m_value >= m_size) return m_size2 - m_value - 1;
return m_value;
}
private:
int m_size;
int m_size2;
int m_add;
int m_mask;
int m_value;
};
*/
public interface IImageBufferAccessorFloat
{
float[] span(int x, int y, int len, out int bufferIndex);
float[] next_x(out int bufferFloatOffset);
float[] next_y(out int bufferFloatOffset);
IImageFloat SourceImage
{
get;
}
};
public class ImageBufferAccessorCommonFloat : IImageBufferAccessorFloat
{
protected IImageFloat m_SourceImage;
protected int m_x, m_x0, m_y, m_DistanceBetweenPixelsInclusive;
protected float[] m_Buffer;
protected int m_CurrentBufferOffset = -1;
private int m_Width;
public ImageBufferAccessorCommonFloat(IImageFloat pixf)
{
attach(pixf);
}
private void attach(IImageFloat pixf)
{
m_SourceImage = pixf;
m_Buffer = m_SourceImage.GetBuffer();
m_Width = m_SourceImage.Width;
m_DistanceBetweenPixelsInclusive = m_SourceImage.GetFloatsBetweenPixelsInclusive();
}
public IImageFloat SourceImage
{
get
{
return m_SourceImage;
}
}
private float[] pixel(out int bufferFloatOffset)
{
int x = m_x;
int y = m_y;
unchecked
{
if ((uint)x >= (uint)m_SourceImage.Width)
{
if (x < 0)
{
x = 0;
}
else
{
x = (int)m_SourceImage.Width - 1;
}
}
if ((uint)y >= (uint)m_SourceImage.Height)
{
if (y < 0)
{
y = 0;
}
else
{
y = (int)m_SourceImage.Height - 1;
}
}
}
bufferFloatOffset = m_SourceImage.GetBufferOffsetXY(x, y);
return m_SourceImage.GetBuffer();
}
public float[] span(int x, int y, int len, out int bufferOffset)
{
m_x = m_x0 = x;
m_y = y;
unchecked
{
if ((uint)y < (uint)m_SourceImage.Height
&& x >= 0 && x + len <= (int)m_SourceImage.Width)
{
bufferOffset = m_SourceImage.GetBufferOffsetXY(x, y);
m_Buffer = m_SourceImage.GetBuffer();
m_CurrentBufferOffset = bufferOffset;
return m_Buffer;
}
}
m_CurrentBufferOffset = -1;
return pixel(out bufferOffset);
}
public float[] next_x(out int bufferOffset)
{
// this is the code (managed) that the original agg used.
// It looks like it doesn't check x but, It should be a bit faster and is valid
// because "span" checked the whole length for good x.
if (m_CurrentBufferOffset != -1)
{
m_CurrentBufferOffset += m_DistanceBetweenPixelsInclusive;
bufferOffset = m_CurrentBufferOffset;
return m_Buffer;
}
++m_x;
return pixel(out bufferOffset);
}
public float[] next_y(out int bufferOffset)
{
++m_y;
m_x = m_x0;
if (m_CurrentBufferOffset != -1
&& (uint)m_y < (uint)m_SourceImage.Height)
{
m_CurrentBufferOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y);
bufferOffset = m_CurrentBufferOffset;
return m_Buffer;
}
m_CurrentBufferOffset = -1;
return pixel(out bufferOffset);
}
};
public sealed class ImageBufferAccessorClipFloat : ImageBufferAccessorCommonFloat
{
private float[] m_OutsideBufferColor;
public ImageBufferAccessorClipFloat(IImageFloat sourceImage, ColorF bk)
: base(sourceImage)
{
m_OutsideBufferColor = new float[4];
m_OutsideBufferColor[0] = bk.red;
m_OutsideBufferColor[1] = bk.green;
m_OutsideBufferColor[2] = bk.blue;
m_OutsideBufferColor[3] = bk.alpha;
}
private float[] pixel(out int bufferFloatOffset)
{
unchecked
{
if (((uint)m_x < (uint)m_SourceImage.Width)
&& ((uint)m_y < (uint)m_SourceImage.Height))
{
bufferFloatOffset = m_SourceImage.GetBufferOffsetXY(m_x, m_y);
return m_SourceImage.GetBuffer();
}
}
bufferFloatOffset = 0;
return m_OutsideBufferColor;
}
//public void background_color(IColorType bk)
//{
// m_pixf.make_pix(m_pBackBufferColor, bk);
//}
};
}
| |
namespace Anycmd.Xacml.Runtime
{
using Interfaces;
using System;
using System.Collections.Specialized;
using Xacml.Policy;
using Xacml.Policy.TargetItems;
/// <summary>
/// The runtime class for the policy set.
/// </summary>
public class PolicySet : IMatchEvaluable, IObligationsContainer
{
#region Private members
/// <summary>
/// All the resources in the policy.
/// </summary>
private readonly StringCollection _allResources = new StringCollection();
/// <summary>
/// All the policies that belongs to this policy set.
/// </summary>
private readonly MatchEvaluableCollection _policies = new MatchEvaluableCollection();
/// <summary>
/// The final decission for this policy set.
/// </summary>
private Decision _evaluationValue;
/// <summary>
/// The policy set defined in the context document.
/// </summary>
private readonly PolicySetElement _policySet;
/// <summary>
/// The target during the evaluation process.
/// </summary>
private readonly Target _target;
/// <summary>
/// The obligations set to this policy.
/// </summary>
private ObligationCollection _obligations;
#endregion
#region Constructor
/// <summary>
/// Creates a new runtime policy set evaluation.
/// </summary>
/// <param name="engine">The evaluation engine.</param>
/// <param name="policySet">The policy set defined in the policy document.</param>
public PolicySet(EvaluationEngine engine, PolicySetElement policySet)
{
if (engine == null) throw new ArgumentNullException("engine");
if (policySet == null) throw new ArgumentNullException("policySet");
_policySet = policySet;
// Create a runtime target of this policy set.
if (policySet.Target != null)
{
_target = new Target((TargetElement)policySet.Target);
foreach (ResourceElement resource in policySet.Target.Resources.ItemsList)
{
foreach (ResourceMatchElement rmatch in resource.Match)
{
if (!_allResources.Contains(rmatch.AttributeValue.Contents))
{
_allResources.Add(rmatch.AttributeValue.Contents);
}
}
}
}
// Add all the policies (or policy set) inside this policy set.
foreach (object child in policySet.Policies)
{
var childPolicySet = child as PolicySetElement;
var childPolicyElement = child as PolicyElement;
var childPolicySetIdReference = child as PolicySetIdReferenceElement;
var childPolicyIdReferenceElement = child as PolicyIdReferenceElement;
if (childPolicySet != null)
{
var policySetEv = new PolicySet(engine, childPolicySet);
foreach (string rName in policySetEv.AllResources)
{
if (!_allResources.Contains(rName))
{
_allResources.Add(rName);
}
}
_policies.Add(policySetEv);
}
else if (childPolicyElement != null)
{
var policyEv = new Policy(childPolicyElement);
foreach (string rName in policyEv.AllResources)
{
if (!_allResources.Contains(rName))
{
_allResources.Add(rName);
}
}
_policies.Add(policyEv);
}
else if (childPolicySetIdReference != null)
{
PolicySetElement policySetDefinition = EvaluationEngine.Resolve(childPolicySetIdReference);
if (policySetDefinition != null)
{
var policySetEv = new PolicySet(engine, policySetDefinition);
foreach (string rName in policySetEv.AllResources)
{
if (!_allResources.Contains(rName))
{
_allResources.Add(rName);
}
}
_policies.Add(policySetEv);
}
else
{
throw new EvaluationException(string.Format(Properties.Resource.exc_policyset_reference_not_resolved, ((PolicySetIdReferenceElement)child).PolicySetId));
}
}
else if (childPolicyIdReferenceElement != null)
{
PolicyElement policyDefinition = EvaluationEngine.Resolve(childPolicyIdReferenceElement);
if (policyDefinition != null)
{
var policyEv = new Policy(policyDefinition);
foreach (string rName in policyEv.AllResources)
{
if (!_allResources.Contains(rName))
{
_allResources.Add(rName);
}
}
_policies.Add(policyEv);
}
else
{
throw new EvaluationException(string.Format(Properties.Resource.exc_policy_reference_not_resolved, ((PolicyIdReferenceElement)child).PolicyId));
}
}
}
}
#endregion
#region Public properties
/// <summary>
/// The obligations that have been fulfilled for this policy set.
/// </summary>
public ObligationCollection Obligations
{
get { return _obligations; }
}
#endregion
#region IMatchEvaluable members
/// <summary>
/// All the resources for this policy.
/// </summary>
public StringCollection AllResources
{
get { return _allResources; }
}
/// <summary>
/// Match the target of this policy set.
/// </summary>
/// <param name="context">The evaluation context instance.</param>
/// <returns>The retult evaluation of the policy set target.</returns>
public TargetEvaluationValue Match(EvaluationContext context)
{
if (context == null) throw new ArgumentNullException("context");
// Evaluate the policy target
var targetEvaluationValue = TargetEvaluationValue.Match;
if (_target != null)
{
targetEvaluationValue = _target.Evaluate(context);
context.TraceContextValues();
}
return targetEvaluationValue;
}
/// <summary>
/// Evaluates the policy set.
/// </summary>
/// <param name="context">The evaluation context instance.</param>
/// <returns>The decission result for this policy set.</returns>
public Decision Evaluate(EvaluationContext context)
{
if (context == null) throw new ArgumentNullException("context");
context.Trace("Evaluating policySet: {0}", _policySet.Description);
context.CurrentPolicySet = this;
try
{
context.Trace("Evaluating Target...");
context.AddIndent();
// Evaluate the policy target
TargetEvaluationValue targetEvaluationValue = Match(context);
context.RemoveIndent();
context.Trace("Target: {0}", targetEvaluationValue);
ProcessTargetEvaluationValue(context, targetEvaluationValue);
context.Trace("PolicySet: {0}", _evaluationValue);
// If the policy evaluated to Deny or Permit add the obligations depending on its fulfill value.
ProcessObligations(context);
return _evaluationValue;
}
finally
{
context.CurrentPolicySet = null;
}
}
/// <summary>
/// Process the obligations for the policy.
/// </summary>
/// <param name="context">The evaluation context instance.</param>
private void ProcessObligations(EvaluationContext context)
{
_obligations = new ObligationCollection();
if (_evaluationValue != Decision.Indeterminate &&
_evaluationValue != Decision.NotApplicable &&
_policySet.Obligations != null &&
_policySet.Obligations.Count != 0)
{
foreach (ObligationElement obl in _policySet.Obligations)
{
if ((obl.FulfillOn == Effect.Deny && _evaluationValue == Decision.Deny) ||
(obl.FulfillOn == Effect.Permit && _evaluationValue == Decision.Permit))
{
context.Trace("Adding obligation: {0} ", obl.ObligationId);
_obligations.Add(obl);
}
}
// Get all obligations from child policies
foreach (IMatchEvaluable child in _policies)
{
var oblig = child as IObligationsContainer;
if (oblig != null && oblig.Obligations != null)
{
foreach (ObligationElement childObligation in oblig.Obligations)
{
if ((childObligation.FulfillOn == Effect.Deny && _evaluationValue == Decision.Deny) ||
(childObligation.FulfillOn == Effect.Permit && _evaluationValue == Decision.Permit))
{
_obligations.Add(childObligation);
}
}
}
}
}
}
/// <summary>
/// Process the match result.
/// </summary>
/// <param name="context">The evaluation context instance.</param>
/// <param name="targetEvaluationValue">The match evaluation result.</param>
private void ProcessTargetEvaluationValue(EvaluationContext context, TargetEvaluationValue targetEvaluationValue)
{
if (targetEvaluationValue == TargetEvaluationValue.Match)
{
try
{
context.Trace("Evaluating policies...");
context.AddIndent();
context.Trace("Policy combination algorithm: {0}", _policySet.PolicyCombiningAlgorithm);
// Evaluate all policies and apply rule combination
IPolicyCombiningAlgorithm pca = EvaluationEngine.CreatePolicyCombiningAlgorithm(_policySet.PolicyCombiningAlgorithm);
if (pca == null)
{
throw new EvaluationException("the policy combining algorithm does not exists."); //TODO: resources
}
_evaluationValue = pca.Evaluate(context, _policies);
// Update the flags for general evaluation status.
context.TraceContextValues();
context.Trace("Policy combination algorithm: {0}", _evaluationValue.ToString());
}
finally
{
context.RemoveIndent();
}
}
else if (targetEvaluationValue == TargetEvaluationValue.NoMatch)
{
_evaluationValue = Decision.NotApplicable;
}
else if (targetEvaluationValue == TargetEvaluationValue.Indeterminate)
{
_evaluationValue = Decision.Indeterminate;
}
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InputState.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System.Collections.Generic;
#endregion
namespace MahjongXNA
{
/// <summary>
/// Helper for reading input from keyboard, gamepad, and touch input. This class
/// tracks both the current and previous state of the input devices, and implements
/// query methods for high level input actions such as "move up through the menu"
/// or "pause the game".
/// </summary>
public class InputState
{
#region Fields
public const int MaxInputs = 4;
public readonly KeyboardState[] CurrentKeyboardStates;
public readonly GamePadState[] CurrentGamePadStates;
public readonly KeyboardState[] LastKeyboardStates;
public readonly GamePadState[] LastGamePadStates;
#if WINDOWS
public MouseState CurrentMouseState
{
get { return currentMouseState; }
}
protected MouseState currentMouseState;
public MouseState LastMouseState
{
get { return lastMouseState; }
}
protected MouseState lastMouseState;
#endif
public readonly bool[] GamePadWasConnected;
public TouchCollection TouchState;
public readonly List<GestureSample> Gestures = new List<GestureSample>();
#endregion
#region Initialization
/// <summary>
/// Constructs a new input state.
/// </summary>
public InputState()
{
CurrentKeyboardStates = new KeyboardState[MaxInputs];
CurrentGamePadStates = new GamePadState[MaxInputs];
LastKeyboardStates = new KeyboardState[MaxInputs];
LastGamePadStates = new GamePadState[MaxInputs];
GamePadWasConnected = new bool[MaxInputs];
#if WINDOWS
currentMouseState = new MouseState();
lastMouseState = new MouseState();
#endif
}
#endregion
#region Update
/// <summary>
/// Reads the latest state of the keyboard and gamepad.
/// </summary>
public void Update()
{
//record gamepad states
for (int i = 0; i < MaxInputs; i++)
{
LastKeyboardStates[i] = CurrentKeyboardStates[i];
LastGamePadStates[i] = CurrentGamePadStates[i];
CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i);
CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);
// Keep track of whether a gamepad has ever been
// connected, so we can detect if it is unplugged.
if (CurrentGamePadStates[i].IsConnected)
{
GamePadWasConnected[i] = true;
}
}
#if WINDOWS
//record mouse state
lastMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
#endif
TouchState = TouchPanel.GetState();
Gestures.Clear();
while (TouchPanel.IsGestureAvailable)
{
Gestures.Add(TouchPanel.ReadGesture());
}
}
#endregion
#region Public Methods
#region Xbox Gamepad Listeners
/// <summary>
/// Helper for checking if a button was newly pressed during this update.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a button press
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
int i = (int)playerIndex;
return (CurrentGamePadStates[i].IsButtonDown(button) &&
LastGamePadStates[i].IsButtonUp(button));
}
else
{
// Accept input from any player.
return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Four, out playerIndex));
}
}
#endregion
#region Keyboard Listeners
/// <summary>
/// Helper for checking if a key was newly pressed during this update. The
/// controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a keypress
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
int i = (int)playerIndex;
return (CurrentKeyboardStates[i].IsKeyDown(key) &&
LastKeyboardStates[i].IsKeyUp(key));
}
else
{
// Accept input from any player.
return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Four, out playerIndex));
}
}
#endregion
#if WINDOWS
#region Mouse Listeners
public bool MouseMoved()
{
return CurrentMouseState.X != lastMouseState.X || CurrentMouseState.Y != LastMouseState.Y;
}
///<summary>
//Checks for a left mouse button click input from the user and returns true
//if a left click was performed.
/// </summary>
/// <returns>True: If left mouse button was clicked.</returns>
public bool IsNewLeftMouseClick()
{
return (currentMouseState.LeftButton == ButtonState.Released &&
lastMouseState.LeftButton == ButtonState.Pressed);
}
/// <summary>
/// Checks for a right mouse button click input form the user and returns
/// true if a right mouse click was performed.
/// </summary>
/// <returns>True: If right mouse button was clicked</returns>
public bool IsNewRightMouseClick()
{
return (currentMouseState.RightButton == ButtonState.Released &&
lastMouseState.RightButton == ButtonState.Pressed);
}
/// <summary>
/// Checks for a third (middle) mouse button click input form the user and returns
/// true if a third mouse click was performed.
/// </summary>
/// <returns>True: If third mouse button was clicked</returns>
public bool IsNewThirdMouseClick()
{
return (currentMouseState.MiddleButton == ButtonState.Pressed &&
lastMouseState.MiddleButton == ButtonState.Released);
}
///<summary>
///Checks if the mouse has been scrolled up
///</summary>
///<returns>True: If the mouse wheel scrolled up</returns>
public bool IsNewMouseScrollUp()
{
return (currentMouseState.ScrollWheelValue > lastMouseState.ScrollWheelValue);
}
///<summary>
///Checks if the mouse has been scrolled down
///</summary>
///<returns>True: If the mouse wheel scrolled down</returns>
public bool IsNewMouseScrollDown()
{
return (currentMouseState.ScrollWheelValue < lastMouseState.ScrollWheelValue);
}
#endregion
#endif
#region "Abstract" Action Listeners
/// <summary>
/// Checks for a "menu select" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuSelect(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) ||
IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu cancel" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuCancel(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu up" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuUp(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
#if XBOX
return IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex);
#endif
#if WINDOWS
return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex) ||
IsNewMouseScrollUp();
#endif
}
/// <summary>
/// Checks for a "menu down" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuDown(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
#if XBOX
return IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
#endif
#if WINDOWS
return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex) ||
IsNewMouseScrollDown();
#endif
}
public bool IsMenuLeft(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
#if XBOX
return IsNewButtonPress(Buttons.DPadLeft, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickLeft, controllingPlayer, out playerIndex);
#endif
#if WINDOWS
return IsNewKeyPress(Keys.Left, controllingPlayer, out playerIndex)
|| IsNewButtonPress(Buttons.DPadLeft, controllingPlayer, out playerIndex)
|| IsNewButtonPress(Buttons.LeftThumbstickLeft, controllingPlayer, out playerIndex)
//|| IsNewMouseScrollDown()
;
#endif
}
public bool IsMenuRight(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
#if XBOX
return IsNewButtonPress(Buttons.DPadRight, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.RightThumbstickRight, controllingPlayer, out playerIndex);
#endif
#if WINDOWS
return IsNewKeyPress(Keys.Right, controllingPlayer, out playerIndex)
|| IsNewButtonPress(Buttons.DPadRight, controllingPlayer, out playerIndex)
|| IsNewButtonPress(Buttons.RightThumbstickRight, controllingPlayer, out playerIndex)
//|| IsNewMouseScrollDown();
;
#endif
}
/// <summary>
/// Checks for a "pause the game" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsPauseGame(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
#endregion
#endregion
}
}
| |
/*
* Splitter.cs - Implementation of the
* "System.Windows.Forms.Splitter" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Toolkit;
using System.ComponentModel;
#if CONFIG_COMPONENT_MODEL
[DefaultEvent("SplitterMoved")]
[DefaultProperty("Dock")]
[Designer("System.Windows.Forms.Design.SplitterDesigner, System.Design")]
#endif
public class Splitter : Control, IMessageFilter
{
// Internal state.
private int minSize;
private int minExtra;
private int thickness;
private bool moving;
private bool drawn;
private Brush xorBrush;
private Rectangle drawnRect;
private int moveX, moveY;
private int startMoveX, startMoveY;
private int startX, startY;
private int margin1, margin2;
// Constructor.
public Splitter()
{
minSize = 25;
minExtra = 25;
thickness = 3;
moving = false;
drawn = false;
xorBrush = new HatchBrush(HatchStyle.Percent50,
Color.White, Color.Black);
xorBrush = ToolkitManager.CreateXorBrush(xorBrush);
Dock = DockStyle.Left;
TabStop = false;
SetStyle(ControlStyles.Selectable, false);
}
// Get or set this control's properties.
public override bool AllowDrop
{
get
{
return base.AllowDrop;
}
set
{
base.AllowDrop = value;
}
}
public override AnchorStyles Anchor
{
get
{
return AnchorStyles.None;
}
set
{
// Nothing to do here: anchoring is not supported.
}
}
public override Image BackgroundImage
{
get
{
return base.BackgroundImage;
}
set
{
base.BackgroundImage = value;
}
}
public BorderStyle BorderStyle
{
get
{
return BorderStyleInternal;
}
set
{
BorderStyleInternal = value;
}
}
protected override CreateParams CreateParams
{
get
{
return base.CreateParams;
}
}
protected override ImeMode DefaultImeMode
{
get
{
return ImeMode.Disable;
}
}
protected override Size DefaultSize
{
get
{
return new Size(3, 3);
}
}
public override Cursor Cursor
{
set
{
if( value == null ) {
switch( Dock ) {
case DockStyle.Left : case DockStyle.Right :
base.Cursor = Cursors.SizeWE;
break;
case DockStyle.Top : case DockStyle.Bottom :
base.Cursor = Cursors.SizeNS;
break;
default:
base.Cursor = value;
break;
}
}
else {
base.Cursor = value;
}
}
}
public override DockStyle Dock
{
get
{
return base.Dock;
}
set
{
if(value == DockStyle.Left || value == DockStyle.Right)
{
base.Dock = value;
Width = thickness;
Cursor = Cursors.SizeWE;
}
else if(value == DockStyle.Top || value == DockStyle.Bottom)
{
base.Dock = value;
Height = thickness;
Cursor = Cursors.SizeNS;
}
else
{
throw new ArgumentException(S._("SWF_DockStyle"));
}
}
}
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
}
}
public override Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
}
}
public new ImeMode ImeMode
{
get
{
return base.ImeMode;
}
set
{
base.ImeMode = value;
}
}
public int MinExtra
{
get
{
return minExtra;
}
set
{
if(minExtra != value)
{
if(value < 0)
{
value = 0;
}
minExtra = value;
}
}
}
public int MinSize
{
get
{
return minSize;
}
set
{
if(minSize != value)
{
if(value < 0)
{
value = 0;
}
minSize = value;
}
}
}
public int SplitPosition
{
get
{
Control adjusted = GetAdjustedControl();
if(adjusted != null)
{
int size;
switch(Dock)
{
case DockStyle.Left:
case DockStyle.Right:
default:
{
size = adjusted.Width;
}
break;
case DockStyle.Top:
case DockStyle.Bottom:
{
size = adjusted.Height;
}
break;
}
if(size < minSize)
{
size = minSize;
}
return size;
}
else
{
return -1;
}
}
set
{
// Bail out if we are in the middle of a move operation.
if(moving)
{
return;
}
// Get the control to be adjusted.
Control adjusted = GetAdjustedControl();
if(adjusted == null)
{
return;
}
// Range-check the size.
if(value < minSize)
{
value = minSize;
}
// Adjust the bounds.
switch(Dock)
{
case DockStyle.Left:
case DockStyle.Right:
{
if(adjusted.Width == value)
{
return;
}
adjusted.Width = value;
}
break;
case DockStyle.Top:
case DockStyle.Bottom:
{
if(adjusted.Height == value)
{
return;
}
adjusted.Height = value;
}
break;
}
// Notify event handlers of the move.
OnSplitterMoved
(new SplitterEventArgs(Left, Top, Left, Top));
}
}
public new bool TabStop
{
get
{
return base.TabStop;
}
set
{
base.TabStop = value;
}
}
public override String Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
// Convert this object into a string.
public override String ToString()
{
return base.ToString() + ", MinExtra=" + MinExtra.ToString() +
", MinSize=" + MinSize.ToString();
}
// Filter a message before it is dispatched.
public bool PreFilterMessage(ref Message m)
{
// Not used in this implementation.
return false;
}
// Event that is emitted when the splitter is moved.
public event SplitterEventHandler SplitterMoved
{
add
{
AddHandler(EventId.SplitterMoved, value);
}
remove
{
RemoveHandler(EventId.SplitterMoved, value);
}
}
// Event that is emitted when the splitter is moving.
public event SplitterEventHandler SplitterMoving
{
add
{
AddHandler(EventId.SplitterMoving, value);
}
remove
{
RemoveHandler(EventId.SplitterMoving, value);
}
}
// Draw the splitter at its current move position.
private void DrawSplitter()
{
if(!drawn)
{
switch(Dock)
{
case DockStyle.Left:
case DockStyle.Right:
{
drawnRect = new Rectangle
(moveX, Top, thickness, Height);
}
break;
case DockStyle.Top:
case DockStyle.Bottom:
{
drawnRect = new Rectangle
(Left, moveY, Width, thickness);
}
break;
}
using(Graphics graphics = Parent.CreateGraphics())
{
graphics.FillRectangle(xorBrush, drawnRect);
}
drawn = true;
}
}
// Erase the splitter from its current move position.
private void EraseSplitter()
{
if(drawn)
{
drawn = false;
using(Graphics graphics = Parent.CreateGraphics())
{
graphics.FillRectangle(xorBrush, drawnRect);
}
}
}
// End a splitter move operation.
private void EndMove()
{
// Erase the splitter and end the move operation.
EraseSplitter();
moving = false;
Capture = false;
// Actually move the position.
switch(Dock)
{
case DockStyle.Left:
{
SplitPosition = moveX - margin1 + minSize;
}
break;
case DockStyle.Right:
{
SplitPosition =
Parent.ClientSize.Width -
(moveX + thickness) -
margin2 + minSize;
}
break;
case DockStyle.Top:
{
SplitPosition = moveY - margin1 + minSize;
}
break;
case DockStyle.Bottom:
{
SplitPosition =
Parent.ClientSize.Height -
(moveY + thickness) -
margin2 + minSize;
}
break;
}
}
// Handle a "KeyDown" event.
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(moving && e.KeyCode == Keys.Escape)
{
EndMove();
}
}
// Handle a "MouseDown" event.
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if(!moving && e.Button == MouseButtons.Left)
{
// Bail out if there is no control to adjust.
Control adjusted = GetAdjustedControl();
if(adjusted == null)
{
return;
}
// Record the starting position so that we know
// how much to offset by when determining movements.
startX = e.X;
startY = e.Y;
// Set the initial move position.
moveX = Left;
moveY = Top;
startMoveX = moveX;
startMoveY = moveY;
// Determine the margins of the splitter move.
switch(Dock)
{
case DockStyle.Left:
{
margin1 = adjusted.Left + minSize;
margin2 = minExtra;
}
break;
case DockStyle.Right:
{
margin1 = minExtra;
margin2 = (Parent.ClientSize.Width -
adjusted.Right + minSize);
}
break;
case DockStyle.Top:
{
margin1 = adjusted.Top + minSize;
margin2 = minExtra;
}
break;
case DockStyle.Bottom:
{
margin1 = minExtra;
margin2 = (Parent.ClientSize.Height -
adjusted.Bottom + minSize);
}
break;
}
// Capture the mouse and draw the splitter.
Capture = true;
moving = true;
DrawSplitter();
}
}
// Handle a "MouseMove" event.
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if(moving)
{
int diffX = e.X - startX;
int diffY = e.Y - startY;
int newX = moveX;
int newY = moveY;
Size parentSize = Parent.ClientSize;
switch(Dock)
{
case DockStyle.Left:
case DockStyle.Right:
{
newX = startMoveX + diffX;
if(newX < margin1)
{
newX = margin1;
}
else if((newX + thickness) >
(parentSize.Width - margin2))
{
newX = parentSize.Width - margin2 - thickness;
}
}
break;
case DockStyle.Top:
case DockStyle.Bottom:
{
newY = startMoveY + diffY;
if(newY < margin1)
{
newY = margin1;
}
else if((newY + thickness) >
(parentSize.Height - margin2))
{
newY = parentSize.Height - margin2 - thickness;
}
}
break;
}
if(newX != moveX || newY != moveY)
{
// Redraw the splitter in its new position.
EraseSplitter();
moveX = newX;
moveY = newY;
DrawSplitter();
// Emit the "SplitterMoving" event.
OnSplitterMoving
(new SplitterEventArgs
(Left + e.X, Top + e.Y, moveX, moveY));
}
}
}
// Handle a "MouseUp" event.
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if(moving && e.Button == MouseButtons.Left)
{
EndMove();
}
}
// Emit the "SplitterMoved" event.
protected virtual void OnSplitterMoved(SplitterEventArgs e)
{
SplitterEventHandler handler;
handler = (SplitterEventHandler)
(GetHandler(EventId.SplitterMoved));
if(handler != null)
{
handler(this, e);
}
}
// Emit the "SplitterMoving" event.
protected virtual void OnSplitterMoving(SplitterEventArgs e)
{
SplitterEventHandler handler;
handler = (SplitterEventHandler)
(GetHandler(EventId.SplitterMoving));
if(handler != null)
{
handler(this, e);
}
}
// Inner core of "SetBounds".
protected override void SetBoundsCore
(int x, int y, int width, int height,
BoundsSpecified specified)
{
// Set the thickness based on the width or height.
DockStyle dock = Dock;
if(dock == DockStyle.Left || dock == DockStyle.Right)
{
if(width <= 0)
{
width = 3;
}
thickness = width;
}
else
{
if(height <= 0)
{
height = 3;
}
thickness = height;
}
// Set the bounds.
base.SetBoundsCore(x, y, width, height, specified);
}
// Get the control that is being adjusted by this splitter.
// Returns null if we cannot find an appropriate control.
private Control GetAdjustedControl()
{
// No adjusted control if we don't have a parent.
Control parent = Parent;
if(parent == null)
{
return null;
}
// Look for a control that has a side adjoining this one.
DockStyle dock = Dock;
foreach(Control control in parent.Controls)
{
if(!control.Visible)
{
continue;
}
switch(dock)
{
case DockStyle.Left:
{
if(control.Right == Left)
{
return control;
}
}
break;
case DockStyle.Right:
{
if(control.Left == Right)
{
return control;
}
}
break;
case DockStyle.Top:
{
if(control.Bottom == Top)
{
return control;
}
}
break;
case DockStyle.Bottom:
{
if(control.Top == Bottom)
{
return control;
}
}
break;
}
}
// We could not find an appropriate control.
return null;
}
}; // class Splitter
}; // namespace System.Windows.Forms
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Reservations
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReservationOrderOperations operations.
/// </summary>
internal partial class ReservationOrderOperations : IServiceOperations<AzureReservationAPIClient>, IReservationOrderOperations
{
/// <summary>
/// Initializes a new instance of the ReservationOrderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReservationOrderOperations(AzureReservationAPIClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureReservationAPIClient
/// </summary>
public AzureReservationAPIClient Client { get; private set; }
/// <summary>
/// Get all `ReservationOrder`s.
/// </summary>
/// <remarks>
/// List of all the `ReservationOrder`s that the user has access to in the
/// current tenant.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ReservationOrderResponse>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ReservationOrderResponse>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ReservationOrderResponse>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a specific `ReservationOrder`.
/// </summary>
/// <remarks>
/// Get the details of the `ReservationOrder`.
/// </remarks>
/// <param name='reservationOrderId'>
/// Order Id of the reservation
///
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ReservationOrderResponse>> GetWithHttpMessagesAsync(string reservationOrderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (reservationOrderId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("reservationOrderId", reservationOrderId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}").ToString();
_url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ReservationOrderResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ReservationOrderResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get all `ReservationOrder`s.
/// </summary>
/// <remarks>
/// List of all the `ReservationOrder`s that the user has access to in the
/// current tenant.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ReservationOrderResponse>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ReservationOrderResponse>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ReservationOrderResponse>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//---------------------------------------------------------------------------
//
// Description: This is a MSBuild task which generates a temporary target assembly
// if current project contains a xaml file with local-type-reference.
//
// It generates a temporary project file and then call build-engine
// to compile it.
//
// The new project file will replace all the Reference Items with the
// resolved ReferenctPath, add all the generated code file into Compile
// Item list.
//
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using MS.Utility;
using MS.Internal.Tasks;
// Since we disable PreSharp warnings in this file, PreSharp warning is unknown to C# compiler.
// We first need to disable warnings about unknown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
namespace Microsoft.Build.Tasks.Windows
{
#region GenerateTemporaryTargetAssembly Task class
/// <summary>
/// This task is used to generate a temporary target assembly. It generates
/// a temporary project file and then compile it.
///
/// The generated project file is based on current project file, with below
/// modification:
///
/// A: Add the generated code files (.g.cs) to Compile Item list.
/// B: Replace Reference Item list with ReferenctPath item list.
/// So that it doesn't need to rerun time-consuming task
/// ResolveAssemblyReference (RAR) again.
///
/// </summary>
public sealed class GenerateTemporaryTargetAssembly : Task
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public GenerateTemporaryTargetAssembly()
: base(SR.SharedResourceManager)
{
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// ITask Execute method
/// </summary>
/// <returns></returns>
/// <remarks>Catching all exceptions in this method is appropriate - it will allow the build process to resume if possible after logging errors</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public override bool Execute()
{
bool retValue = true;
// Verification
try
{
XmlDocument xmlProjectDoc = null;
xmlProjectDoc = new XmlDocument( );
xmlProjectDoc.Load(CurrentProject);
//
// remove all the WinFX specific item lists
// ApplicationDefinition, Page, MarkupResource and Resource
//
RemoveItemsByName(xmlProjectDoc, APPDEFNAME);
RemoveItemsByName(xmlProjectDoc, PAGENAME);
RemoveItemsByName(xmlProjectDoc, MARKUPRESOURCENAME);
RemoveItemsByName(xmlProjectDoc, RESOURCENAME);
// Replace the Reference Item list with ReferencePath
RemoveItemsByName(xmlProjectDoc, REFERENCETYPENAME);
AddNewItems(xmlProjectDoc, ReferencePathTypeName, ReferencePath);
// Add GeneratedCodeFiles to Compile item list.
AddNewItems(xmlProjectDoc, CompileTypeName, GeneratedCodeFiles);
string currentProjectName = Path.GetFileNameWithoutExtension(CurrentProject);
string currentProjectExtension = Path.GetExtension(CurrentProject);
// Create a random file name
// This can fix the problem of project cache in VS.NET environment.
//
// GetRandomFileName( ) could return any possible file name and extension
// Since this temporary file will be used to represent an MSBUILD project file,
// we will use the same extension as that of the current project file
//
string randomFileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
// Don't call Path.ChangeExtension to append currentProjectExtension. It will do
// odd things with project names that already contains a period (like System.Windows.
// Contols.Ribbon.csproj). Instead, just append the extension - after all, we already know
// for a fact that this name (i.e., tempProj) lacks a file extension.
string tempProjPrefix = string.Join("_", currentProjectName, randomFileName, WPFTMP);
string tempProj = tempProjPrefix + currentProjectExtension;
// Save the xmlDocument content into the temporary project file.
xmlProjectDoc.Save(tempProj);
//
// Invoke MSBUILD engine to build this temporary project file.
//
Hashtable globalProperties = new Hashtable(3);
// Add AssemblyName, IntermediateOutputPath and _TargetAssemblyProjectName to the global property list
// Note that _TargetAssemblyProjectName is not defined as a property with Output attribute - that doesn't do us much
// good here. We need _TargetAssemblyProjectName to be a well-known property in the new (temporary) project
// file, and having it be available in the current MSBUILD process is not useful.
globalProperties[intermediateOutputPathPropertyName] = IntermediateOutputPath;
globalProperties[assemblyNamePropertyName] = AssemblyName;
globalProperties[targetAssemblyProjectNamePropertyName] = currentProjectName;
retValue = BuildEngine.BuildProjectFile(tempProj, new string[] { CompileTargetName }, globalProperties, null);
// Delete the temporary project file and generated files unless diagnostic mode has been requested
if (!GenerateTemporaryTargetAssemblyDebuggingInformation)
{
try
{
File.Delete(tempProj);
DirectoryInfo intermediateOutputPath = new DirectoryInfo(IntermediateOutputPath);
foreach (FileInfo temporaryProjectFile in intermediateOutputPath.EnumerateFiles(string.Concat(tempProjPrefix, "*")))
{
temporaryProjectFile.Delete();
}
}
catch (IOException e)
{
// Failure to delete the file is a non fatal error
Log.LogWarningFromException(e);
}
}
}
catch (Exception e)
{
Log.LogErrorFromException(e);
retValue = false;
}
return retValue;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// CurrentProject
/// The full path of current project file.
/// </summary>
[Required]
public string CurrentProject
{
get { return _currentProject; }
set { _currentProject = value; }
}
/// <summary>
/// MSBuild Binary Path.
/// This is required for Project to work correctly.
/// </summary>
[Required]
public string MSBuildBinPath
{
get { return _msbuildBinPath; }
set { _msbuildBinPath = value; }
}
/// <summary>
/// GeneratedCodeFiles
/// A list of generated code files, it could be empty.
/// The list will be added to the Compile item list in new generated project file.
/// </summary>
public ITaskItem[] GeneratedCodeFiles
{
get { return _generatedCodeFiles; }
set { _generatedCodeFiles = value; }
}
/// <summary>
/// CompileTypeName
/// The appropriate item name which can be accepted by managed compiler task.
/// It is "Compile" for now.
///
/// Adding this property is to make the type name configurable, if it is changed,
/// No code is required to change in this task, but set a new type name in project file.
/// </summary>
[Required]
public string CompileTypeName
{
get { return _compileTypeName; }
set { _compileTypeName = value; }
}
public string BaseIntermediateOutputPath { set; get; }
public string Analyzers { set; get; }
public string TemporaryTargetAssemblyProjectName { set; get; }
public string IncludePackageReferencesDuringMarkupCompilation { set; get; }
/// <summary>
/// ReferencePath
/// A list of resolved reference assemblies.
/// The list will replace the original Reference item list in generated project file.
/// </summary>
public ITaskItem[] ReferencePath
{
get { return _referencePath; }
set { _referencePath = value; }
}
/// <summary>
/// ReferencePathTypeName
/// The appropriate item name which is used to keep the Reference list in managed compiler task.
/// It is "ReferencePath" for now.
///
/// Adding this property is to make the type name configurable, if it is changed,
/// No code is required to change in this task, but set a new type name in project file.
/// </summary>
[Required]
public string ReferencePathTypeName
{
get { return _referencePathTypeName; }
set { _referencePathTypeName = value; }
}
/// <summary>
/// IntermediateOutputPath
///
/// The value which is set to IntermediateOutputPath property in current project file.
///
/// Passing this value explicitly is to make sure to generate temporary target assembly
/// in expected directory.
/// </summary>
[Required]
public string IntermediateOutputPath
{
get { return _intermediateOutputPath; }
set { _intermediateOutputPath = value; }
}
/// <summary>
/// AssemblyName
///
/// The value which is set to AssemblyName property in current project file.
/// Passing this value explicitly is to make sure to generate the expected
/// temporary target assembly.
///
/// </summary>
[Required]
public string AssemblyName
{
get { return _assemblyName; }
set { _assemblyName = value; }
}
/// <summary>
/// CompileTargetName
///
/// The msbuild target name which is used to generate assembly from source code files.
/// Usually it is "CoreCompile"
///
/// </summary>
[Required]
public string CompileTargetName
{
get { return _compileTargetName; }
set { _compileTargetName = value; }
}
/// <summary>
/// Optional <see cref="Boolean"/> task parameter
///
/// When <code>true</code>, debugging information is enabled for the <see cref="GenerateTemporaryTargetAssembly"/>
/// Task. At this time, the only debugging information that is generated consists of the temporary project that is
/// created to generate the temporary target assembly. This temporary project is normally deleted at the end of this
/// MSBUILD task; when <see cref="GenerateTemporaryTargetAssemblyDebuggingInformation"/> is enable, this temporary project
/// will be retained for inspection by the developer.
///
/// This is a diagnostic parameter, and it defaults to <code>false</code>.
/// </summary>
public bool GenerateTemporaryTargetAssemblyDebuggingInformation
{
get { return _generateTemporaryTargetAssemblyDebuggingInformation; }
set { _generateTemporaryTargetAssemblyDebuggingInformation = value; }
}
#endregion Public Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
//
// Remove specific items from project file. Every item should be under an ItemGroup.
//
private void RemoveItemsByName(XmlDocument xmlProjectDoc, string sItemName)
{
if (xmlProjectDoc == null || String.IsNullOrEmpty(sItemName))
{
// When the parameters are not valid, simply return it, instead of throwing exceptions.
return;
}
//
// The project file format is always like below:
//
// <Project xmlns="...">
// <ProjectGroup>
// ......
// </ProjectGroup>
//
// ...
// <ItemGroup>
// <ItemNameHere ..../>
// ....
// </ItemGroup>
//
// ....
// <Import ... />
// ...
// <Target Name="xxx" ..../>
//
// ...
//
// </Project>
//
//
// The order of children nodes under Project Root element is random
//
XmlNode root = xmlProjectDoc.DocumentElement;
if (root.HasChildNodes == false)
{
// If there is no child element in this project file, just return immediatelly.
return;
}
for (int i = 0; i < root.ChildNodes.Count; i++)
{
XmlElement nodeGroup = root.ChildNodes[i] as XmlElement;
if (nodeGroup != null && String.Compare(nodeGroup.Name, ITEMGROUP_NAME, StringComparison.OrdinalIgnoreCase) == 0)
{
//
// This is ItemGroup element.
//
if (nodeGroup.HasChildNodes)
{
ArrayList itemToRemove = new ArrayList();
for (int j = 0; j < nodeGroup.ChildNodes.Count; j++)
{
XmlElement nodeItem = nodeGroup.ChildNodes[j] as XmlElement;
if (nodeItem != null && String.Compare(nodeItem.Name, sItemName, StringComparison.OrdinalIgnoreCase) == 0)
{
// This is the item that need to remove.
// Add it into the temporary array list.
// Don't delete it here, since it would affect the ChildNodes of parent element.
//
itemToRemove.Add(nodeItem);
}
}
//
// Now it is the right time to delete the elements.
//
if (itemToRemove.Count > 0)
{
foreach (object node in itemToRemove)
{
XmlElement item = node as XmlElement;
//
// Remove this item from its parent node.
// the parent node should be nodeGroup.
//
if (item != null)
{
nodeGroup.RemoveChild(item);
}
}
}
}
//
// Removed all the items with given name from this item group.
//
// Continue the loop for the next ItemGroup.
}
} // end of "for i" statement.
}
//
// Add a list of files into an Item in the project file, the ItemName is specified by sItemName.
//
private void AddNewItems(XmlDocument xmlProjectDoc, string sItemName, ITaskItem[] pItemList)
{
if (xmlProjectDoc == null || String.IsNullOrEmpty(sItemName) || pItemList == null)
{
// When the parameters are not valid, simply return it, instead of throwing exceptions.
return;
}
XmlNode root = xmlProjectDoc.DocumentElement;
// Create a new ItemGroup element
XmlNode nodeItemGroup = xmlProjectDoc.CreateElement(ITEMGROUP_NAME, root.NamespaceURI);
// Append this new ItemGroup item into the list of children of the document root.
root.AppendChild(nodeItemGroup);
XmlElement embedItem = null;
for (int i = 0; i < pItemList.Length; i++)
{
// Create an element for the given sItemName
XmlElement nodeItem = xmlProjectDoc.CreateElement(sItemName, root.NamespaceURI);
// Create an Attribute "Include"
XmlAttribute attrInclude = xmlProjectDoc.CreateAttribute(INCLUDE_ATTR_NAME);
ITaskItem pItem = pItemList[i];
// Set the value for Include attribute.
attrInclude.Value = pItem.ItemSpec;
// Add the attribute to current item node.
nodeItem.SetAttributeNode(attrInclude);
if (TRUE == pItem.GetMetadata(EMBEDINTEROPTYPES))
{
embedItem = xmlProjectDoc.CreateElement(EMBEDINTEROPTYPES, root.NamespaceURI);
embedItem.InnerText = TRUE;
nodeItem.AppendChild(embedItem);
}
string aliases = pItem.GetMetadata(ALIASES);
if (!String.IsNullOrEmpty(aliases))
{
embedItem = xmlProjectDoc.CreateElement(ALIASES, root.NamespaceURI);
embedItem.InnerText = aliases;
nodeItem.AppendChild(embedItem);
}
// Add current item node into the children list of ItemGroup
nodeItemGroup.AppendChild(nodeItem);
}
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private string _currentProject = String.Empty;
private ITaskItem[] _generatedCodeFiles;
private ITaskItem[] _referencePath;
private string _referencePathTypeName;
private string _compileTypeName;
private string _msbuildBinPath;
private string _intermediateOutputPath;
private string _assemblyName;
private string _compileTargetName;
private bool _generateTemporaryTargetAssemblyDebuggingInformation = false;
private const string intermediateOutputPathPropertyName = "IntermediateOutputPath";
private const string assemblyNamePropertyName = "AssemblyName";
private const string targetAssemblyProjectNamePropertyName = "_TargetAssemblyProjectName";
private const string ALIASES = "Aliases";
private const string REFERENCETYPENAME = "Reference";
private const string EMBEDINTEROPTYPES = "EmbedInteropTypes";
private const string APPDEFNAME = "ApplicationDefinition";
private const string PAGENAME = "Page";
private const string MARKUPRESOURCENAME = "MarkupResource";
private const string RESOURCENAME = "Resource";
private const string ITEMGROUP_NAME = "ItemGroup";
private const string INCLUDE_ATTR_NAME = "Include";
private const string TRUE = "True";
private const string WPFTMP = "wpftmp";
#endregion Private Fields
}
#endregion GenerateProjectForLocalTypeReference Task class
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using MindTouch.Dream;
using MindTouch.Data;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Deki.CheckDb {
[TestFixture]
public class DatabaseTests {
private DataFactory _factory;
private DataCatalog _catalog;
private string _dbConfigFile = "mindtouch.deki.checkdb.config.xml";
private XDoc _dbConfig;
private string _dbSchemaFile = "mindtouch.deki.checkdb.schema.xml";
private XDoc _dbSchema;
public static int Main(string[] args) {
DatabaseTests test = new DatabaseTests();
test.RunAllTests();
return 0;
}
public void RunAllTests() {
Init();
List<string> errors = new List<string>();
Type type = typeof(DatabaseTests);
MethodInfo[] methods = type.GetMethods();
foreach(MethodInfo method in methods) {
object[] testAttributes = method.GetCustomAttributes(typeof(NUnit.Framework.TestAttribute), false);
object[] ignoreAttributes = method.GetCustomAttributes(typeof(NUnit.Framework.IgnoreAttribute), false);
if(testAttributes.Length > 0 && ignoreAttributes.Length == 0) {
// this is a test method, run it
try {
method.Invoke(this, null);
} catch(Exception e) {
string message = "";
if(e.InnerException != null)
message = e.InnerException.Message;
else
message = e.Message;
Console.WriteLine(message);
errors.Add(message);
}
}
}
if(errors.Count > 0) {
Console.WriteLine("\n**************************************");
Console.WriteLine(" checkdb found the following errors:");
Console.WriteLine("**************************************");
foreach(string error in errors) {
Console.WriteLine(error);
}
} else {
Console.WriteLine("\n**************************************");
Console.WriteLine(" database verification successful!");
Console.WriteLine("**************************************");
}
}
[TestFixtureSetUp]
public void Init() {
LoadDbConfig();
LoadDbSchema();
}
[Test]
public void TestDbConnection() {
//Assumptions:
// valid DB connection
//Actions:
// check connection with the database
//Expected result:
// successful connection
bool canConnect = true;
try {
_catalog.TestConnection();
} catch {
canConnect = false;
}
Console.WriteLine("* checking connection to database...");
Assert.IsTrue(canConnect, string.Format(ERR_CANNOT_CONNECT, _catalog.ConnectionString));
}
[Test]
public void CheckTablesExist() {
Console.WriteLine("* checking tables");
foreach(XDoc table in _dbSchema["table"]) {
string tableName = table["@name"].AsText;
Console.WriteLine(string.Format("** checking table {0}", tableName));
string checkTableName = _catalog.NewQuery("SHOW TABLES LIKE ?TABLE_NAME")
.With("TABLE_NAME", tableName)
.Read();
//verify the table exists
Assert.IsTrue(!string.IsNullOrEmpty(checkTableName) && tableName == checkTableName, string.Format(ERR_MISSING_TABLE, tableName));
}
}
[Test]
public void CheckColumns() {
foreach(XDoc table in _dbSchema["table"]) {
string tableName = table["@name"].AsText;
// loop over the columns
Console.WriteLine(string.Format("* checking columns in table {0}", tableName));
foreach(XDoc column in table["column"]) {
string columnName = column["@name"].AsText;
DataSet results = _catalog.NewQuery(string.Format("SHOW COLUMNS FROM {0} WHERE Field=?COLUMN", tableName))
.With("COLUMN", columnName)
.ReadAsDataSet();
Console.WriteLine(string.Format("** checking column {0}", columnName));
Assert.IsTrue(results.Tables[0].Rows.Count == 1, string.Format(ERR_MISSING_COLUMN, columnName));
// validate default values
string defaultValue = column["@default"].AsText;
if(!string.IsNullOrEmpty(defaultValue)) {
Assert.IsTrue(defaultValue == (string)results.Tables[0].Rows[0]["Default"],
string.Format(ERR_INCORRECT_DEFAULT_VALUE, column["@name"].AsText));
}
}
foreach(XDoc index in table["indexes/index"]) {
string indexName = index["@name"].AsText;
string[] indexColumns = index["@columns"].AsText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
DataSet results = _catalog.NewQuery(string.Format("SHOW INDEXES FROM {0} WHERE Key_name=?INDEX", tableName))
.With("INDEX", indexName).ReadAsDataSet();
foreach(string indexColumn in indexColumns) {
bool foundColumn = false;
foreach(DataRow row in results.Tables[0].Rows) {
if((string)row["Column_name"] == indexColumn)
foundColumn = true;
}
Assert.IsTrue(foundColumn, string.Format(ERR_INCORRECT_INDEX, indexName));
}
}
}
}
[Test]
public void CheckWikiDbPermissions() {
// NOTE: mysql doesn't allow us to get specific grants without being an admin user so we need to do an approximation.
// It might also be the case that wikiuser was given more specific grants (not GRANT ALL) in which case this test
// will produce a false negative
string wikiGrant = string.Format("GRANT ALL PRIVILEGES ON `{0}`.* TO '{1}'", _dbConfig["db-catalog"].AsText, _dbConfig["db-user"].AsText);
bool foundGrant = false;
_catalog.NewQuery("SHOW GRANTS").Execute(delegate(IDataReader reader) {
while(reader.Read()) {
string grant = (string)reader[0];
if(grant.Length >= wikiGrant.Length && grant.Substring(0, wikiGrant.Length) == wikiGrant) {
foundGrant = true;
break;
}
}
});
Assert.IsTrue(foundGrant);
}
[Test]
public void CheckMySqlProcPermissions() {
string wikiGrant = string.Format("GRANT SELECT ON `mysql`.`proc` TO '{0}'", _dbConfig["db-user"].AsText);
bool foundGrant = false;
_catalog.NewQuery("SHOW GRANTS").Execute(delegate(IDataReader reader) {
while(reader.Read()) {
string grant = (string)reader[0];
if(grant.Substring(0, wikiGrant.Length) == wikiGrant) {
foundGrant = true;
break;
}
}
});
Assert.IsTrue(foundGrant);
}
[Test]
public void CheckCatalogCharsetUtf8() {
_catalog.NewQuery("SHOW VARIABLES LIKE 'character_set_database'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
string charset = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(charset) && charset.ToLower() == "utf8",
string.Format(ERR_WRONG_CATALOG_CHARSET, charset));
}
});
}
[Test]
public void CheckCatalogCollationUtf8() {
_catalog.NewQuery("SHOW VARIABLES LIKE 'collation_database'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
string collation = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(collation) && collation.ToLower() == "utf8_general_ci",
string.Format(ERR_WRONG_CATALOG_COLLATION, collation));
}
});
}
[Test]
public void CheckConnectionCharsetMatchesDatabaseCharset() {
string charset_database = null;
string charset_connection = null;
_catalog.NewQuery("SHOW VARIABLES LIKE 'character_set_database'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
charset_database = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(charset_database));
}
});
_catalog.NewQuery("SHOW VARIABLES LIKE 'character_set_connection'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
charset_connection = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(charset_connection));
}
});
Assert.IsTrue(charset_database == charset_connection, string.Format(ERR_CHARSET_MISMATCH, charset_connection, charset_database));
}
[Test]
public void CheckConnectionCollationMatchesDatabaseCollation() {
string collation_database = null;
string collation_connection = null;
_catalog.NewQuery("SHOW VARIABLES LIKE 'collation_database'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
collation_database = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(collation_database));
}
});
_catalog.NewQuery("SHOW VARIABLES LIKE 'collation_connection'").Execute(delegate(IDataReader reader) {
if(reader.Read()) {
collation_connection = (string)reader["Value"];
Assert.IsTrue(!string.IsNullOrEmpty(collation_connection));
}
});
Assert.IsTrue(collation_database == collation_connection, string.Format(ERR_COLLATION_MISMATCH, collation_connection, collation_database));
}
[Test]
public void CheckHomePageExists() {
uint id = _catalog.NewQuery("SELECT page_id from pages where page_namespace=0 and page_title=''").ReadAsUInt() ?? 0;
Assert.IsTrue(id > 0, ERR_HOME_PAGE_NOT_FOUND);
}
[Test]
public void CheckParentPages() {
List<string> orphanedPages = new List<string>();
_catalog.NewQuery("SELECT page_id, page_title, page_parent from pages where page_namespace=0 and page_parent != 0 and page_is_redirect=0")
.Execute(delegate(IDataReader reader) {
while(reader.Read()) {
uint page_id = (uint)reader["page_id"];
int parentPage = (int?)reader["page_parent"] ?? 0;
if(parentPage == 0 || !PageExists((uint)parentPage))
orphanedPages.Add(page_id.ToString());
}
});
string.Join(",", orphanedPages.ToArray());
Assert.IsTrue(orphanedPages.Count == 0,
string.Format(ERR_ORPHANED_PAGES, string.Join(",", orphanedPages.ToArray())));
}
[Test]
public void CheckForOrphanedFiles() {
List<string> oprhanedFiles = new List<string>();
_catalog.NewQuery("SELECT res_id, resrev_parent_page_id, file_id from resources r JOIN resourcefilemap rfm on r.res_id=rfm.resource_id where r.res_type=2 and r.res_deleted=0")
.Execute(delegate(IDataReader reader) {
while(reader.Read()) {
uint res_id = (uint)reader["res_id"];
uint page_id = (uint?)reader["resrev_parent_page_id"] ?? 0;
uint file_id = (uint)reader["file_id"];
if(page_id == 0 || !PageExists(page_id))
oprhanedFiles.Add(file_id.ToString());
}
});
Assert.IsTrue(oprhanedFiles.Count == 0,
string.Format(ERR_ORPHANED_FILES, string.Join(",", oprhanedFiles.ToArray())));
}
[Test]
public void CheckTalkPageLanguage() {
List<string> invalidTalkPageIds = new List<string>();
// Talk: pages don't have a parent_page id so we match based on the page_title
_catalog.NewQuery("SELECT page_id, page_title, page_language FROM pages WHERE page_namespace=1")
.Execute(delegate(IDataReader reader) {
while(reader.Read()) {
uint page_id = SysUtil.ChangeType<uint?>(reader["page_id"]) ?? 0;
string page_title = SysUtil.ChangeType<string>(reader["page_title"]) ?? "";
string page_language = SysUtil.ChangeType<string>(reader["page_language"]) ?? "";
_catalog.NewQuery("SELECT page_language FROM pages where page_title=?PAGE_TITLE AND page_namespace=0").With("PAGE_TITLE", page_title)
.Execute(delegate(IDataReader reader2) {
while(reader2.Read()) {
string main_page_language = SysUtil.ChangeType<string>(reader2["page_language"]) ?? "";
if(main_page_language != page_language)
invalidTalkPageIds.Add(page_id.ToString());
}
}
);
}
}
);
Assert.IsTrue(invalidTalkPageIds.Count == 0,
string.Format(ERR_INVALID_TALK_LANGUAGE, string.Join(",", invalidTalkPageIds.ToArray())));
}
[Test]
public void Mysql_can_handle_large_title_in_clause() {
var titles = new List<string>();
for(var i = 0; i < 1000; i++) {
titles.Add("'" + StringUtil.CreateAlphaNumericKey(255) + "'");
}
Assert.Greater(
_catalog.NewQuery(string.Format("SELECT count(*) FROM pages WHERE page_title in ('',{0})", string.Join(",", titles.ToArray())))
.ReadAsInt() ?? 0,
0);
}
[Test]
public void Mysql_can_handle_large_id_in_clause() {
var homepageId = _catalog.NewQuery("SELECT page_id from pages where page_namespace=0 and page_title=''").ReadAsUInt() ?? 0;
var ids = new List<string>();
ids.Add(homepageId.ToString());
for(var i = 0; i < 100000; i++) {
ids.Add("" + 100000 + i);
}
Assert.Greater(
_catalog.NewQuery(string.Format("SELECT count(*) FROM pages WHERE page_id in ({0})", string.Join(",", ids.ToArray())))
.ReadAsInt() ?? 0,
0);
}
private void LoadDbConfig() {
_dbConfig = XDocFactory.LoadFrom(_dbConfigFile, MimeType.XML);
_factory = new MindTouch.Data.DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?");
_catalog = new DataCatalog(_factory, _dbConfig);
}
private void LoadDbSchema() {
_dbSchema = XDocFactory.LoadFrom(_dbSchemaFile, MimeType.XML);
}
private bool PageExists(uint pageId) {
uint? id = _catalog.NewQuery("SELECT page_id from pages where page_id=?PAGEID").With("PAGEID", pageId).ReadAsUInt();
if(id == null)
return false;
return true;
}
public static string ERR_ORPHANED_PAGES = "ERROR: the following pages are orphans: {0}";
public static string ERR_HOME_PAGE_NOT_FOUND = "ERROR: home page not found";
public static string ERR_WRONG_CATALOG_CHARSET = "ERROR: the database character set is {0}, should be 'utf8'";
public static string ERR_WRONG_CATALOG_COLLATION = "ERROR: the database collation is {0}, should be 'utf8_general_ci'";
public static string ERR_CHARSET_MISMATCH = "ERROR: the connection character set '{0}' does not match the database character set '{1}'";
public static string ERR_COLLATION_MISMATCH = "ERROR: the connection collation '{0}' does not match the database collation '{1}'";
public static string ERR_INCORRECT_INDEX = "ERROR: index {0} is incorrectly defined";
public static string ERR_INCORRECT_DEFAULT_VALUE = "ERROR: incorrect default value for column: {0}";
public static string ERR_MISSING_COLUMN = "ERROR: missing column: {0}";
public static string ERR_MISSING_TABLE = "ERROR: table {0} does not exsit";
public static string ERR_CANNOT_CONNECT = "ERROR: cannot connect to mysql using connection string: {0}";
public static string ERR_ORPHANED_FILES = "ERROR: the following files are orphans: {0}";
public static string ERR_INVALID_TALK_LANGUAGE = "ERROR: the following talk pages have a different page_language than their parent page: {0}";
}
}
| |
using System;
using System.Collections;
using LumiSoft.Net;
namespace LumiSoft.Net.IMAP.Server
{
/// <summary>
/// IMAP search command grouped(parenthesized) search-key collection.
/// </summary>
internal class SearchGroup
{
private ArrayList m_pSearchKeys = null;
/// <summary>
/// Default constructor.
/// </summary>
public SearchGroup()
{
m_pSearchKeys = new ArrayList();
}
#region method Parse
/// <summary>
/// Parses search key from current position.
/// </summary>
/// <param name="reader"></param>
public void Parse(StringReader reader)
{
//Remove spaces from string start
reader.ReadToFirstChar();
if(reader.StartsWith("(")){
reader = new StringReader(reader.ReadParenthesized().Trim());
}
//--- Start parsing search keys --------------//
while(reader.Available > 0){
object searchKey = ParseSearchKey(reader);
if(searchKey != null){
m_pSearchKeys.Add(searchKey);
}
}
//--------------------------------------------//
}
#endregion
#region method IsHeaderNeeded
/// <summary>
/// Gets if message Header is needed for matching.
/// </summary>
/// <returns></returns>
public bool IsHeaderNeeded()
{
foreach(object searchKey in m_pSearchKeys){
if(SearchGroup.IsHeaderNeededForKey(searchKey)){
return true;
}
}
return false;
}
#endregion
#region method IsBodyTextNeeded
/// <summary>
/// Gets if message body text is needed for matching.
/// </summary>
/// <returns></returns>
public bool IsBodyTextNeeded()
{
foreach(object searchKey in m_pSearchKeys){
if(SearchGroup.IsBodyTextNeededForKey(searchKey)){
return true;
}
}
return false;
}
#endregion
#region static method ParseSearchKey
/// <summary>
/// Parses SearchGroup or SearchItem from reader. If reader starts with (, then parses searchGroup, otherwise SearchItem.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
internal static object ParseSearchKey(StringReader reader)
{
//Remove spaces from string start
reader.ReadToFirstChar();
// SearchGroup
if(reader.StartsWith("(")){
SearchGroup searchGroup = new SearchGroup();
searchGroup.Parse(reader);
return searchGroup;
}
// SearchItem
else{
return SearchKey.Parse(reader);
}
}
#endregion
#region static method Match_Key_Value
/// <summary>
/// Gets if specified message matches to specified search key.
/// </summary>
/// <param name="searchKey">SearchKey or SearchGroup.</param>
/// <param name="no">IMAP message sequence number.</param>
/// <param name="uid">IMAP message UID.</param>
/// <param name="size">IMAP message size in bytes.</param>
/// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param>
/// <param name="flags">IMAP message flags.</param>
/// <param name="mime">Mime message main header only.</param>
/// <param name="bodyText">Message body text.</param>
/// <returns></returns>
internal static bool Match_Key_Value(object searchKey,long no,long uid,long size,DateTime internalDate,IMAP_MessageFlags flags,LumiSoft.Net.Mime.Mime mime,string bodyText)
{
if(searchKey.GetType() == typeof(SearchKey)){
if(!((SearchKey)searchKey).Match(no,uid,size,internalDate,flags,mime,bodyText)){
return false;
}
}
else if(searchKey.GetType() == typeof(SearchGroup)){
if(!((SearchGroup)searchKey).Match(no,uid,size,internalDate,flags,mime,bodyText)){
return false;
}
}
return true;
}
#endregion
#region static method IsHeaderNeededForKey
/// <summary>
/// Gets if message header is needed for matching.
/// </summary>
/// <param name="searchKey"></param>
/// <returns></returns>
internal static bool IsHeaderNeededForKey(object searchKey)
{
if(searchKey.GetType() == typeof(SearchKey)){
if(((SearchKey)searchKey).IsHeaderNeeded()){
return true;
}
}
else if(searchKey.GetType() == typeof(SearchGroup)){
if(((SearchGroup)searchKey).IsHeaderNeeded()){
return true;
}
}
return false;
}
#endregion
#region static method IsBodyTextNeededForKey
/// <summary>
/// Gets if message body text is needed for matching.
/// </summary>
/// <param name="searchKey"></param>
/// <returns></returns>
internal static bool IsBodyTextNeededForKey(object searchKey)
{
if(searchKey.GetType() == typeof(SearchKey)){
if(((SearchKey)searchKey).IsBodyTextNeeded()){
return true;
}
}
else if(searchKey.GetType() == typeof(SearchGroup)){
if(((SearchGroup)searchKey).IsBodyTextNeeded()){
return true;
}
}
return false;
}
#endregion
#region method Match
/// <summary>
/// Gets if specified message matches with this class search-key.
/// </summary>
/// <param name="no">IMAP message sequence number.</param>
/// <param name="uid">IMAP message UID.</param>
/// <param name="size">IMAP message size in bytes.</param>
/// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param>
/// <param name="flags">IMAP message flags.</param>
/// <param name="mime">Mime message main header only.</param>
/// <param name="bodyText">Message body text.</param>
/// <returns></returns>
public bool Match(long no,long uid,long size,DateTime internalDate,IMAP_MessageFlags flags,LumiSoft.Net.Mime.Mime mime,string bodyText)
{
// We must match all keys, if one fails, no need to check others
foreach(object searckKey in m_pSearchKeys){
if(!Match_Key_Value(searckKey,no,uid,size,internalDate,flags,mime,bodyText)){
return false;
}
}
return true;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using BurnSystems.Logging;
using DatenMeister.Core.EMOF.Interface.Common;
using DatenMeister.Core.EMOF.Interface.Identifiers;
using DatenMeister.Core.EMOF.Interface.Reflection;
using DatenMeister.Core.Helper;
using DatenMeister.Core.Models;
using DatenMeister.Core.Models.EMOF;
using DatenMeister.Core.Runtime.Workspaces;
using DatenMeister.Core.Uml.Helper;
namespace DatenMeister.Core.Runtime
{
/// <summary>
/// Stores the default classifier hints which allow a harmonized identification
/// of common classifier, like packages,
/// </summary>
public class DefaultClassifierHints
{
/// <summary>
/// Stores the logger
/// </summary>
private static readonly ILogger Logger = new ClassLogger(typeof(DefaultClassifierHints));
/// <summary>
/// Gets the default package classifier for a given extent
/// </summary>
/// <param name="uriExtent">Extent to be used</param>
/// <returns>The found extent</returns>
public IElement? GetDefaultPackageClassifier(IHasExtent uriExtent)
{
var extent = uriExtent.Extent ?? throw new InvalidOperationException("UriExtent does not have an extent");
return GetDefaultPackageClassifier(extent);
}
/// <summary>
/// Gets the default package classifier for a given extent
/// </summary>
/// <param name="extent">Extent to be used</param>
/// <returns>The found extent</returns>
public static IElement? GetDefaultPackageClassifier(IExtent extent)
{
// First look into the standard uml meta classes
var findByUrl = GetDefaultPackageClassifiers(extent).FirstOrDefault();
if (findByUrl == null)
{
Logger.Warn("No default package was found in the given extent");
}
return findByUrl;
}
/// <summary>
/// Gets the default classifiers defining packaging elements
/// </summary>
/// <param name="extent">Extent whose packages are evaluated</param>
/// <returns>The defined packages</returns>
public static IEnumerable<IElement> GetDefaultPackageClassifiers(IExtent extent)
{
var workspace = extent.GetWorkspace();
if (workspace != null && workspace.MetaWorkspaces.Any(x => x.id == WorkspaceNames.WorkspaceUml || x.id == WorkspaceNames.WorkspaceMof))
{
yield return _UML.TheOne.Packages.__Package;
}
yield return _DatenMeister.TheOne.CommonTypes.Default.__Package;
}
/// <summary>
/// Gets the default name of the property which contains the elements of a property
/// This name is dependent upon the element to which the object will be added and
/// the extent in which the element will be added.
/// </summary>
/// <param name="packagingElement">Element in which the element will be added</param>
/// <returns>The name of the property to which the element will be added</returns>
public static string GetDefaultPackagePropertyName(IObject packagingElement)
{
return _UML._Packages._Package.packagedElement;
}
/// <summary>
/// Adds the given child to the container by considering whether the container
/// is an extent or is a MOF object. If an extent, it will be simply added as a child
/// otherwise, it will be added to the property
/// </summary>
/// <param name="container">Container to which the element will be added</param>
/// <param name="child">Child element which will be added</param>
public static void AddToExtentOrElement(IObject container, IObject child)
{
switch (container)
{
case null:
throw new InvalidOperationException("container is null");
case IExtent extent:
extent.elements().add(child);
break;
default:
{
var propertyName = GetDefaultPackagePropertyName(container);
container.AddCollectionItem(propertyName, child);
break;
}
}
}
/// <summary>
/// Gets the default reflective collection for the given element.
/// For extents, it is an enumeration of all elements, for the objects, it is the default
/// property being used for compositions
/// </summary>
/// <param name="element">Element to be used. </param>
/// <returns>the reflectiv collection</returns>
public static IReflectiveCollection GetDefaultReflectiveCollection(IObject element)
{
return element switch
{
null => throw new InvalidOperationException("container is null"),
IExtent extent => extent.elements(),
_ => element.get<IReflectiveCollection>(GetDefaultPackagePropertyName(element))
};
}
public static void RemoveFromExtentOrElement(IObject container, IObject child)
{
if (container is IExtent extent)
{
extent.elements().remove(child);
}
else
{
var propertyName = GetDefaultPackagePropertyName(container);
container.RemoveCollectionItem(propertyName, child);
}
}
/// <summary>
/// Gets the information whether the given element is a package to which
/// an additional object can be added as an enumeration. If this method returns true,
/// an element can be added via AddToExtentOrElement
/// </summary>
/// <param name="value">Element which shall be checked</param>
/// <returns>true, if the given element is a package</returns>
public static bool IsPackageLike(IObject value)
{
// At the moment, every element is a package
return true;
}
public static IEnumerable<string> GetPackagingPropertyNames(IObject item)
{
var metaClass = (item as IElement)?.getMetaClass();
if (metaClass?.Equals(_DatenMeister.TheOne.Management.__Workspace) == true)
{
yield return _DatenMeister._Management._Workspace.extents;
}
// Hard coded at the moment, will be replaced by composite property identification
if (metaClass?.Equals(_UML.TheOne.StructuredClassifiers.__Class) == true)
{
yield return _UML._StructuredClassifiers._Class.ownedAttribute;
yield return _UML._StructuredClassifiers._Class.ownedOperation;
yield return _UML._StructuredClassifiers._Class.ownedReception;
}
else
{
var hadPackagedElement = false;
if (metaClass != null)
{
var compositing = ClassifierMethods.GetCompositingProperties(metaClass).ToList();
if (compositing != null && compositing.Count > 0)
{
foreach (var composite in compositing)
{
var name = NamedElementMethods.GetName(composite);
if (name == _UML._Packages._Package.packagedElement)
{
hadPackagedElement = true;
}
yield return name;
}
}
}
// If we know nothing, then add the packaged element
if (!hadPackagedElement)
{
yield return _UML._Packages._Package.packagedElement;
}
}
}
public static IEnumerable<IElement> GetPackagedElements(IObject item)
{
// Gets the items as elements
if (item is IExtent asExtent)
{
foreach (var element in asExtent.elements())
{
if (element is IElement asElement)
{
yield return asElement;
}
}
yield break;
}
// Gets the items as properties
var propertyName = GetPackagingPropertyNames(item).ToList();
foreach (var property in propertyName)
{
if (item.isSet(property))
{
var value = item.get(property);
if (DotNetHelper.IsOfEnumeration(value))
{
var valueAsEnumerable = (value as IEnumerable)!;
foreach (var valueItem in valueAsEnumerable)
{
if (valueItem is IElement asElement)
{
yield return asElement;
}
}
}
}
}
}
/// <summary>
/// Gets the information whether the propertyname is a generic property
/// </summary>
/// <param name="element">Element to be handled</param>
/// <param name="propertyName">Name of the property</param>
/// <returns></returns>
public static bool IsPackagingProperty(IObject element, string propertyName)
{
return GetPackagingPropertyNames(element).Contains(propertyName);
}
/// <summary>
/// Checks whether the property is so generic, that it shall be kept in the lists.
/// This method is especially used in the FormCreator.ListForm which tries to minimize
/// the number of columns within the subelementsfield.
///
/// All properties which return 'true' here, are kept even though they sould have
/// been removed since the property is not available in other fields
/// </summary>
/// <param name="element">Element containing the property</param>
/// <param name="propertyName">Name of the property</param>
/// <returns>true, if the field shall be kept</returns>
public static bool IsGenericProperty(IObject element, string propertyName)
=>
propertyName == _UML._CommonStructure._NamedElement.name
|| propertyName.ToLower(CultureInfo.InvariantCulture) == "id";
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/taxed_reservation_quote.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Folio {
/// <summary>Holder for reflection information generated from folio/taxed_reservation_quote.proto</summary>
public static partial class TaxedReservationQuoteReflection {
#region Descriptor
/// <summary>File descriptor for folio/taxed_reservation_quote.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TaxedReservationQuoteReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiNmb2xpby90YXhlZF9yZXNlcnZhdGlvbl9xdW90ZS5wcm90bxIRaG9sbXMu",
"dHlwZXMuZm9saW8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJvdG8a",
"GmZvbGlvL3RheF9hc3Nlc3NtZW50LnByb3RvGitmb2xpby90YXhlZF9yZXNl",
"cnZhdGlvbl9uaWdodGx5X3F1b3RlLnByb3RvGjZmb2xpby90YXhlZF9pbmNp",
"ZGVudGFsX3Jlc2VydmF0aW9uX25pZ2h0bHlfcXVvdGUucHJvdG8aLmJvb2tp",
"bmcvaW5kaWNhdG9ycy9yZXNlcnZhdGlvbl9pbmRpY2F0b3IucHJvdG8i9QMK",
"FVRheGVkUmVzZXJ2YXRpb25RdW90ZRJHCg5sb2RnaW5nX3F1b3RlcxgBIAMo",
"CzIvLmhvbG1zLnR5cGVzLmZvbGlvLlRheGVkUmVzZXJ2YXRpb25OaWdodGx5",
"UXVvdGUSVAoRaW5jaWRlbnRhbF9xdW90ZXMYAiADKAsyOS5ob2xtcy50eXBl",
"cy5mb2xpby5UYXhlZEluY2lkZW50YWxSZXNlcnZhdGlvbk5pZ2h0bHlRdW90",
"ZRJMCh1wcmV0YXhfbG9kZ2luZ19wcmljZV9zdWJ0b3RhbBgDIAEoCzIlLmhv",
"bG1zLnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudBJPCiBwcmV0YXhf",
"aW5jaWRlbnRhbF9wcmljZV9zdWJ0b3RhbBgEIAEoCzIlLmhvbG1zLnR5cGVz",
"LnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudBI5Cg90YXhfYXNzZXNzbWVudHMY",
"BSADKAsyIC5ob2xtcy50eXBlcy5mb2xpby5UYXhBc3Nlc3NtZW50EkkKC3Jl",
"c2VydmF0aW9uGAYgASgLMjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0",
"b3JzLlJlc2VydmF0aW9uSW5kaWNhdG9yEhgKEHJlc2VydmF0aW9uX3RhZ3MY",
"ByADKAlCG1oFZm9saW+qAhFIT0xNUy5UeXBlcy5Gb2xpb2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Folio.TaxAssessmentReflection.Descriptor, global::HOLMS.Types.Folio.TaxedReservationNightlyQuoteReflection.Descriptor, global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuoteReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Folio.TaxedReservationQuote), global::HOLMS.Types.Folio.TaxedReservationQuote.Parser, new[]{ "LodgingQuotes", "IncidentalQuotes", "PretaxLodgingPriceSubtotal", "PretaxIncidentalPriceSubtotal", "TaxAssessments", "Reservation", "ReservationTags" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class TaxedReservationQuote : pb::IMessage<TaxedReservationQuote> {
private static readonly pb::MessageParser<TaxedReservationQuote> _parser = new pb::MessageParser<TaxedReservationQuote>(() => new TaxedReservationQuote());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TaxedReservationQuote> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Folio.TaxedReservationQuoteReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationQuote() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationQuote(TaxedReservationQuote other) : this() {
lodgingQuotes_ = other.lodgingQuotes_.Clone();
incidentalQuotes_ = other.incidentalQuotes_.Clone();
PretaxLodgingPriceSubtotal = other.pretaxLodgingPriceSubtotal_ != null ? other.PretaxLodgingPriceSubtotal.Clone() : null;
PretaxIncidentalPriceSubtotal = other.pretaxIncidentalPriceSubtotal_ != null ? other.PretaxIncidentalPriceSubtotal.Clone() : null;
taxAssessments_ = other.taxAssessments_.Clone();
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
reservationTags_ = other.reservationTags_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationQuote Clone() {
return new TaxedReservationQuote(this);
}
/// <summary>Field number for the "lodging_quotes" field.</summary>
public const int LodgingQuotesFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Folio.TaxedReservationNightlyQuote> _repeated_lodgingQuotes_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Folio.TaxedReservationNightlyQuote.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedReservationNightlyQuote> lodgingQuotes_ = new pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedReservationNightlyQuote>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedReservationNightlyQuote> LodgingQuotes {
get { return lodgingQuotes_; }
}
/// <summary>Field number for the "incidental_quotes" field.</summary>
public const int IncidentalQuotesFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuote> _repeated_incidentalQuotes_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuote.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuote> incidentalQuotes_ = new pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuote>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Folio.TaxedIncidentalReservationNightlyQuote> IncidentalQuotes {
get { return incidentalQuotes_; }
}
/// <summary>Field number for the "pretax_lodging_price_subtotal" field.</summary>
public const int PretaxLodgingPriceSubtotalFieldNumber = 3;
private global::HOLMS.Types.Primitive.MonetaryAmount pretaxLodgingPriceSubtotal_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount PretaxLodgingPriceSubtotal {
get { return pretaxLodgingPriceSubtotal_; }
set {
pretaxLodgingPriceSubtotal_ = value;
}
}
/// <summary>Field number for the "pretax_incidental_price_subtotal" field.</summary>
public const int PretaxIncidentalPriceSubtotalFieldNumber = 4;
private global::HOLMS.Types.Primitive.MonetaryAmount pretaxIncidentalPriceSubtotal_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount PretaxIncidentalPriceSubtotal {
get { return pretaxIncidentalPriceSubtotal_; }
set {
pretaxIncidentalPriceSubtotal_ = value;
}
}
/// <summary>Field number for the "tax_assessments" field.</summary>
public const int TaxAssessmentsFieldNumber = 5;
private static readonly pb::FieldCodec<global::HOLMS.Types.Folio.TaxAssessment> _repeated_taxAssessments_codec
= pb::FieldCodec.ForMessage(42, global::HOLMS.Types.Folio.TaxAssessment.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessment> taxAssessments_ = new pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessment>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessment> TaxAssessments {
get { return taxAssessments_; }
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 6;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "reservation_tags" field.</summary>
public const int ReservationTagsFieldNumber = 7;
private static readonly pb::FieldCodec<string> _repeated_reservationTags_codec
= pb::FieldCodec.ForString(58);
private readonly pbc::RepeatedField<string> reservationTags_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> ReservationTags {
get { return reservationTags_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TaxedReservationQuote);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TaxedReservationQuote other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!lodgingQuotes_.Equals(other.lodgingQuotes_)) return false;
if(!incidentalQuotes_.Equals(other.incidentalQuotes_)) return false;
if (!object.Equals(PretaxLodgingPriceSubtotal, other.PretaxLodgingPriceSubtotal)) return false;
if (!object.Equals(PretaxIncidentalPriceSubtotal, other.PretaxIncidentalPriceSubtotal)) return false;
if(!taxAssessments_.Equals(other.taxAssessments_)) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
if(!reservationTags_.Equals(other.reservationTags_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= lodgingQuotes_.GetHashCode();
hash ^= incidentalQuotes_.GetHashCode();
if (pretaxLodgingPriceSubtotal_ != null) hash ^= PretaxLodgingPriceSubtotal.GetHashCode();
if (pretaxIncidentalPriceSubtotal_ != null) hash ^= PretaxIncidentalPriceSubtotal.GetHashCode();
hash ^= taxAssessments_.GetHashCode();
if (reservation_ != null) hash ^= Reservation.GetHashCode();
hash ^= reservationTags_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
lodgingQuotes_.WriteTo(output, _repeated_lodgingQuotes_codec);
incidentalQuotes_.WriteTo(output, _repeated_incidentalQuotes_codec);
if (pretaxLodgingPriceSubtotal_ != null) {
output.WriteRawTag(26);
output.WriteMessage(PretaxLodgingPriceSubtotal);
}
if (pretaxIncidentalPriceSubtotal_ != null) {
output.WriteRawTag(34);
output.WriteMessage(PretaxIncidentalPriceSubtotal);
}
taxAssessments_.WriteTo(output, _repeated_taxAssessments_codec);
if (reservation_ != null) {
output.WriteRawTag(50);
output.WriteMessage(Reservation);
}
reservationTags_.WriteTo(output, _repeated_reservationTags_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += lodgingQuotes_.CalculateSize(_repeated_lodgingQuotes_codec);
size += incidentalQuotes_.CalculateSize(_repeated_incidentalQuotes_codec);
if (pretaxLodgingPriceSubtotal_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PretaxLodgingPriceSubtotal);
}
if (pretaxIncidentalPriceSubtotal_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PretaxIncidentalPriceSubtotal);
}
size += taxAssessments_.CalculateSize(_repeated_taxAssessments_codec);
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
size += reservationTags_.CalculateSize(_repeated_reservationTags_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TaxedReservationQuote other) {
if (other == null) {
return;
}
lodgingQuotes_.Add(other.lodgingQuotes_);
incidentalQuotes_.Add(other.incidentalQuotes_);
if (other.pretaxLodgingPriceSubtotal_ != null) {
if (pretaxLodgingPriceSubtotal_ == null) {
pretaxLodgingPriceSubtotal_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
PretaxLodgingPriceSubtotal.MergeFrom(other.PretaxLodgingPriceSubtotal);
}
if (other.pretaxIncidentalPriceSubtotal_ != null) {
if (pretaxIncidentalPriceSubtotal_ == null) {
pretaxIncidentalPriceSubtotal_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
PretaxIncidentalPriceSubtotal.MergeFrom(other.PretaxIncidentalPriceSubtotal);
}
taxAssessments_.Add(other.taxAssessments_);
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
reservationTags_.Add(other.reservationTags_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
lodgingQuotes_.AddEntriesFrom(input, _repeated_lodgingQuotes_codec);
break;
}
case 18: {
incidentalQuotes_.AddEntriesFrom(input, _repeated_incidentalQuotes_codec);
break;
}
case 26: {
if (pretaxLodgingPriceSubtotal_ == null) {
pretaxLodgingPriceSubtotal_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(pretaxLodgingPriceSubtotal_);
break;
}
case 34: {
if (pretaxIncidentalPriceSubtotal_ == null) {
pretaxIncidentalPriceSubtotal_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(pretaxIncidentalPriceSubtotal_);
break;
}
case 42: {
taxAssessments_.AddEntriesFrom(input, _repeated_taxAssessments_codec);
break;
}
case 50: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 58: {
reservationTags_.AddEntriesFrom(input, _repeated_reservationTags_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
using System.Diagnostics.Contracts;
[Serializable]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UIntPtr : ISerializable
{
[SecurityCritical]
unsafe private void* m_value;
public static readonly UIntPtr Zero;
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
m_value = (void *)value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
m_value = (void *)value;
#else // 32
m_value = (void*)checked((uint)value);
#endif
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(void* value)
{
m_value = value;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
ulong l = info.GetUInt64("value");
if (Size==4 && l>UInt32.MaxValue) {
throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
}
m_value = (void *)l;
}
[System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("value", (ulong)m_value);
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override bool Equals(Object obj) {
if (obj is UIntPtr) {
return (m_value == ((UIntPtr)obj).m_value);
}
return false;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
#if FEATURE_CORECLR
#if BIT64
ulong l = (ulong)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // 32
return unchecked((int)m_value);
#endif
#else
return unchecked((int)((long)m_value)) & 0x7fffffff;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe uint ToUInt32() {
#if BIT64
return checked((uint)m_value);
#else // 32
return (uint)m_value;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe ulong ToUInt64() {
return (ulong)m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
return ((ulong)m_value).ToString(CultureInfo.InvariantCulture);
#else // 32
return ((uint)m_value).ToString(CultureInfo.InvariantCulture);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (uint value)
{
return new UIntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
public static explicit operator UIntPtr (ulong value)
{
return new UIntPtr(value);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator uint(UIntPtr value)
{
#if BIT64
return checked((uint)value.m_value);
#else // 32
return (uint)value.m_value;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value.m_value;
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator UIntPtr (void* value)
{
return new UIntPtr(value);
}
[System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (UIntPtr value1, UIntPtr value2)
{
return value1.m_value == value2.m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (UIntPtr value1, UIntPtr value2)
{
return value1.m_value != value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset) {
return pointer + offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset) {
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset) {
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset) {
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
public static int Size
{
[System.Runtime.Versioning.NonVersionable]
get
{
#if BIT64
return 8;
#else // 32
return 4;
#endif
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
return m_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.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using Microsoft.Xml;
using System.ServiceModel.Dispatcher;
namespace System.ServiceModel.Security
{
internal class RequestSecurityTokenResponse : BodyWriter
{
private SecurityStandardsManager _standardsManager;
private string _context;
private int _keySize;
private bool _computeKey;
private string _tokenType;
private SecurityKeyIdentifierClause _requestedAttachedReference;
private SecurityKeyIdentifierClause _requestedUnattachedReference;
private SecurityToken _issuedToken;
private SecurityToken _proofToken;
private XmlElement _rstrXml;
private DateTime _effectiveTime;
private DateTime _expirationTime;
private bool _isLifetimeSet;
private bool _isReceiver;
private bool _isReadOnly;
private ArraySegment<byte> _cachedWriteBuffer;
private int _cachedWriteBufferLength;
private bool _isRequestedTokenClosed;
private object _appliesTo;
private XmlObjectSerializer _appliesToSerializer;
private Type _appliesToType;
private Object _thisLock = new Object();
private System.IdentityModel.XmlBuffer _issuedTokenBuffer;
public RequestSecurityTokenResponse()
: this(SecurityStandardsManager.DefaultInstance)
{
}
public RequestSecurityTokenResponse(MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer))
{
}
public RequestSecurityTokenResponse(XmlElement requestSecurityTokenResponseXml,
string context,
string tokenType,
int keySize,
SecurityKeyIdentifierClause requestedAttachedReference,
SecurityKeyIdentifierClause requestedUnattachedReference,
bool computeKey,
DateTime validFrom,
DateTime validTo,
bool isRequestedTokenClosed)
: this(SecurityStandardsManager.DefaultInstance,
requestSecurityTokenResponseXml,
context,
tokenType,
keySize,
requestedAttachedReference,
requestedUnattachedReference,
computeKey,
validFrom,
validTo,
isRequestedTokenClosed,
null)
{
}
public RequestSecurityTokenResponse(MessageSecurityVersion messageSecurityVersion,
SecurityTokenSerializer securityTokenSerializer,
XmlElement requestSecurityTokenResponseXml,
string context,
string tokenType,
int keySize,
SecurityKeyIdentifierClause requestedAttachedReference,
SecurityKeyIdentifierClause requestedUnattachedReference,
bool computeKey,
DateTime validFrom,
DateTime validTo,
bool isRequestedTokenClosed)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer),
requestSecurityTokenResponseXml,
context,
tokenType,
keySize,
requestedAttachedReference,
requestedUnattachedReference,
computeKey,
validFrom,
validTo,
isRequestedTokenClosed,
null)
{
}
internal RequestSecurityTokenResponse(SecurityStandardsManager standardsManager)
: base(true)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
_effectiveTime = SecurityUtils.MinUtcDateTime;
_expirationTime = SecurityUtils.MaxUtcDateTime;
_isRequestedTokenClosed = false;
_isLifetimeSet = false;
_isReceiver = false;
_isReadOnly = false;
}
internal RequestSecurityTokenResponse(SecurityStandardsManager standardsManager,
XmlElement rstrXml,
string context,
string tokenType,
int keySize,
SecurityKeyIdentifierClause requestedAttachedReference,
SecurityKeyIdentifierClause requestedUnattachedReference,
bool computeKey,
DateTime validFrom,
DateTime validTo,
bool isRequestedTokenClosed,
System.IdentityModel.XmlBuffer issuedTokenBuffer)
: base(true)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
if (rstrXml == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstrXml");
_rstrXml = rstrXml;
_context = context;
_tokenType = tokenType;
_keySize = keySize;
_requestedAttachedReference = requestedAttachedReference;
_requestedUnattachedReference = requestedUnattachedReference;
_computeKey = computeKey;
_effectiveTime = validFrom.ToUniversalTime();
_expirationTime = validTo.ToUniversalTime();
_isLifetimeSet = true;
_isRequestedTokenClosed = isRequestedTokenClosed;
_issuedTokenBuffer = issuedTokenBuffer;
_isReceiver = true;
_isReadOnly = true;
}
public string Context
{
get
{
return _context;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_context = value;
}
}
public string TokenType
{
get
{
return _tokenType;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_tokenType = value;
}
}
public SecurityKeyIdentifierClause RequestedAttachedReference
{
get
{
return _requestedAttachedReference;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_requestedAttachedReference = value;
}
}
public SecurityKeyIdentifierClause RequestedUnattachedReference
{
get
{
return _requestedUnattachedReference;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_requestedUnattachedReference = value;
}
}
public DateTime ValidFrom
{
get
{
return _effectiveTime;
}
}
public DateTime ValidTo
{
get
{
return _expirationTime;
}
}
public bool ComputeKey
{
get
{
return _computeKey;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_computeKey = value;
}
}
public int KeySize
{
get
{
return _keySize;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (value < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SRServiceModel.ValueMustBeNonNegative));
_keySize = value;
}
}
public bool IsRequestedTokenClosed
{
get
{
return _isRequestedTokenClosed;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_isRequestedTokenClosed = value;
}
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
protected Object ThisLock
{
get
{
return _thisLock;
}
}
internal bool IsReceiver
{
get
{
return _isReceiver;
}
}
internal SecurityStandardsManager StandardsManager
{
get
{
return _standardsManager;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_standardsManager = (value != null ? value : SecurityStandardsManager.DefaultInstance);
}
}
public SecurityToken EntropyToken
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRSTR, "EntropyToken")));
}
return null;
}
}
public SecurityToken RequestedSecurityToken
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRSTR, "IssuedToken")));
}
return _issuedToken;
}
set
{
if (_isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_issuedToken = value;
}
}
public SecurityToken RequestedProofToken
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRSTR, "ProofToken")));
}
return _proofToken;
}
set
{
if (_isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_proofToken = value;
}
}
public XmlElement RequestSecurityTokenResponseXml
{
get
{
if (!_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemAvailableInDeserializedRSTROnly, "RequestSecurityTokenXml")));
}
return _rstrXml;
}
}
internal object AppliesTo
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesTo")));
}
return _appliesTo;
}
}
internal XmlObjectSerializer AppliesToSerializer
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesToSerializer")));
}
return _appliesToSerializer;
}
}
internal Type AppliesToType
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesToType")));
}
return _appliesToType;
}
}
internal bool IsLifetimeSet
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRSTR, "IsLifetimeSet")));
}
return _isLifetimeSet;
}
}
internal SecurityToken GetIssuerEntropy(SecurityTokenResolver resolver)
{
if (_isReceiver)
{
return _standardsManager.TrustDriver.GetEntropy(this, resolver);
}
else
return null;
}
public void SetLifetime(DateTime validFrom, DateTime validTo)
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (validFrom.ToUniversalTime() > validTo.ToUniversalTime())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.EffectiveGreaterThanExpiration);
}
_effectiveTime = validFrom.ToUniversalTime();
_expirationTime = validTo.ToUniversalTime();
_isLifetimeSet = true;
}
public void SetAppliesTo<T>(T appliesTo, XmlObjectSerializer serializer)
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (appliesTo != null && serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
_appliesTo = appliesTo;
_appliesToSerializer = serializer;
_appliesToType = typeof(T);
}
public void GetAppliesToQName(out string localName, out string namespaceUri)
{
if (!_isReceiver)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemAvailableInDeserializedRSTOnly, "MatchesAppliesTo")));
_standardsManager.TrustDriver.GetAppliesToQName(this, out localName, out namespaceUri);
}
public T GetAppliesTo<T>()
{
return this.GetAppliesTo<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), DataContractSerializerDefaults.MaxItemsInObjectGraph));
}
public T GetAppliesTo<T>(XmlObjectSerializer serializer)
{
if (_isReceiver)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
return _standardsManager.TrustDriver.GetAppliesTo<T>(this, serializer);
}
else
{
return (T)_appliesTo;
}
}
private void OnWriteTo(XmlWriter w)
{
if (_isReceiver)
{
_rstrXml.WriteTo(w);
}
else
{
_standardsManager.TrustDriver.WriteRequestSecurityTokenResponse(this, w);
}
}
public void WriteTo(XmlWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
if (this.IsReadOnly)
{
// cache the serialized bytes to ensure repeatability
if (_cachedWriteBuffer.Array == null)
{
MemoryStream stream = new MemoryStream();
using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary))
{
this.OnWriteTo(binaryWriter);
binaryWriter.Flush();
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
bool gotBuffer = stream.TryGetBuffer(out _cachedWriteBuffer);
if (!gotBuffer)
{
throw new UnauthorizedAccessException(SRServiceModel.UnauthorizedAccess_MemStreamBuffer);
}
_cachedWriteBufferLength = (int)stream.Length;
}
}
writer.WriteNode(XmlDictionaryReader.CreateBinaryReader(_cachedWriteBuffer.Array, 0, _cachedWriteBufferLength, XD.Dictionary, XmlDictionaryReaderQuotas.Max), false);
}
else
this.OnWriteTo(writer);
}
public static RequestSecurityTokenResponse CreateFrom(XmlReader reader)
{
return CreateFrom(SecurityStandardsManager.DefaultInstance, reader);
}
public static RequestSecurityTokenResponse CreateFrom(XmlReader reader, MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
{
return CreateFrom(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer), reader);
}
internal static RequestSecurityTokenResponse CreateFrom(SecurityStandardsManager standardsManager, XmlReader reader)
{
return standardsManager.TrustDriver.CreateRequestSecurityTokenResponse(reader);
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
WriteTo(writer);
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_isReadOnly = true;
this.OnMakeReadOnly();
}
}
protected internal virtual void OnWriteCustomAttributes(XmlWriter writer)
{ }
protected internal virtual void OnWriteCustomElements(XmlWriter writer)
{ }
protected virtual void OnMakeReadOnly() { }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type decimal with 2 columns and 4 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct decmat2x4 : IEnumerable<decimal>, IEquatable<decmat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public decimal m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public decimal m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public decimal m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
public decimal m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public decimal m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public decimal m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public decimal m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
public decimal m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public decmat2x4(decimal m00, decimal m01, decimal m02, decimal m03, decimal m10, decimal m11, decimal m12, decimal m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a decmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a decmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a decmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a decmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decvec2 c0, decvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0m;
this.m03 = 0m;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0m;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decvec3 c0, decvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = 0m;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = 0m;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat2x4(decvec4 c0, decvec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public decimal[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public decimal[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public decvec4 Column0
{
get
{
return new decvec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public decvec4 Column1
{
get
{
return new decvec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public decvec2 Row0
{
get
{
return new decvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public decvec2 Row1
{
get
{
return new decvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public decvec2 Row2
{
get
{
return new decvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public decvec2 Row3
{
get
{
return new decvec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static decmat2x4 Zero { get; } = new decmat2x4(0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static decmat2x4 Ones { get; } = new decmat2x4(1m, 1m, 1m, 1m, 1m, 1m, 1m, 1m);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static decmat2x4 Identity { get; } = new decmat2x4(1m, 0m, 0m, 0m, 0m, 1m, 0m, 0m);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static decmat2x4 AllMaxValue { get; } = new decmat2x4(decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static decmat2x4 DiagonalMaxValue { get; } = new decmat2x4(decimal.MaxValue, 0m, 0m, 0m, 0m, decimal.MaxValue, 0m, 0m);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static decmat2x4 AllMinValue { get; } = new decmat2x4(decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static decmat2x4 DiagonalMinValue { get; } = new decmat2x4(decimal.MinValue, 0m, 0m, 0m, 0m, decimal.MinValue, 0m, 0m);
/// <summary>
/// Predefined all-MinusOne matrix
/// </summary>
public static decmat2x4 AllMinusOne { get; } = new decmat2x4(decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne);
/// <summary>
/// Predefined diagonal-MinusOne matrix
/// </summary>
public static decmat2x4 DiagonalMinusOne { get; } = new decmat2x4(decimal.MinusOne, 0m, 0m, 0m, 0m, decimal.MinusOne, 0m, 0m);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<decimal> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public decimal this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public decimal this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(decmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is decmat2x4 && Equals((decmat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(decmat2x4 lhs, decmat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(decmat2x4 lhs, decmat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public decmat4x2 Transposed => new decmat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public decimal MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public decimal MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public decimal Length => (decimal)((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))).Sqrt();
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public decimal LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public decimal Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public decimal Norm => (decimal)((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))).Sqrt();
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public decimal Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public decimal Norm2 => (decimal)((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))).Sqrt();
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public decimal NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication decmat2x4 * decmat2 -> decmat2x4.
/// </summary>
public static decmat2x4 operator*(decmat2x4 lhs, decmat2 rhs) => new decmat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication decmat2x4 * decmat3x2 -> decmat3x4.
/// </summary>
public static decmat3x4 operator*(decmat2x4 lhs, decmat3x2 rhs) => new decmat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication decmat2x4 * decmat4x2 -> decmat4.
/// </summary>
public static decmat4 operator*(decmat2x4 lhs, decmat4x2 rhs) => new decmat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static decvec4 operator*(decmat2x4 m, decvec2 v) => new decvec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static decmat2x4 CompMul(decmat2x4 A, decmat2x4 B) => new decmat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static decmat2x4 CompDiv(decmat2x4 A, decmat2x4 B) => new decmat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static decmat2x4 CompAdd(decmat2x4 A, decmat2x4 B) => new decmat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static decmat2x4 CompSub(decmat2x4 A, decmat2x4 B) => new decmat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static decmat2x4 operator+(decmat2x4 lhs, decmat2x4 rhs) => new decmat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static decmat2x4 operator+(decmat2x4 lhs, decimal rhs) => new decmat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static decmat2x4 operator+(decimal lhs, decmat2x4 rhs) => new decmat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static decmat2x4 operator-(decmat2x4 lhs, decmat2x4 rhs) => new decmat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static decmat2x4 operator-(decmat2x4 lhs, decimal rhs) => new decmat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static decmat2x4 operator-(decimal lhs, decmat2x4 rhs) => new decmat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static decmat2x4 operator/(decmat2x4 lhs, decimal rhs) => new decmat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static decmat2x4 operator/(decimal lhs, decmat2x4 rhs) => new decmat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static decmat2x4 operator*(decmat2x4 lhs, decimal rhs) => new decmat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static decmat2x4 operator*(decimal lhs, decmat2x4 rhs) => new decmat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x4 operator<(decmat2x4 lhs, decmat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(decmat2x4 lhs, decimal rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(decimal lhs, decmat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x4 operator<=(decmat2x4 lhs, decmat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(decmat2x4 lhs, decimal rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(decimal lhs, decmat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x4 operator>(decmat2x4 lhs, decmat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(decmat2x4 lhs, decimal rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(decimal lhs, decmat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x4 operator>=(decmat2x4 lhs, decmat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(decmat2x4 lhs, decimal rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(decimal lhs, decmat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13);
}
}
| |
// comment this in games that don't use any of the unity3d 4.3 2D features (Physics2D raycasts basically)
#define Physics2D
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LugusInput : LugusSingletonRuntime<LugusInputDefault>
{
}
public class LugusInputDefault : MonoBehaviour
{
protected bool acceptInput = true;
public bool dragging = false;
public bool down = false;
public bool up = false;
public bool mouseMoving
{
get
{
if( dragging )
return true;
else
{
if( inputPoints.Count < 2 )
return false;
else
{
Vector3 previousPoint = inputPoints[ inputPoints.Count - 2 ];
if( Vector3.Distance(lastPoint, previousPoint) > 2 )
return true;
else
return false;
}
}
}
}
public List<Vector3> inputPoints = new List<Vector3>();
public Vector3 lastPoint;
protected void OnMouseDown()
{
inputPoints.Clear(); //= new List<Vector3>(); // reset the inputPoints array
Vector3 inputPoint = Input.mousePosition;
inputPoints.Add( inputPoint );
lastPoint = inputPoint;
}
protected void OnMouseDrag()
{
Vector3 inputPoint = Input.mousePosition;
// we're storing inputPoints even if we're not really dragging...
// if the user then just leaves screen open for a long time, we will have a huge inputpoints array -> not good
if( !dragging && inputPoints.Count > 1000 )
inputPoints.Clear();
//if( dragging )
inputPoints.Add( inputPoint );
lastPoint = inputPoint;
}
protected void OnMouseUp()
{
Vector3 inputPoint = Input.mousePosition;
inputPoints.Add( inputPoint );
lastPoint = inputPoint;
}
public Transform RayCastFromMouse(Camera camera)
{
if( inputPoints.Count == 0 )
return RaycastFromScreenPoint( camera, lastPoint );
else
return RaycastFromScreenPoint( camera, inputPoints[ inputPoints.Count - 1 ] );
}
public Transform RaycastFromScreenPoint(Vector3 screenPoint)
{
return RaycastFromScreenPoint(LugusCamera.ui, screenPoint);
}
public Transform RaycastFromScreenPoint(Camera camera, Vector3 screenPoint)
{
//if( inputPoints.Count == 0 )
// return null;
Ray ray = camera.ScreenPointToRay( screenPoint );
RaycastHit hit;
if ( Physics.Raycast(ray, out hit) )
{
return hit.collider.transform;
}
#if Physics2D
else
{
//Debug.Log ("Checking 2D physics " + (camera.ScreenToWorldPoint(screenPoint)) );
RaycastHit2D hit2 = Physics2D.Raycast( camera.ScreenToWorldPoint(screenPoint)/*new Vector2(screenPoint.x, screenPoint.y)*/ , Vector2.zero );
if( hit2.collider != null )
{
//Debug.Log ("FOUND! 2D physics " + hit2.collider.transform.name );
return hit2.collider.transform;
}
}
#endif
return null;
}
public Transform RayCastFromMouse()
{
return RayCastFromMouse(LugusCamera.ui);
}
public Vector3 ScreenTo3DPoint( Transform referenceObject )
{
return ScreenTo3DPoint( Input.mousePosition, referenceObject );
}
public Vector3 ScreenTo3DPoint( Vector3 screenPoint, Transform referenceObject )
{
return ScreenTo3DPoint( screenPoint, referenceObject.position );
}
public Vector3 ScreenTo3DPoint( Vector3 screenPoint, Vector3 referencePosition )
{
Ray ray = LugusCamera.ui.ScreenPointToRay( screenPoint );
Vector3 output = ray.GetPoint( Vector3.Distance(referencePosition, LugusCamera.ui.transform.position) );
return output.z(referencePosition.z);
/*
float distance = Vector3.Distance(referenceObject.position, LuGusCamera.ui.transform.position);
Vector3 mousePos = new Vector3( Input.mousePosition.x, Input.mousePosition.y, distance - 5.0f);
Debug.Log("ScreenTo3D : " + distance + " and " + mousePos );
return LuGusCamera.ui.ScreenToWorldPoint( mousePos );
*/
}
public Vector3 ScreenTo3DPoint( Vector3 screenPoint, Vector3 referencePosition, Camera camera )
{
Ray ray = camera.ScreenPointToRay( screenPoint );
Vector3 output = ray.GetPoint( Vector3.Distance(referencePosition, camera.transform.position) );
return output.z(referencePosition.z);
/*
float distance = Vector3.Distance(referenceObject.position, LuGusCamera.ui.transform.position);
Vector3 mousePos = new Vector3( Input.mousePosition.x, Input.mousePosition.y, distance - 5.0f);
Debug.Log("ScreenTo3D : " + distance + " and " + mousePos );
return LuGusCamera.ui.ScreenToWorldPoint( mousePos );
*/
}
public Vector3 ScreenTo3DPointOnPlane( Vector3 screenPoint, Plane plane)
{
float distance;
Ray ray = LugusCamera.ui.ScreenPointToRay( screenPoint );
if( plane.Raycast(ray, out distance) )
{
return ray.GetPoint(distance);
}
return Vector3.zero;
/*
float distance = Vector3.Distance(planeOrigin.position, LuGusCamera.ui.transform.position);
Vector3 mousePos = new Vector3( screenPoint.x, screenPoint.y, distance);
Debug.Log("ScreenTo3D : " + distance + " and " + mousePos );
return LuGusCamera.ui.ScreenToWorldPoint( mousePos );
*/
}
public Transform RayCastFromMouseDown()
{
if( down )
return RayCastFromMouse();
else
return null;
}
public Transform RayCastFromMouseUp()
{
if( up )
return RayCastFromMouse();
else
return null;
}
public Transform RayCastFromMouseDown(Camera camera)
{
if( down )
return RayCastFromMouse(camera);
else
return null;
}
public Transform RayCastFromMouseUp(Camera camera)
{
if( up )
return RayCastFromMouse(camera);
else
return null;
}
protected void ProcessMouse()
{
if( !acceptInput )
return;
down = false;
up = false;
// code for a single touch (mouse-like behaviour on touch)
if( Input.touchCount == 1 )
{
Touch touch = Input.touches[0];
if( touch.phase == TouchPhase.Began )
{
down = true;
dragging = true;
OnMouseDown();
}
if( touch.phase == TouchPhase.Ended )
{
up = true;
dragging = false;
OnMouseUp();
}
if( dragging )
{
if ( touch.deltaPosition == Vector2.zero )
{
return;
}
OnMouseDrag();
}
}
else
{
if( Input.GetMouseButtonDown(0) ) // left click
{
down = true;
dragging = true;
OnMouseDown();
}
if( Input.GetMouseButtonUp(0) )
{
up = true;
dragging = false;
OnMouseUp();
}
//if( dragging )
//{
OnMouseDrag();
//}
}
}
// Update is called once per frame
void Update ()
{
ProcessMouse();
if( Input.GetKeyDown(KeyCode.Tab) )
{
LugusDebug.debug = !LugusDebug.debug;
}
}
public bool KeyDown(KeyCode key)
{
return Input.GetKeyDown(key);
}
public bool KeyUp(KeyCode key)
{
return Input.GetKeyUp(key);
}
public bool Key(KeyCode key)
{
return Input.GetKey(key);
}
void OnGUI()
{
if( !LugusDebug.debug )
return;
if( GUI.Button( new Rect(200, Screen.height - 30, 200, 30), "Toggle debug") )
{
LugusDebug.debug = !LugusDebug.debug;
}
}
}
| |
// 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.Net.Sockets;
namespace System.Net
{
/// <devdoc>
/// <para>
/// Provides an Internet Protocol (IP) address.
/// </para>
/// </devdoc>
[Serializable]
public class IPAddress
{
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF);
public static readonly IPAddress None = Broadcast;
internal const long LoopbackMask = 0x00000000000000FF;
public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0);
public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
/// <summary>
/// For IPv4 addresses, this field stores the Address.
/// For IPv6 addresses, this field stores the ScopeId.
/// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties.
/// </summary>
private uint _addressOrScopeId;
/// <summary>
/// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address.
/// </summary>
private readonly ushort[] _numbers;
/// <summary>
/// A lazily initialized cache of the result of calling <see cref="ToString"/>.
/// </summary>
[NonSerialized]
private string _toString;
/// <summary>
/// This field is only used for IPv6 addresses. A lazily initialized cache of the <see cref="GetHashCode"/> value.
/// </summary>
private int _hashCode;
// Maximum length of address literals (potentially including a port number)
// generated by any address-to-string conversion routine. This length can
// be used when declaring buffers used with getnameinfo, WSAAddressToString,
// inet_ntoa, etc. We just provide one define, rather than one per api,
// to avoid confusion.
//
// The totals are derived from the following data:
// 15: IPv4 address
// 45: IPv6 address including embedded IPv4 address
// 11: Scope Id
// 2: Brackets around IPv6 address when port is present
// 6: Port (including colon)
// 1: Terminating null byte
internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2;
private bool IsIPv4
{
get { return _numbers == null; }
}
private bool IsIPv6
{
get { return _numbers != null; }
}
private uint PrivateAddress
{
get
{
Debug.Assert(IsIPv4);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv4);
_addressOrScopeId = value;
}
}
private uint PrivateScopeId
{
get
{
Debug.Assert(IsIPv6);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv6);
_addressOrScopeId = value;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.IPAddress'/>
/// class with the specified address.
/// </para>
/// </devdoc>
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(newAddress));
}
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Constructor for an IPv6 Address with a specified Scope.
/// </para>
/// </devdoc>
public IPAddress(byte[] address, long scopeid)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Length != IPAddressParserStatics.IPv6AddressBytes)
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(scopeid));
}
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
PrivateScopeId = (uint)scopeid;
}
internal unsafe IPAddress(byte* address, int addressLength, long scopeid)
{
Debug.Assert(address != null);
Debug.Assert(addressLength == IPAddressParserStatics.IPv6AddressBytes);
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(scopeid));
}
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
PrivateScopeId = (uint)scopeid;
}
internal unsafe IPAddress(ushort* numbers, int numbersLength, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbersLength == NumberOfLabels);
var arr = new ushort[NumberOfLabels];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = numbers[i];
}
_numbers = arr;
PrivateScopeId = scopeid;
}
private IPAddress(ushort[] numbers, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbers.Length == NumberOfLabels);
_numbers = numbers;
PrivateScopeId = scopeid;
}
/// <devdoc>
/// <para>
/// Constructor for IPv4 and IPv6 Address.
/// </para>
/// </devdoc>
public IPAddress(byte[] address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Length != IPAddressParserStatics.IPv4AddressBytes && address.Length != IPAddressParserStatics.IPv6AddressBytes)
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
if (address.Length == IPAddressParserStatics.IPv4AddressBytes)
{
PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
}
else
{
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
}
}
internal unsafe IPAddress(byte* address, int addressLength)
{
Debug.Assert(address != null);
Debug.Assert(addressLength > 0);
Debug.Assert(
addressLength == IPAddressParserStatics.IPv4AddressBytes ||
addressLength == IPAddressParserStatics.IPv6AddressBytes);
if (addressLength == IPAddressParserStatics.IPv4AddressBytes)
{
PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
}
else
{
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
}
}
// We need this internally since we need to interface with winsock,
// and winsock only understands Int32.
internal IPAddress(int newAddress)
{
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance.
/// </para>
/// </devdoc>
public static bool TryParse(string ipString, out IPAddress address)
{
address = IPAddressParser.Parse(ipString, true);
return (address != null);
}
public static IPAddress Parse(string ipString)
{
return IPAddressParser.Parse(ipString, false);
}
/// <devdoc>
/// <para>
/// Provides a copy of the IPAddress internals as an array of bytes.
/// </para>
/// </devdoc>
public byte[] GetAddressBytes()
{
byte[] bytes;
if (IsIPv6)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
int j = 0;
for (int i = 0; i < NumberOfLabels; i++)
{
bytes[j++] = (byte)((_numbers[i] >> 8) & 0xFF);
bytes[j++] = (byte)((_numbers[i]) & 0xFF);
}
}
else
{
uint address = PrivateAddress;
bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
unchecked
{
bytes[0] = (byte)(address);
bytes[1] = (byte)(address >> 8);
bytes[2] = (byte)(address >> 16);
bytes[3] = (byte)(address >> 24);
}
}
return bytes;
}
public AddressFamily AddressFamily
{
get
{
return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
}
}
/// <devdoc>
/// <para>
/// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant
/// </para>
/// </devdoc>
public long ScopeId
{
get
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
return PrivateScopeId;
}
set
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (value < 0 || value > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
PrivateScopeId = (uint)value;
}
}
/// <devdoc>
/// <para>
/// Converts the Internet address to either standard dotted quad format
/// or standard IPv6 representation.
/// </para>
/// </devdoc>
public override string ToString()
{
if (_toString == null)
{
_toString = IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId);
}
return _toString;
}
public static long HostToNetworkOrder(long host)
{
#if BIGENDIAN
return host;
#else
return (((long)HostToNetworkOrder(unchecked((int)host)) & 0xFFFFFFFF) << 32)
| ((long)HostToNetworkOrder(unchecked((int)(host >> 32))) & 0xFFFFFFFF);
#endif
}
public static int HostToNetworkOrder(int host)
{
#if BIGENDIAN
return host;
#else
return (((int)HostToNetworkOrder(unchecked((short)host)) & 0xFFFF) << 16)
| ((int)HostToNetworkOrder(unchecked((short)(host >> 16))) & 0xFFFF);
#endif
}
public static short HostToNetworkOrder(short host)
{
#if BIGENDIAN
return host;
#else
return unchecked((short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)));
#endif
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
public static bool IsLoopback(IPAddress address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.IsIPv6)
{
// Do Equals test for IPv6 addresses
return address.Equals(IPv6Loopback);
}
else
{
return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask));
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Multicast address
/// </para>
/// </devdoc>
public bool IsIPv6Multicast
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Link Local address
/// </para>
/// </devdoc>
public bool IsIPv6LinkLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Site Local address
/// </para>
/// </devdoc>
public bool IsIPv6SiteLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0);
}
}
public bool IsIPv6Teredo
{
get
{
return IsIPv6 &&
(_numbers[0] == 0x2001) &&
(_numbers[1] == 0);
}
}
// 0:0:0:0:0:FFFF:x.x.x.x
public bool IsIPv4MappedToIPv6
{
get
{
if (IsIPv4)
{
return false;
}
for (int i = 0; i < 5; i++)
{
if (_numbers[i] != 0)
{
return false;
}
}
return (_numbers[5] == 0xFFFF);
}
}
[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")]
public long Address
{
get
{
//
// IPv6 Changes: Can't do this for IPv6, so throw an exception.
//
//
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
return PrivateAddress;
}
}
set
{
//
// IPv6 Changes: Can't do this for IPv6 addresses
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
if (PrivateAddress != value)
{
_toString = null;
PrivateAddress = unchecked((uint)value);
}
}
}
}
internal bool Equals(object comparandObj, bool compareScopeId)
{
IPAddress comparand = comparandObj as IPAddress;
if (comparand == null)
{
return false;
}
// Compare families before address representations
if (AddressFamily != comparand.AddressFamily)
{
return false;
}
if (IsIPv6)
{
// For IPv6 addresses, we must compare the full 128-bit representation.
for (int i = 0; i < NumberOfLabels; i++)
{
if (comparand._numbers[i] != _numbers[i])
{
return false;
}
}
// The scope IDs must also match
return comparand.PrivateScopeId == PrivateScopeId || !compareScopeId;
}
else
{
// For IPv4 addresses, compare the integer representation.
return comparand.PrivateAddress == PrivateAddress;
}
}
/// <devdoc>
/// <para>
/// Compares two IP addresses.
/// </para>
/// </devdoc>
public override bool Equals(object comparand)
{
return Equals(comparand, true);
}
public override int GetHashCode()
{
// For IPv6 addresses, we cannot simply return the integer
// representation as the hashcode. Instead, we calculate
// the hashcode from the string representation of the address.
if (IsIPv6)
{
if (_hashCode == 0)
{
_hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(ToString());
}
return _hashCode;
}
else
{
// For IPv4 addresses, we can simply use the integer representation.
return unchecked((int)PrivateAddress);
}
}
// For security, we need to be able to take an IPAddress and make a copy that's immutable and not derived.
internal IPAddress Snapshot()
{
return IsIPv4 ?
new IPAddress(PrivateAddress) :
new IPAddress(_numbers, PrivateScopeId);
}
// IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1
public IPAddress MapToIPv6()
{
if (IsIPv6)
{
return this;
}
uint address = PrivateAddress;
ushort[] labels = new ushort[NumberOfLabels];
labels[5] = 0xFFFF;
labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8));
labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8));
return new IPAddress(labels, 0);
}
// Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address.
// This does not restrict to address with the ::FFFF: prefix because other types of
// addresses display the tail segments as IPv4 like Terado.
public IPAddress MapToIPv4()
{
if (IsIPv4)
{
return this;
}
// Cast the ushort values to a uint and mask with unsigned literal before bit shifting.
// Otherwise, we can end up getting a negative value for any IPv4 address that ends with
// a byte higher than 127 due to sign extension of the most significant 1 bit.
long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
(((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16);
return new IPAddress(address);
}
}
}
| |
// 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 gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.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.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignSharedSetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignSharedSetRequestObject()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet response = client.GetCampaignSharedSet(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSharedSetRequestObjectAsync()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet responseCallSettings = await client.GetCampaignSharedSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSharedSet responseCancellationToken = await client.GetCampaignSharedSetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignSharedSet()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet response = client.GetCampaignSharedSet(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSharedSetAsync()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet responseCallSettings = await client.GetCampaignSharedSetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSharedSet responseCancellationToken = await client.GetCampaignSharedSetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignSharedSetResourceNames()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet response = client.GetCampaignSharedSet(request.ResourceNameAsCampaignSharedSetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignSharedSetResourceNamesAsync()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
GetCampaignSharedSetRequest request = new GetCampaignSharedSetRequest
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
};
gagvr::CampaignSharedSet expectedResponse = new gagvr::CampaignSharedSet
{
ResourceNameAsCampaignSharedSetName = gagvr::CampaignSharedSetName.FromCustomerCampaignSharedSet("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[SHARED_SET_ID]"),
Status = gagve::CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Enabled,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
SharedSetAsSharedSetName = gagvr::SharedSetName.FromCustomerSharedSet("[CUSTOMER_ID]", "[SHARED_SET_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignSharedSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignSharedSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignSharedSet responseCallSettings = await client.GetCampaignSharedSetAsync(request.ResourceNameAsCampaignSharedSetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignSharedSet responseCancellationToken = await client.GetCampaignSharedSetAsync(request.ResourceNameAsCampaignSharedSetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignSharedSetsRequestObject()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignSharedSetsRequest request = new MutateCampaignSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignSharedSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignSharedSetsResponse expectedResponse = new MutateCampaignSharedSetsResponse
{
Results =
{
new MutateCampaignSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignSharedSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignSharedSetsResponse response = client.MutateCampaignSharedSets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignSharedSetsRequestObjectAsync()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignSharedSetsRequest request = new MutateCampaignSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignSharedSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignSharedSetsResponse expectedResponse = new MutateCampaignSharedSetsResponse
{
Results =
{
new MutateCampaignSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignSharedSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignSharedSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignSharedSetsResponse responseCallSettings = await client.MutateCampaignSharedSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignSharedSetsResponse responseCancellationToken = await client.MutateCampaignSharedSetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignSharedSets()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignSharedSetsRequest request = new MutateCampaignSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignSharedSetOperation(),
},
};
MutateCampaignSharedSetsResponse expectedResponse = new MutateCampaignSharedSetsResponse
{
Results =
{
new MutateCampaignSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignSharedSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignSharedSetsResponse response = client.MutateCampaignSharedSets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignSharedSetsAsync()
{
moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient> mockGrpcClient = new moq::Mock<CampaignSharedSetService.CampaignSharedSetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignSharedSetsRequest request = new MutateCampaignSharedSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignSharedSetOperation(),
},
};
MutateCampaignSharedSetsResponse expectedResponse = new MutateCampaignSharedSetsResponse
{
Results =
{
new MutateCampaignSharedSetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignSharedSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignSharedSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignSharedSetServiceClient client = new CampaignSharedSetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignSharedSetsResponse responseCallSettings = await client.MutateCampaignSharedSetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignSharedSetsResponse responseCancellationToken = await client.MutateCampaignSharedSetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
public class XsdTest
{
static readonly char SEP = Path.DirectorySeparatorChar;
static ValidationEventHandler noValidateHandler =
new ValidationEventHandler (NoValidate);
bool version2;
bool verbose;
bool stopOnError;
bool noResolver;
bool reportAsXml;
bool reportDetails;
bool reportSuccess;
bool testAll;
bool noValidate;
string specificTarget;
TextWriter ReportWriter = Console.Out;
XmlTextWriter XmlReport;
public static void Main (string [] args)
{
new XsdTest ().Run (args);
}
void Usage ()
{
Console.WriteLine (@"
USAGE: mono xsdtest.exe options target-pattern
options:
--stoponerr: stops at unexpected error.
--noresolve: don't resolve external resources.
--novalidate: don't validate and continue reading.
{0}
--verbose: includes processing status.
--xml: report as XML format.
--details: report stack trace for errors.
--reportsuccess: report successful test as well.
--testall: process NISTTest/SunTest as well as MSXsdTest.
target-pattern: Part of the target schema file name.
(No Regex support.)
",
" --v2 use XmlReader.Create() [2.0 only]"
);
return;
}
void Run (string [] args)
{
foreach (string s in args) {
switch (s) {
case "--help":
Usage ();
return;
case "--v2":
version2 = true; break;
case "--verbose":
verbose = true; break;
case "--stoponerr":
stopOnError = true; break;
case "--noresolve":
noResolver = true; break;
case "--novalidate":
noValidate = true; break;
case "--xml":
reportAsXml = true; break;
case "--details":
reportDetails = true; break;
case "--reportsuccess":
reportSuccess = true; break;
case "--testall":
testAll = true; break;
default:
if (s.StartsWith ("--report:"))
ReportWriter = new StreamWriter (
s.Substring (9));
else
specificTarget = s;
break;
}
}
RunTest ("msxsdtest");
if (testAll) {
RunTest ("suntest");
RunTest ("nisttest");
}
ReportWriter.Close ();
}
static void NoValidate (object o, ValidationEventArgs e)
{
}
void RunTest (string subdir)
{
string basePath = @"xsd-test-suite" + SEP;
XmlDocument doc = new XmlDocument ();
if (noResolver)
doc.XmlResolver = null;
doc.Load (basePath + subdir + SEP + "tests-all.xml");
if (reportAsXml) {
XmlReport = new XmlTextWriter (ReportWriter);
XmlReport.Formatting = Formatting.Indented;
XmlReport.WriteStartElement ("test-results");
}
Console.WriteLine ("Started: " + DateTime.Now);
foreach (XmlElement test in doc.SelectNodes ("/tests/test")) {
// Test schema
string schemaFile = test.SelectSingleNode ("@schema").InnerText;
if (specificTarget != null &&
schemaFile.IndexOf (specificTarget) < 0)
continue;
if (schemaFile.Length > 2)
schemaFile = schemaFile.Substring (2);
if (verbose)
Report (schemaFile, true, "compiling", "");
bool isValidSchema = test.SelectSingleNode ("@out_s").InnerText == "1";
XmlSchema schema = null;
XmlTextReader sxr = null;
try {
sxr = new XmlTextReader (basePath + schemaFile);
if (noResolver)
sxr.XmlResolver = null;
schema = XmlSchema.Read (sxr, null);
schema.Compile (noValidate ? noValidateHandler : null, noResolver ? null : new XmlUrlResolver ());
if (!isValidSchema && !noValidate) {
Report (schemaFile, true, "should fail", "");
continue;
}
if (reportSuccess)
Report (schemaFile, true, "OK", "");
} catch (XmlSchemaException ex) {
if (isValidSchema)
Report (schemaFile, true, "should succeed",
reportDetails ?
ex.ToString () : ex.Message);
else if (reportSuccess)
Report (schemaFile, true, "OK", "");
continue;
} catch (Exception ex) {
if (stopOnError)
throw;
Report (schemaFile, true, "unexpected",
reportDetails ?
ex.ToString () : ex.Message);
continue;
} finally {
if (sxr != null)
sxr.Close ();
}
// Test instances
string instanceFile = test.SelectSingleNode ("@instance").InnerText;
if (instanceFile.Length == 0)
continue;
else if (instanceFile.StartsWith ("./"))
instanceFile = instanceFile.Substring (2);
if (verbose)
Report (instanceFile, false, "reading ", "");
bool isValidInstance = test.SelectSingleNode ("@out_x").InnerText == "1";
XmlReader xvr = null;
try {
XmlTextReader ixtr = new XmlTextReader (
Path.Combine (basePath, instanceFile));
xvr = ixtr;
#if NET_2_0
if (version2) {
XmlReaderSettings settings =
new XmlReaderSettings ();
settings.ValidationType = ValidationType.Schema;
if (noValidate)
settings.ValidationEventHandler +=
noValidateHandler;
if (noResolver)
settings.Schemas.XmlResolver = null;
settings.Schemas.Add (schema);
if (noResolver)
settings.XmlResolver = null;
xvr = XmlReader.Create (ixtr, settings);
} else {
#endif
XmlValidatingReader vr = new XmlValidatingReader (ixtr);
if (noResolver)
vr.XmlResolver = null;
if (noValidate)
vr.ValidationEventHandler += noValidateHandler;
vr.Schemas.Add (schema);
xvr = vr;
#if NET_2_0
}
#endif
while (!xvr.EOF)
xvr.Read ();
if (!isValidInstance && !noValidate)
Report (instanceFile, false, "should fail", "");
else if (reportSuccess)
Report (instanceFile, false, "OK", "");
} catch (XmlSchemaException ex) {
if (isValidInstance)
Report (instanceFile, false, "should succeed",
reportDetails ?
ex.ToString () : ex.Message);
else if (reportSuccess)
Report (instanceFile, false, "OK", "");
} catch (Exception ex) {
if (stopOnError)
throw;
Report (instanceFile, false, "unexpected",
reportDetails ?
ex.ToString () : ex.Message);
} finally {
if (xvr != null)
xvr.Close ();
}
}
if (reportAsXml) {
XmlReport.WriteEndElement ();
XmlReport.Flush ();
}
Console.WriteLine ("Finished: " + DateTime.Now);
}
void Report (string id, bool compile, string category, string s)
{
string phase = compile ? "compile" : "read";
if (reportAsXml) {
XmlReport.WriteStartElement ("testresult");
XmlReport.WriteAttributeString ("id", id);
XmlReport.WriteAttributeString ("phase", phase);
XmlReport.WriteAttributeString ("category", category);
XmlReport.WriteString (s);
XmlReport.WriteEndElement ();
}
else
ReportWriter.WriteLine ("{0}/{1} : {2} {3}",
phase, category, id, s);
}
}
| |
//-----------------------------------------------------------------------------
// CurveControlCommands.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace Xna.Tools
{
/// <summary>
/// Command that saves old and new EditCurveKey selection.
/// </summary>
public class SelectCommand : ICommand
{
public SelectCommand(EditCurve curve, EditCurveKeySelection newSelection,
EditCurveKeySelection oldSelection)
{
this.curve = curve;
this.oldSelection = oldSelection;
this.newSelection = newSelection;
}
#region ICommand Members
public void Execute()
{
curve.ApplySelection(newSelection, false);
}
public void Unexecute()
{
curve.ApplySelection(oldSelection, false);
}
#endregion
EditCurve curve;
EditCurveKeySelection oldSelection;
EditCurveKeySelection newSelection;
}
/// <summary>
/// Command that saves add or remove EditCurveKey information.
/// </summary>
public class EditCurveKeyAddRemoveCommand : ICommand
{
public EditCurveKeyAddRemoveCommand(EditCurve curve,
ICollection<EditCurveKey> deleteKeys)
{
this.curve = curve;
addKey = false;
keys = new List<EditCurveKey>(deleteKeys.Count);
foreach ( EditCurveKey key in deleteKeys )
keys.Add(key.Clone());
}
public EditCurveKeyAddRemoveCommand(EditCurve curve, EditCurveKey addKey,
EditCurveKeySelection selection)
{
this.curve = curve;
this.addKey = true;
this.selection = selection.Clone();
keys = new List<EditCurveKey>();
keys.Add(addKey.Clone());
}
#region ICommand Members
public void Execute()
{
if (addKey)
AddKeys();
else
RemoveKeys();
}
public void Unexecute()
{
if (addKey)
RemoveKeys();
else
AddKeys();
}
#endregion
#region Private Methods
private void AddKeys()
{
foreach (EditCurveKey savedKey in keys)
{
EditCurveKey addingKey = savedKey.Clone();
curve.Keys.Add(addingKey);
// Removing key requires re-compute neighbor keys tangents.
curve.ComputeTangents(curve.Keys.IndexOf(addingKey));
}
curve.ApplySelection(new EditCurveKeySelection(keys), false);
}
private void RemoveKeys()
{
foreach (EditCurveKey savedKey in keys)
{
long keyId = savedKey.Id;
EditCurveKey key;
curve.Keys.TryGetValue(keyId, out key);
// Remember key index.
int idx = curve.Keys.IndexOf(key);
// Remove key from keys.
curve.Keys.Remove(key);
// Removing key requires re-compute neighbor keys tangents.
curve.ComputeTangents(idx);
}
if ( selection != null )
curve.ApplySelection(selection, false);
}
#endregion
EditCurve curve;
EditCurveKeySelection selection;
List<EditCurveKey> keys;
bool addKey;
}
/// <summary>
/// Command that saves multiple EditCurveKey values.
/// </summary>
public class EditCurveKeyUpdateCommand : ICommand
{
public EditCurveKeyUpdateCommand(EditCurve curve,
ICollection<EditCurveKey> oldKeyValues,
ICollection<EditCurveKey> newKeyValues)
{
this.curve = curve;
this.oldKeyValues = oldKeyValues;
this.newKeyValues = newKeyValues;
}
#region ICommand Members
public void Execute()
{
curve.ApplyKeyValues(newKeyValues);
}
public void Unexecute()
{
curve.ApplyKeyValues(oldKeyValues);
}
#endregion
EditCurve curve;
ICollection<EditCurveKey> oldKeyValues;
ICollection<EditCurveKey> newKeyValues;
}
/// <summary>
/// Command that saves EditCurveState.
/// </summary>
public class EditCurveStateChangeCommand : ICommand
{
public EditCurveStateChangeCommand(EditCurve curve, EditCurveState oldState,
EditCurveState newState)
{
if (oldState == null) throw new ArgumentNullException("oldState");
if (newState == null) throw new ArgumentNullException("newState");
this.curve = curve;
this.oldState = (EditCurveState)oldState.Clone();
this.newState = (EditCurveState)newState.Clone();
}
#region ICommand Members
public void Execute()
{
curve.ApplyState(newState);
}
public void Unexecute()
{
curve.ApplyState(oldState);
}
#endregion
EditCurve curve;
EditCurveState newState;
EditCurveState oldState;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
/**
* <summary>Collection of predefined handlers for various system types.</summary>
*/
internal static class BinarySystemHandlers
{
/** Write handlers. */
private static readonly CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler> WriteHandlers =
new CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler>();
/** Read handlers. */
private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255];
/// <summary>
/// Initializes the <see cref="BinarySystemHandlers"/> class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability.")]
static BinarySystemHandlers()
{
// 1. Primitives.
ReadHandlers[BinaryTypeId.Bool] = new BinarySystemReader<bool>(s => s.ReadBool());
ReadHandlers[BinaryTypeId.Byte] = new BinarySystemReader<byte>(s => s.ReadByte());
ReadHandlers[BinaryTypeId.Short] = new BinarySystemReader<short>(s => s.ReadShort());
ReadHandlers[BinaryTypeId.Char] = new BinarySystemReader<char>(s => s.ReadChar());
ReadHandlers[BinaryTypeId.Int] = new BinarySystemReader<int>(s => s.ReadInt());
ReadHandlers[BinaryTypeId.Long] = new BinarySystemReader<long>(s => s.ReadLong());
ReadHandlers[BinaryTypeId.Float] = new BinarySystemReader<float>(s => s.ReadFloat());
ReadHandlers[BinaryTypeId.Double] = new BinarySystemReader<double>(s => s.ReadDouble());
ReadHandlers[BinaryTypeId.Decimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal);
// 2. Date.
ReadHandlers[BinaryTypeId.Timestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp);
// 3. String.
ReadHandlers[BinaryTypeId.String] = new BinarySystemReader<string>(BinaryUtils.ReadString);
// 4. Guid.
ReadHandlers[BinaryTypeId.Guid] = new BinarySystemReader<Guid?>(s => BinaryUtils.ReadGuid(s));
// 5. Primitive arrays.
ReadHandlers[BinaryTypeId.ArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray);
ReadHandlers[BinaryTypeId.ArrayByte] =
new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray);
ReadHandlers[BinaryTypeId.ArrayShort] =
new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray,
BinaryUtils.ReadUshortArray);
ReadHandlers[BinaryTypeId.ArrayChar] =
new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray);
ReadHandlers[BinaryTypeId.ArrayInt] =
new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray);
ReadHandlers[BinaryTypeId.ArrayLong] =
new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray,
BinaryUtils.ReadUlongArray);
ReadHandlers[BinaryTypeId.ArrayFloat] =
new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray);
ReadHandlers[BinaryTypeId.ArrayDouble] =
new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray);
ReadHandlers[BinaryTypeId.ArrayDecimal] =
new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray);
// 6. Date array.
ReadHandlers[BinaryTypeId.ArrayTimestamp] =
new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray);
// 7. String array.
ReadHandlers[BinaryTypeId.ArrayString] = new BinarySystemTypedArrayReader<string>();
// 8. Guid array.
ReadHandlers[BinaryTypeId.ArrayGuid] = new BinarySystemTypedArrayReader<Guid?>();
// 9. Array.
ReadHandlers[BinaryTypeId.Array] = new BinarySystemReader(ReadArray);
// 11. Arbitrary collection.
ReadHandlers[BinaryTypeId.Collection] = new BinarySystemReader(ReadCollection);
// 13. Arbitrary dictionary.
ReadHandlers[BinaryTypeId.Dictionary] = new BinarySystemReader(ReadDictionary);
// 14. Enum. Should be read as Array, see WriteEnumArray implementation.
ReadHandlers[BinaryTypeId.ArrayEnum] = new BinarySystemReader(ReadArray);
}
/// <summary>
/// Try getting write handler for type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IBinarySystemWriteHandler GetWriteHandler(Type type)
{
return WriteHandlers.GetOrAdd(type, t =>
{
return FindWriteHandler(t);
});
}
/// <summary>
/// Find write handler for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>
/// Write handler or NULL.
/// </returns>
private static IBinarySystemWriteHandler FindWriteHandler(Type type)
{
// 1. Well-known types.
if (type == typeof(string))
return new BinarySystemWriteHandler<string>(WriteString, false);
if (type == typeof(decimal))
return new BinarySystemWriteHandler<decimal>(WriteDecimal, false);
if (type == typeof(Guid))
return new BinarySystemWriteHandler<Guid>(WriteGuid, false);
if (type == typeof (BinaryObject))
return new BinarySystemWriteHandler<BinaryObject>(WriteBinary, false);
if (type == typeof (BinaryEnum))
return new BinarySystemWriteHandler<BinaryEnum>(WriteBinaryEnum, false);
if (type.IsEnum)
{
var underlyingType = Enum.GetUnderlyingType(type);
if (underlyingType == typeof(int))
return new BinarySystemWriteHandler<int>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(uint))
return new BinarySystemWriteHandler<uint>((w, i) => w.WriteEnum(unchecked((int) i), type), false);
if (underlyingType == typeof(byte))
return new BinarySystemWriteHandler<byte>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(sbyte))
return new BinarySystemWriteHandler<sbyte>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(short))
return new BinarySystemWriteHandler<short>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(ushort))
return new BinarySystemWriteHandler<ushort>((w, i) => w.WriteEnum(i, type), false);
return null; // Other enums, such as long and ulong, can't be expressed as int.
}
if (type == typeof(Ignite))
return new BinarySystemWriteHandler<object>(WriteIgnite, false);
// All types below can be written as handles.
if (type == typeof (ArrayList))
return new BinarySystemWriteHandler<ICollection>(WriteArrayList, true);
if (type == typeof (Hashtable))
return new BinarySystemWriteHandler<IDictionary>(WriteHashtable, true);
if (type.IsArray)
{
if (type.GetArrayRank() > 1)
{
// int[,]-style arrays are wrapped, see comments in holder.
return new BinarySystemWriteHandler<Array>(
(w, o) => w.WriteObject(new MultidimensionalArrayHolder(o)), true);
}
// We know how to write any array type.
Type elemType = type.GetElementType();
// Primitives.
if (elemType == typeof (bool))
return new BinarySystemWriteHandler<bool[]>(WriteBoolArray, true);
if (elemType == typeof(byte))
return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true);
if (elemType == typeof(short))
return new BinarySystemWriteHandler<short[]>(WriteShortArray, true);
if (elemType == typeof(char))
return new BinarySystemWriteHandler<char[]>(WriteCharArray, true);
if (elemType == typeof(int))
return new BinarySystemWriteHandler<int[]>(WriteIntArray, true);
if (elemType == typeof(long))
return new BinarySystemWriteHandler<long[]>(WriteLongArray, true);
if (elemType == typeof(float))
return new BinarySystemWriteHandler<float[]>(WriteFloatArray, true);
if (elemType == typeof(double))
return new BinarySystemWriteHandler<double[]>(WriteDoubleArray, true);
// Non-CLS primitives.
if (elemType == typeof(sbyte))
return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true);
if (elemType == typeof(ushort))
return new BinarySystemWriteHandler<short[]>(WriteShortArray, true);
if (elemType == typeof(uint))
return new BinarySystemWriteHandler<int[]>(WriteIntArray, true);
if (elemType == typeof(ulong))
return new BinarySystemWriteHandler<long[]>(WriteLongArray, true);
// Special types.
if (elemType == typeof (decimal?))
return new BinarySystemWriteHandler<decimal?[]>(WriteDecimalArray, true);
if (elemType == typeof(string))
return new BinarySystemWriteHandler<string[]>(WriteStringArray, true);
if (elemType == typeof(Guid?))
return new BinarySystemWriteHandler<Guid?[]>(WriteGuidArray, true);
// Enums.
if (BinaryUtils.IsIgniteEnum(elemType) || elemType == typeof(BinaryEnum))
return new BinarySystemWriteHandler<object>(WriteEnumArray, true);
// Object array.
return new BinarySystemWriteHandler<object>(WriteArray, true);
}
return null;
}
/// <summary>
/// Reads an object of predefined type.
/// </summary>
public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res)
{
var handler = ReadHandlers[typeId];
if (handler == null)
{
res = default(T);
return false;
}
res = handler.Read<T>(ctx);
return true;
}
/// <summary>
/// Write decimal.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDecimal(BinaryWriter ctx, decimal obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Decimal);
BinaryUtils.WriteDecimal(obj, ctx.Stream);
}
/// <summary>
/// Write string.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Object.</param>
private static void WriteString(BinaryWriter ctx, string obj)
{
ctx.Stream.WriteByte(BinaryTypeId.String);
BinaryUtils.WriteString(obj, ctx.Stream);
}
/// <summary>
/// Write Guid.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteGuid(BinaryWriter ctx, Guid obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Guid);
BinaryUtils.WriteGuid(obj, ctx.Stream);
}
/// <summary>
/// Write boolaen array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteBoolArray(BinaryWriter ctx, bool[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayBool);
BinaryUtils.WriteBooleanArray(obj, ctx.Stream);
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteByteArray(BinaryWriter ctx, byte[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayByte);
BinaryUtils.WriteByteArray(obj, ctx.Stream);
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteShortArray(BinaryWriter ctx, short[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayShort);
BinaryUtils.WriteShortArray(obj, ctx.Stream);
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteCharArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayChar);
BinaryUtils.WriteCharArray((char[])obj, ctx.Stream);
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteIntArray(BinaryWriter ctx, int[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayInt);
BinaryUtils.WriteIntArray(obj, ctx.Stream);
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteLongArray(BinaryWriter ctx, long[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayLong);
BinaryUtils.WriteLongArray(obj, ctx.Stream);
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteFloatArray(BinaryWriter ctx, float[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayFloat);
BinaryUtils.WriteFloatArray(obj, ctx.Stream);
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDoubleArray(BinaryWriter ctx, double[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayDouble);
BinaryUtils.WriteDoubleArray(obj, ctx.Stream);
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDecimalArray(BinaryWriter ctx, decimal?[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayDecimal);
BinaryUtils.WriteDecimalArray(obj, ctx.Stream);
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteStringArray(BinaryWriter ctx, string[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayString);
BinaryUtils.WriteStringArray(obj, ctx.Stream);
}
/// <summary>
/// Write nullable GUID array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteGuidArray(BinaryWriter ctx, Guid?[] obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayGuid);
BinaryUtils.WriteGuidArray(obj, ctx.Stream);
}
/// <summary>
/// Writes the enum array.
/// </summary>
private static void WriteEnumArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryTypeId.ArrayEnum);
BinaryUtils.WriteArray((Array) obj, ctx);
}
/// <summary>
/// Writes the array.
/// </summary>
private static void WriteArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Array);
BinaryUtils.WriteArray((Array) obj, ctx);
}
/**
* <summary>Write ArrayList.</summary>
*/
private static void WriteArrayList(BinaryWriter ctx, ICollection obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Collection);
BinaryUtils.WriteCollection(obj, ctx, BinaryUtils.CollectionArrayList);
}
/**
* <summary>Write Hashtable.</summary>
*/
private static void WriteHashtable(BinaryWriter ctx, IDictionary obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Dictionary);
BinaryUtils.WriteDictionary(obj, ctx, BinaryUtils.MapHashMap);
}
/**
* <summary>Write binary object.</summary>
*/
private static void WriteBinary(BinaryWriter ctx, BinaryObject obj)
{
ctx.Stream.WriteByte(BinaryTypeId.Binary);
BinaryUtils.WriteBinary(ctx.Stream, obj);
}
/// <summary>
/// Write enum.
/// </summary>
private static void WriteBinaryEnum(BinaryWriter ctx, BinaryEnum obj)
{
var binEnum = obj;
ctx.Stream.WriteByte(BinaryTypeId.BinaryEnum);
ctx.WriteInt(binEnum.TypeId);
ctx.WriteInt(binEnum.EnumValue);
}
/// <summary>
/// Reads the array.
/// </summary>
private static object ReadArray(BinaryReader ctx, Type type)
{
var elemType = type.GetElementType();
if (elemType == null)
{
if (ctx.Mode == BinaryMode.ForceBinary)
{
// Forced binary mode: use object because primitives are not represented as IBinaryObject.
elemType = typeof(object);
}
else
{
// Infer element type from typeId.
var typeId = ctx.ReadInt();
elemType = BinaryUtils.GetArrayElementType(typeId, ctx.Marshaller);
return BinaryUtils.ReadTypedArray(ctx, false, elemType ?? typeof(object));
}
}
// Element type is known, no need to check typeId.
// In case of incompatible types we'll get exception either way.
return BinaryUtils.ReadTypedArray(ctx, true, elemType);
}
/**
* <summary>Read collection.</summary>
*/
private static object ReadCollection(BinaryReader ctx, Type type)
{
return BinaryUtils.ReadCollection(ctx, null, null);
}
/**
* <summary>Read dictionary.</summary>
*/
private static object ReadDictionary(BinaryReader ctx, Type type)
{
return BinaryUtils.ReadDictionary(ctx, null);
}
/// <summary>
/// Write Ignite.
/// </summary>
private static void WriteIgnite(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryUtils.HdrNull);
}
/**
* <summary>Read delegate.</summary>
* <param name="ctx">Read context.</param>
* <param name="type">Type.</param>
*/
private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type);
/// <summary>
/// System type reader.
/// </summary>
private interface IBinarySystemReader
{
/// <summary>
/// Reads a value of specified type from reader.
/// </summary>
T Read<T>(BinaryReader ctx);
}
/// <summary>
/// System type generic reader.
/// </summary>
private interface IBinarySystemReader<out T>
{
/// <summary>
/// Reads a value of specified type from reader.
/// </summary>
T Read(BinaryReader ctx);
}
/// <summary>
/// Default reader with boxing.
/// </summary>
private class BinarySystemReader : IBinarySystemReader
{
/** */
private readonly BinarySystemReadDelegate _readDelegate;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemReader"/> class.
/// </summary>
/// <param name="readDelegate">The read delegate.</param>
public BinarySystemReader(BinarySystemReadDelegate readDelegate)
{
Debug.Assert(readDelegate != null);
_readDelegate = readDelegate;
}
/** <inheritdoc /> */
public T Read<T>(BinaryReader ctx)
{
return (T)_readDelegate(ctx, typeof(T));
}
}
/// <summary>
/// Reader without boxing.
/// </summary>
private class BinarySystemReader<T> : IBinarySystemReader
{
/** */
private readonly Func<IBinaryStream, T> _readDelegate;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class.
/// </summary>
/// <param name="readDelegate">The read delegate.</param>
public BinarySystemReader(Func<IBinaryStream, T> readDelegate)
{
Debug.Assert(readDelegate != null);
_readDelegate = readDelegate;
}
/** <inheritdoc /> */
public TResult Read<TResult>(BinaryReader ctx)
{
return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream));
}
}
/// <summary>
/// Reader without boxing.
/// </summary>
private class BinarySystemTypedArrayReader<T> : IBinarySystemReader
{
public TResult Read<TResult>(BinaryReader ctx)
{
return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false));
}
}
/// <summary>
/// Reader with selection based on requested type.
/// </summary>
private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2>
{
/** */
private readonly Func<IBinaryStream, T1> _readDelegate1;
/** */
private readonly Func<IBinaryStream, T2> _readDelegate2;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class.
/// </summary>
/// <param name="readDelegate1">The read delegate1.</param>
/// <param name="readDelegate2">The read delegate2.</param>
public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2)
{
Debug.Assert(readDelegate1 != null);
Debug.Assert(readDelegate2 != null);
_readDelegate1 = readDelegate1;
_readDelegate2 = readDelegate2;
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
T2 IBinarySystemReader<T2>.Read(BinaryReader ctx)
{
return _readDelegate2(ctx.Stream);
}
/** <inheritdoc /> */
public T Read<T>(BinaryReader ctx)
{
// Can't use "as" because of variance.
// For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which
// will cause incorrect behavior.
if (typeof (T) == typeof (T2))
return ((IBinarySystemReader<T>) this).Read(ctx);
return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream));
}
}
}
/// <summary>
/// Write delegate + handles flag.
/// </summary>
internal interface IBinarySystemWriteHandler
{
/// <summary>
/// Gets a value indicating whether this handler supports handles.
/// </summary>
bool SupportsHandles { get; }
/// <summary>
/// Writes object to a specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="obj">The object.</param>
void Write<T>(BinaryWriter writer, T obj);
}
/// <summary>
/// Write delegate + handles flag.
/// </summary>
internal class BinarySystemWriteHandler<T1> : IBinarySystemWriteHandler
{
/** */
private readonly Action<BinaryWriter, T1> _writeAction;
/** */
private readonly bool _supportsHandles;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemWriteHandler{T1}" /> class.
/// </summary>
/// <param name="writeAction">The write action.</param>
/// <param name="supportsHandles">Handles flag.</param>
public BinarySystemWriteHandler(Action<BinaryWriter, T1> writeAction, bool supportsHandles)
{
Debug.Assert(writeAction != null);
_writeAction = writeAction;
_supportsHandles = supportsHandles;
}
/** <inheritdoc /> */
public void Write<T>(BinaryWriter writer, T obj)
{
_writeAction(writer, TypeCaster<T1>.Cast(obj));
}
/** <inheritdoc /> */
public bool SupportsHandles
{
get { return _supportsHandles; }
}
}
}
| |
namespace EIDSS.Reports.Document.Lim.Transfer
{
partial class TransferReport
{
#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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TransferReport));
this.DetailReportTransfer = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailTransfer = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.m_Adapter = new EIDSS.Reports.Document.Lim.Transfer.TransferDataSetTableAdapters.TransferAdapter();
this.m_TransferDataSet = new EIDSS.Reports.Document.Lim.Transfer.TransferDataSet();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_TransferDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReportTransfer
//
this.DetailReportTransfer.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailTransfer});
this.DetailReportTransfer.DataAdapter = this.m_Adapter;
this.DetailReportTransfer.DataMember = "Transfer";
this.DetailReportTransfer.DataSource = this.m_TransferDataSet;
resources.ApplyResources(this.DetailReportTransfer, "DetailReportTransfer");
this.DetailReportTransfer.Level = 0;
this.DetailReportTransfer.Name = "DetailReportTransfer";
this.DetailReportTransfer.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
//
// DetailTransfer
//
this.DetailTransfer.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DetailTransfer.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4});
resources.ApplyResources(this.DetailTransfer, "DetailTransfer");
this.DetailTransfer.Name = "DetailTransfer";
this.DetailTransfer.StylePriority.UseBorders = false;
this.DetailTransfer.StylePriority.UseTextAlignment = false;
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow11});
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell33,
this.xrTableCell32,
this.xrTableCell20,
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell31});
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
this.xrTableRow11.Name = "xrTableRow11";
//
// xrTableCell16
//
this.xrTableCell16.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable5});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
//
// xrTable5
//
this.xrTable5.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow12,
this.xrTableRow13});
this.xrTable5.StylePriority.UseBorders = false;
this.xrTable5.StylePriority.UsePadding = false;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23});
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
this.xrTableRow12.Name = "xrTableRow12";
//
// xrTableCell23
//
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.SourceLabID", "*{0}*")});
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell21});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
//
// xrTableCell21
//
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.SourceLabID")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.SampleType")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.DateSampleReceived", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
//
// xrTableCell33
//
this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.ReceivedBy")});
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Name = "xrTableCell33";
//
// xrTableCell32
//
this.xrTableCell32.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.LabSampleID")});
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.Condition")});
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
//
// xrTableCell34
//
this.xrTableCell34.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.StorageLocation")});
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
//
// xrTableCell35
//
this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.Comment")});
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
this.xrTableCell35.Name = "xrTableCell35";
//
// xrTableCell31
//
this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.FunctionalArea")});
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_TransferDataSet
//
this.m_TransferDataSet.DataSetName = "TransferDataSet";
this.m_TransferDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow4,
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow5,
this.xrTableRow6});
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell22,
this.xrTableCell17});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.Name = "xrTableRow4";
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.TransferOutBarcode", "*{0}*")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.TransferOutBarcode")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell1});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
//
// xrTableCell1
//
this.xrTableCell1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.PurposeOfTransfer")});
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseBorders = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.xrTableCell4});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
//
// xrTableCell4
//
this.xrTableCell4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.TransferredFrom")});
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
//
// xrTableCell6
//
this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.SentBy")});
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell10});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
//
// xrTableCell10
//
this.xrTableCell10.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.SampleTrasnferredTo")});
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseBorders = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell24,
this.xrTableCell25});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
//
// xrTableCell25
//
this.xrTableCell25.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_TransferDataSet, "Transfer.DateSent", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseBorders = false;
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
//
// xrTableCell8
//
this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Transfer.DateSent", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10});
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell15,
this.xrTableCell26,
this.xrTableCell27,
this.xrTableCell29,
this.xrTableCell13,
this.xrTableCell30,
this.xrTableCell28});
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
this.xrTableRow10.Name = "xrTableRow10";
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
//
// xrTableCell15
//
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
//
// xrTableCell29
//
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Name = "xrTableCell29";
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
//
// xrTableCell28
//
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Name = "xrTableCell28";
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.DataAdapter = this.m_Adapter;
this.DetailReport.DataMember = "Transfer";
this.DetailReport.DataSource = this.m_TransferDataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 1;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// TransferReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReportTransfer,
this.DetailReport});
resources.ApplyResources(this, "$this");
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.Version = "14.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.DetailReportTransfer, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_TransferDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportTransfer;
private DevExpress.XtraReports.UI.DetailBand DetailTransfer;
private TransferDataSetTableAdapters.TransferAdapter m_Adapter;
private TransferDataSet m_TransferDataSet;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTable xrTable5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using sly.buildresult;
using sly.lexer;
using sly.lexer.fsm;
using sly.parser.generator.visitor;
using sly.parser.llparser;
using sly.parser.syntax.grammar;
namespace sly.parser.generator
{
public delegate BuildResult<Parser<IN, OUT>> ParserChecker<IN, OUT>(BuildResult<Parser<IN, OUT>> result,
NonTerminal<IN> nonterminal) where IN : struct;
/// <summary>
/// this class provides API to build parser
/// </summary>
public class ParserBuilder<IN, OUT> where IN : struct
{
#region API
/// <summary>
/// Builds a parser (lexer, syntax parser and syntax tree visitor) according to a parser definition instance
/// </summary>
/// <typeparam name="IN"></typeparam>
/// <param name="parserInstance">
/// a parser definition instance , containing
/// [Reduction] methods for grammar rules
/// <param name="parserType">
/// a ParserType enum value stating the analyser type (LR, LL ...) for now only LL recurive
/// descent parser available
/// </param>
/// <param name="rootRule">the name of the root non terminal of the grammar</param>
/// <returns></returns>
public virtual BuildResult<Parser<IN, OUT>> BuildParser(object parserInstance, ParserType parserType,
string rootRule, BuildExtension<IN> extensionBuilder = null)
{
Parser<IN, OUT> parser = null;
var result = new BuildResult<Parser<IN, OUT>>();
if (parserType == ParserType.LL_RECURSIVE_DESCENT)
{
var configuration = ExtractParserConfiguration(parserInstance.GetType());
configuration.StartingRule = rootRule;
var syntaxParser = BuildSyntaxParser(configuration, parserType, rootRule);
var visitor = new SyntaxTreeVisitor<IN, OUT>(configuration, parserInstance);
parser = new Parser<IN, OUT>(syntaxParser, visitor);
var lexerResult = BuildLexer(extensionBuilder);
parser.Lexer = lexerResult.Result;
if (lexerResult.IsError) result.AddErrors(lexerResult.Errors);
parser.Instance = parserInstance;
parser.Configuration = configuration;
result.Result = parser;
}
else if (parserType == ParserType.EBNF_LL_RECURSIVE_DESCENT)
{
var builder = new EBNFParserBuilder<IN, OUT>();
result = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, rootRule);
}
parser = result.Result;
if (!result.IsError)
{
var expressionResult = parser.BuildExpressionParser(result, rootRule);
if (expressionResult.IsError) result.AddErrors(expressionResult.Errors);
result.Result.Configuration = expressionResult.Result;
result = CheckParser(result);
}
return result;
}
protected virtual ISyntaxParser<IN, OUT> BuildSyntaxParser(ParserConfiguration<IN, OUT> conf,
ParserType parserType, string rootRule)
{
ISyntaxParser<IN, OUT> parser = null;
switch (parserType)
{
case ParserType.LL_RECURSIVE_DESCENT:
{
parser = new RecursiveDescentSyntaxParser<IN, OUT>(conf, rootRule);
break;
}
default:
{
parser = null;
break;
}
}
return parser;
}
#endregion
#region CONFIGURATION
private Tuple<string, string> ExtractNTAndRule(string ruleString)
{
Tuple<string, string> result = null;
if (ruleString != null)
{
var nt = "";
var rule = "";
var i = ruleString.IndexOf(":");
if (i > 0)
{
nt = ruleString.Substring(0, i).Trim();
rule = ruleString.Substring(i + 1);
result = new Tuple<string, string>(nt, rule);
}
}
return result;
}
protected virtual BuildResult<ILexer<IN>> BuildLexer(BuildExtension<IN> extensionBuilder = null)
{
var lexer = LexerBuilder.BuildLexer(new BuildResult<ILexer<IN>>(), extensionBuilder);
return lexer;
}
protected virtual ParserConfiguration<IN, OUT> ExtractParserConfiguration(Type parserClass)
{
var conf = new ParserConfiguration<IN, OUT>();
var functions = new Dictionary<string, MethodInfo>();
var nonTerminals = new Dictionary<string, NonTerminal<IN>>();
var methods = parserClass.GetMethods().ToList();
methods = methods.Where(m =>
{
var attributes = m.GetCustomAttributes().ToList();
var attr = attributes.Find(a => a.GetType() == typeof(ProductionAttribute));
return attr != null;
}).ToList();
parserClass.GetMethods();
methods.ForEach(m =>
{
var attributes = (ProductionAttribute[]) m.GetCustomAttributes(typeof(ProductionAttribute), true);
foreach (var attr in attributes)
{
var ntAndRule = ExtractNTAndRule(attr.RuleString);
var r = BuildNonTerminal(ntAndRule);
r.SetVisitor(m);
r.NonTerminalName = ntAndRule.Item1;
var key = ntAndRule.Item1 + "__" + r.Key;
functions[key] = m;
NonTerminal<IN> nonT = null;
if (!nonTerminals.ContainsKey(ntAndRule.Item1))
nonT = new NonTerminal<IN>(ntAndRule.Item1, new List<Rule<IN>>());
else
nonT = nonTerminals[ntAndRule.Item1];
nonT.Rules.Add(r);
nonTerminals[ntAndRule.Item1] = nonT;
}
});
conf.NonTerminals = nonTerminals;
return conf;
}
private Rule<IN> BuildNonTerminal(Tuple<string, string> ntAndRule)
{
var rule = new Rule<IN>();
var clauses = new List<IClause<IN>>();
var ruleString = ntAndRule.Item2;
var clausesString = ruleString.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in clausesString)
{
IClause<IN> clause = null;
var isTerminal = false;
var token = default(IN);
try
{
var tIn = typeof(IN);
var b = Enum.TryParse(item, out token);
if (b)
{
isTerminal = true;
}
//token = (IN)Enum.Parse(tIn , item);
//isTerminal = true;
}
catch (ArgumentException)
{
isTerminal = false;
}
if (isTerminal)
{
clause = new TerminalClause<IN>(token);
}
else if (item == "[d]")
{
if (clauses.Last() is TerminalClause<IN> discardedTerminal) discardedTerminal.Discarded = true;
}
else
{
clause = new NonTerminalClause<IN>(item);
}
if (clause != null) clauses.Add(clause);
}
rule.Clauses = clauses;
//rule.Key = ntAndRule.Item1 + "_" + ntAndRule.Item2.Replace(" ", "_");
return rule;
}
#endregion
#region parser checking
private BuildResult<Parser<IN, OUT>> CheckParser(BuildResult<Parser<IN, OUT>> result)
{
var checkers = new List<ParserChecker<IN, OUT>>();
checkers.Add(CheckUnreachable);
checkers.Add(CheckNotFound);
checkers.Add(CheckAlternates);
if (result.Result != null && !result.IsError)
foreach (var checker in checkers)
if (checker != null)
result.Result.Configuration.NonTerminals.Values.ToList()
.ForEach(nt => result = checker(result, nt));
return result;
}
private static BuildResult<Parser<IN, OUT>> CheckUnreachable(BuildResult<Parser<IN, OUT>> result,
NonTerminal<IN> nonTerminal)
{
var conf = result.Result.Configuration;
var found = false;
if (nonTerminal.Name != conf.StartingRule)
{
foreach (var nt in result.Result.Configuration.NonTerminals.Values.ToList())
if (nt.Name != nonTerminal.Name)
{
found = NonTerminalReferences(nt, nonTerminal.Name);
if (found) break;
}
if (!found)
result.AddError(new ParserInitializationError(ErrorLevel.WARN,
$"non terminal [{nonTerminal.Name}] is never used."));
}
return result;
}
private static bool NonTerminalReferences(NonTerminal<IN> nonTerminal, string referenceName)
{
var found = false;
var iRule = 0;
while (iRule < nonTerminal.Rules.Count && !found)
{
var rule = nonTerminal.Rules[iRule];
var iClause = 0;
while (iClause < rule.Clauses.Count && !found)
{
var clause = rule.Clauses[iClause];
if (clause is NonTerminalClause<IN> ntClause)
{
found = ntClause.NonTerminalName == referenceName;
}
else if (clause is OptionClause<IN> option)
{
if (option.Clause is NonTerminalClause<IN> inner)
found = inner.NonTerminalName == referenceName;
}
else if (clause is ZeroOrMoreClause<IN> zeroOrMore)
{
if (zeroOrMore.Clause is NonTerminalClause<IN> inner)
found = inner.NonTerminalName == referenceName;
}
else if (clause is OneOrMoreClause<IN> oneOrMore)
{
if (oneOrMore.Clause is NonTerminalClause<IN> inner)
found = inner.NonTerminalName == referenceName;
}
else if (clause is ChoiceClause<IN> choice)
{
int i = 0;
while (i < choice.Choices.Count && !found)
{
if (choice.Choices[i] is NonTerminalClause<IN> nonTerm)
{
found = nonTerm.NonTerminalName == referenceName;
}
i++;
}
}
iClause++;
}
iRule++;
}
return found;
}
private static BuildResult<Parser<IN, OUT>> CheckNotFound(BuildResult<Parser<IN, OUT>> result,
NonTerminal<IN> nonTerminal)
{
var conf = result.Result.Configuration;
foreach (var rule in nonTerminal.Rules)
foreach (var clause in rule.Clauses)
if (clause is NonTerminalClause<IN> ntClause)
if (!conf.NonTerminals.ContainsKey(ntClause.NonTerminalName))
result.AddError(new ParserInitializationError(ErrorLevel.ERROR,
$"{ntClause.NonTerminalName} references from {rule.RuleString} does not exist."));
return result;
}
private static BuildResult<Parser<IN, OUT>> CheckAlternates(BuildResult<Parser<IN, OUT>> result,
NonTerminal<IN> nonTerminal)
{
var conf = result.Result.Configuration;
foreach (var rule in nonTerminal.Rules)
{
foreach (var clause in rule.Clauses)
{
if (clause is ChoiceClause<IN> choice)
{
if (!choice.IsTerminalChoice && !choice.IsNonTerminalChoice)
{
result.AddError(new ParserInitializationError(ErrorLevel.ERROR,
$"{rule.RuleString} contains {choice.ToString()} with mixed terminal and nonterminal."));
}
else if (choice.IsDiscarded && choice.IsNonTerminalChoice)
{
result.AddError(new ParserInitializationError(ErrorLevel.ERROR,
$"{rule.RuleString} : {choice.ToString()} can not be marked as discarded as it is a non terminal choice."));
}
}
}
}
return result;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderUpnpOrgContentDirectory1 : IDisposable
{
/// <summary>
/// Set the value of the TransferIDs property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyTransferIDs(string aValue);
/// <summary>
/// Get a copy of the value of the TransferIDs property
/// </summary>
/// <returns>Value of the TransferIDs property.</param>
string PropertyTransferIDs();
/// <summary>
/// Set the value of the SystemUpdateID property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertySystemUpdateID(uint aValue);
/// <summary>
/// Get a copy of the value of the SystemUpdateID property
/// </summary>
/// <returns>Value of the SystemUpdateID property.</param>
uint PropertySystemUpdateID();
/// <summary>
/// Set the value of the ContainerUpdateIDs property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyContainerUpdateIDs(string aValue);
/// <summary>
/// Get a copy of the value of the ContainerUpdateIDs property
/// </summary>
/// <returns>Value of the ContainerUpdateIDs property.</param>
string PropertyContainerUpdateIDs();
}
/// <summary>
/// Provider for the upnp.org:ContentDirectory:1 UPnP service
/// </summary>
public class DvProviderUpnpOrgContentDirectory1 : DvProvider, IDisposable, IDvProviderUpnpOrgContentDirectory1
{
private GCHandle iGch;
private ActionDelegate iDelegateGetSearchCapabilities;
private ActionDelegate iDelegateGetSortCapabilities;
private ActionDelegate iDelegateGetSystemUpdateID;
private ActionDelegate iDelegateBrowse;
private ActionDelegate iDelegateSearch;
private ActionDelegate iDelegateCreateObject;
private ActionDelegate iDelegateDestroyObject;
private ActionDelegate iDelegateUpdateObject;
private ActionDelegate iDelegateImportResource;
private ActionDelegate iDelegateExportResource;
private ActionDelegate iDelegateStopTransferResource;
private ActionDelegate iDelegateGetTransferProgress;
private ActionDelegate iDelegateDeleteResource;
private ActionDelegate iDelegateCreateReference;
private PropertyString iPropertyTransferIDs;
private PropertyUint iPropertySystemUpdateID;
private PropertyString iPropertyContainerUpdateIDs;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderUpnpOrgContentDirectory1(DvDevice aDevice)
: base(aDevice, "upnp.org", "ContentDirectory", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the TransferIDs property.
/// </summary>
public void EnablePropertyTransferIDs()
{
List<String> allowedValues = new List<String>();
iPropertyTransferIDs = new PropertyString(new ParameterString("TransferIDs", allowedValues));
AddProperty(iPropertyTransferIDs);
}
/// <summary>
/// Enable the SystemUpdateID property.
/// </summary>
public void EnablePropertySystemUpdateID()
{
iPropertySystemUpdateID = new PropertyUint(new ParameterUint("SystemUpdateID"));
AddProperty(iPropertySystemUpdateID);
}
/// <summary>
/// Enable the ContainerUpdateIDs property.
/// </summary>
public void EnablePropertyContainerUpdateIDs()
{
List<String> allowedValues = new List<String>();
iPropertyContainerUpdateIDs = new PropertyString(new ParameterString("ContainerUpdateIDs", allowedValues));
AddProperty(iPropertyContainerUpdateIDs);
}
/// <summary>
/// Set the value of the TransferIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyTransferIDs has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyTransferIDs(string aValue)
{
if (iPropertyTransferIDs == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyTransferIDs, aValue);
}
/// <summary>
/// Get a copy of the value of the TransferIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyTransferIDs has previously been called.</remarks>
/// <returns>Value of the TransferIDs property.</returns>
public string PropertyTransferIDs()
{
if (iPropertyTransferIDs == null)
throw new PropertyDisabledError();
return iPropertyTransferIDs.Value();
}
/// <summary>
/// Set the value of the SystemUpdateID property
/// </summary>
/// <remarks>Can only be called if EnablePropertySystemUpdateID has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertySystemUpdateID(uint aValue)
{
if (iPropertySystemUpdateID == null)
throw new PropertyDisabledError();
return SetPropertyUint(iPropertySystemUpdateID, aValue);
}
/// <summary>
/// Get a copy of the value of the SystemUpdateID property
/// </summary>
/// <remarks>Can only be called if EnablePropertySystemUpdateID has previously been called.</remarks>
/// <returns>Value of the SystemUpdateID property.</returns>
public uint PropertySystemUpdateID()
{
if (iPropertySystemUpdateID == null)
throw new PropertyDisabledError();
return iPropertySystemUpdateID.Value();
}
/// <summary>
/// Set the value of the ContainerUpdateIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyContainerUpdateIDs has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyContainerUpdateIDs(string aValue)
{
if (iPropertyContainerUpdateIDs == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyContainerUpdateIDs, aValue);
}
/// <summary>
/// Get a copy of the value of the ContainerUpdateIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyContainerUpdateIDs has previously been called.</remarks>
/// <returns>Value of the ContainerUpdateIDs property.</returns>
public string PropertyContainerUpdateIDs()
{
if (iPropertyContainerUpdateIDs == null)
throw new PropertyDisabledError();
return iPropertyContainerUpdateIDs.Value();
}
/// <summary>
/// Signal that the action GetSearchCapabilities is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetSearchCapabilities must be overridden if this is called.</remarks>
protected void EnableActionGetSearchCapabilities()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetSearchCapabilities");
List<String> allowedValues = new List<String>();
action.AddOutputParameter(new ParameterString("SearchCaps", allowedValues));
iDelegateGetSearchCapabilities = new ActionDelegate(DoGetSearchCapabilities);
EnableAction(action, iDelegateGetSearchCapabilities, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetSortCapabilities is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetSortCapabilities must be overridden if this is called.</remarks>
protected void EnableActionGetSortCapabilities()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetSortCapabilities");
List<String> allowedValues = new List<String>();
action.AddOutputParameter(new ParameterString("SortCaps", allowedValues));
iDelegateGetSortCapabilities = new ActionDelegate(DoGetSortCapabilities);
EnableAction(action, iDelegateGetSortCapabilities, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetSystemUpdateID is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetSystemUpdateID must be overridden if this is called.</remarks>
protected void EnableActionGetSystemUpdateID()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetSystemUpdateID");
action.AddOutputParameter(new ParameterRelated("Id", iPropertySystemUpdateID));
iDelegateGetSystemUpdateID = new ActionDelegate(DoGetSystemUpdateID);
EnableAction(action, iDelegateGetSystemUpdateID, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Browse is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Browse must be overridden if this is called.</remarks>
protected void EnableActionBrowse()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Browse");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ObjectID", allowedValues));
allowedValues.Add("BrowseMetadata");
allowedValues.Add("BrowseDirectChildren");
action.AddInputParameter(new ParameterString("BrowseFlag", allowedValues));
allowedValues.Clear();
action.AddInputParameter(new ParameterString("Filter", allowedValues));
action.AddInputParameter(new ParameterUint("StartingIndex"));
action.AddInputParameter(new ParameterUint("RequestedCount"));
action.AddInputParameter(new ParameterString("SortCriteria", allowedValues));
action.AddOutputParameter(new ParameterString("Result", allowedValues));
action.AddOutputParameter(new ParameterUint("NumberReturned"));
action.AddOutputParameter(new ParameterUint("TotalMatches"));
action.AddOutputParameter(new ParameterUint("UpdateID"));
iDelegateBrowse = new ActionDelegate(DoBrowse);
EnableAction(action, iDelegateBrowse, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Search is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Search must be overridden if this is called.</remarks>
protected void EnableActionSearch()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Search");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ContainerID", allowedValues));
action.AddInputParameter(new ParameterString("SearchCriteria", allowedValues));
action.AddInputParameter(new ParameterString("Filter", allowedValues));
action.AddInputParameter(new ParameterUint("StartingIndex"));
action.AddInputParameter(new ParameterUint("RequestedCount"));
action.AddInputParameter(new ParameterString("SortCriteria", allowedValues));
action.AddOutputParameter(new ParameterString("Result", allowedValues));
action.AddOutputParameter(new ParameterUint("NumberReturned"));
action.AddOutputParameter(new ParameterUint("TotalMatches"));
action.AddOutputParameter(new ParameterUint("UpdateID"));
iDelegateSearch = new ActionDelegate(DoSearch);
EnableAction(action, iDelegateSearch, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action CreateObject is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// CreateObject must be overridden if this is called.</remarks>
protected void EnableActionCreateObject()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("CreateObject");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ContainerID", allowedValues));
action.AddInputParameter(new ParameterString("Elements", allowedValues));
action.AddOutputParameter(new ParameterString("ObjectID", allowedValues));
action.AddOutputParameter(new ParameterString("Result", allowedValues));
iDelegateCreateObject = new ActionDelegate(DoCreateObject);
EnableAction(action, iDelegateCreateObject, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action DestroyObject is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// DestroyObject must be overridden if this is called.</remarks>
protected void EnableActionDestroyObject()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DestroyObject");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ObjectID", allowedValues));
iDelegateDestroyObject = new ActionDelegate(DoDestroyObject);
EnableAction(action, iDelegateDestroyObject, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action UpdateObject is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// UpdateObject must be overridden if this is called.</remarks>
protected void EnableActionUpdateObject()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("UpdateObject");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ObjectID", allowedValues));
action.AddInputParameter(new ParameterString("CurrentTagValue", allowedValues));
action.AddInputParameter(new ParameterString("NewTagValue", allowedValues));
iDelegateUpdateObject = new ActionDelegate(DoUpdateObject);
EnableAction(action, iDelegateUpdateObject, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ImportResource is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ImportResource must be overridden if this is called.</remarks>
protected void EnableActionImportResource()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ImportResource");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("SourceURI", allowedValues));
action.AddInputParameter(new ParameterString("DestinationURI", allowedValues));
action.AddOutputParameter(new ParameterUint("TransferID"));
iDelegateImportResource = new ActionDelegate(DoImportResource);
EnableAction(action, iDelegateImportResource, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ExportResource is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ExportResource must be overridden if this is called.</remarks>
protected void EnableActionExportResource()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ExportResource");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("SourceURI", allowedValues));
action.AddInputParameter(new ParameterString("DestinationURI", allowedValues));
action.AddOutputParameter(new ParameterUint("TransferID"));
iDelegateExportResource = new ActionDelegate(DoExportResource);
EnableAction(action, iDelegateExportResource, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action StopTransferResource is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// StopTransferResource must be overridden if this is called.</remarks>
protected void EnableActionStopTransferResource()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("StopTransferResource");
action.AddInputParameter(new ParameterUint("TransferID"));
iDelegateStopTransferResource = new ActionDelegate(DoStopTransferResource);
EnableAction(action, iDelegateStopTransferResource, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetTransferProgress is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetTransferProgress must be overridden if this is called.</remarks>
protected void EnableActionGetTransferProgress()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetTransferProgress");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterUint("TransferID"));
allowedValues.Add("COMPLETED");
allowedValues.Add("ERROR");
allowedValues.Add("IN_PROGRESS");
allowedValues.Add("STOPPED");
action.AddOutputParameter(new ParameterString("TransferStatus", allowedValues));
allowedValues.Clear();
action.AddOutputParameter(new ParameterString("TransferLength", allowedValues));
action.AddOutputParameter(new ParameterString("TransferTotal", allowedValues));
iDelegateGetTransferProgress = new ActionDelegate(DoGetTransferProgress);
EnableAction(action, iDelegateGetTransferProgress, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action DeleteResource is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// DeleteResource must be overridden if this is called.</remarks>
protected void EnableActionDeleteResource()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeleteResource");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ResourceURI", allowedValues));
iDelegateDeleteResource = new ActionDelegate(DoDeleteResource);
EnableAction(action, iDelegateDeleteResource, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action CreateReference is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// CreateReference must be overridden if this is called.</remarks>
protected void EnableActionCreateReference()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("CreateReference");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("ContainerID", allowedValues));
action.AddInputParameter(new ParameterString("ObjectID", allowedValues));
action.AddOutputParameter(new ParameterString("NewID", allowedValues));
iDelegateCreateReference = new ActionDelegate(DoCreateReference);
EnableAction(action, iDelegateCreateReference, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// GetSearchCapabilities action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetSearchCapabilities action for the owning device.
///
/// Must be implemented iff EnableActionGetSearchCapabilities was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSearchCaps"></param>
protected virtual void GetSearchCapabilities(IDvInvocation aInvocation, out string aSearchCaps)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetSortCapabilities action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetSortCapabilities action for the owning device.
///
/// Must be implemented iff EnableActionGetSortCapabilities was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSortCaps"></param>
protected virtual void GetSortCapabilities(IDvInvocation aInvocation, out string aSortCaps)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetSystemUpdateID action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetSystemUpdateID action for the owning device.
///
/// Must be implemented iff EnableActionGetSystemUpdateID was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
protected virtual void GetSystemUpdateID(IDvInvocation aInvocation, out uint aId)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Browse action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Browse action for the owning device.
///
/// Must be implemented iff EnableActionBrowse was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aObjectID"></param>
/// <param name="aBrowseFlag"></param>
/// <param name="aFilter"></param>
/// <param name="aStartingIndex"></param>
/// <param name="aRequestedCount"></param>
/// <param name="aSortCriteria"></param>
/// <param name="aResult"></param>
/// <param name="aNumberReturned"></param>
/// <param name="aTotalMatches"></param>
/// <param name="aUpdateID"></param>
protected virtual void Browse(IDvInvocation aInvocation, string aObjectID, string aBrowseFlag, string aFilter, uint aStartingIndex, uint aRequestedCount, string aSortCriteria, out string aResult, out uint aNumberReturned, out uint aTotalMatches, out uint aUpdateID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Search action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Search action for the owning device.
///
/// Must be implemented iff EnableActionSearch was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aContainerID"></param>
/// <param name="aSearchCriteria"></param>
/// <param name="aFilter"></param>
/// <param name="aStartingIndex"></param>
/// <param name="aRequestedCount"></param>
/// <param name="aSortCriteria"></param>
/// <param name="aResult"></param>
/// <param name="aNumberReturned"></param>
/// <param name="aTotalMatches"></param>
/// <param name="aUpdateID"></param>
protected virtual void Search(IDvInvocation aInvocation, string aContainerID, string aSearchCriteria, string aFilter, uint aStartingIndex, uint aRequestedCount, string aSortCriteria, out string aResult, out uint aNumberReturned, out uint aTotalMatches, out uint aUpdateID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// CreateObject action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// CreateObject action for the owning device.
///
/// Must be implemented iff EnableActionCreateObject was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aContainerID"></param>
/// <param name="aElements"></param>
/// <param name="aObjectID"></param>
/// <param name="aResult"></param>
protected virtual void CreateObject(IDvInvocation aInvocation, string aContainerID, string aElements, out string aObjectID, out string aResult)
{
throw (new ActionDisabledError());
}
/// <summary>
/// DestroyObject action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// DestroyObject action for the owning device.
///
/// Must be implemented iff EnableActionDestroyObject was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aObjectID"></param>
protected virtual void DestroyObject(IDvInvocation aInvocation, string aObjectID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// UpdateObject action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// UpdateObject action for the owning device.
///
/// Must be implemented iff EnableActionUpdateObject was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aObjectID"></param>
/// <param name="aCurrentTagValue"></param>
/// <param name="aNewTagValue"></param>
protected virtual void UpdateObject(IDvInvocation aInvocation, string aObjectID, string aCurrentTagValue, string aNewTagValue)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ImportResource action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ImportResource action for the owning device.
///
/// Must be implemented iff EnableActionImportResource was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSourceURI"></param>
/// <param name="aDestinationURI"></param>
/// <param name="aTransferID"></param>
protected virtual void ImportResource(IDvInvocation aInvocation, string aSourceURI, string aDestinationURI, out uint aTransferID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ExportResource action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ExportResource action for the owning device.
///
/// Must be implemented iff EnableActionExportResource was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSourceURI"></param>
/// <param name="aDestinationURI"></param>
/// <param name="aTransferID"></param>
protected virtual void ExportResource(IDvInvocation aInvocation, string aSourceURI, string aDestinationURI, out uint aTransferID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// StopTransferResource action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// StopTransferResource action for the owning device.
///
/// Must be implemented iff EnableActionStopTransferResource was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aTransferID"></param>
protected virtual void StopTransferResource(IDvInvocation aInvocation, uint aTransferID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetTransferProgress action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetTransferProgress action for the owning device.
///
/// Must be implemented iff EnableActionGetTransferProgress was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aTransferID"></param>
/// <param name="aTransferStatus"></param>
/// <param name="aTransferLength"></param>
/// <param name="aTransferTotal"></param>
protected virtual void GetTransferProgress(IDvInvocation aInvocation, uint aTransferID, out string aTransferStatus, out string aTransferLength, out string aTransferTotal)
{
throw (new ActionDisabledError());
}
/// <summary>
/// DeleteResource action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// DeleteResource action for the owning device.
///
/// Must be implemented iff EnableActionDeleteResource was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aResourceURI"></param>
protected virtual void DeleteResource(IDvInvocation aInvocation, string aResourceURI)
{
throw (new ActionDisabledError());
}
/// <summary>
/// CreateReference action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// CreateReference action for the owning device.
///
/// Must be implemented iff EnableActionCreateReference was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aContainerID"></param>
/// <param name="aObjectID"></param>
/// <param name="aNewID"></param>
protected virtual void CreateReference(IDvInvocation aInvocation, string aContainerID, string aObjectID, out string aNewID)
{
throw (new ActionDisabledError());
}
private static int DoGetSearchCapabilities(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string searchCaps;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetSearchCapabilities(invocation, out searchCaps);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetSearchCapabilities");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetSearchCapabilities" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSearchCapabilities" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("SearchCaps", searchCaps);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSearchCapabilities" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetSortCapabilities(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string sortCaps;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetSortCapabilities(invocation, out sortCaps);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetSortCapabilities");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetSortCapabilities" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSortCapabilities" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("SortCaps", sortCaps);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSortCapabilities" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetSystemUpdateID(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint id;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetSystemUpdateID(invocation, out id);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetSystemUpdateID");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetSystemUpdateID" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSystemUpdateID" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Id", id);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSystemUpdateID" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoBrowse(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string objectID;
string browseFlag;
string filter;
uint startingIndex;
uint requestedCount;
string sortCriteria;
string result;
uint numberReturned;
uint totalMatches;
uint updateID;
try
{
invocation.ReadStart();
objectID = invocation.ReadString("ObjectID");
browseFlag = invocation.ReadString("BrowseFlag");
filter = invocation.ReadString("Filter");
startingIndex = invocation.ReadUint("StartingIndex");
requestedCount = invocation.ReadUint("RequestedCount");
sortCriteria = invocation.ReadString("SortCriteria");
invocation.ReadEnd();
self.Browse(invocation, objectID, browseFlag, filter, startingIndex, requestedCount, sortCriteria, out result, out numberReturned, out totalMatches, out updateID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Browse");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Browse" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Browse" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Result", result);
invocation.WriteUint("NumberReturned", numberReturned);
invocation.WriteUint("TotalMatches", totalMatches);
invocation.WriteUint("UpdateID", updateID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Browse" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSearch(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string containerID;
string searchCriteria;
string filter;
uint startingIndex;
uint requestedCount;
string sortCriteria;
string result;
uint numberReturned;
uint totalMatches;
uint updateID;
try
{
invocation.ReadStart();
containerID = invocation.ReadString("ContainerID");
searchCriteria = invocation.ReadString("SearchCriteria");
filter = invocation.ReadString("Filter");
startingIndex = invocation.ReadUint("StartingIndex");
requestedCount = invocation.ReadUint("RequestedCount");
sortCriteria = invocation.ReadString("SortCriteria");
invocation.ReadEnd();
self.Search(invocation, containerID, searchCriteria, filter, startingIndex, requestedCount, sortCriteria, out result, out numberReturned, out totalMatches, out updateID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Search");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Search" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Search" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Result", result);
invocation.WriteUint("NumberReturned", numberReturned);
invocation.WriteUint("TotalMatches", totalMatches);
invocation.WriteUint("UpdateID", updateID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Search" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoCreateObject(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string containerID;
string elements;
string objectID;
string result;
try
{
invocation.ReadStart();
containerID = invocation.ReadString("ContainerID");
elements = invocation.ReadString("Elements");
invocation.ReadEnd();
self.CreateObject(invocation, containerID, elements, out objectID, out result);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "CreateObject");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "CreateObject" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "CreateObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("ObjectID", objectID);
invocation.WriteString("Result", result);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "CreateObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoDestroyObject(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string objectID;
try
{
invocation.ReadStart();
objectID = invocation.ReadString("ObjectID");
invocation.ReadEnd();
self.DestroyObject(invocation, objectID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "DestroyObject");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DestroyObject" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DestroyObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DestroyObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoUpdateObject(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string objectID;
string currentTagValue;
string newTagValue;
try
{
invocation.ReadStart();
objectID = invocation.ReadString("ObjectID");
currentTagValue = invocation.ReadString("CurrentTagValue");
newTagValue = invocation.ReadString("NewTagValue");
invocation.ReadEnd();
self.UpdateObject(invocation, objectID, currentTagValue, newTagValue);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "UpdateObject");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "UpdateObject" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "UpdateObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "UpdateObject" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoImportResource(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string sourceURI;
string destinationURI;
uint transferID;
try
{
invocation.ReadStart();
sourceURI = invocation.ReadString("SourceURI");
destinationURI = invocation.ReadString("DestinationURI");
invocation.ReadEnd();
self.ImportResource(invocation, sourceURI, destinationURI, out transferID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ImportResource");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ImportResource" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ImportResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("TransferID", transferID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ImportResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoExportResource(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string sourceURI;
string destinationURI;
uint transferID;
try
{
invocation.ReadStart();
sourceURI = invocation.ReadString("SourceURI");
destinationURI = invocation.ReadString("DestinationURI");
invocation.ReadEnd();
self.ExportResource(invocation, sourceURI, destinationURI, out transferID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ExportResource");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ExportResource" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ExportResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("TransferID", transferID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ExportResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoStopTransferResource(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint transferID;
try
{
invocation.ReadStart();
transferID = invocation.ReadUint("TransferID");
invocation.ReadEnd();
self.StopTransferResource(invocation, transferID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "StopTransferResource");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "StopTransferResource" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "StopTransferResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "StopTransferResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetTransferProgress(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint transferID;
string transferStatus;
string transferLength;
string transferTotal;
try
{
invocation.ReadStart();
transferID = invocation.ReadUint("TransferID");
invocation.ReadEnd();
self.GetTransferProgress(invocation, transferID, out transferStatus, out transferLength, out transferTotal);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetTransferProgress");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetTransferProgress" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetTransferProgress" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("TransferStatus", transferStatus);
invocation.WriteString("TransferLength", transferLength);
invocation.WriteString("TransferTotal", transferTotal);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetTransferProgress" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoDeleteResource(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string resourceURI;
try
{
invocation.ReadStart();
resourceURI = invocation.ReadString("ResourceURI");
invocation.ReadEnd();
self.DeleteResource(invocation, resourceURI);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "DeleteResource");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DeleteResource" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeleteResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeleteResource" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoCreateReference(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgContentDirectory1 self = (DvProviderUpnpOrgContentDirectory1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string containerID;
string objectID;
string newID;
try
{
invocation.ReadStart();
containerID = invocation.ReadString("ContainerID");
objectID = invocation.ReadString("ObjectID");
invocation.ReadEnd();
self.CreateReference(invocation, containerID, objectID, out newID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "CreateReference");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "CreateReference" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "CreateReference" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("NewID", newID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "CreateReference" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Apress.Recipes.WebApi.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);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.ManagedReference.BuildOutputs
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using YamlDotNet.Serialization;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.DataContracts.Common;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using Microsoft.DocAsCode.YamlSerialization;
[Serializable]
public class ApiReferenceBuildOutput
{
[YamlMember(Alias = "uid")]
[JsonProperty("uid")]
public string Uid { get; set; }
[YamlMember(Alias = "isEii")]
[JsonProperty("isEii")]
public bool IsExplicitInterfaceImplementation { get; set; }
[YamlMember(Alias = "isExtensionMethod")]
[JsonProperty("isExtensionMethod")]
public bool IsExtensionMethod { get; set; }
[YamlMember(Alias = "parent")]
[JsonProperty("parent")]
public string Parent { get; set; }
[YamlMember(Alias = "definition")]
[JsonProperty("definition")]
public string Definition { get; set; }
[JsonProperty("isExternal")]
[YamlMember(Alias = "isExternal")]
public bool? IsExternal { get; set; }
[YamlMember(Alias = "href")]
[JsonProperty("href")]
public string Href { get; set; }
[YamlMember(Alias = "name")]
[JsonProperty("name")]
public List<ApiLanguageValuePair> Name { get; set; }
[YamlMember(Alias = "nameWithType")]
[JsonProperty("nameWithType")]
public List<ApiLanguageValuePair> NameWithType { get; set; }
[YamlMember(Alias = "fullName")]
[JsonProperty("fullName")]
public List<ApiLanguageValuePair> FullName { get; set; }
[YamlMember(Alias = "specName")]
[JsonProperty("specName")]
public List<ApiLanguageValuePair> Spec { get; set; }
[YamlMember(Alias = "syntax")]
[JsonProperty("syntax")]
public ApiSyntaxBuildOutput Syntax { get; set; }
[YamlMember(Alias = "source")]
[JsonProperty("source")]
public SourceDetail Source { get; set; }
[YamlMember(Alias = "documentation")]
[JsonProperty("documentation")]
public SourceDetail Documentation { get; set; }
[YamlMember(Alias = "assemblies")]
[JsonProperty("assemblies")]
public List<string> AssemblyNameList { get; set; }
[YamlMember(Alias = "namespace")]
[JsonProperty("namespace")]
public string NamespaceName { get; set; }
[YamlMember(Alias = "remarks")]
[JsonProperty("remarks")]
public string Remarks { get; set; }
[YamlMember(Alias = "example")]
[JsonProperty("example")]
public List<string> Examples { get; set; }
[YamlMember(Alias = "overridden")]
[JsonProperty("overridden")]
public ApiNames Overridden { get; set; }
[YamlMember(Alias = "overload")]
[JsonProperty("overload")]
public ApiNames Overload { get; set; }
[YamlMember(Alias = "exceptions")]
[JsonProperty("exceptions")]
public List<ApiExceptionInfoBuildOutput> Exceptions { get; set; }
[YamlMember(Alias = "seealso")]
[JsonProperty("seealso")]
public List<ApiLinkInfoBuildOutput> SeeAlsos { get; set; }
[YamlMember(Alias = "see")]
[JsonProperty("see")]
public List<ApiLinkInfoBuildOutput> Sees { get; set; }
[YamlMember(Alias = "inheritance")]
[JsonProperty("inheritance")]
public List<ApiReferenceBuildOutput> Inheritance { get; set; }
[YamlMember(Alias = "level")]
[JsonProperty("level")]
public int Level => Inheritance != null ? Inheritance.Count : 0;
[YamlMember(Alias = "implements")]
[JsonProperty("implements")]
public List<ApiNames> Implements { get; set; }
[YamlMember(Alias = "inheritedMembers")]
[JsonProperty("inheritedMembers")]
public List<string> InheritedMembers { get; set; }
[YamlMember(Alias = "extensionMethods")]
[JsonProperty("extensionMethods")]
public List<string> ExtensionMethods { get; set; }
[ExtensibleMember(Constants.ExtensionMemberPrefix.Modifiers)]
[JsonIgnore]
public SortedList<string, List<string>> Modifiers { get; set; } = new SortedList<string, List<string>>();
[YamlMember(Alias = "conceptual")]
[JsonProperty("conceptual")]
public string Conceptual { get; set; }
[YamlMember(Alias = "attributes")]
[JsonProperty("attributes")]
public List<AttributeInfo> Attributes { get; set; }
[YamlMember(Alias = "index")]
[JsonProperty("index")]
public int? Index { get; set; }
[ExtensibleMember]
[JsonIgnore]
public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
[JsonExtensionData]
public CompositeDictionary MetadataJson =>
CompositeDictionary
.CreateBuilder()
.Add(Constants.ExtensionMemberPrefix.Modifiers, Modifiers, JTokenConverter.Convert<List<string>>)
.Add(string.Empty, Metadata)
.Create();
private bool _needExpand = true;
public static ApiReferenceBuildOutput FromUid(string uid)
{
if (string.IsNullOrEmpty(uid))
{
return null;
}
return new ApiReferenceBuildOutput
{
Uid = uid,
};
}
public static ApiReferenceBuildOutput FromModel(ReferenceViewModel vm, string[] supportedLanguages)
{
if (vm == null)
{
return null;
}
// TODO: may lead to potential problems with have vm.Additional["syntax"] as SyntaxDetailViewModel
// It is now working as syntax is set only in FillReferenceInformation and not from YAML deserialization
var result = new ApiReferenceBuildOutput
{
Uid = vm.Uid,
Parent = vm.Parent,
Definition = vm.Definition,
IsExternal = vm.IsExternal,
Href = vm.Href,
Name = ApiBuildOutputUtility.TransformToLanguagePairList(vm.Name, vm.NameInDevLangs, supportedLanguages),
NameWithType = ApiBuildOutputUtility.TransformToLanguagePairList(vm.NameWithType, vm.NameWithTypeInDevLangs, supportedLanguages),
FullName = ApiBuildOutputUtility.TransformToLanguagePairList(vm.FullName, vm.FullNameInDevLangs, supportedLanguages),
Spec = GetSpecNames(ApiBuildOutputUtility.GetXref(vm.Uid, vm.Name, vm.FullName), supportedLanguages, vm.Specs),
Metadata = vm.Additional,
};
if (result.Metadata.TryGetValue("syntax", out object syntax))
{
result.Syntax = ApiSyntaxBuildOutput.FromModel(syntax as SyntaxDetailViewModel, supportedLanguages);
result.Metadata.Remove("syntax");
}
return result;
}
public static ApiReferenceBuildOutput FromModel(ItemViewModel vm)
{
if (vm == null)
{
return null;
}
var output = new ApiReferenceBuildOutput
{
Uid = vm.Uid,
IsExplicitInterfaceImplementation = vm.IsExplicitInterfaceImplementation,
IsExtensionMethod = vm.IsExtensionMethod,
Parent = vm.Parent,
IsExternal = false,
Href = vm.Href,
Name = ApiBuildOutputUtility.TransformToLanguagePairList(vm.Name, vm.Names, vm.SupportedLanguages),
NameWithType = ApiBuildOutputUtility.TransformToLanguagePairList(vm.NameWithType, vm.NamesWithType, vm.SupportedLanguages),
FullName = ApiBuildOutputUtility.TransformToLanguagePairList(vm.FullName, vm.FullNames, vm.SupportedLanguages),
Spec = GetSpecNames(ApiBuildOutputUtility.GetXref(vm.Uid, vm.Name, vm.FullName), vm.SupportedLanguages),
Source = vm.Source,
Documentation = vm.Documentation,
AssemblyNameList = vm.AssemblyNameList,
NamespaceName = vm.NamespaceName,
Remarks = vm.Remarks,
Examples = vm.Examples,
Overridden = ApiNames.FromUid(vm.Overridden),
Overload = ApiNames.FromUid(vm.Overload),
SeeAlsos = vm.SeeAlsos?.Select(ApiLinkInfoBuildOutput.FromModel).ToList(),
Sees = vm.Sees?.Select(ApiLinkInfoBuildOutput.FromModel).ToList(),
Inheritance = vm.Inheritance?.Select(FromUid).ToList(),
Implements = vm.Implements?.Select(ApiNames.FromUid).ToList(),
InheritedMembers = vm.InheritedMembers,
ExtensionMethods = vm.ExtensionMethods,
Modifiers = vm.Modifiers,
Conceptual = vm.Conceptual,
Metadata = vm.Metadata,
Attributes = vm.Attributes,
Syntax = ApiSyntaxBuildOutput.FromModel(vm.Syntax, vm.SupportedLanguages),
Exceptions = vm.Exceptions?.Select(ApiExceptionInfoBuildOutput.FromModel).ToList(),
};
output.Metadata["type"] = vm.Type;
output.Metadata["summary"] = vm.Summary;
output.Metadata["platform"] = vm.Platform;
return output;
}
public void Expand(Dictionary<string, ApiReferenceBuildOutput> references, string[] supportedLanguages)
{
if (_needExpand)
{
_needExpand = false;
Inheritance = Inheritance?.Select(i => ApiBuildOutputUtility.GetReferenceViewModel(i.Uid, references, supportedLanguages)).ToList();
Implements = Implements?.Select(i => ApiBuildOutputUtility.GetApiNames(i.Uid, references, supportedLanguages)).ToList();
Syntax?.Expand(references, supportedLanguages);
Overridden = ApiBuildOutputUtility.GetApiNames(Overridden?.Uid, references, supportedLanguages);
SeeAlsos?.ForEach(e => e.Expand(references, supportedLanguages));
Sees?.ForEach(e => e.Expand(references, supportedLanguages));
Exceptions?.ForEach(e => e.Expand(references, supportedLanguages));
Overload = ApiBuildOutputUtility.GetApiNames(Overload?.Uid, references, supportedLanguages);
}
}
public static List<ApiLanguageValuePair> GetSpecNames(string xref, string[] supportedLanguages, SortedList<string, List<SpecViewModel>> specs = null)
{
if (specs != null && specs.Count > 0)
{
return (from spec in specs
where supportedLanguages.Contains(spec.Key)
select new ApiLanguageValuePair
{
Language = spec.Key,
Value = GetSpecName(spec.Value),
}).ToList();
}
if (!string.IsNullOrEmpty(xref))
{
return (from lang in supportedLanguages
select new ApiLanguageValuePair
{
Language = lang,
Value = xref,
}).ToList();
}
return null;
}
private static string GetSpecName(List<SpecViewModel> spec)
{
if (spec == null)
{
return null;
}
return string.Concat(spec.Select(GetCompositeName));
}
private static string GetCompositeName(SpecViewModel svm)
{
// If href does not exists, return full name
if (string.IsNullOrEmpty(svm.Uid))
{
return HttpUtility.HtmlEncode(svm.FullName);
}
// If href exists, return name with href
return ApiBuildOutputUtility.GetXref(svm.Uid, svm.Name, svm.FullName);
}
}
}
| |
// 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.
//
namespace System.Security
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Util;
using System.Text;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
internal enum SecurityElementType
{
Regular = 0,
Format = 1,
Comment = 2
}
internal interface ISecurityElementFactory
{
SecurityElement CreateSecurityElement();
Object Copy();
String GetTag();
String Attribute( String attributeName );
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SecurityElement : ISecurityElementFactory
{
internal String m_strTag;
internal String m_strText;
private ArrayList m_lChildren;
internal ArrayList m_lAttributes;
internal SecurityElementType m_type = SecurityElementType.Regular;
private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' };
private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' };
private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' };
private const String s_strIndent = " ";
private const int c_AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute
private const int c_ChildrenTypical = 1;
private static readonly String[] s_escapeStringPairs = new String[]
{
// these must be all once character escape sequences or a new escaping algorithm is needed
"<", "<",
">", ">",
"\"", """,
"\'", "'",
"&", "&"
};
private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
//-------------------------- Constructors ---------------------------
internal SecurityElement()
{
}
////// ISecurityElementFactory implementation
SecurityElement ISecurityElementFactory.CreateSecurityElement()
{
return this;
}
String ISecurityElementFactory.GetTag()
{
return ((SecurityElement)this).Tag;
}
Object ISecurityElementFactory.Copy()
{
return ((SecurityElement)this).Copy();
}
String ISecurityElementFactory.Attribute( String attributeName )
{
return ((SecurityElement)this).Attribute( attributeName );
}
//////////////
#if FEATURE_CAS_POLICY
public static SecurityElement FromString( String xml )
{
if (xml == null)
throw new ArgumentNullException( "xml" );
Contract.EndContractBlock();
return new Parser( xml ).GetTopElement();
}
#endif // FEATURE_CAS_POLICY
public SecurityElement( String tag )
{
if (tag == null)
throw new ArgumentNullException( "tag" );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = null;
}
public SecurityElement( String tag, String text )
{
if (tag == null)
throw new ArgumentNullException( "tag" );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
if (text != null && !IsValidText( text ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementText" ), text ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = text;
}
//-------------------------- Properties -----------------------------
public String Tag
{
[Pure]
get
{
return m_strTag;
}
set
{
if (value == null)
throw new ArgumentNullException( "Tag" );
if (!IsValidTag( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
Contract.EndContractBlock();
m_strTag = value;
}
}
public Hashtable Attributes
{
get
{
if (m_lAttributes == null || m_lAttributes.Count == 0)
{
return null;
}
else
{
Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
hashtable.Add( m_lAttributes[i], m_lAttributes[i+1]);
}
return hashtable;
}
}
set
{
if (value == null || value.Count == 0)
{
m_lAttributes = null;
}
else
{
ArrayList list = new ArrayList(value.Count);
System.Collections.IDictionaryEnumerator enumerator = (System.Collections.IDictionaryEnumerator)value.GetEnumerator();
while (enumerator.MoveNext())
{
String attrName = (String)enumerator.Key;
String attrValue = (String)enumerator.Value;
if (!IsValidAttributeName( attrName ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), (String)enumerator.Current ) );
if (!IsValidAttributeValue( attrValue ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), (String)enumerator.Value ) );
list.Add(attrName);
list.Add(attrValue);
}
m_lAttributes = list;
}
}
}
public String Text
{
get
{
return Unescape( m_strText );
}
set
{
if (value == null)
{
m_strText = null;
}
else
{
if (!IsValidText( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
m_strText = value;
}
}
}
public ArrayList Children
{
get
{
ConvertSecurityElementFactories();
return m_lChildren;
}
set
{
if (value != null)
{
IEnumerator enumerator = value.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current == null)
throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Child" ) );
}
}
m_lChildren = value;
}
}
internal void ConvertSecurityElementFactories()
{
if (m_lChildren == null)
return;
for (int i = 0; i < m_lChildren.Count; ++i)
{
ISecurityElementFactory iseFactory = m_lChildren[i] as ISecurityElementFactory;
if (iseFactory != null && !(m_lChildren[i] is SecurityElement))
m_lChildren[i] = iseFactory.CreateSecurityElement();
}
}
internal ArrayList InternalChildren
{
get
{
// Beware! This array list can contain SecurityElements and other ISecurityElementFactories.
// If you want to get a consistent SecurityElement view, call get_Children.
return m_lChildren;
}
}
//-------------------------- Public Methods -----------------------------
internal void AddAttributeSafe( String name, String value )
{
if (m_lAttributes == null)
{
m_lAttributes = new ArrayList( c_AttributesTypical );
}
else
{
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
throw new ArgumentException( Environment.GetResourceString( "Argument_AttributeNamesMustBeUnique" ) );
}
}
m_lAttributes.Add(name);
m_lAttributes.Add(value);
}
public void AddAttribute( String name, String value )
{
if (name == null)
throw new ArgumentNullException( "name" );
if (value == null)
throw new ArgumentNullException( "value" );
if (!IsValidAttributeName( name ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) );
if (!IsValidAttributeValue( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), value ) );
Contract.EndContractBlock();
AddAttributeSafe( name, value );
}
public void AddChild( SecurityElement child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChild( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChildNoDuplicates( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
{
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
else
{
for (int i = 0; i < m_lChildren.Count; ++i)
{
if (m_lChildren[i] == child)
return;
}
m_lChildren.Add( child );
}
}
public bool Equal( SecurityElement other )
{
if (other == null)
return false;
// Check if the tags are the same
if (!String.Equals(m_strTag, other.m_strTag))
return false;
// Check if the text is the same
if (!String.Equals(m_strText, other.m_strText))
return false;
// Check if the attributes are the same and appear in the same
// order.
// Maybe we can get away by only checking the number of attributes
if (m_lAttributes == null || other.m_lAttributes == null)
{
if (m_lAttributes != other.m_lAttributes)
return false;
}
else
{
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
if (iMax != other.m_lAttributes.Count)
return false;
for (int i = 0; i < iMax; i++)
{
String lhs = (String)m_lAttributes[i];
String rhs = (String)other.m_lAttributes[i];
if (!String.Equals(lhs, rhs))
return false;
}
}
// Finally we must check the child and make sure they are
// equal and in the same order
// Maybe we can get away by only checking the number of children
if (m_lChildren == null || other.m_lChildren == null)
{
if (m_lChildren != other.m_lChildren)
return false;
}
else
{
if (m_lChildren.Count != other.m_lChildren.Count)
return false;
this.ConvertSecurityElementFactories();
other.ConvertSecurityElementFactories();
// Okay, we'll need to go through each one of them
IEnumerator lhs = m_lChildren.GetEnumerator();
IEnumerator rhs = other.m_lChildren.GetEnumerator();
SecurityElement e1, e2;
while (lhs.MoveNext())
{
rhs.MoveNext();
e1 = (SecurityElement)lhs.Current;
e2 = (SecurityElement)rhs.Current;
if (e1 == null || !e1.Equal(e2))
return false;
}
}
return true;
}
[System.Runtime.InteropServices.ComVisible(false)]
public SecurityElement Copy()
{
SecurityElement element = new SecurityElement( this.m_strTag, this.m_strText );
element.m_lChildren = this.m_lChildren == null ? null : new ArrayList( this.m_lChildren );
element.m_lAttributes = this.m_lAttributes == null ? null : new ArrayList(this.m_lAttributes);
return element;
}
[Pure]
public static bool IsValidTag( String tag )
{
if (tag == null)
return false;
return tag.IndexOfAny( s_tagIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidText( String text )
{
if (text == null)
return false;
return text.IndexOfAny( s_textIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidAttributeName( String name )
{
return IsValidTag( name );
}
[Pure]
public static bool IsValidAttributeValue( String value )
{
if (value == null)
return false;
return value.IndexOfAny( s_valueIllegalCharacters ) == -1;
}
private static String GetEscapeSequence( char c )
{
int iMax = s_escapeStringPairs.Length;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
if (strEscSeq[0] == c)
return strEscValue;
}
Contract.Assert( false, "Unable to find escape sequence for this character" );
return c.ToString();
}
public static String Escape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
do
{
index = str.IndexOfAny( s_escapeChars, newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append( str, newIndex, index - newIndex );
sb.Append( GetEscapeSequence( str[index] ) );
newIndex = ( index + 1 );
}
}
while (true);
// no normal exit is possible
}
private static String GetUnescapeSequence( String str, int index, out int newIndex )
{
int maxCompareLength = str.Length - index;
int iMax = s_escapeStringPairs.Length;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
int length = strEscValue.Length;
if (length <= maxCompareLength && String.Compare( strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0)
{
newIndex = index + strEscValue.Length;
return strEscSeq;
}
}
newIndex = index + 1;
return str[index].ToString();
}
private static String Unescape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed).
do
{
index = str.IndexOf( '&', newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append(str, newIndex, index - newIndex);
sb.Append( GetUnescapeSequence( str, index, out newIndex ) ); // updates the newIndex too
}
}
while (true);
// C# reports a warning if I leave this in, but I still kinda want to just in case.
// Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" );
// return str;
}
private delegate void ToStringHelperFunc( Object obj, String str );
private static void ToStringHelperStringBuilder( Object obj, String str )
{
((StringBuilder)obj).Append( str );
}
public override String ToString ()
{
StringBuilder sb = new StringBuilder();
ToString( "", sb, new ToStringHelperFunc( ToStringHelperStringBuilder ) );
return sb.ToString();
}
#if !FEATURE_CORECLR
private static void ToStringHelperStreamWriter(Object obj, String str)
{
((StreamWriter)obj).Write(str);
}
internal void ToWriter( StreamWriter writer )
{
ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) );
}
#endif
private void ToString( String indent, Object obj, ToStringHelperFunc func )
{
// First add the indent
// func( obj, indent );
// Add in the opening bracket and the tag.
func( obj, "<" );
switch (m_type)
{
case SecurityElementType.Format:
func( obj, "?" );
break;
case SecurityElementType.Comment:
func( obj, "!" );
break;
default:
break;
}
func( obj, m_strTag );
// If there are any attributes, plop those in.
if (m_lAttributes != null && m_lAttributes.Count > 0)
{
func( obj, " " );
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
String strAttrValue = (String)m_lAttributes[i+1];
func( obj, strAttrName );
func( obj, "=\"" );
func( obj, strAttrValue );
func( obj, "\"" );
if (i != m_lAttributes.Count - 2)
{
if (m_type == SecurityElementType.Regular)
{
func( obj, Environment.NewLine );
}
else
{
func( obj, " " );
}
}
}
}
if (m_strText == null && (m_lChildren == null || m_lChildren.Count == 0))
{
// If we are a single tag with no children, just add the end of tag text.
switch (m_type)
{
case SecurityElementType.Comment:
func( obj, ">" );
break;
case SecurityElementType.Format:
func( obj, " ?>" );
break;
default:
func( obj, "/>" );
break;
}
func( obj, Environment.NewLine );
}
else
{
// Close the current tag.
func( obj, ">" );
// Output the text
func( obj, m_strText );
// Output any children.
if (m_lChildren != null)
{
this.ConvertSecurityElementFactories();
func( obj, Environment.NewLine );
// String childIndent = indent + s_strIndent;
for (int i = 0; i < m_lChildren.Count; ++i)
{
((SecurityElement)m_lChildren[i]).ToString( "", obj, func );
}
// In the case where we have children, the close tag will not be on the same line as the
// opening tag, so we need to indent.
// func( obj, indent );
}
// Output the closing tag
func( obj, "</" );
func( obj, m_strTag );
func( obj, ">" );
func( obj, Environment.NewLine );
}
}
public String Attribute( String name )
{
if (name == null)
throw new ArgumentNullException( "name" );
Contract.EndContractBlock();
// Note: we don't check for validity here because an
// if an invalid name is passed we simply won't find it.
if (m_lAttributes == null)
return null;
// Go through all the attribute and see if we know about
// the one we are asked for
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
{
String strAttrValue = (String)m_lAttributes[i+1];
return Unescape(strAttrValue);
}
}
// In the case where we didn't find it, we are expected to
// return null
return null;
}
public SecurityElement SearchForChildByTag( String tag )
{
// Go through all the children and see if we can
// find the one are are asked for (matching tags)
if (tag == null)
throw new ArgumentNullException( "tag" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
SecurityElement current = (SecurityElement)enumerator.Current;
if (current != null && String.Equals(current.Tag, tag))
return current;
}
return null;
}
#if FEATURE_CAS_POLICY
internal IPermission ToPermission(bool ignoreTypeLoadFailures)
{
IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures );
if (ip == null)
return null;
ip.FromXml(this);
// Get the permission token here to ensure that the token
// type is updated appropriately now that we've loaded the type.
PermissionToken token = PermissionToken.GetToken( ip );
Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned");
return ip;
}
[System.Security.SecurityCritical] // auto-generated
internal Object ToSecurityObject()
{
switch (m_strTag)
{
case "PermissionSet":
PermissionSet pset = new PermissionSet(PermissionState.None);
pset.FromXml(this);
return pset;
default:
return ToPermission(false);
}
}
#endif // FEATURE_CAS_POLICY
internal String SearchForTextOfLocalName(String strLocalName)
{
// Search on each child in order and each
// child's child, depth-first
if (strLocalName == null)
throw new ArgumentNullException( "strLocalName" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (m_strTag == null) return null;
if (m_strTag.Equals( strLocalName ) || m_strTag.EndsWith( ":" + strLocalName, StringComparison.Ordinal ))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfLocalName( strLocalName );
if (current != null)
return current;
}
return null;
}
public String SearchForTextOfTag( String tag )
{
// Search on each child in order and each
// child's child, depth-first
if (tag == null)
throw new ArgumentNullException( "tag" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (String.Equals(m_strTag, tag))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
this.ConvertSecurityElementFactories();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfTag( tag );
if (current != null)
return current;
}
return null;
}
}
}
| |
//
// 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.
//
#if !READ_ONLY
#if !PCL && !NET_CORE
using System;
using System.Security.Cryptography;
namespace 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
#endif
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.decoration
{
/// <summary>
/// <para>Border implementation with two CSS borders. Both borders can be styled
/// independent of each other. This decorator is used to create 3D effects like
/// inset, outset, ridge or groove.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.decoration.Double", OmitOptionalParameters = true, Export = false)]
public partial class Double : qx.ui.decoration.Abstract
{
#region Properties
/// <summary>
/// <para>Color of the background</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "backgroundColor", NativeField = true)]
public string BackgroundColor { get; set; }
/// <summary>
/// <para>Property group for the inner color properties.</para>
/// </summary>
[JsProperty(Name = "innerColor", NativeField = true)]
public object InnerColor { get; set; }
/// <summary>
/// <para>bottom inner color of border</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "innerColorBottom", NativeField = true)]
public string InnerColorBottom { get; set; }
/// <summary>
/// <para>left inner color of border</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "innerColorLeft", NativeField = true)]
public string InnerColorLeft { get; set; }
/// <summary>
/// <para>right inner color of border</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "innerColorRight", NativeField = true)]
public string InnerColorRight { get; set; }
/// <summary>
/// <para>top inner color of border</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "innerColorTop", NativeField = true)]
public string InnerColorTop { get; set; }
/// <summary>
/// <para>Property group to set the inner border width of all sides</para>
/// </summary>
[JsProperty(Name = "innerWidth", NativeField = true)]
public object InnerWidth { get; set; }
/// <summary>
/// <para>bottom width of border</para>
/// </summary>
[JsProperty(Name = "innerWidthBottom", NativeField = true)]
public double InnerWidthBottom { get; set; }
/// <summary>
/// <para>left width of border</para>
/// </summary>
[JsProperty(Name = "innerWidthLeft", NativeField = true)]
public double InnerWidthLeft { get; set; }
/// <summary>
/// <para>right width of border</para>
/// </summary>
[JsProperty(Name = "innerWidthRight", NativeField = true)]
public double InnerWidthRight { get; set; }
/// <summary>
/// <para>top width of border</para>
/// </summary>
[JsProperty(Name = "innerWidthTop", NativeField = true)]
public double InnerWidthTop { get; set; }
#endregion Properties
#region Methods
public Double() { throw new NotImplementedException(); }
/// <param name="width">Width of the border</param>
/// <param name="style">Any supported border style</param>
/// <param name="color">The border color</param>
/// <param name="innerWidth">Width of the inner border</param>
/// <param name="innerColor">The inner border color</param>
public Double(double width, string style, string color, string innerWidth, string innerColor) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the basic markup structure used for this decoration.
/// This later updated on DOM to resize or tint the element.</para>
/// </summary>
/// <returns>Basic markup</returns>
[JsMethod(Name = "getMarkup")]
public string GetMarkup() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resizes the element respecting the configured borders
/// to the given width and height. Should automatically
/// respect the box model of the client to correctly
/// compute the dimensions.</para>
/// </summary>
/// <param name="element">The element to update</param>
/// <param name="width">Width of the element</param>
/// <param name="height">Height of the element</param>
[JsMethod(Name = "resize")]
public void Resize(qx.html.Element element, double width, double height) { throw new NotImplementedException(); }
/// <summary>
/// <para>Applies the given background color to the element
/// or fallback to the background color defined
/// by the decoration itself.</para>
/// </summary>
/// <param name="element">The element to update</param>
/// <param name="bgcolor">The color to apply or null</param>
[JsMethod(Name = "tint")]
public void Tint(qx.html.Element element, string bgcolor) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property backgroundColor.</para>
/// </summary>
[JsMethod(Name = "getBackgroundColor")]
public string GetBackgroundColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property backgroundColor
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property backgroundColor.</param>
[JsMethod(Name = "initBackgroundColor")]
public void InitBackgroundColor(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property backgroundColor.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetBackgroundColor")]
public void ResetBackgroundColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property backgroundColor.</para>
/// </summary>
/// <param name="value">New value for property backgroundColor.</param>
[JsMethod(Name = "setBackgroundColor")]
public void SetBackgroundColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerColorBottom.</para>
/// </summary>
[JsMethod(Name = "getInnerColorBottom")]
public string GetInnerColorBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerColorLeft.</para>
/// </summary>
[JsMethod(Name = "getInnerColorLeft")]
public string GetInnerColorLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerColorRight.</para>
/// </summary>
[JsMethod(Name = "getInnerColorRight")]
public string GetInnerColorRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerColorTop.</para>
/// </summary>
[JsMethod(Name = "getInnerColorTop")]
public string GetInnerColorTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerWidthBottom.</para>
/// </summary>
[JsMethod(Name = "getInnerWidthBottom")]
public double GetInnerWidthBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerWidthLeft.</para>
/// </summary>
[JsMethod(Name = "getInnerWidthLeft")]
public double GetInnerWidthLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerWidthRight.</para>
/// </summary>
[JsMethod(Name = "getInnerWidthRight")]
public double GetInnerWidthRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property innerWidthTop.</para>
/// </summary>
[JsMethod(Name = "getInnerWidthTop")]
public double GetInnerWidthTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerColorBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerColorBottom.</param>
[JsMethod(Name = "initInnerColorBottom")]
public void InitInnerColorBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerColorLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerColorLeft.</param>
[JsMethod(Name = "initInnerColorLeft")]
public void InitInnerColorLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerColorRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerColorRight.</param>
[JsMethod(Name = "initInnerColorRight")]
public void InitInnerColorRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerColorTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerColorTop.</param>
[JsMethod(Name = "initInnerColorTop")]
public void InitInnerColorTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerWidthBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerWidthBottom.</param>
[JsMethod(Name = "initInnerWidthBottom")]
public void InitInnerWidthBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerWidthLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerWidthLeft.</param>
[JsMethod(Name = "initInnerWidthLeft")]
public void InitInnerWidthLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerWidthRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerWidthRight.</param>
[JsMethod(Name = "initInnerWidthRight")]
public void InitInnerWidthRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property innerWidthTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property innerWidthTop.</param>
[JsMethod(Name = "initInnerWidthTop")]
public void InitInnerWidthTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerColor.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerColor")]
public void ResetInnerColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerColorBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerColorBottom")]
public void ResetInnerColorBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerColorLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerColorLeft")]
public void ResetInnerColorLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerColorRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerColorRight")]
public void ResetInnerColorRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerColorTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerColorTop")]
public void ResetInnerColorTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerWidth.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerWidth")]
public void ResetInnerWidth() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerWidthBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerWidthBottom")]
public void ResetInnerWidthBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerWidthLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerWidthLeft")]
public void ResetInnerWidthLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerWidthRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerWidthRight")]
public void ResetInnerWidthRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property innerWidthTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInnerWidthTop")]
public void ResetInnerWidthTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group innerColor.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="innerColorTop">Sets the value of the property #innerColorTop.</param>
/// <param name="innerColorRight">Sets the value of the property #innerColorRight.</param>
/// <param name="innerColorBottom">Sets the value of the property #innerColorBottom.</param>
/// <param name="innerColorLeft">Sets the value of the property #innerColorLeft.</param>
[JsMethod(Name = "setInnerColor")]
public void SetInnerColor(object innerColorTop, object innerColorRight, object innerColorBottom, object innerColorLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerColorBottom.</para>
/// </summary>
/// <param name="value">New value for property innerColorBottom.</param>
[JsMethod(Name = "setInnerColorBottom")]
public void SetInnerColorBottom(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerColorLeft.</para>
/// </summary>
/// <param name="value">New value for property innerColorLeft.</param>
[JsMethod(Name = "setInnerColorLeft")]
public void SetInnerColorLeft(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerColorRight.</para>
/// </summary>
/// <param name="value">New value for property innerColorRight.</param>
[JsMethod(Name = "setInnerColorRight")]
public void SetInnerColorRight(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerColorTop.</para>
/// </summary>
/// <param name="value">New value for property innerColorTop.</param>
[JsMethod(Name = "setInnerColorTop")]
public void SetInnerColorTop(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group innerWidth.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="innerWidthTop">Sets the value of the property #innerWidthTop.</param>
/// <param name="innerWidthRight">Sets the value of the property #innerWidthRight.</param>
/// <param name="innerWidthBottom">Sets the value of the property #innerWidthBottom.</param>
/// <param name="innerWidthLeft">Sets the value of the property #innerWidthLeft.</param>
[JsMethod(Name = "setInnerWidth")]
public void SetInnerWidth(object innerWidthTop, object innerWidthRight, object innerWidthBottom, object innerWidthLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerWidthBottom.</para>
/// </summary>
/// <param name="value">New value for property innerWidthBottom.</param>
[JsMethod(Name = "setInnerWidthBottom")]
public void SetInnerWidthBottom(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerWidthLeft.</para>
/// </summary>
/// <param name="value">New value for property innerWidthLeft.</param>
[JsMethod(Name = "setInnerWidthLeft")]
public void SetInnerWidthLeft(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerWidthRight.</para>
/// </summary>
/// <param name="value">New value for property innerWidthRight.</param>
[JsMethod(Name = "setInnerWidthRight")]
public void SetInnerWidthRight(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property innerWidthTop.</para>
/// </summary>
/// <param name="value">New value for property innerWidthTop.</param>
[JsMethod(Name = "setInnerWidthTop")]
public void SetInnerWidthTop(double value) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public static partial class CastingHelper
{
/// <summary>
/// Returns true if '<paramref name="thisType"/>' can be cast to '<paramref name="otherType"/>'.
/// Assumes '<paramref name="thisType"/>' is in it's boxed form if it's a value type (i.e.
/// [System.Int32].CanCastTo([System.Object]) will return true).
/// </summary>
public static bool CanCastTo(this TypeDesc thisType, TypeDesc otherType)
{
return thisType.CanCastToInternal(otherType, null);
}
private static bool CanCastToInternal(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (thisType == otherType)
{
return true;
}
switch (thisType.Category)
{
case TypeFlags.GenericParameter:
return ((GenericParameterDesc)thisType).CanCastGenericParameterTo(otherType, protect);
case TypeFlags.Array:
case TypeFlags.SzArray:
return ((ArrayType)thisType).CanCastArrayTo(otherType, protect);
default:
Debug.Assert(thisType.IsDefType);
return thisType.CanCastToClassOrInterface(otherType, protect);
}
}
private static bool CanCastGenericParameterTo(this GenericParameterDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// A boxed variable type can be cast to any of its constraints, or object, if none are specified
if (otherType.IsObject)
{
return true;
}
if (thisType.HasNotNullableValueTypeConstraint &&
thisType.Context.IsWellKnownType(otherType, WellKnownType.ValueType))
{
return true;
}
foreach (var typeConstraint in thisType.TypeConstraints)
{
if (typeConstraint.CanCastToInternal(otherType, protect))
{
return true;
}
}
return false;
}
private static bool CanCastArrayTo(this ArrayType thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// Casting the array to one of the base types or interfaces?
if (otherType.IsDefType)
{
return thisType.CanCastToClassOrInterface(otherType, protect);
}
// Casting array to something else (between SzArray and Array, for example)?
if (thisType.Category != otherType.Category)
{
return false;
}
ArrayType otherArrayType = (ArrayType)otherType;
// Check ranks if we're casting multidim arrays
if (!thisType.IsSzArray && thisType.Rank != otherArrayType.Rank)
{
return false;
}
return thisType.CanCastParamTo(otherArrayType.ParameterType, protect);
}
private static bool CanCastParamTo(this ParameterizedType thisType, TypeDesc paramType, StackOverflowProtect protect)
{
// While boxed value classes inherit from object their
// unboxed versions do not. Parameterized types have the
// unboxed version, thus, if the from type parameter is value
// class then only an exact match/equivalence works.
if (thisType.ParameterType == paramType)
{
return true;
}
TypeDesc curTypesParm = thisType.ParameterType;
// Object parameters don't need an exact match but only inheritance, check for that
TypeDesc fromParamUnderlyingType = curTypesParm.UnderlyingType;
if (fromParamUnderlyingType.IsObjRef)
{
return curTypesParm.CanCastToInternal(paramType, protect);
}
else if (curTypesParm.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)curTypesParm;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(paramType, protect);
}
}
else if (fromParamUnderlyingType.IsPrimitive)
{
TypeDesc toParamUnderlyingType = paramType.UnderlyingType;
if (toParamUnderlyingType.IsPrimitive)
{
if (toParamUnderlyingType == fromParamUnderlyingType)
{
return true;
}
if (ArePrimitveTypesEquivalentSize(fromParamUnderlyingType, toParamUnderlyingType))
{
return true;
}
}
}
// Anything else is not a match
return false;
}
// Returns true of the two types are equivalent primitive types. Used by array casts.
static private bool ArePrimitveTypesEquivalentSize(TypeDesc type1, TypeDesc type2)
{
Debug.Assert(type1.IsPrimitive && type2.IsPrimitive);
// Primitive types such as E_T_I4 and E_T_U4 are interchangeable
// Enums with interchangeable underlying types are interchangable
// BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2
// Float and double are not interchangable here.
int sourcePrimitiveTypeEquivalenceSize = type1.GetIntegralTypeMatchSize();
// Quick check to see if the first type can be matched.
if (sourcePrimitiveTypeEquivalenceSize == 0)
{
return false;
}
int targetPrimitiveTypeEquivalenceSize = type2.GetIntegralTypeMatchSize();
return sourcePrimitiveTypeEquivalenceSize == targetPrimitiveTypeEquivalenceSize;
}
private static int GetIntegralTypeMatchSize(this TypeDesc type)
{
Debug.Assert(type.IsPrimitive);
switch (type.Category)
{
case TypeFlags.SByte:
case TypeFlags.Byte:
return 1;
case TypeFlags.UInt16:
case TypeFlags.Int16:
return 2;
case TypeFlags.Int32:
case TypeFlags.UInt32:
return 4;
case TypeFlags.Int64:
case TypeFlags.UInt64:
return 8;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return type.Context.Target.PointerSize;
default:
return 0;
}
}
private static bool CanCastToClassOrInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType.IsInterface)
{
return thisType.CanCastToInterface(otherType, protect);
}
else
{
return thisType.CanCastToClass(otherType, protect);
}
}
private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (!otherType.HasVariance)
{
return thisType.CanCastToNonVariantInterface(otherType,protect);
}
else
{
if (thisType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
}
}
return false;
}
private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType == thisType)
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType == otherType)
{
return true;
}
}
return false;
}
private static bool CanCastByVarianceToInterfaceOrDelegate(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protectInput)
{
if (!thisType.HasSameTypeDefinition(otherType))
{
return false;
}
var stackOverflowProtectKey = new CastingPair(thisType, otherType);
if (protectInput != null)
{
if (protectInput.Contains(stackOverflowProtectKey))
return false;
}
StackOverflowProtect protect = new StackOverflowProtect(stackOverflowProtectKey, protectInput);
Instantiation instantiationThis = thisType.Instantiation;
Instantiation instantiationTarget = otherType.Instantiation;
Instantiation instantiationOpen = thisType.GetTypeDefinition().Instantiation;
Debug.Assert(instantiationThis.Length == instantiationTarget.Length &&
instantiationThis.Length == instantiationOpen.Length);
for (int i = 0; i < instantiationThis.Length; i++)
{
TypeDesc arg = instantiationThis[i];
TypeDesc targetArg = instantiationTarget[i];
if (arg != targetArg)
{
GenericParameterDesc openArgType = (GenericParameterDesc)instantiationOpen[i];
switch (openArgType.Variance)
{
case GenericVariance.Covariant:
if (!arg.IsBoxedAndCanCastTo(targetArg, protect))
return false;
break;
case GenericVariance.Contravariant:
if (!targetArg.IsBoxedAndCanCastTo(arg, protect))
return false;
break;
default:
// non-variant
Debug.Assert(openArgType.Variance == GenericVariance.None);
return false;
}
}
}
return true;
}
private static bool CanCastToClass(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc curType = thisType;
// If the target type has variant type parameters, we take a slower path
if (curType.HasVariance)
{
// First chase inheritance hierarchy until we hit a class that only differs in its instantiation
do
{
if (curType == otherType)
{
return true;
}
if (curType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
curType = curType.BaseType;
}
while (curType != null);
}
else
{
// If there are no variant type parameters, just chase the hierarchy
// Allow curType to be nullable, which means this method
// will additionally return true if curType is Nullable<T> && (
// currType == otherType
// OR otherType is System.ValueType or System.Object)
// Always strip Nullable from the otherType, if present
if (otherType.IsNullable && !curType.IsNullable)
{
return thisType.CanCastTo(otherType.Instantiation[0]);
}
do
{
if (curType == otherType)
return true;
curType = curType.BaseType;
} while (curType != null);
}
return false;
}
private static bool IsBoxedAndCanCastTo(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc fromUnderlyingType = thisType.UnderlyingType;
if (fromUnderlyingType.IsObjRef)
{
return thisType.CanCastToInternal(otherType, protect);
}
else if (thisType.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)thisType;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(otherType, protect);
}
}
return false;
}
private class StackOverflowProtect
{
private CastingPair _value;
private StackOverflowProtect _previous;
public StackOverflowProtect(CastingPair value, StackOverflowProtect previous)
{
_value = value;
_previous = previous;
}
public bool Contains(CastingPair value)
{
for (var current = this; current != null; current = current._previous)
if (current._value.Equals(value))
return true;
return false;
}
}
private struct CastingPair
{
public readonly TypeDesc FromType;
public readonly TypeDesc ToType;
public CastingPair(TypeDesc fromType, TypeDesc toType)
{
FromType = fromType;
ToType = toType;
}
public bool Equals(CastingPair other) => FromType == other.FromType && ToType == other.ToType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Umbraco.Core;
using Umbraco.Core.Dynamics;
using Umbraco.Core.IO;
using Umbraco.Core.Profiling;
using Umbraco.Web.Mvc;
using umbraco;
using umbraco.cms.businesslogic.member;
namespace Umbraco.Web
{
/// <summary>
/// HtmlHelper extensions for use in templates
/// </summary>
public static class HtmlHelperRenderExtensions
{
/// <summary>
/// Renders the markup for the profiler
/// </summary>
/// <param name="helper"></param>
/// <returns></returns>
public static IHtmlString RenderProfiler(this HtmlHelper helper)
{
return new HtmlString(ProfilerResolver.Current.Profiler.Render());
}
/// <summary>
/// Renders a partial view that is found in the specified area
/// </summary>
/// <param name="helper"></param>
/// <param name="partial"></param>
/// <param name="area"></param>
/// <param name="model"></param>
/// <param name="viewData"></param>
/// <returns></returns>
public static MvcHtmlString AreaPartial(this HtmlHelper helper, string partial, string area, object model = null, ViewDataDictionary viewData = null)
{
var originalArea = helper.ViewContext.RouteData.DataTokens["area"];
helper.ViewContext.RouteData.DataTokens["area"] = area;
var result = helper.Partial(partial, model, viewData);
helper.ViewContext.RouteData.DataTokens["area"] = originalArea;
return result;
}
/// <summary>
/// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are
/// using does not inherit from UmbracoTemplatePage
/// </summary>
/// <param name="helper"></param>
/// <returns></returns>
/// <remarks>
/// See: http://issues.umbraco.org/issue/U4-1614
/// </remarks>
public static MvcHtmlString PreviewBadge(this HtmlHelper helper)
{
if (UmbracoContext.Current.InPreviewMode)
{
var htmlBadge =
String.Format(UmbracoSettings.PreviewBadge,
IOHelper.ResolveUrl(SystemDirectories.Umbraco),
IOHelper.ResolveUrl(SystemDirectories.UmbracoClient),
UmbracoContext.Current.HttpContext.Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path));
return new MvcHtmlString(htmlBadge);
}
return new MvcHtmlString("");
}
public static IHtmlString CachedPartial(
this HtmlHelper htmlHelper,
string partialViewName,
object model,
int cachedSeconds,
bool cacheByPage = false,
bool cacheByMember = false,
ViewDataDictionary viewData = null)
{
var cacheKey = new StringBuilder(partialViewName);
if (cacheByPage)
{
if (UmbracoContext.Current == null)
{
throw new InvalidOperationException("Cannot cache by page if the UmbracoContext has not been initialized, this parameter can only be used in the context of an Umbraco request");
}
cacheKey.AppendFormat("{0}-", UmbracoContext.Current.PageId);
}
if (cacheByMember)
{
var currentMember = Member.GetCurrentMember();
cacheKey.AppendFormat("m{0}-", currentMember == null ? 0 : currentMember.Id);
}
return ApplicationContext.Current.ApplicationCache.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData);
}
public static MvcHtmlString EditorFor<T>(this HtmlHelper htmlHelper, string templateName = "", string htmlFieldName = "", object additionalViewData = null)
where T : new()
{
var model = new T();
var typedHelper = new HtmlHelper<T>(
htmlHelper.ViewContext.CopyWithModel(model),
htmlHelper.ViewDataContainer.CopyWithModel(model));
return typedHelper.EditorFor(x => model, templateName, htmlFieldName, additionalViewData);
}
/// <summary>
/// A validation summary that lets you pass in a prefix so that the summary only displays for elements
/// containing the prefix. This allows you to have more than on validation summary on a page.
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="prefix"></param>
/// <param name="excludePropertyErrors"></param>
/// <param name="message"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper,
string prefix = "",
bool excludePropertyErrors = false,
string message = "",
IDictionary<string, object> htmlAttributes = null)
{
if (prefix.IsNullOrWhiteSpace())
{
return htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes);
}
//if there's a prefix applied, we need to create a new html helper with a filtered ModelState collection so that it only looks for
//specific model state with the prefix.
var filteredHtmlHelper = new HtmlHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer.FilterContainer(prefix));
return filteredHtmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes);
}
/// <summary>
/// Returns the result of a child action of a strongly typed SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="actionName"></param>
/// <returns></returns>
public static IHtmlString Action<T>(this HtmlHelper htmlHelper, string actionName)
where T : SurfaceController
{
return htmlHelper.Action(actionName, typeof(T));
}
/// <summary>
/// Returns the result of a child action of a SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="actionName"></param>
/// <param name="surfaceType"></param>
/// <returns></returns>
public static IHtmlString Action(this HtmlHelper htmlHelper, string actionName, Type surfaceType)
{
Mandate.ParameterNotNull(surfaceType, "surfaceType");
Mandate.ParameterNotNullOrEmpty(actionName, "actionName");
var routeVals = new RouteValueDictionary(new {area = ""});
var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
.SingleOrDefault(x => x == surfaceType);
if (surfaceController == null)
throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
var metaData = PluginController.GetMetadata(surfaceController);
if (!metaData.AreaName.IsNullOrWhiteSpace())
{
//set the area to the plugin area
routeVals.Add("area", metaData.AreaName);
}
return htmlHelper.Action(actionName, metaData.ControllerName, routeVals);
}
#region BeginUmbracoForm
/// <summary>
/// Used for rendering out the Form for BeginUmbracoForm
/// </summary>
internal class UmbracoForm : MvcForm
{
/// <summary>
/// Creates an UmbracoForm
/// </summary>
/// <param name="viewContext"></param>
/// <param name="controllerName"></param>
/// <param name="controllerAction"></param>
/// <param name="area"></param>
/// <param name="method"></param>
/// <param name="additionalRouteVals"></param>
public UmbracoForm(
ViewContext viewContext,
string controllerName,
string controllerAction,
string area,
FormMethod method,
object additionalRouteVals = null)
: base(viewContext)
{
_viewContext = viewContext;
_method = method;
_encryptedString = UmbracoHelper.CreateEncryptedRouteString(controllerName, controllerAction, area, additionalRouteVals);
}
private readonly ViewContext _viewContext;
private readonly FormMethod _method;
private bool _disposed;
private readonly string _encryptedString;
protected override void Dispose(bool disposing)
{
if (this._disposed)
return;
this._disposed = true;
//write out the hidden surface form routes
_viewContext.Writer.Write("<input name='ufprt' type='hidden' value='" + _encryptedString + "' />");
base.Dispose(disposing);
}
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, FormMethod method)
{
return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName)
{
return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, FormMethod method)
{
return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals)
{
return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName,
object additionalRouteVals,
object htmlAttributes,
FormMethod method)
{
return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, htmlAttributes.ToDictionary<object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName,
object additionalRouteVals,
object htmlAttributes)
{
return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, htmlAttributes.ToDictionary<object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes,
FormMethod method)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes, method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, FormMethod method)
{
return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType)
{
return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, FormMethod method)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T));
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals, FormMethod method)
{
return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals)
{
return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, FormMethod method)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals,
object htmlAttributes,
FormMethod method)
{
return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes.ToDictionary<object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals,
object htmlAttributes)
{
return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes.ToDictionary<object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action,
object additionalRouteVals,
object htmlAttributes,
FormMethod method)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action,
object additionalRouteVals,
object htmlAttributes)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes,
FormMethod method)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNull(surfaceType, "surfaceType");
var area = "";
var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
.SingleOrDefault(x => x == surfaceType);
if (surfaceController == null)
throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
var metaData = PluginController.GetMetadata(surfaceController);
if (metaData.AreaName.IsNullOrWhiteSpace() == false)
{
//set the area to the plugin area
area = metaData.AreaName;
}
return html.BeginUmbracoForm(action, metaData.ControllerName, area, additionalRouteVals, htmlAttributes, method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="surfaceType">The surface controller to route to</param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes)
{
return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes, FormMethod.Post);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes,
FormMethod method)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes)
where T : SurfaceController
{
return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, FormMethod method)
{
return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>(), method);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area)
{
return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>());
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <param name="method"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes,
FormMethod method)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
var formAction = UmbracoContext.Current.OriginalRequestUrl.PathAndQuery;
return html.RenderForm(formAction, method, htmlAttributes, controllerName, action, area, additionalRouteVals);
}
/// <summary>
/// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
/// </summary>
/// <param name="html"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area,
object additionalRouteVals,
IDictionary<string, object> htmlAttributes)
{
return html.BeginUmbracoForm(action, controllerName, area, additionalRouteVals, htmlAttributes, FormMethod.Post);
}
/// <summary>
/// This renders out the form for us
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="formAction"></param>
/// <param name="method"></param>
/// <param name="htmlAttributes"></param>
/// <param name="surfaceController"></param>
/// <param name="surfaceAction"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
/// <remarks>
/// This code is pretty much the same as the underlying MVC code that writes out the form
/// </remarks>
private static MvcForm RenderForm(this HtmlHelper htmlHelper,
string formAction,
FormMethod method,
IDictionary<string, object> htmlAttributes,
string surfaceController,
string surfaceAction,
string area,
object additionalRouteVals = null)
{
//ensure that the multipart/form-data is added to the html attributes
if (htmlAttributes.ContainsKey("enctype") == false)
{
htmlAttributes.Add("enctype", "multipart/form-data");
}
var tagBuilder = new TagBuilder("form");
tagBuilder.MergeAttributes(htmlAttributes);
// action is implicitly generated, so htmlAttributes take precedence.
tagBuilder.MergeAttribute("action", formAction);
// method is an explicit parameter, so it takes precedence over the htmlAttributes.
tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
var traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled && htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled == false;
if (traditionalJavascriptEnabled)
{
// forms must have an ID for client validation
tagBuilder.GenerateId("form" + Guid.NewGuid().ToString("N"));
}
htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
//new UmbracoForm:
var theForm = new UmbracoForm(htmlHelper.ViewContext, surfaceController, surfaceAction, area, method, additionalRouteVals);
if (traditionalJavascriptEnabled)
{
htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
}
return theForm;
}
#endregion
#region Wrap
public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, params IHtmlTagWrapper[] children)
{
var item = html.Wrap(tag, innerText, (object)null);
foreach (var child in children)
{
item.AddChild(child);
}
return item;
}
public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner, object anonymousAttributes, params IHtmlTagWrapper[] children)
{
string innerText = null;
if (inner != null && inner.GetType() != typeof(DynamicNull))
{
innerText = string.Format("{0}", inner);
}
var item = html.Wrap(tag, innerText, anonymousAttributes);
foreach (var child in children)
{
item.AddChild(child);
}
return item;
}
public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner)
{
string innerText = null;
if (inner != null && inner.GetType() != typeof(DynamicNull))
{
innerText = string.Format("{0}", inner);
}
return html.Wrap(tag, innerText, (object)null);
}
public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children)
{
var wrap = new HtmlTagWrapper(tag);
if (anonymousAttributes != null)
{
wrap.ReflectAttributesFromAnonymousType(anonymousAttributes);
}
if (!string.IsNullOrWhiteSpace(innerText))
{
wrap.AddChild(new HtmlTagWrapperTextNode(innerText));
}
foreach (var child in children)
{
wrap.AddChild(child);
}
return wrap;
}
public static HtmlTagWrapper Wrap(this HtmlHelper html, bool visible, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children)
{
var item = html.Wrap(tag, innerText, anonymousAttributes, children);
item.Visible = visible;
foreach (var child in children)
{
item.AddChild(child);
}
return item;
}
#endregion
}
}
| |
using J2N.Threading;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.TestFramework;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Base test class for testing Unicode collation.
/// </summary>
public abstract class CollationTestBase : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
{
public CollationTestBase(BeforeAfterClass beforeAfter)
: base(beforeAfter)
{
}
#else
{
#endif
protected string m_firstRangeBeginningOriginal = "\u062F";
protected string m_firstRangeEndOriginal = "\u0698";
protected string m_secondRangeBeginningOriginal = "\u0633";
protected string m_secondRangeEndOriginal = "\u0638";
// LUCENENET: The all locales may are not available for collation.
// LUCENENET: Removed this (only) reference to the ICU library, since it has a lot of data and we don't
// want to unnecessarily reference it in all test projects.
//protected readonly string[] availableCollationLocales = RuleBasedCollator.GetAvailableCollationLocales().ToArray();
/// <summary>
/// Convenience method to perform the same function as CollationKeyFilter.
/// </summary>
/// <param name="keyBits"> the result from
/// <c>collator.GetCollationKey(original).ToByteArray()</c></param>
/// <returns> The encoded collation key for the original string.</returns>
[Obsolete("only for testing deprecated filters")]
protected virtual string EncodeCollationKey(byte[] keyBits)
{
// Ensure that the backing char[] array is large enough to hold the encoded
// Binary String
int encodedLength = IndexableBinaryStringTools.GetEncodedLength(keyBits, 0, keyBits.Length);
char[] encodedBegArray = new char[encodedLength];
IndexableBinaryStringTools.Encode(keyBits, 0, keyBits.Length, encodedBegArray, 0, encodedLength);
return new string(encodedBegArray);
}
public virtual void TestFarsiRangeFilterCollating(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
using (Directory dir = NewDirectory())
{
using (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer)))
{
Document doc = new Document();
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
doc.Add(new StringField("body", "body", Field.Store.YES));
writer.AddDocument(doc);
} // writer.Dispose();
using (IndexReader reader = DirectoryReader.Open(dir))
{
IndexSearcher searcher = new IndexSearcher(reader);
Search.Query query = new TermQuery(new Term("body", "body"));
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeFilter with a Farsi
// Collator (or an Arabic one for the case when Farsi searcher not
// supported).
ScoreDoc[] result = searcher.Search(query, new TermRangeFilter("content", firstBeg, firstEnd, true, true), 1).ScoreDocs;
Assert.AreEqual(0, result.Length, "The index Term should not be included.");
result = searcher.Search(query, new TermRangeFilter("content", secondBeg, secondEnd, true, true), 1).ScoreDocs;
Assert.AreEqual(1, result.Length, "The index Term should be included.");
} // reader.Dispose();
} // dir.Dispose();
}
public virtual void TestFarsiRangeQueryCollating(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
using (Directory dir = NewDirectory())
{
using (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer)))
{
Document doc = new Document();
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeQuery with a Farsi
// Collator (or an Arabic one for the case when Farsi is not supported).
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
writer.AddDocument(doc);
} // writer.Dispose();
using (IndexReader reader = DirectoryReader.Open(dir))
{
IndexSearcher searcher = new IndexSearcher(reader);
Search.Query query = new TermRangeQuery("content", firstBeg, firstEnd, true, true);
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "The index Term should not be included.");
query = new TermRangeQuery("content", secondBeg, secondEnd, true, true);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "The index Term should be included.");
} // reader.Dispose();
} // dir.Dispose();
}
public virtual void TestFarsiTermRangeQuery(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
using (Directory farsiIndex = NewDirectory())
{
using (IndexWriter writer = new IndexWriter(farsiIndex, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer)))
{
Document doc = new Document();
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
doc.Add(new StringField("body", "body", Field.Store.YES));
writer.AddDocument(doc);
} // writer.Dispose();
using (IndexReader reader = DirectoryReader.Open(farsiIndex))
{
IndexSearcher search = NewSearcher(reader);
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeQuery
// with a Farsi Collator (or an Arabic one for the case when Farsi is
// not supported).
Search.Query csrq = new TermRangeQuery("content", firstBeg, firstEnd, true, true);
ScoreDoc[] result = search.Search(csrq, null, 1000).ScoreDocs;
Assert.AreEqual(0, result.Length, "The index Term should not be included.");
csrq = new TermRangeQuery("content", secondBeg, secondEnd, true, true);
result = search.Search(csrq, null, 1000).ScoreDocs;
Assert.AreEqual(1, result.Length, "The index Term should be included.");
} // reader.Dispose();
} // farsiIndex.Dispose();
}
/// <summary>
/// Test using various international locales with accented characters (which
/// sort differently depending on locale).
/// </summary>
// Copied (and slightly modified) from
// Lucene.Net.Search.TestSort.TestInternationalSort()
//
// TODO: this test is really fragile. there are already 3 different cases,
// depending upon unicode version.
public virtual void TestCollationKeySort(Analyzer usAnalyzer,
Analyzer franceAnalyzer,
Analyzer swedenAnalyzer,
Analyzer denmarkAnalyzer,
string usResult,
string frResult,
string svResult,
string dkResult)
{
using (Directory indexStore = NewDirectory())
{
using (IndexWriter writer = new IndexWriter(indexStore, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false))))
{
// document data:
// the tracer field is used to determine which document was hit
string[][] sortData = new string[][] { new string[] { "A", "x", "p\u00EAche", "p\u00EAche", "p\u00EAche", "p\u00EAche" }, new string[] { "B", "y", "HAT", "HAT", "HAT", "HAT" }, new string[] { "C", "x", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9" }, new string[] { "D", "y", "HUT", "HUT", "HUT", "HUT" }, new string[] { "E", "x", "peach", "peach", "peach", "peach" }, new string[] { "F", "y", "H\u00C5T", "H\u00C5T", "H\u00C5T", "H\u00C5T" }, new string[] { "G", "x", "sin", "sin", "sin", "sin" }, new string[] { "H", "y", "H\u00D8T", "H\u00D8T", "H\u00D8T", "H\u00D8T" }, new string[] { "I", "x", "s\u00EDn", "s\u00EDn", "s\u00EDn", "s\u00EDn" }, new string[] { "J", "y", "HOT", "HOT", "HOT", "HOT" } };
FieldType customType = new FieldType();
customType.IsStored = true;
for (int i = 0; i < sortData.Length; ++i)
{
Document doc = new Document();
doc.Add(new Field("tracer", sortData[i][0], customType));
doc.Add(new TextField("contents", sortData[i][1], Field.Store.NO));
if (sortData[i][2] != null)
{
doc.Add(new TextField("US", usAnalyzer.GetTokenStream("US", new StringReader(sortData[i][2]))));
}
if (sortData[i][3] != null)
{
doc.Add(new TextField("France", franceAnalyzer.GetTokenStream("France", new StringReader(sortData[i][3]))));
}
if (sortData[i][4] != null)
{
doc.Add(new TextField("Sweden", swedenAnalyzer.GetTokenStream("Sweden", new StringReader(sortData[i][4]))));
}
if (sortData[i][5] != null)
{
doc.Add(new TextField("Denmark", denmarkAnalyzer.GetTokenStream("Denmark", new StringReader(sortData[i][5]))));
}
writer.AddDocument(doc);
}
writer.ForceMerge(1);
} // writer.Dispose();
using (IndexReader reader = DirectoryReader.Open(indexStore))
{
IndexSearcher searcher = new IndexSearcher(reader);
Sort sort = new Sort();
Search.Query queryX = new TermQuery(new Term("contents", "x"));
Search.Query queryY = new TermQuery(new Term("contents", "y"));
sort.SetSort(new SortField("US", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, usResult);
sort.SetSort(new SortField("France", SortFieldType.STRING));
this.AssertMatches(searcher, queryX, sort, frResult);
sort.SetSort(new SortField("Sweden", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, svResult);
sort.SetSort(new SortField("Denmark", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, dkResult);
} // reader.Dispose();
} // indexStore.Dispose();
}
/// <summary>
/// Make sure the documents returned by the search match the expected list
/// </summary>
// Copied from TestSort.java
private void AssertMatches(IndexSearcher searcher, Search.Query query, Sort sort, string expectedResult)
{
ScoreDoc[] result = searcher.Search(query, null, 1000, sort).ScoreDocs;
StringBuilder buff = new StringBuilder(10);
int n = result.Length;
for (int i = 0; i < n; ++i)
{
Document doc = searcher.Doc(result[i].Doc);
IIndexableField[] v = doc.GetFields("tracer");
for (var j = 0; j < v.Length; ++j)
{
buff.Append(v[j].GetStringValue());
}
}
Assert.AreEqual(expectedResult, buff.ToString());
}
public virtual void AssertThreadSafe(Analyzer analyzer)
{
int numTestPoints = 100;
int numThreads = TestUtil.NextInt32(Random, 3, 5);
Dictionary<string, BytesRef> map = new Dictionary<string, BytesRef>();
// create a map<String,SortKey> up front.
// then with multiple threads, generate sort keys for all the keys in the map
// and ensure they are the same as the ones we produced in serial fashion.
for (int i = 0; i < numTestPoints; i++)
{
string term = TestUtil.RandomSimpleString(Random);
IOException priorException = null;
TokenStream ts = analyzer.GetTokenStream("fake", new StringReader(term));
try
{
ITermToBytesRefAttribute termAtt = ts.AddAttribute<ITermToBytesRefAttribute>();
BytesRef bytes = termAtt.BytesRef;
ts.Reset();
Assert.IsTrue(ts.IncrementToken());
termAtt.FillBytesRef();
// ensure we make a copy of the actual bytes too
map[term] = BytesRef.DeepCopyOf(bytes);
Assert.IsFalse(ts.IncrementToken());
ts.End();
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
ThreadJob[] threads = new ThreadJob[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper(this, analyzer, map);
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
}
private class ThreadAnonymousInnerClassHelper : ThreadJob
{
private readonly CollationTestBase outerInstance;
private Analyzer analyzer;
private IDictionary<string, BytesRef> map;
public ThreadAnonymousInnerClassHelper(CollationTestBase outerInstance, Analyzer analyzer, IDictionary<string, BytesRef> map)
{
this.outerInstance = outerInstance;
this.analyzer = analyzer;
this.map = map;
}
public override void Run()
{
try
{
foreach (var mapping in this.map)
{
string term = mapping.Key;
BytesRef expected = mapping.Value;
IOException priorException = null;
TokenStream ts = this.analyzer.GetTokenStream("fake", new StringReader(term));
try
{
ITermToBytesRefAttribute termAtt = ts.AddAttribute<ITermToBytesRefAttribute>();
BytesRef bytes = termAtt.BytesRef;
ts.Reset();
Assert.IsTrue(ts.IncrementToken());
termAtt.FillBytesRef();
Assert.AreEqual(expected, bytes);
Assert.IsFalse(ts.IncrementToken());
ts.End();
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
}
catch (IOException e)
{
throw (Exception)e;
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Routing;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
using Umbraco.Cms.Infrastructure.PublishedCache;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Published;
using Umbraco.Cms.Tests.UnitTests.TestHelpers;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Routing
{
[TestFixture]
public class GetContentUrlsTests : PublishedSnapshotServiceTestBase
{
private WebRoutingSettings _webRoutingSettings;
private RequestHandlerSettings _requestHandlerSettings;
[SetUp]
public override void Setup()
{
base.Setup();
_webRoutingSettings = new WebRoutingSettings();
_requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true };
GlobalSettings.HideTopLevelNodeFromPath = false;
string xml = PublishedContentXml.BaseWebTestXml(1234);
IEnumerable<ContentNodeKit> kits = PublishedContentXmlAdapter.GetContentNodeKits(
xml,
TestHelper.ShortStringHelper,
out ContentType[] contentTypes,
out DataType[] dataTypes).ToList();
InitializedCache(kits, contentTypes, dataTypes: dataTypes);
}
private ILocalizedTextService GetTextService()
{
var textService = new Mock<ILocalizedTextService>();
textService.Setup(x => x.Localize(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<CultureInfo>(),
It.IsAny<IDictionary<string, string>>()
))
.Returns((string key, string alias, CultureInfo culture, IDictionary<string, string> args)
=> $"{key}/{alias}");
return textService.Object;
}
private ILocalizationService GetLangService(params string[] isoCodes)
{
var allLangs = isoCodes
.Select(CultureInfo.GetCultureInfo)
.Select(culture => new Language(GlobalSettings, culture.Name)
{
CultureName = culture.DisplayName,
IsDefault = true,
IsMandatory = true
}).ToArray();
var langServiceMock = new Mock<ILocalizationService>();
langServiceMock.Setup(x => x.GetAllLanguages()).Returns(allLangs);
langServiceMock.Setup(x => x.GetDefaultLanguageIsoCode()).Returns(allLangs.First(x=>x.IsDefault).IsoCode);
return langServiceMock.Object;
}
[Test]
public async Task Content_Not_Published()
{
var contentType = ContentTypeBuilder.CreateBasicContentType();
var content = ContentBuilder.CreateBasicContent(contentType);
content.Id = 1046; // FIXME: we are using this ID only because it's built into the test XML published cache
content.Path = "-1,1046";
var umbracoContextAccessor = GetUmbracoContextAccessor("http://localhost:8000");
var publishedRouter = CreatePublishedRouter(
umbracoContextAccessor,
new[] { new ContentFinderByUrl(Mock.Of<ILogger<ContentFinderByUrl>>(), umbracoContextAccessor) });
var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();
UrlProvider urlProvider = GetUrlProvider(umbracoContextAccessor, _requestHandlerSettings, _webRoutingSettings, out UriUtility uriUtility);
var urls = (await content.GetContentUrlsAsync(
publishedRouter,
umbracoContext,
GetLangService("en-US", "fr-FR"),
GetTextService(),
Mock.Of<IContentService>(),
VariationContextAccessor,
Mock.Of<ILogger<IContent>>(),
uriUtility,
urlProvider)).ToList();
Assert.AreEqual(1, urls.Count);
Assert.AreEqual("content/itemNotPublished", urls[0].Text);
Assert.IsFalse(urls[0].IsUrl);
}
[Test]
public async Task Invariant_Root_Content_Published_No_Domains()
{
var contentType = ContentTypeBuilder.CreateBasicContentType();
var content = ContentBuilder.CreateBasicContent(contentType);
content.Id = 1046; // FIXME: we are using this ID only because it's built into the test XML published cache
content.Path = "-1,1046";
content.Published = true;
var umbracoContextAccessor = GetUmbracoContextAccessor("http://localhost:8000");
var publishedRouter = CreatePublishedRouter(
umbracoContextAccessor,
new[] { new ContentFinderByUrl(Mock.Of<ILogger<ContentFinderByUrl>>(), umbracoContextAccessor) });
var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();
UrlProvider urlProvider = GetUrlProvider(umbracoContextAccessor, _requestHandlerSettings, _webRoutingSettings, out UriUtility uriUtility);
var urls = (await content.GetContentUrlsAsync(
publishedRouter,
umbracoContext,
GetLangService("en-US", "fr-FR"),
GetTextService(),
Mock.Of<IContentService>(),
VariationContextAccessor,
Mock.Of<ILogger<IContent>>(),
uriUtility,
urlProvider)).ToList();
Assert.AreEqual(2, urls.Count);
var enUrl = urls.First(x => x.Culture == "en-US");
Assert.AreEqual("/home/", enUrl.Text);
Assert.AreEqual("en-US", enUrl.Culture);
Assert.IsTrue(enUrl.IsUrl);
var frUrl = urls.First(x => x.Culture == "fr-FR");
Assert.IsFalse(frUrl.IsUrl);
}
[Test]
public async Task Invariant_Child_Content_Published_No_Domains()
{
var contentType = ContentTypeBuilder.CreateBasicContentType();
var parent = ContentBuilder.CreateBasicContent(contentType);
parent.Id = 1046; // FIXME: we are using this ID only because it's built into the test XML published cache
parent.Name = "home";
parent.Path = "-1,1046";
parent.Published = true;
var child = ContentBuilder.CreateBasicContent(contentType);
child.Name = "sub1";
child.Id = 1173; // FIXME: we are using this ID only because it's built into the test XML published cache
child.Path = "-1,1046,1173";
child.Published = true;
var umbracoContextAccessor = GetUmbracoContextAccessor("http://localhost:8000");
var publishedRouter = CreatePublishedRouter(
umbracoContextAccessor,
new[] { new ContentFinderByUrl(Mock.Of<ILogger<ContentFinderByUrl>>(), umbracoContextAccessor) });
var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();
var localizationService = GetLangService("en-US", "fr-FR");
UrlProvider urlProvider = GetUrlProvider(umbracoContextAccessor, _requestHandlerSettings, _webRoutingSettings, out UriUtility uriUtility);
var urls = (await child.GetContentUrlsAsync(
publishedRouter,
umbracoContext,
localizationService,
GetTextService(),
Mock.Of<IContentService>(),
VariationContextAccessor,
Mock.Of<ILogger<IContent>>(),
uriUtility,
urlProvider)).ToList();
Assert.AreEqual(2, urls.Count);
var enUrl = urls.First(x => x.Culture == "en-US");
Assert.AreEqual("/home/sub1/", enUrl.Text);
Assert.AreEqual("en-US", enUrl.Culture);
Assert.IsTrue(enUrl.IsUrl);
var frUrl = urls.First(x => x.Culture == "fr-FR");
Assert.IsFalse(frUrl.IsUrl);
}
// TODO: We need a lot of tests here, the above was just to get started with being able to unit test this method
// * variant URLs without domains assigned, what happens?
// * variant URLs with domains assigned, but also having more languages installed than there are domains/cultures assigned
// * variant URLs with an ancestor culture unpublished
// * invariant URLs with ancestors as variants
// * ... probably a lot more
}
}
| |
using System;
using System.Globalization;
namespace Yarn
{
// A value from inside Yarn.
public class Value : IComparable, IComparable<Value> {
public static readonly Value NULL = new Value();
public enum Type {
Number, // a constant number
#pragma warning disable CA1720 // Identifier contains type name
String, // a string
#pragma warning restore CA1720 // Identifier contains type name
Bool, // a boolean value
Variable, // the name of a variable; will be expanded at runtime
Null, // the null value
}
public Value.Type type { get; internal set; }
// The underlying values for this object
internal float numberValue {get; private set;}
internal string variableName {get; set;}
internal string stringValue {get; private set;}
internal bool boolValue {get; private set;}
private object backingValue {
get {
switch( this.type ) {
case Type.Null: return null;
case Type.String: return this.stringValue;
case Type.Number: return this.numberValue;
case Type.Bool: return this.boolValue;
}
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, "Can't get good backing type for {0}", this.type)
);
}
}
public float AsNumber {
get {
switch (type) {
case Type.Number:
return numberValue;
case Type.String:
try {
return float.Parse (stringValue, CultureInfo.InvariantCulture);
} catch (FormatException) {
return 0.0f;
}
case Type.Bool:
return boolValue ? 1.0f : 0.0f;
case Type.Null:
return 0.0f;
default:
throw new InvalidOperationException ("Cannot cast to number from " + type.ToString());
}
}
}
public bool AsBool {
get {
switch (type) {
case Type.Number:
return !float.IsNaN(numberValue) && numberValue != 0.0f;
case Type.String:
return !String.IsNullOrEmpty(stringValue);
case Type.Bool:
return boolValue;
case Type.Null:
return false;
default:
throw new InvalidOperationException ("Cannot cast to bool from " + type.ToString());
}
}
}
public string AsString {
get {
switch (type) {
case Type.Number:
if (float.IsNaN(numberValue) ) {
return "NaN";
}
return numberValue.ToString (CultureInfo.InvariantCulture);
case Type.String:
return stringValue;
case Type.Bool:
return boolValue.ToString (CultureInfo.InvariantCulture);
case Type.Null:
return "null";
default:
throw new ArgumentOutOfRangeException ();
}
}
}
// Create a null value
public Value () : this(null) { }
// Create a value with a C# object
public Value (object value)
{
// Copy an existing value
if (typeof(Value).IsInstanceOfType(value)) {
var otherValue = value as Value;
type = otherValue.type;
switch (type) {
case Type.Number:
numberValue = otherValue.numberValue;
break;
case Type.String:
stringValue = otherValue.stringValue;
break;
case Type.Bool:
boolValue = otherValue.boolValue;
break;
case Type.Variable:
variableName = otherValue.variableName;
break;
case Type.Null:
break;
default:
throw new ArgumentOutOfRangeException ();
}
return;
}
if (value == null) {
type = Type.Null;
return;
}
if (value.GetType() == typeof(string) ) {
type = Type.String;
stringValue = System.Convert.ToString(value, CultureInfo.InvariantCulture);
return;
}
if (value.GetType() == typeof(int) ||
value.GetType() == typeof(float) ||
value.GetType() == typeof(double)) {
type = Type.Number;
numberValue = System.Convert.ToSingle(value, CultureInfo.InvariantCulture);
return;
}
if (value.GetType() == typeof(bool) ) {
type = Type.Bool;
boolValue = System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);
return;
}
var error = string.Format(CultureInfo.CurrentCulture, "Attempted to create a Value using a {0}; currently, " +
"Values can only be numbers, strings, bools or null.", value.GetType().Name);
throw new YarnException(error);
}
public virtual int CompareTo(object obj) {
if (obj == null) return 1;
// soft, fast coercion
var other = obj as Value;
// not a value
if( other == null ) throw new ArgumentException("Object is not a Value");
// it is a value!
return this.CompareTo(other);
}
public virtual int CompareTo(Value other) {
if (other == null) {
return 1;
}
if (other.type == this.type) {
switch (this.type) {
case Type.Null:
return 0;
case Type.String:
return string.Compare(this.stringValue, other.stringValue, StringComparison.InvariantCulture);
case Type.Number:
return this.numberValue.CompareTo (other.numberValue);
case Type.Bool:
return this.boolValue.CompareTo (other.boolValue);
}
}
// try to do a string test at that point!
return string.Compare(this.AsString, other.AsString, StringComparison.InvariantCulture);
}
public override bool Equals (object obj)
{
if (obj == null || GetType() != obj.GetType()) {
return false;
}
var other = (Value)obj;
switch (this.type) {
case Type.Number:
return this.AsNumber == other.AsNumber;
case Type.String:
return this.AsString == other.AsString;
case Type.Bool:
return this.AsBool == other.AsBool;
case Type.Null:
return other.type == Type.Null || other.AsNumber == 0 || other.AsBool == false;
default:
throw new ArgumentOutOfRangeException ();
}
}
// override object.GetHashCode
public override int GetHashCode()
{
var backing = this.backingValue;
// TODO: yeah hay maybe fix this
if( backing != null ) {
return backing.GetHashCode();
}
return 0;
}
public override string ToString ()
{
return string.Format (CultureInfo.CurrentCulture, "[Value: type={0}, AsNumber={1}, AsBool={2}, AsString={3}]", type, AsNumber, AsBool, AsString);
}
public static Value operator+ (Value a, Value b) {
// catches:
// undefined + string
// number + string
// string + string
// bool + string
// null + string
if (a.type == Type.String || b.type == Type.String ) {
// we're headed for string town!
return new Value( a.AsString + b.AsString );
}
// catches:
// number + number
// bool (=> 0 or 1) + number
// null (=> 0) + number
// bool (=> 0 or 1) + bool (=> 0 or 1)
// null (=> 0) + null (=> 0)
if ((a.type == Type.Number || b.type == Type.Number) ||
(a.type == Type.Bool && b.type == Type.Bool) ||
(a.type == Type.Null && b.type == Type.Null)
) {
return new Value( a.AsNumber + b.AsNumber );
}
throw new System.ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Cannot add types {0} and {1}.", a.type, b.type )
);
}
public static Value operator- (Value a, Value b) {
if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) ||
b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null)
) {
return new Value( a.AsNumber - b.AsNumber );
}
throw new System.ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Cannot subtract types {0} and {1}.", a.type, b.type )
);
}
public static Value operator* (Value a, Value b) {
if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) ||
b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null)
) {
return new Value( a.AsNumber * b.AsNumber );
}
throw new System.ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Cannot multiply types {0} and {1}.", a.type, b.type )
);
}
public static Value operator/ (Value a, Value b) {
if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) ||
b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null)
) {
return new Value( a.AsNumber / b.AsNumber );
}
throw new System.ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Cannot divide types {0} and {1}.", a.type, b.type )
);
}
public static Value operator %(Value a, Value b) {
if (a.type == Type.Number && (b.type == Type.Number || b.type == Type.Null) ||
b.type == Type.Number && (a.type == Type.Number || a.type == Type.Null)) {
return new Value (a.AsNumber % b.AsNumber);
}
throw new System.ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Cannot modulo types {0} and {1}.", a.type, b.type )
);
}
public static Value operator- (Value a) {
if( a.type == Type.Number ) {
return new Value( -a.AsNumber );
}
if (a.type == Type.Null &&
a.type == Type.String &&
(a.AsString == null || a.AsString.Trim() == "")
) {
return new Value( -0 );
}
return new Value( float.NaN );
}
// Define the is greater than operator.
public static bool operator > (Value operand1, Value operand2)
{
return operand1.CompareTo(operand2) == 1;
}
// Define the is less than operator.
public static bool operator < (Value operand1, Value operand2)
{
return operand1.CompareTo(operand2) == -1;
}
// Define the is greater than or equal to operator.
public static bool operator >= (Value operand1, Value operand2)
{
return operand1.CompareTo(operand2) >= 0;
}
// Define the is less than or equal to operator.
public static bool operator <= (Value operand1, Value operand2)
{
return operand1.CompareTo(operand2) <= 0;
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Roton.Emulation.Actions;
using Roton.Emulation.Cheats;
using Roton.Emulation.Commands;
using Roton.Emulation.Conditions;
using Roton.Emulation.Data;
using Roton.Emulation.Data.Impl;
using Roton.Emulation.Directions;
using Roton.Emulation.Draws;
using Roton.Emulation.Infrastructure;
using Roton.Emulation.Interactions;
using Roton.Emulation.Items;
using Roton.Emulation.Targets;
using Roton.Infrastructure.Impl;
namespace Roton.Emulation.Core.Impl
{
[Context(Context.Original)]
[Context(Context.Super)]
public sealed class Engine : IEngine, IDisposable
{
private readonly Lazy<IActionList> _actionList;
private readonly Lazy<IActors> _actors;
private readonly Lazy<IAlerts> _alerts;
private readonly Lazy<IBoard> _board;
private readonly Lazy<IBoards> _boards;
private readonly Lazy<ICheatList> _cheats;
private readonly Lazy<IClock> _clock;
private readonly Lazy<IColors> _colors;
private readonly Lazy<ICommandList> _commands;
private readonly Lazy<IConditionList> _conditions;
private readonly Lazy<IConfig> _config;
private readonly Lazy<IDirectionList> _directions;
private readonly Lazy<IDrawList> _drawList;
private readonly Lazy<IElementList> _elements;
private readonly Lazy<IFacts> _facts;
private readonly Lazy<IMemory> _memory;
private readonly Lazy<IHeap> _heap;
private readonly Lazy<IAnsiKeyTransformer> _ansiKeyTransformer;
private readonly Lazy<IScrollFormatter> _scrollFormatter;
private readonly Lazy<ISpeaker> _speaker;
private readonly Lazy<IDrumBank> _drumBank;
private readonly Lazy<IObjectMover> _objectMover;
private readonly Lazy<IMusicEncoder> _musicEncoder;
private readonly Lazy<IHighScoreListFactory> _highScoreListFactory;
private readonly Lazy<IConfigFileService> _configFileService;
private readonly Lazy<IFileDialog> _fileDialog;
private readonly Lazy<ITracer> _tracer;
private readonly Lazy<IFeatures> _features;
private readonly Lazy<IFileSystem> _fileSystem;
private readonly Lazy<IGameSerializer> _gameSerializer;
private readonly Lazy<IHud> _hud;
private readonly Lazy<IInteractionList> _interactionList;
private readonly Lazy<IInterpreter> _interpreter;
private readonly Lazy<IItemList> _items;
private readonly Lazy<IKeyboard> _keyboard;
private readonly Lazy<IParser> _parser;
private readonly Lazy<IRandomizer> _randomizer;
private readonly Lazy<ISounds> _sounds;
private readonly Lazy<IState> _state;
private readonly Lazy<ITargetList> _targets;
private readonly Lazy<ITiles> _tiles;
private readonly Lazy<ITimers> _timers;
private readonly Lazy<IWorld> _world;
private int _ticksToRun;
private bool _step;
public Engine(Lazy<IClockFactory> clockFactory, Lazy<IActors> actors, Lazy<IAlerts> alerts, Lazy<IBoard> board,
Lazy<IFileSystem> fileSystem, Lazy<IElementList> elements,
Lazy<IInterpreter> interpreter, Lazy<IRandomizer> randomizer, Lazy<IKeyboard> keyboard,
Lazy<ITiles> tiles, Lazy<ISounds> sounds, Lazy<ITimers> timers, Lazy<IParser> parser,
Lazy<IConfig> config, Lazy<IConditionList> conditions, Lazy<IDirectionList> directions,
Lazy<IColors> colors, Lazy<ICheatList> cheats, Lazy<ICommandList> commands, Lazy<ITargetList> targets,
Lazy<IFeatures> features, Lazy<IGameSerializer> gameSerializer, Lazy<IHud> hud, Lazy<IState> state,
Lazy<IWorld> world, Lazy<IItemList> items, Lazy<IBoards> boards, Lazy<IActionList> actionList,
Lazy<IDrawList> drawList, Lazy<IInteractionList> interactionList, Lazy<IFacts> facts, Lazy<IMemory> memory,
Lazy<IHeap> heap, Lazy<IAnsiKeyTransformer> ansiKeyTransformer, Lazy<IScrollFormatter> scrollFormatter,
Lazy<ISpeaker> speaker, Lazy<IDrumBank> drumBank, Lazy<IObjectMover> objectMover, Lazy<IMusicEncoder> musicEncoder,
Lazy<IHighScoreListFactory> highScoreListFactory, Lazy<IConfigFileService> configFileService,
Lazy<IFileDialog> fileDialog, Lazy<ITracer> tracer)
{
_clock = new Lazy<IClock>(() =>
{
var clock = clockFactory.Value.Create(
_config.Value.MasterClockNumerator,
_config.Value.MasterClockDenominator);
if (clock != null)
clock.OnTick += ClockTick;
return clock;
});
_actors = actors;
_alerts = alerts;
_board = board;
_fileSystem = fileSystem;
_elements = elements;
_interpreter = interpreter;
_randomizer = randomizer;
_keyboard = keyboard;
_tiles = tiles;
_sounds = sounds;
_timers = timers;
_parser = parser;
_config = config;
_conditions = conditions;
_directions = directions;
_colors = colors;
_cheats = cheats;
_commands = commands;
_targets = targets;
_features = features;
_gameSerializer = gameSerializer;
_hud = hud;
_state = state;
_world = world;
_items = items;
_boards = boards;
_actionList = actionList;
_drawList = drawList;
_interactionList = interactionList;
_facts = facts;
_memory = memory;
_heap = heap;
_ansiKeyTransformer = ansiKeyTransformer;
_scrollFormatter = scrollFormatter;
_speaker = speaker;
_drumBank = drumBank;
_objectMover = objectMover;
_musicEncoder = musicEncoder;
_highScoreListFactory = highScoreListFactory;
_configFileService = configFileService;
_fileDialog = fileDialog;
_tracer = tracer;
}
private void ClockTick(object sender, EventArgs args)
{
if (_ticksToRun < 3) _ticksToRun++;
if (!ThreadActive)
Clock.Stop();
}
private IHighScoreListFactory HighScoreListFactory => _highScoreListFactory.Value;
private IObjectMover ObjectMover => _objectMover.Value;
public IMusicEncoder MusicEncoder => _musicEncoder.Value;
private IClock Clock => _clock.Value;
private IBoards Boards => _boards.Value;
private ITile BorderTile => State.BorderTile;
public IFileSystem Disk => _fileSystem.Value;
private IFeatures Features => _features.Value;
private ISpeaker Speaker => _speaker.Value;
public IGameSerializer GameSerializer => _gameSerializer.Value;
private IInterpreter Interpreter => _interpreter.Value;
private IKeyboard Keyboard => _keyboard.Value;
private IScrollFormatter ScrollFormatter => _scrollFormatter.Value;
public ITimers Timers => _timers.Value;
public IDrumBank DrumBank => _drumBank.Value;
private ITracer Tracer => _tracer.Value;
private Thread Thread { get; set; }
public bool ThreadActive => Thread != null || _step;
public int MemoryUsage => Features.BaseMemoryUsage + Heap.Size + Boards.Sum(b => b.Data.Length);
public void Cheat()
{
var cheatText = Hud.EnterCheat().ToUpper();
var clear = false;
if (!ThreadActive)
return;
if (!string.IsNullOrEmpty(cheatText))
{
if (cheatText[0] == '-')
{
cheatText = cheatText.Substring(1);
while (World.Flags.Contains(cheatText))
World.Flags.Remove(cheatText);
clear = true;
}
else if (cheatText[0] == '+')
{
cheatText = cheatText.Substring(1);
World.Flags.Add(cheatText);
}
}
var cheat = CheatList.Get(cheatText);
cheat?.Execute(cheatText, clear);
Hud.UpdateStatus();
// TODO: figure out the actual priority of this sound
PlaySound(3, Sounds.Cheat);
}
public void PlayStep()
{
if (State.GameOver || State.GameQuiet || State.SoundPlaying)
return;
Speaker.PlayStep();
}
public string GetHighScoreName(string fileName) => Features.GetHighScoreName(fileName);
public void ShowHighScores()
{
var list = HighScoreListFactory.Load();
if (list == null)
return;
Hud.ShowHighScores(list);
}
public IActionList ActionList
=> _actionList.Value;
public IActor ActorAt(IXyPair location)
{
return Actors
.FirstOrDefault(actor => actor.Location.X == location.X && actor.Location.Y == location.Y) ??
Actors[-1];
}
public int ActorIndexAt(IXyPair location)
{
var index = 0;
foreach (var actor in Actors)
{
if (actor.Location.X == location.X && actor.Location.Y == location.Y)
return index;
index++;
}
return -1;
}
public event EventHandler Exited;
public event EventHandler Tick;
public IActors Actors => _actors.Value;
public int Adjacent(IXyPair location, int id)
{
return (location.Y <= 1 || Tiles[location.Sum(Vector.North)].Id == id ? 1 : 0) |
(location.Y >= Tiles.Height || Tiles[location.Sum(Vector.South)].Id == id ? 2 : 0) |
(location.X <= 1 || Tiles[location.Sum(Vector.West)].Id == id ? 4 : 0) |
(location.X >= Tiles.Width || Tiles[location.Sum(Vector.East)].Id == id ? 8 : 0);
}
public IAlerts Alerts => _alerts.Value;
public void Attack(int index, IXyPair location)
{
if (index == 0 && World.EnergyCycles > 0)
{
World.Score += ElementAt(location).Points;
UpdateStatus();
}
else
{
Harm(index);
}
if (index > 0 && index <= State.ActIndex) State.ActIndex--;
if (Tiles[location].Id == ElementList.PlayerId && World.EnergyCycles > 0)
{
World.Score += ElementAt(Actors[index].Location).Points;
UpdateStatus();
}
else
{
Destroy(location);
PlaySound(2, Sounds.EnemySuicide);
}
}
public IBoard Board => _board.Value;
public bool BroadcastLabel(int sender, string label, bool force)
{
var external = false;
var success = false;
if (sender < 0)
{
external = true;
sender = -sender;
}
var info = new SearchContext
{
SearchIndex = 0,
SearchOffset = 0,
SearchTarget = label,
Index = sender
};
while (ExecuteLabel(sender, info, "\x000D:"))
{
if (!ActorIsLocked(info.SearchIndex) || force || sender == info.SearchIndex && !external)
{
if (sender == info.SearchIndex) success = true;
Actors[info.SearchIndex].Instruction = info.SearchOffset;
}
info.SearchTarget = label;
}
return success;
}
public ICheatList CheatList => _cheats.Value;
public void CleanUpPassageMovement() => Features.CleanUpPassageMovement();
public void ClearForest(IXyPair location) => Features.ClearForest(location);
public void ClearSound()
{
State.SoundPlaying = false;
Speaker.StopNote();
}
public void ClearWorld()
{
State.BoardCount = 0;
Boards.Clear();
Alerts.Reset();
ClearBoard();
Boards.Add(new PackedBoard(GameSerializer.PackBoard(Tiles)));
World.BoardIndex = 0;
World.Ammo = Facts.DefaultAmmo;
World.Gems = Facts.DefaultGems;
World.Health = Facts.DefaultHealth;
World.EnergyCycles = Facts.DefaultEnergyCycles;
World.Torches = Facts.DefaultTorches;
World.TorchCycles = Facts.DefaultTorchCycles;
World.Score = Facts.DefaultScore;
World.TimePassed = Facts.DefaultTimePassed;
World.Stones = Facts.DefaultStones;
World.Keys.Clear();
World.Flags.Clear();
SetBoard(0);
Board.Name = Facts.DefaultBoardTitle;
World.Name = Facts.DefaultWorldTitle;
State.WorldFileName = string.Empty;
}
public IColors Colors => _colors.Value;
public ICommandList CommandList => _commands.Value;
public IConditionList ConditionList => _conditions.Value;
public IConfig Config => _config.Value;
public void Convey(IXyPair center, int direction)
{
int beginIndex;
int endIndex;
var surrounding = new ITile[8];
if (direction == 1)
{
beginIndex = 0;
endIndex = 8;
}
else
{
beginIndex = 7;
endIndex = -1;
}
var pushable = true;
for (var i = beginIndex; i != endIndex; i += direction)
{
surrounding[i] = Tiles[center.Sum(GetConveyorVector(i))].Clone();
var element = ElementList[surrounding[i].Id];
if (element.Id == ElementList.EmptyId)
pushable = true;
else if (!element.IsPushable)
pushable = false;
}
for (var i = beginIndex; i != endIndex; i += direction)
{
var element = ElementList[surrounding[i].Id];
if (pushable)
{
if (element.IsPushable)
{
var source = center.Sum(GetConveyorVector(i));
var target = center.Sum(GetConveyorVector((i + 8 - direction) % 8));
if (element.Cycle > -1)
{
var tile = Tiles[source];
var index = ActorIndexAt(source);
Tiles[source].CopyFrom(surrounding[i]);
Tiles[target].Id = ElementList.EmptyId;
MoveActor(index, target);
Tiles[source].CopyFrom(tile);
}
else
{
Tiles[target].CopyFrom(surrounding[i]);
UpdateBoard(target);
}
if (!ElementList[surrounding[(i + 8 + direction) % 8].Id].IsPushable)
{
Tiles[source].Id = ElementList.EmptyId;
UpdateBoard(source);
}
}
else
{
pushable = false;
}
}
else
{
if (element.Id == ElementList.EmptyId)
pushable = true;
}
}
}
public void Destroy(IXyPair location)
{
var index = ActorIndexAt(location);
if (index == -1)
RemoveItem(location);
else
Harm(index);
}
public IDirectionList DirectionList => _directions.Value;
public AnsiChar Draw(IXyPair location)
{
if (Board.IsDark && !ElementAt(location).IsAlwaysVisible &&
(World.TorchCycles <= 0 || Distance(Player.Location, location) >= Facts.TorchRadius) &&
!State.EditorMode)
return Facts.DarknessTile;
var tile = Tiles[location];
var element = ElementList[tile.Id];
var elementCount = ElementList.Count;
if (tile.Id == ElementList.EmptyId)
return Facts.EmptyTile;
if (element.HasDrawCode)
return DrawList.Get(tile.Id).Draw(location);
if (tile.Id < elementCount - 7) return new AnsiChar(element.Character, tile.Color);
return tile.Id != elementCount - 1
? new AnsiChar(tile.Color, ((tile.Id - (elementCount - 8)) << 4) | 0x0F)
: new AnsiChar(tile.Color, 0x0F);
}
public IDrawList DrawList => _drawList.Value;
public IElement ElementAt(IXyPair location) => ElementList[Tiles[location].Id];
public IElementList ElementList => _elements.Value;
public void EnterBoard() => Features.EnterBoard();
public void ExecuteCode(int index, IExecutable instructionSource, string name)
{
var context = new OopContext(index, instructionSource, name, this)
{
Moved = false,
Repeat = false,
Died = false,
Finished = false,
CommandsExecuted = 0
};
context.PreviousInstruction = context.Instruction;
while (true)
{
if (context.Instruction < 0)
break;
Tracer?.TraceOop(context);
context.NextLine = true;
context.PreviousInstruction = context.Instruction;
context.Command = ReadActorCodeByte(index, context);
switch (context.Command)
{
case 0x3A: // :
case 0x27: // '
case 0x40: // @
Parser.ReadLine(index, context);
break;
case 0x2F: // /
case 0x3F: // ?
if (context.Command == 0x2F)
context.Repeat = true;
var vector = Parser.GetDirection(context);
if (vector == null)
{
RaiseError("Bad direction");
break;
}
ObjectMover.ExecuteDirection(context, vector);
ReadActorCodeByte(index, context);
if (State.OopByte != 0x0D)
context.Instruction--;
context.Moved = true;
break;
case 0x23: // #
Interpreter.Execute(context);
break;
case 0x0D: // enter
if (context.Message.Count > 0)
context.Message.Add(string.Empty);
break;
case 0x00:
context.Finished = true;
break;
default:
context.Message.Add($"{context.Command.ToStringValue()}{Parser.ReadLine(context.Index, context)}");
break;
}
if (context.Finished ||
context.Moved ||
context.Repeat ||
context.Died ||
context.CommandsExecuted > 32)
break;
}
if (context.Repeat)
context.Instruction = context.PreviousInstruction;
if (State.OopByte == 0)
context.Instruction = -1;
if (context.Message.Count > 0)
ExecuteMessage(context);
if (context.Died)
ExecuteDeath(context);
}
public bool ExecuteLabel(int sender, ISearchContext context, string prefix)
{
var label = context.SearchTarget;
var success = false;
var split = label.IndexOf(':');
if (split > 0)
{
var target = label.Substring(0, split);
label = label.Substring(split + 1);
context.SearchTarget = target;
success = Parser.GetTarget(context);
}
else if (context.SearchIndex < sender)
{
context.SearchIndex = sender;
split = 0;
success = true;
}
while (true)
{
if (!success) break;
if (label.ToUpper() == Facts.RestartLabel)
{
context.SearchOffset = 0;
}
else
{
context.SearchOffset = Parser.Search(context.SearchIndex, 0, prefix + label);
if (context.SearchOffset < 0 && split > 0)
{
success = Parser.GetTarget(context);
continue;
}
}
success = context.SearchOffset >= 0;
break;
}
return success;
}
public bool ExecuteTransaction(IOopContext context, bool take)
{
// Does the item exist?
var item = Parser.GetItem(context);
if (item == null)
return false;
// Do we have a valid amount?
var amount = Parser.ReadNumber(context.Index, context);
if (amount <= 0)
return true;
// Modify value if we are taking.
if (take)
State.OopNumber = -State.OopNumber;
// Determine if the result will be in range.
var pendingAmount = item.Value + State.OopNumber;
if ((pendingAmount & 0xFFFF) >= 0x8000)
return true;
// Successful transaction.
item.Value = pendingAmount;
return false;
}
public IFacts Facts => _facts.Value;
public IHeap Heap => _heap.Value;
public IMemory Memory => _memory.Value;
public void StepOnce()
{
_step = true;
MainLoop(true);
_step = false;
}
public string[] GetMessageLines() => Features.GetMessageLines();
public void FadePurple()
{
FadeBoard(Facts.FadeTile);
Hud.RedrawBoard();
}
public bool FindTile(ITile kind, IXyPair location)
{
location.X++;
while (location.Y <= Tiles.Height)
{
while (location.X <= Tiles.Width)
{
var tile = Tiles[location];
if (tile.Id == kind.Id)
if (kind.Color == 0 || ColorMatch(Tiles[location]) == kind.Color)
return true;
location.X++;
}
location.X = 1;
location.Y++;
}
return false;
}
public void ForcePlayerColor(int index) => Features.ForcePlayerColor(index);
public IXyPair GetCardinalVector(int index) => new Vector(State.Vector4[index], State.Vector4[index + 4]);
public void HandlePlayerInput(IActor actor) => Features.HandlePlayerInput(actor);
public void Harm(int index)
{
var actor = Actors[index];
if (index == 0)
{
if (World.Health > 0)
{
World.Health -= Facts.HealthLostPerHit;
UpdateStatus();
SetMessage(Facts.ShortMessageDuration, Alerts.OuchMessage);
var color = Tiles[actor.Location].Color;
color &= 0x0F;
color |= 0x70;
Tiles[actor.Location].Color = color;
if (World.Health > 0)
{
World.TimePassed = 0;
if (Board.RestartOnZap)
{
PlaySound(4, Sounds.TimeOut);
Tiles[actor.Location].Id = ElementList.EmptyId;
UpdateBoard(actor.Location);
var oldLocation = actor.Location.Clone();
actor.Location.CopyFrom(Board.Entrance);
UpdateRadius(oldLocation, 0);
UpdateRadius(actor.Location, 0);
State.GamePaused = true;
}
PlaySound(4, Sounds.Ouch);
}
else
{
PlaySound(5, Sounds.GameOver);
}
}
}
else
{
var element = Tiles[actor.Location].Id;
if (element == ElementList.BulletId)
PlaySound(3, Sounds.BulletDie);
else if (element != ElementList.ObjectId) PlaySound(3, Sounds.EnemyDie);
RemoveActor(index);
}
}
public IHud Hud => _hud.Value;
public IInteractionList InteractionList => _interactionList.Value;
public IItemList ItemList => _items.Value;
private void ShowFormattedScroll(string error) => Hud.ShowScroll(false, "Roton Error", ScrollFormatter.Format(error));
public void LoadWorld(string name)
{
byte[] TryLoadWorld()
{
try
{
return Disk.GetFile(Features.GetWorldName(name));
}
catch (IOException e)
{
ShowFormattedScroll(e.ToString());
return new byte[0];
}
}
var worldData = TryLoadWorld();
if (worldData == null || worldData.Length == 0)
{
ShowDosError();
return;
}
using (var stream = new MemoryStream(worldData))
{
if (stream.Length == 0)
return;
using (var reader = new BinaryReader(stream))
{
var type = reader.ReadInt16();
if (type != World.WorldType)
throw new Exception("Incompatible world for this engine.");
var numBoards = reader.ReadInt16();
if (numBoards < 0)
throw new Exception("Board count must be zero or greater.");
GameSerializer.LoadWorld(stream);
var newBoards = Enumerable
.Range(0, numBoards + 1)
.Select(i => new PackedBoard(GameSerializer.LoadBoardData(stream)))
.ToList();
Boards.Clear();
foreach (var rawBoard in newBoards)
Boards.Add(rawBoard);
}
}
Hud.CreateStatusWorld();
UnpackBoard(World.BoardIndex);
State.WorldLoaded = true;
}
private void ShowDosError()
{
Hud.ShowScroll(false, "Error",
new[]
{
"$DOS Error:",
string.Empty,
"This may be caused by missing",
"files or a bad disk. If you",
"are trying to save a game,",
"your disk may be full -- try",
"using a blank, formatted disk",
"for saving the game!"
}
);
}
public void LockActor(int index) => Features.LockActor(index);
public void MoveActor(int index, IXyPair target)
{
var actor = Actors[index];
var sourceLocation = actor.Location.Clone();
var sourceTile = Tiles[actor.Location];
var targetTile = Tiles[target];
var underTile = actor.UnderTile.Clone();
actor.UnderTile.CopyFrom(targetTile);
if (targetTile.Id == ElementList.EmptyId)
targetTile.SetTo(sourceTile.Id, sourceTile.Color & 0x0F);
else
targetTile.SetTo(sourceTile.Id, (targetTile.Color & 0x70) | (sourceTile.Color & 0x0F));
sourceTile.CopyFrom(underTile);
actor.Location.CopyFrom(target);
if (targetTile.Id == ElementList.PlayerId)
ForcePlayerColor(index);
UpdateBoard(target);
UpdateBoard(sourceLocation);
if (index == 0 && Board.IsDark)
{
var squareDistanceX = (target.X - sourceLocation.X).Square();
var squareDistanceY = (target.Y - sourceLocation.Y).Square();
if (squareDistanceX + squareDistanceY == 1)
{
var glowLocation = new Location();
for (var x = target.X - Facts.TorchDrawBoxVerticalSize;
x <= target.X + Facts.TorchDrawBoxVerticalSize;
x++)
for (var y = target.Y - Facts.TorchDrawBoxHorizontalSize;
y <= target.Y + Facts.TorchDrawBoxHorizontalSize;
y++)
{
glowLocation.SetTo(x, y);
if (glowLocation.X >= 1 && glowLocation.X <= Tiles.Width && glowLocation.Y >= 1 &&
glowLocation.Y <= Tiles.Height)
if ((Distance(sourceLocation, glowLocation) < Facts.TorchRadius) ^
(Distance(target, glowLocation) < Facts.TorchRadius))
UpdateBoard(glowLocation);
}
}
}
if (index == 0)
Hud.UpdateCamera();
}
public void MoveActorOnRiver(int index)
{
var actor = Actors[index];
var vector = new Vector();
var underId = actor.UnderTile.Id;
if (underId == ElementList.RiverNId)
vector.SetTo(0, -1);
else if (underId == ElementList.RiverSId)
vector.SetTo(0, 1);
else if (underId == ElementList.RiverWId)
vector.SetTo(-1, 0);
else if (underId == ElementList.RiverEId)
vector.SetTo(1, 0);
if (vector.IsNonZero())
{
var actorTile = Tiles[actor.Location];
if (actorTile.Id == ElementList.PlayerId)
{
var targetLocation = actor.Location.Sum(vector);
InteractionList.Get(Tiles[targetLocation].Id).Interact(targetLocation, 0, vector);
}
}
if (vector.IsNonZero())
{
var target = actor.Location.Sum(vector);
if (ElementAt(target).IsFloor)
MoveActor(index, target);
}
}
public IParser Parser => _parser.Value;
public IActor Player => Actors[0];
public void PlaySound(int priority, ISound sound, int? offset = null, int? length = null)
{
if (State.GameOver || State.GameQuiet)
return;
var soundIsNotPlaying = !State.SoundPlaying;
var soundIsMusic = priority == -1;
var soundIsHigherPriority = State.SoundPriority != -1 && priority >= State.SoundPriority;
if (!(soundIsNotPlaying || soundIsMusic || soundIsHigherPriority))
return;
if (!soundIsMusic)
State.SoundBuffer.Clear();
State.SoundBuffer.Enqueue(sound, offset, length);
State.SoundPlaying = true;
State.SoundPriority = priority;
}
public void PlotTile(IXyPair location, ITile tile)
{
if (ElementAt(location).Id == ElementList.PlayerId)
return;
var targetElement = ElementList[tile.Id];
var existingTile = Tiles[location];
var targetColor = tile.Color;
if (targetElement.Color >= 0xF0)
{
if (targetColor == 0)
targetColor = existingTile.Color;
if (targetColor == 0)
targetColor = 0x0F;
if (targetElement.Color == 0xFE)
targetColor = ((targetColor - 8) << 4) + 0x0F;
}
else
{
targetColor = targetElement.Color;
}
if (targetElement.Id == existingTile.Id)
{
existingTile.Color = targetColor;
}
else
{
Destroy(location);
if (targetElement.Cycle < 0)
existingTile.SetTo(targetElement.Id, targetColor);
else
SpawnActor(location, new Tile(targetElement.Id, targetColor), targetElement.Cycle,
State.DefaultActor);
}
UpdateBoard(location);
}
public void Push(IXyPair location, IXyPair vector)
{
// this is here to prevent endless push loops
// but doesn't exist in the original code
if (vector.IsZero())
throw Exceptions.PushStackOverflow;
var tile = Tiles[location];
if (tile.Id == ElementList.SliderEwId && vector.Y == 0 ||
tile.Id == ElementList.SliderNsId && vector.X == 0 ||
ElementList[tile.Id].IsPushable)
{
var furtherTile = Tiles[location.Sum(vector)];
if (furtherTile.Id == ElementList.TransporterId)
PushThroughTransporter(location, vector);
else if (furtherTile.Id != ElementList.EmptyId) Push(location.Sum(vector), vector);
var furtherElement = ElementList[furtherTile.Id];
if (!furtherElement.IsFloor && furtherElement.IsDestructible && furtherTile.Id != ElementList.PlayerId)
Destroy(location.Sum(vector));
furtherElement = ElementList[furtherTile.Id];
if (furtherElement.IsFloor) MoveTile(location, location.Sum(vector));
}
}
public void PushThroughTransporter(IXyPair location, IXyPair vector)
{
var actor = ActorAt(location.Sum(vector));
if (actor.Vector.Matches(vector))
{
var search = actor.Location.Clone();
var target = new Location();
var ended = false;
var success = true;
while (!ended)
{
search.Add(vector);
var element = ElementAt(search);
if (element.Id == ElementList.BoardEdgeId)
{
ended = true;
}
else
{
if (success)
{
success = false;
if (!element.IsFloor)
{
Push(search, vector);
element = ElementAt(search);
}
if (element.IsFloor)
{
ended = true;
target.CopyFrom(search);
}
else
{
target.X = 0;
}
}
}
if (element.Id == ElementList.TransporterId)
if (ActorAt(search).Vector.Matches(vector.Opposite()))
success = true;
}
if (target.X > 0)
{
MoveTile(actor.Location.Difference(vector), target);
PlaySound(3, Sounds.Transporter);
}
}
}
public void PutTile(IXyPair location, IXyPair vector, ITile kind)
{
if (!Features.CanPutTile(location))
return;
if (location.X >= 1 && location.X <= Tiles.Width && location.Y >= 1 &&
location.Y <= Tiles.Height)
{
if (!ElementAt(location).IsFloor) Push(location, vector);
PlotTile(location, kind);
}
}
public void RaiseError(string error)
{
SetMessage(Facts.LongMessageDuration, Alerts.ErrorMessage(error));
PlaySound(5, Sounds.Error);
}
public IRandomizer Random => _randomizer.Value;
public void RemoveActor(int index)
{
var actor = Actors[index];
if (index < State.ActIndex) State.ActIndex--;
Tiles[actor.Location].CopyFrom(actor.UnderTile);
if (actor.Location.Y > 0) UpdateBoard(actor.Location);
for (var i = 1; i <= State.ActorCount; i++)
{
var a = Actors[i];
if (a.Follower >= index)
{
if (a.Follower == index)
a.Follower = -1;
else
a.Follower--;
}
if (a.Leader >= index)
{
if (a.Leader == index)
a.Leader = -1;
else
a.Leader--;
}
}
if (index < State.ActorCount)
for (var i = index; i < State.ActorCount; i++)
Actors[i].CopyFrom(Actors[i + 1]);
State.ActorCount--;
}
public void RemoveItem(IXyPair location) => Features.RemoveItem(location);
public IXyPair Rnd()
{
var result = new Vector();
Rnd(result);
return result;
}
public IXyPair RndP(IXyPair vector)
{
var result = new Vector();
result.CopyFrom(
Random.GetNext(2) == 0
? vector.Clockwise()
: vector.CounterClockwise());
return result;
}
public IXyPair Seek(IXyPair location)
{
var result = new Vector();
if (Random.GetNext(2) == 0 || Player.Location.Y == location.Y)
result.X = (Player.Location.X - location.X).Polarity();
if (result.X == 0) result.Y = (Player.Location.Y - location.Y).Polarity();
if (World.EnergyCycles > 0) result.SetOpposite();
return result;
}
public void SetBoard(int boardIndex)
{
var element = ElementList.Player();
Tiles[Player.Location].SetTo(element.Id, element.Color);
PackBoard();
UnpackBoard(boardIndex);
}
public void SetEditorMode()
{
InitializeElements(true);
State.EditorMode = true;
}
public void SetGameMode()
{
InitializeElements(false);
State.EditorMode = false;
}
public void SetMessage(int duration, IMessage message)
{
var index = ActorIndexAt(new Location(0, 0));
if (index >= 0)
{
RemoveActor(index);
Hud.UpdateBorder();
}
var topMessage = message.Text[0];
var bottomMessage = message.Text.Length > 1 ? message.Text[1] : string.Empty;
SpawnActor(new Location(0, 0), new Tile(ElementList.MessengerId, 0), 1, State.DefaultActor);
Actors[State.ActorCount].P2 = duration / (State.GameWaitTime + 1);
State.Message = topMessage;
State.Message2 = bottomMessage;
}
public void ShowHelp(string title, string filename) => Hud.ShowHelp(title, filename);
public void ShowInGameHelp() => Features.ShowInGameHelp();
public void OpenWorld()
{
var name = Features.OpenWorld();
if (!string.IsNullOrEmpty(name))
{
LoadWorld(name);
State.StartBoard = World.BoardIndex;
SetBoard(0);
FadePurple();
}
}
public string ShowLoad(string title, string extension)
{
return _fileDialog.Value.Open(title, extension);
}
public ISounds Sounds => _sounds.Value;
public void SpawnActor(IXyPair location, ITile tile, int cycle, IActor source)
{
// must reserve one actor for player, and one for messenger
if (State.ActorCount < Actors.Capacity - 2)
{
State.ActorCount++;
var actor = Actors[State.ActorCount];
if (source == null) source = State.DefaultActor;
actor.CopyFrom(source);
actor.Location.CopyFrom(location);
actor.Cycle = cycle;
actor.UnderTile.CopyFrom(Tiles[location]);
if (ElementAt(actor.Location).IsEditorFloor)
{
var newColor = Tiles[actor.Location].Color & 0x70;
newColor |= tile.Color & 0x0F;
Tiles[actor.Location].Color = newColor;
}
else
{
Tiles[actor.Location].Color = tile.Color;
}
Tiles[actor.Location].Id = tile.Id;
if (actor.Location.Y > 0) UpdateBoard(actor.Location);
}
}
public bool SpawnProjectile(int id, IXyPair location, IXyPair vector, bool enemyOwned)
{
var target = location.Sum(vector);
var element = ElementAt(target);
if (element.IsFloor || element.Id == ElementList.WaterId)
{
SpawnActor(target, new Tile(id, ElementList[id].Color), 1, State.DefaultActor);
var actor = Actors[State.ActorCount];
actor.P1 = enemyOwned ? 1 : 0;
actor.Vector.CopyFrom(vector);
actor.P2 = 0x64;
return true;
}
if (element.Id != ElementList.BreakableId &&
(!element.IsDestructible ||
(element.Id != ElementList.PlayerId || World.EnergyCycles != 0) && enemyOwned))
return false;
Destroy(target);
PlaySound(2, Sounds.BulletDie);
return true;
}
public void Start()
{
if (Thread == null)
{
_ticksToRun = 0;
Thread = new Thread(StartMain);
Thread.Start();
}
}
public IState State => _state.Value;
public void Stop()
{
Thread = null;
}
public ITargetList TargetList => _targets.Value;
public ITiles Tiles => _tiles.Value;
public bool TitleScreen => State.PlayerElement != ElementList.PlayerId;
public void UnlockActor(int index) => Features.UnlockActor(index);
public void UpdateBoard(IXyPair location) => DrawTile(location, Draw(location));
public void UpdateRadius(IXyPair location, RadiusMode mode)
{
var source = location.Clone();
var left = source.X - 9;
var right = source.X + 9;
var top = source.Y - 6;
var bottom = source.Y + 6;
for (var x = left; x <= right; x++)
for (var y = top; y <= bottom; y++)
if (x >= 1 && x <= Tiles.Width && y >= 1 && y <= Tiles.Height)
{
var target = new Location(x, y);
if (mode != RadiusMode.Update)
if (Distance(source, target) < Facts.TorchRadius)
{
var element = ElementAt(target);
if (mode == RadiusMode.Explode)
{
if (element.CodeEditText.Length > 0)
{
var actorIndex = ActorIndexAt(target);
if (actorIndex > 0) BroadcastLabel(-actorIndex, Facts.BombedLabel, false);
}
if (element.IsDestructible || element.Id == ElementList.StarId) Destroy(target);
if (element.Id == ElementList.EmptyId || element.Id == ElementList.BreakableId)
Tiles[target].SetTo(ElementList.BreakableId, Random.GetNext(7) + 9);
}
else
{
if (Tiles[target].Id == ElementList.BreakableId) Tiles[target].Id = ElementList.EmptyId;
}
}
UpdateBoard(target);
}
}
public void UpdateStatus() => Hud.UpdateStatus();
private void UpdateSound()
{
if (!State.SoundPlaying)
return;
if (State.SoundTicks <= 0)
{
if (State.SoundBuffer.Count > 0)
{
var sound = State.SoundBuffer.Dequeue();
State.SoundTicks = sound.Duration << 2;
if (sound.Note >= 0xF0)
{
Speaker.PlayDrum(sound.Note - 0xF0);
}
else if (sound.Note > 0x00)
{
var actualNote = (sound.Note & 0xF) + (sound.Note >> 4) * 12;
Speaker.PlayNote(actualNote);
}
else
{
Speaker.StopNote();
}
}
else
{
State.SoundPlaying = false;
State.SoundPriority = 0;
Speaker.StopNote();
}
}
if (State.SoundPlaying)
State.SoundTicks--;
}
public void WaitForTick()
{
var isFast = State.GameWaitTime <= 0 && Config.FastMode;
if (isFast)
{
while (_ticksToRun > 0)
{
UpdateSound();
if (Clock != null)
Tick?.Invoke(this, EventArgs.Empty);
_ticksToRun--;
}
}
else
{
UpdateSound();
if (Clock == null)
return;
Tick?.Invoke(this, EventArgs.Empty);
while (_ticksToRun <= 0 && ThreadActive)
Thread.Sleep(1);
if (_ticksToRun > 0)
_ticksToRun--;
}
}
public IWorld World
=> _world.Value;
private bool ActorIsLocked(int index) => Features.IsActorLocked(index);
public void ClearBoard()
{
var emptyId = ElementList.EmptyId;
var boardEdgeId = State.EdgeTile.Id;
var boardBorderId = BorderTile.Id;
var boardBorderColor = BorderTile.Color;
// board properties
Board.Name = string.Empty;
State.Message = string.Empty;
Board.MaximumShots = Facts.DefaultMaximumShots;
Board.IsDark = false;
Board.RestartOnZap = false;
Board.TimeLimit = 0;
Board.ExitEast = 0;
Board.ExitNorth = 0;
Board.ExitSouth = 0;
Board.ExitWest = 0;
// build board edges
for (var y = 0; y <= Tiles.Height + 1; y++)
{
Tiles[new Location(0, y)].Id = boardEdgeId;
Tiles[new Location(Tiles.Width + 1, y)].Id = boardEdgeId;
}
for (var x = 0; x <= Tiles.Width + 1; x++)
{
Tiles[new Location(x, 0)].Id = boardEdgeId;
Tiles[new Location(x, Tiles.Height + 1)].Id = boardEdgeId;
}
// clear out board
for (var x = 1; x <= Tiles.Width; x++)
for (var y = 1; y <= Tiles.Height; y++)
Tiles[new Location(x, y)].SetTo(emptyId, 0);
// build border
for (var y = 1; y <= Tiles.Height; y++)
{
Tiles[new Location(1, y)].SetTo(boardBorderId, boardBorderColor);
Tiles[new Location(Tiles.Width, y)].SetTo(boardBorderId, boardBorderColor);
}
for (var x = 1; x <= Tiles.Width; x++)
{
Tiles[new Location(x, 1)].SetTo(boardBorderId, boardBorderColor);
Tiles[new Location(x, Tiles.Height)].SetTo(boardBorderId, boardBorderColor);
}
// generate player actor
var element = ElementList.Player();
State.ActorCount = 0;
Player.Location.SetTo(Tiles.Width / 2, Tiles.Height / 2);
Tiles[Player.Location].SetTo(element.Id, element.Color);
Player.Cycle = 1;
Player.UnderTile.SetTo(0, 0);
Player.Pointer = 0;
Player.Length = 0;
}
private int ColorMatch(ITile tile)
{
var element = ElementList[tile.Id];
if (element.Color < 0xF0)
return element.Color & 7;
if (element.Color == 0xFE)
return ((tile.Color >> 4) & 0x0F) + 8;
return tile.Color & 0x0F;
}
private static int Distance(IXyPair a, IXyPair b) => (a.Y - b.Y).Square() * 2 + (a.X - b.X).Square();
private void DrawTile(IXyPair location, AnsiChar ac) => Hud.DrawTile(location.X - 1, location.Y - 1, ac);
private void EnterHighScore(int score)
{
var list = HighScoreListFactory.Load();
if (list == null)
return;
var name = Hud.EnterHighScore(list, score);
if (name == null)
return;
list.Add(name, score);
HighScoreListFactory.Save(list);
ShowHighScores();
}
private void ExecuteDeath(IOopContext context)
{
var location = context.Actor.Location.Clone();
Harm(context.Index);
PlotTile(location, context.DeathTile);
}
private void ExecuteMessage(IOopContext context)
{
var result = Features.ExecuteMessage(context);
if (result != null && !result.Cancelled && result.Label != null)
context.NextLine = BroadcastLabel(context.Index, result.Label, false);
}
private void FadeBoard(AnsiChar ac) => Hud.FadeBoard(ac);
public void FadeRed()
{
FadeBoard(Facts.ErrorFadeTile);
Hud.RedrawBoard();
}
private IXyPair GetConveyorVector(int index) => new Vector(State.Vector8[index], State.Vector8[index + 8]);
private void InitializeElements(bool showInvisibles)
{
ElementList.Reset();
// this isn't all the initializations.
// todo: replace this with the ability to completely reinitialize engine default memory
ElementList.Invisible().Character = showInvisibles ? 0xB0 : 0x20;
ElementList.Invisible().Color = 0xFF;
ElementList.Player().Character = 0x02;
}
private void MainLoop(bool doFade)
{
var alternating = false;
if (!_step)
{
Hud.CreateStatusText();
Hud.UpdateStatus();
MainLoopInit(doFade);
}
while (ThreadActive)
{
if (!State.GamePaused)
{
if (State.ActIndex <= State.ActorCount)
{
var actorData = Actors[State.ActIndex];
if (actorData.Cycle != 0)
if (State.ActIndex % actorData.Cycle == State.GameCycle % actorData.Cycle)
ActionList.Get(Tiles[actorData.Location].Id).Act(State.ActIndex);
State.ActIndex++;
}
}
else
{
State.ActIndex = State.ActorCount + 1;
if (Timers.Player.Clock(Facts.PauseFlashInterval))
alternating = !alternating;
if (alternating)
{
var playerElement = ElementList.Player();
DrawTile(Player.Location, new AnsiChar(playerElement.Character, playerElement.Color));
}
else
{
if (Tiles[Player.Location].Id == ElementList.PlayerId)
DrawTile(Player.Location, new AnsiChar(0x20, 0x0F));
else
UpdateBoard(Player.Location);
}
Hud.DrawPausing();
ReadInput();
if (State.KeyPressed == EngineKeyCode.Escape)
{
if (World.Health > 0)
{
State.BreakGameLoop = Hud.EndGameConfirmation();
}
else
{
State.BreakGameLoop = true;
Hud.UpdateBorder();
}
State.KeyPressed = 0;
}
if (!State.KeyVector.IsZero() && State.KeyArrow)
{
var target = Player.Location.Sum(State.KeyVector);
InteractionList.Get(ElementAt(target).Id).Interact(target, 0, State.KeyVector);
}
if (!State.KeyVector.IsZero() && State.KeyArrow)
{
var target = Player.Location.Sum(State.KeyVector);
if (ElementAt(target).IsFloor)
{
Features.CleanUpPauseMovement();
State.GamePaused = false;
Hud.ClearPausing();
State.GameCycle = Random.GetNext(Facts.MainLoopRandomCycleRange);
World.IsLocked = true;
}
}
}
if (State.ActIndex > State.ActorCount)
{
if (!State.BreakGameLoop && !State.GamePaused)
if (State.GameWaitTime <= 0 || Timers.Player.Clock(State.GameWaitTime))
{
State.GameCycle++;
if (State.GameCycle > Facts.MaxGameCycle) State.GameCycle = 1;
State.ActIndex = 0;
ReadInput();
}
Tracer.TraceStep();
if (_step)
break;
WaitForTick();
}
if (State.BreakGameLoop)
{
ClearSound();
if (State.PlayerElement == ElementList.PlayerId)
{
if (World.Health <= 0) EnterHighScore(World.Score);
}
else if (State.PlayerElement == ElementList.MonitorId)
{
Hud.ClearTitleStatus();
}
var element = ElementList.Player();
Tiles[Player.Location].SetTo(element.Id, element.Color);
State.GameOver = false;
break;
}
}
}
private void MainLoopInit(bool doFade)
{
if (State.Init)
{
if (!State.AboutShown)
ShowAbout();
if (!ThreadActive)
return;
if (State.DefaultWorldName.Length > 0)
{
State.AboutShown = true;
LoadWorld(State.DefaultWorldName);
}
State.StartBoard = World.BoardIndex;
SetBoard(0);
State.Init = false;
}
var element = ElementList[State.PlayerElement];
Tiles[Player.Location].SetTo(element.Id, element.Color);
if (State.PlayerElement == ElementList.MonitorId)
{
SetMessage(0, new Message());
Hud.DrawTitleStatus();
}
if (doFade)
FadePurple();
State.GameWaitTime = State.GameSpeed << 1;
State.BreakGameLoop = false;
State.GameCycle = Random.GetNext(Facts.MainLoopRandomCycleRange);
State.ActIndex = State.ActorCount + 1;
}
private void MoveTile(IXyPair source, IXyPair target)
{
var sourceIndex = ActorIndexAt(source);
if (sourceIndex >= 0)
{
MoveActor(sourceIndex, target);
}
else
{
Tiles[target].CopyFrom(Tiles[source]);
UpdateBoard(target);
RemoveItem(source);
UpdateBoard(source);
}
}
public void PackBoard()
{
var board = new PackedBoard(GameSerializer.PackBoard(Tiles));
PackBoard(World.BoardIndex, board);
}
private void PackBoard(int boardIndex, IPackedBoard board)
{
// bit of a hack to make sure we don't go out of bounds
while (Boards.Count <= boardIndex)
Boards.Add(null);
Boards[World.BoardIndex] = board;
}
private bool PlayWorld()
{
var gameIsActive = false;
if (World.IsLocked)
{
LoadWorld(World.Name);
if (State.WorldLoaded)
{
gameIsActive = State.WorldLoaded;
State.StartBoard = World.BoardIndex;
}
}
else
{
gameIsActive = true;
}
if (gameIsActive)
{
SetBoard(State.StartBoard);
EnterBoard();
State.PlayerElement = ElementList.PlayerId;
State.GamePaused = true;
MainLoop(true);
}
return gameIsActive;
}
private int ReadActorCodeByte(int index, IExecutable instructionSource)
{
var actor = Actors[index];
var value = 0;
if (instructionSource.Instruction < 0 || instructionSource.Instruction >= actor.Length)
{
State.OopByte = 0;
}
else
{
Debug.Assert(actor.Length == actor.Code.Length, @"Actor length and actual code length mismatch.");
value = actor.Code[instructionSource.Instruction];
State.OopByte = value;
instructionSource.Instruction++;
}
return value;
}
private IAnsiKeyTransformer AnsiKeyTransformer => _ansiKeyTransformer.Value;
private EngineKeyCode ConvertKey(IKeyPress keyPress)
{
var bytes = AnsiKeyTransformer.GetBytes(keyPress)?.ToList();
if (bytes == null || bytes.Count == 0)
return EngineKeyCode.None;
if (bytes.Count > 1 && (bytes[0] == 0 || bytes[0] >= 0x80))
return (EngineKeyCode) (bytes[1] | 0x80);
return (EngineKeyCode) bytes[0];
}
public void ReadInput()
{
//State.KeyShift = false;
State.KeyArrow = false;
State.KeyPressed = 0;
var key = Keyboard.GetKey();
if (key == null || key.Key == AnsiKey.None)
return;
State.KeyPressed = ConvertKey(key);
State.KeyShift = key.Shift;
switch (State.KeyPressed)
{
case EngineKeyCode.Left:
State.KeyVector.CopyFrom(Vector.West);
State.KeyArrow = true;
break;
case EngineKeyCode.Right:
State.KeyVector.CopyFrom(Vector.East);
State.KeyArrow = true;
break;
case EngineKeyCode.Up:
State.KeyVector.CopyFrom(Vector.North);
State.KeyArrow = true;
break;
case EngineKeyCode.Down:
State.KeyVector.CopyFrom(Vector.South);
State.KeyArrow = true;
break;
}
}
private void Rnd(IXyPair result)
{
result.X = Random.GetNext(3) - 1;
if (result.X == 0)
result.Y = (Random.GetNext(2) << 1) - 1;
else
result.Y = 0;
}
private void ShowAbout() => Features.ShowAbout();
private void StartInit()
{
State.GameSpeed = Facts.DefaultGameSpeed;
State.GameWaitTime = 1;
State.DefaultSaveName = Facts.DefaultSavedGameName;
State.DefaultBoardName = Facts.DefaultBoardName;
State.DefaultWorldName = Config.DefaultWorld ?? Facts.DefaultWorldName;
State.ForestIndex = 2;
State.Init = true;
ClearWorld();
var cfg = _configFileService.Value.Load();
if (Config.DefaultWorld == null && cfg != null)
{
if (!string.IsNullOrEmpty(cfg.WorldName))
{
State.DefaultWorldName = cfg.WorldName.StartsWith("*")
? cfg.WorldName.Substring(1)
: cfg.WorldName;
}
}
SetGameMode();
Clock.Start();
}
private void StartMain()
{
StartInit();
TitleScreenLoop();
Exited?.Invoke(this, EventArgs.Empty);
}
private void TitleScreenLoop()
{
State.QuitEngine = false;
State.Init = true;
State.StartBoard = 0;
var gameEnded = true;
Hud.Initialize();
while (ThreadActive)
{
if (!State.Init) SetBoard(0);
while (ThreadActive)
{
State.PlayerElement = ElementList.MonitorId;
State.GamePaused = false;
MainLoop(gameEnded);
gameEnded = false;
if (!ThreadActive)
break;
var startPlaying = Features.HandleTitleInput();
if (startPlaying)
gameEnded = PlayWorld();
if (gameEnded || State.QuitEngine)
break;
}
if (State.QuitEngine) break;
}
}
public void UnpackBoard(int boardIndex)
{
GameSerializer.UnpackBoard(Tiles, Boards[boardIndex].Data);
World.BoardIndex = boardIndex;
}
public void Dispose()
{
Clock?.Stop();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using BasicTestApp;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using Microsoft.AspNetCore.Testing;
using OpenQA.Selenium;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Components.E2ETest.Tests
{
public class EventBubblingTest : ServerTestBase<ToggleExecutionModeServerFixture<Program>>
{
// Note that currently we only support custom events if they have bubble:true.
// That's because the event delegator doesn't know which custom events bubble and which don't,
// so it doesn't know whether to register a normal handler or a capturing one. If this becomes
// a problem, we could consider registering both types of handler and just bailing out from
// the one that doesn't match the 'bubbles' flag on the received event object.
public EventBubblingTest(
BrowserFixture browserFixture,
ToggleExecutionModeServerFixture<Program> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}
protected override void InitializeAsyncCore()
{
Navigate(ServerPathBase, noReload: _serverFixture.ExecutionMode == ExecutionMode.Client);
Browser.MountTestComponent<EventBubblingComponent>();
Browser.Exists(By.Id("event-bubbling"));
}
[Fact]
public void BubblingStandardEvent_FiredOnElementWithHandler()
{
Browser.Exists(By.Id("button-with-onclick")).Click();
// Triggers event on target and ancestors with handler in upwards direction
Browser.Equal(
new[] { "target onclick", "parent onclick" },
GetLogLines);
}
[Fact]
public void BubblingStandardEvent_FiredOnElementWithoutHandler()
{
Browser.Exists(By.Id("button-without-onclick")).Click();
// Triggers event on ancestors with handler in upwards direction
Browser.Equal(
new[] { "parent onclick" },
GetLogLines);
}
[Fact]
public void BubblingCustomEvent_FiredOnElementWithHandler()
{
TriggerCustomBubblingEvent("element-with-onsneeze", "sneeze");
// Triggers event on target and ancestors with handler in upwards direction
Browser.Equal(
new[] { "target onsneeze", "parent onsneeze" },
GetLogLines);
}
[Fact]
public void BubblingCustomEvent_FiredOnElementWithoutHandler()
{
TriggerCustomBubblingEvent("element-without-onsneeze", "sneeze");
// Triggers event on ancestors with handler in upwards direction
Browser.Equal(
new[] { "parent onsneeze" },
GetLogLines);
}
[Fact]
public void NonBubblingEvent_FiredOnElementWithHandler()
{
Browser.Exists(By.Id("input-with-onfocus")).Click();
// Triggers event only on target, not other ancestors with event handler
Browser.Equal(
new[] { "target onfocus" },
GetLogLines);
}
[Fact]
public void NonBubblingEvent_FiredOnElementWithoutHandler()
{
Browser.Exists(By.Id("input-without-onfocus")).Click();
// Triggers no event
Browser.Empty(GetLogLines);
}
[Theory]
[InlineData("target")]
[InlineData("intermediate")]
public void StopPropagation(string whereToStopPropagation)
{
// If stopPropagation is off, we observe the event on the listener and all its ancestors
Browser.Exists(By.Id("button-with-onclick")).Click();
Browser.Equal(new[] { "target onclick", "parent onclick" }, GetLogLines);
// If stopPropagation is on, the event doesn't reach the ancestor
// Note that in the "intermediate element" case, the intermediate element does *not* itself
// listen for this event, which shows that stopPropagation works independently of handling
ClearLog();
Browser.Exists(By.Id($"{whereToStopPropagation}-stop-propagation")).Click();
Browser.Exists(By.Id("button-with-onclick")).Click();
Browser.Equal(new[] { "target onclick" }, GetLogLines);
// We can also toggle it back off
ClearLog();
Browser.Exists(By.Id($"{whereToStopPropagation}-stop-propagation")).Click();
Browser.Exists(By.Id("button-with-onclick")).Click();
Browser.Equal(new[] { "target onclick", "parent onclick" }, GetLogLines);
}
[Fact]
public void PreventDefaultWorksOnTarget()
{
// Clicking a checkbox without preventDefault produces both "click" and "change"
// events, and it becomes checked
var checkboxWithoutPreventDefault = Browser.Exists(By.Id("checkbox-with-preventDefault-false"));
checkboxWithoutPreventDefault.Click();
Browser.Equal(new[] { "Checkbox click", "Checkbox change" }, GetLogLines);
Browser.True(() => checkboxWithoutPreventDefault.Selected);
// Clicking a checkbox with preventDefault produces a "click" event, but no "change"
// event, and it remains unchecked
ClearLog();
var checkboxWithPreventDefault = Browser.Exists(By.Id("checkbox-with-preventDefault-true"));
checkboxWithPreventDefault.Click();
Browser.Equal(new[] { "Checkbox click" }, GetLogLines);
Browser.False(() => checkboxWithPreventDefault.Selected);
}
[Fact]
public void PreventDefault_WorksOnAncestorElement()
{
// Even though the checkbox we're clicking this case does *not* have preventDefault,
// if its ancestor does, then we don't get the "change" event and it remains unchecked
Browser.Exists(By.Id($"ancestor-prevent-default")).Click();
var checkboxWithoutPreventDefault = Browser.Exists(By.Id("checkbox-with-preventDefault-false"));
checkboxWithoutPreventDefault.Click();
Browser.Equal(new[] { "Checkbox click" }, GetLogLines);
Browser.False(() => checkboxWithoutPreventDefault.Selected);
// We can also toggle it back off dynamically
Browser.Exists(By.Id($"ancestor-prevent-default")).Click();
ClearLog();
checkboxWithoutPreventDefault.Click();
Browser.Equal(new[] { "Checkbox click", "Checkbox change" }, GetLogLines);
Browser.True(() => checkboxWithoutPreventDefault.Selected);
}
[Fact]
public void PreventDefaultCanBlockKeystrokes()
{
// By default, the textbox accepts keystrokes
var textbox = Browser.Exists(By.Id($"textbox-that-can-block-keystrokes"));
textbox.SendKeys("a");
Browser.Equal(new[] { "Received keydown" }, GetLogLines);
Browser.Equal("a", () => textbox.GetAttribute("value"));
// We can turn on preventDefault to stop keystrokes
// There will still be a keydown event, but we're preventing it from actually changing the textbox value
ClearLog();
Browser.Exists(By.Id($"prevent-keydown")).Click();
textbox.SendKeys("b");
Browser.Equal(new[] { "Received keydown" }, GetLogLines);
Browser.Equal("a", () => textbox.GetAttribute("value"));
// We can turn it back off
ClearLog();
Browser.Exists(By.Id($"prevent-keydown")).Click();
textbox.SendKeys("c");
Browser.Equal(new[] { "Received keydown" }, GetLogLines);
Browser.Equal("ac", () => textbox.GetAttribute("value"));
}
private string[] GetLogLines()
=> Browser.Exists(By.TagName("textarea"))
.GetAttribute("value")
.Replace("\r\n", "\n")
.Split('\n', StringSplitOptions.RemoveEmptyEntries);
void ClearLog()
=> Browser.Exists(By.Id("clear-log")).Click();
private void TriggerCustomBubblingEvent(string elementId, string eventName)
{
var jsExecutor = (IJavaScriptExecutor)Browser;
jsExecutor.ExecuteScript(
$"window.testelem = document.getElementById('{elementId}')");
jsExecutor.ExecuteScript(
$"window.testelem.dispatchEvent(new Event('{eventName}', {{ bubbles: true }}))");
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubnetsOperations operations.
/// </summary>
public partial interface ISubnetsOperations
{
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary reader implementation.
/// </summary>
internal class BinaryReader : IBinaryReader, IBinaryRawReader
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Parent builder. */
private readonly BinaryObjectBuilder _builder;
/** Handles. */
private BinaryReaderHandleDictionary _hnds;
/** Detach flag. */
private bool _detach;
/** Binary read mode. */
private BinaryMode _mode;
/** Current frame. */
private Frame _frame;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Input stream.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
public BinaryReader
(Marshaller marsh,
IBinaryStream stream,
BinaryMode mode,
BinaryObjectBuilder builder)
{
_marsh = marsh;
_mode = mode;
_builder = builder;
_frame.Pos = stream.Position;
Stream = stream;
}
/// <summary>
/// Gets the marshaller.
/// </summary>
public Marshaller Marshaller
{
get { return _marsh; }
}
/** <inheritdoc /> */
public IBinaryRawReader GetRawReader()
{
MarkRaw();
return this;
}
/** <inheritdoc /> */
public bool ReadBoolean(string fieldName)
{
return ReadField(fieldName, r => r.ReadBoolean(), BinaryUtils.TypeBool);
}
/** <inheritdoc /> */
public bool ReadBoolean()
{
return Stream.ReadBool();
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray()
{
return Read(BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public byte ReadByte(string fieldName)
{
return ReadField(fieldName, ReadByte, BinaryUtils.TypeByte);
}
/** <inheritdoc /> */
public byte ReadByte()
{
return Stream.ReadByte();
}
/** <inheritdoc /> */
public byte[] ReadByteArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public byte[] ReadByteArray()
{
return Read(BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public short ReadShort(string fieldName)
{
return ReadField(fieldName, ReadShort, BinaryUtils.TypeShort);
}
/** <inheritdoc /> */
public short ReadShort()
{
return Stream.ReadShort();
}
/** <inheritdoc /> */
public short[] ReadShortArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public short[] ReadShortArray()
{
return Read(BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public char ReadChar(string fieldName)
{
return ReadField(fieldName, ReadChar, BinaryUtils.TypeChar);
}
/** <inheritdoc /> */
public char ReadChar()
{
return Stream.ReadChar();
}
/** <inheritdoc /> */
public char[] ReadCharArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public char[] ReadCharArray()
{
return Read(BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public int ReadInt(string fieldName)
{
return ReadField(fieldName, ReadInt, BinaryUtils.TypeInt);
}
/** <inheritdoc /> */
public int ReadInt()
{
return Stream.ReadInt();
}
/** <inheritdoc /> */
public int[] ReadIntArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public int[] ReadIntArray()
{
return Read(BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public long ReadLong(string fieldName)
{
return ReadField(fieldName, ReadLong, BinaryUtils.TypeLong);
}
/** <inheritdoc /> */
public long ReadLong()
{
return Stream.ReadLong();
}
/** <inheritdoc /> */
public long[] ReadLongArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public long[] ReadLongArray()
{
return Read(BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public float ReadFloat(string fieldName)
{
return ReadField(fieldName, ReadFloat, BinaryUtils.TypeFloat);
}
/** <inheritdoc /> */
public float ReadFloat()
{
return Stream.ReadFloat();
}
/** <inheritdoc /> */
public float[] ReadFloatArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public float[] ReadFloatArray()
{
return Read(BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public double ReadDouble(string fieldName)
{
return ReadField(fieldName, ReadDouble, BinaryUtils.TypeDouble);
}
/** <inheritdoc /> */
public double ReadDouble()
{
return Stream.ReadDouble();
}
/** <inheritdoc /> */
public double[] ReadDoubleArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public double[] ReadDoubleArray()
{
return Read(BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public decimal? ReadDecimal(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal? ReadDecimal()
{
return Read(BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray()
{
return Read(BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp()
{
return Read(BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray()
{
return Read(BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public string ReadString(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string ReadString()
{
return Read(BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string[] ReadStringArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public string[] ReadStringArray()
{
return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public Guid? ReadGuid(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadGuid, BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid? ReadGuid()
{
return Read(BinaryUtils.ReadGuid, BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray()
{
return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public T ReadEnum<T>(string fieldName)
{
return SeekField(fieldName) ? ReadEnum<T>() : default(T);
}
/** <inheritdoc /> */
public T ReadEnum<T>()
{
var hdr = ReadByte();
switch (hdr)
{
case BinaryUtils.HdrNull:
return default(T);
case BinaryUtils.TypeEnum:
// Never read enums in binary mode when reading a field (we do not support half-binary objects)
return ReadEnum0<T>(this, false);
case BinaryUtils.HdrFull:
// Unregistered enum written as serializable
Stream.Seek(-1, SeekOrigin.Current);
return ReadObject<T>();
default:
throw new BinaryObjectException(
string.Format("Invalid header on enum deserialization. Expected: {0} or {1} but was: {2}",
BinaryUtils.TypeEnum, BinaryUtils.HdrFull, hdr));
}
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T ReadObject<T>(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (SeekField(fieldName))
return Deserialize<T>();
return default(T);
}
/** <inheritdoc /> */
public T ReadObject<T>()
{
return Deserialize<T>();
}
/** <inheritdoc /> */
public T[] ReadArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public T[] ReadArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName)
{
return ReadCollection(fieldName, null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection()
{
return ReadCollection(null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName, Func<int, ICollection> factory,
Action<ICollection, object> adder)
{
return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public ICollection ReadCollection(Func<int, ICollection> factory, Action<ICollection, object> adder)
{
return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName)
{
return ReadDictionary(fieldName, null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary()
{
return ReadDictionary((Func<int, IDictionary>) null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName, Func<int, IDictionary> factory)
{
return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(Func<int, IDictionary> factory)
{
return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/// <summary>
/// Enable detach mode for the next object read.
/// </summary>
public BinaryReader DetachNext()
{
_detach = true;
return this;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <returns>Deserialized object.</returns>
public T Deserialize<T>()
{
T res;
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (!TryDeserialize(out res) && default(T) != null)
throw new BinaryObjectException(string.Format("Invalid data on deserialization. " +
"Expected: '{0}' But was: null", typeof (T)));
return res;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <returns>Deserialized object.</returns>
public bool TryDeserialize<T>(out T res)
{
int pos = Stream.Position;
byte hdr = Stream.ReadByte();
var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper
_detach = false;
switch (hdr)
{
case BinaryUtils.HdrNull:
res = default(T);
return false;
case BinaryUtils.HdrHnd:
res = ReadHandleObject<T>(pos);
return true;
case BinaryUtils.HdrFull:
res = ReadFullObject<T>(pos);
return true;
case BinaryUtils.TypeBinary:
res = ReadBinaryObject<T>(doDetach);
return true;
case BinaryUtils.TypeEnum:
res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
return true;
}
if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res))
return true;
throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']');
}
/// <summary>
/// Reads the binary object.
/// </summary>
private T ReadBinaryObject<T>(bool doDetach)
{
var len = Stream.ReadInt();
var binaryBytesPos = Stream.Position;
if (_mode != BinaryMode.Deserialize)
return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach));
Stream.Seek(len, SeekOrigin.Current);
var offset = Stream.ReadInt();
var retPos = Stream.Position;
Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin);
_mode = BinaryMode.KeepBinary;
try
{
return Deserialize<T>();
}
finally
{
_mode = BinaryMode.Deserialize;
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the binary object in binary form.
/// </summary>
private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach)
{
try
{
Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin);
var offs = Stream.ReadInt(); // offset inside data
var pos = binaryBytesPos + offs;
var hdr = BinaryObjectHeader.Read(Stream, pos);
if (!doDetach)
return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
Stream.Seek(pos, SeekOrigin.Begin);
return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
finally
{
Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the full object.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")]
private T ReadFullObject<T>(int pos)
{
var hdr = BinaryObjectHeader.Read(Stream, pos);
// Validate protocol version.
BinaryUtils.ValidateProtocolVersion(hdr.Version);
try
{
// Already read this object?
object hndObj;
if (_hnds != null && _hnds.TryGetValue(pos, out hndObj))
return (T) hndObj;
if (hdr.IsUserType && _mode == BinaryMode.ForceBinary)
{
BinaryObject portObj;
if (_detach)
{
Stream.Seek(pos, SeekOrigin.Begin);
portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
else
portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj));
AddHandle(pos, obj);
return obj;
}
else
{
// Find descriptor.
var desc = _marsh.GetDescriptor(hdr.IsUserType, hdr.TypeId);
// Instantiate object.
if (desc.Type == null)
{
if (desc is BinarySurrogateTypeDescriptor)
{
throw new BinaryObjectException(string.Format(
"Unknown type ID: {0}. " +
"This usually indicates missing BinaryConfiguration." +
"Make sure that all nodes have the same BinaryConfiguration.", hdr.TypeId));
}
throw new BinaryObjectException(string.Format(
"No matching type found for object [typeId={0}, typeName={1}]." +
"This usually indicates that assembly with specified type is not loaded on a node." +
"When using Apache.Ignite.exe, make sure to load assemblies with -assembly parameter.",
desc.TypeId, desc.TypeName));
}
// Preserve old frame.
var oldFrame = _frame;
// Set new frame.
_frame.Hdr = hdr;
_frame.Pos = pos;
SetCurSchema(desc);
_frame.Struct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure);
_frame.Raw = false;
// Read object.
var obj = desc.Serializer.ReadBinary<T>(this, desc.Type, pos);
_frame.Struct.UpdateReaderStructure();
// Restore old frame.
_frame = oldFrame;
return obj;
}
}
finally
{
// Advance stream pointer.
Stream.Seek(pos + hdr.Length, SeekOrigin.Begin);
}
}
/// <summary>
/// Sets the current schema.
/// </summary>
private void SetCurSchema(IBinaryTypeDescriptor desc)
{
_frame.SchemaMap = null;
if (_frame.Hdr.HasSchema)
{
_frame.Schema = desc.Schema.Get(_frame.Hdr.SchemaId);
if (_frame.Schema == null)
{
_frame.Schema = ReadSchema(desc.TypeId);
desc.Schema.Add(_frame.Hdr.SchemaId, _frame.Schema);
}
}
else
{
_frame.Schema = null;
}
}
/// <summary>
/// Reads the schema.
/// </summary>
private int[] ReadSchema(int typeId)
{
if (_frame.Hdr.IsCompactFooter)
{
// Get schema from Java
var ignite = Marshaller.Ignite;
var schema = ignite == null
? null
: ignite.BinaryProcessor.GetSchema(_frame.Hdr.TypeId, _frame.Hdr.SchemaId);
if (schema == null)
throw new BinaryObjectException("Cannot find schema for object with compact footer [" +
"typeId=" + typeId + ", schemaId=" + _frame.Hdr.SchemaId + ']');
return schema;
}
var pos = Stream.Position;
Stream.Seek(_frame.Pos + _frame.Hdr.SchemaOffset, SeekOrigin.Begin);
var count = _frame.Hdr.SchemaFieldCount;
var offsetSize = _frame.Hdr.SchemaFieldOffsetSize;
var res = new int[count];
for (int i = 0; i < count; i++)
{
res[i] = Stream.ReadInt();
Stream.Seek(offsetSize, SeekOrigin.Current);
}
Stream.Seek(pos, SeekOrigin.Begin);
return res;
}
/// <summary>
/// Reads the handle object.
/// </summary>
private T ReadHandleObject<T>(int pos)
{
// Get handle position.
int hndPos = pos - Stream.ReadInt();
int retPos = Stream.Position;
try
{
object hndObj;
if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj))
{
if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj))
{
// No such handler, i.e. we trying to deserialize inner object before deserializing outer.
Stream.Seek(hndPos, SeekOrigin.Begin);
hndObj = Deserialize<T>();
}
// Notify builder that we deserialized object on other location.
if (_builder != null)
_builder.CacheField(hndPos, hndObj);
}
return (T) hndObj;
}
finally
{
// Position stream to correct place.
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Adds a handle to the dictionary.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="obj">Object.</param>
internal void AddHandle(int pos, object obj)
{
if (_hnds == null)
_hnds = new BinaryReaderHandleDictionary(pos, obj);
else
_hnds.Add(pos, obj);
}
/// <summary>
/// Underlying stream.
/// </summary>
public IBinaryStream Stream
{
get;
private set;
}
/// <summary>
/// Mark current output as raw.
/// </summary>
private void MarkRaw()
{
if (!_frame.Raw)
{
_frame.Raw = true;
Stream.Seek(_frame.Pos + _frame.Hdr.GetRawOffset(Stream, _frame.Pos), SeekOrigin.Begin);
}
}
/// <summary>
/// Seeks the field by name.
/// </summary>
private bool SeekField(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (!_frame.Hdr.HasSchema)
return false;
var actionId = _frame.Struct.CurStructAction;
var fieldId = _frame.Struct.GetFieldId(fieldName);
if (_frame.Schema == null || actionId >= _frame.Schema.Length || fieldId != _frame.Schema[actionId])
{
_frame.SchemaMap = _frame.SchemaMap ?? BinaryObjectSchemaSerializer.ReadSchema(Stream, _frame.Pos,
_frame.Hdr, () => _frame.Schema).ToDictionary();
_frame.Schema = null; // read order is different, ignore schema for future reads
int pos;
if (!_frame.SchemaMap.TryGetValue(fieldId, out pos))
return false;
Stream.Seek(pos + _frame.Pos, SeekOrigin.Begin);
}
return true;
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr)
{
return Read(() => readFunc(this), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr)
{
return Read(() => readFunc(Stream), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<T> readFunc, byte expHdr)
{
var hdr = ReadByte();
if (hdr == BinaryUtils.HdrNull)
return default(T);
if (hdr == BinaryUtils.HdrHnd)
return ReadHandleObject<T>(Stream.Position - 1);
if (expHdr != hdr)
throw new BinaryObjectException(string.Format("Invalid header on deserialization. " +
"Expected: {0} but was: {1}", expHdr, hdr));
return readFunc();
}
/// <summary>
/// Reads the enum.
/// </summary>
private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary)
{
var enumType = reader.ReadInt();
var enumValue = reader.ReadInt();
if (!keepBinary)
return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller);
return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller));
}
/// <summary>
/// Stores current reader stack frame.
/// </summary>
private struct Frame
{
/** Current position. */
public int Pos;
/** Current raw flag. */
public bool Raw;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Current schema. */
public int[] Schema;
/** Current schema with positions. */
public Dictionary<int, int> SchemaMap;
/** Current header. */
public BinaryObjectHeader Hdr;
}
}
}
| |
// Copyright (c) 2013 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace Icu
{
/// <summary>
/// A Locale object represents a specific geographical, political, or cultural region.
/// </summary>
public class Locale
#if FEATURE_ICLONEABLE
: ICloneable
#endif
{
/// <summary>
/// Construct a default locale object, a Locale for the default locale ID
/// </summary>
public Locale()
{
Id = Canonicalize(CultureInfo.CurrentUICulture.Name);
}
/// <summary>
/// Initializes a new instance of the <see cref="Icu.Locale"/> class.
/// <paramref name="localeId"/> can either be a full locale like "en-US", or a language.
/// </summary>
/// <param name="localeId">Locale.</param>
public Locale(string localeId)
{
Id = Canonicalize(localeId);
}
/// <summary>
/// Initializes a new instance of the <see cref="Icu.Locale"/> class.
/// </summary>
/// <param name="language">Language.</param>
/// <param name="country">Country or script.</param>
public Locale(string language, string country):
this (language, country, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Locale"/> class.
/// </summary>
/// <param name="language">Lowercase two-letter or three-letter ISO-639 code.</param>
/// <param name="country">Uppercase two-letter ISO-3166 code.</param>
/// <param name="variant">Uppercase vendor and browser specific code.</param>
public Locale(string language, string country, string variant):
this (language, country, variant, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Locale"/> class.
/// </summary>
/// <param name="language">Lowercase two-letter or three-letter ISO-639 code.</param>
/// <param name="country">Uppercase two-letter ISO-3166 code.</param>
/// <param name="variant">Uppercase vendor and browser specific code.</param>
/// <param name="keywordsAndValues">A string consisting of keyword/values pairs, such as "collation=phonebook;currency=euro"</param>
public Locale(string language, string country, string variant, string keywordsAndValues)
{
var bldr = new StringBuilder();
bldr.AppendFormat("{0}_{1}", language, country);
if (!string.IsNullOrEmpty(variant))
{
bldr.AppendFormat("_{0}", variant);
}
if (!string.IsNullOrEmpty(keywordsAndValues))
{
bldr.AppendFormat("@{0}", keywordsAndValues);
}
Id = Canonicalize(bldr.ToString());
}
/// <summary>
/// Clone this object. (Not Implemented.)
/// </summary>
public object Clone()
{
throw new NotImplementedException();
}
/// <summary>
/// Gets or sets the identifier of the ICU locale.
/// </summary>
public string Id { get; private set; }
/// <summary>
/// Gets the two-letter language code as defined by ISO-639.
/// </summary>
public string Language
{
get { return GetString(NativeMethods.uloc_getLanguage, Id); }
}
/// <summary>
/// Gets the script code as defined by ISO-15924.
/// </summary>
public string Script
{
get { return GetString(NativeMethods.uloc_getScript, Id); }
}
/// <summary>
/// Gets the two-letter country code as defined by ISO-3166.
/// </summary>
public string Country
{
get { return GetString(NativeMethods.uloc_getCountry, Id); }
}
/// <summary>
/// Gets the variant code for the Locale.
/// </summary>
public string Variant
{
get { return GetString(NativeMethods.uloc_getVariant, Id); }
}
/// <summary>
/// Gets the full name for the specified locale.
/// </summary>
public string Name
{
get { return GetString(NativeMethods.uloc_getName, Id); }
}
/// <summary>
/// Gets the full name for the specified locale, like <see cref="Name"/>,
/// but without keywords.
/// </summary>
public string BaseName
{
get { return GetString(NativeMethods.uloc_getBaseName, Id); }
}
/// <summary>
/// Gets the 3-letter ISO 639-3 language code
/// </summary>
public string Iso3Language
{
get { return Marshal.PtrToStringAnsi(NativeMethods.uloc_getISO3Language(Id)); }
}
/// <summary>
/// Gets the 3-letter ISO country code
/// </summary>
public string Iso3Country
{
get { return Marshal.PtrToStringAnsi(NativeMethods.uloc_getISO3Country(Id)); }
}
/// <summary>
/// Gets the Win32 LCID value for the specified locale.
/// </summary>
public int Lcid
{
get { return NativeMethods.uloc_getLCID(Id); }
}
/// <summary>
/// Gets the language for the UI's locale.
/// </summary>
public string DisplayLanguage
{
get { return GetDisplayLanguage(new Locale().Id); }
}
/// <summary>
/// Gets the language name suitable for display for the specified locale
/// </summary>
/// <param name="displayLocale">The display locale</param>
public string GetDisplayLanguage(Locale displayLocale)
{
return GetString(NativeMethods.uloc_getDisplayLanguage, Id, displayLocale.Id);
}
/// <summary>
/// Gets the country for the UI's locale.
/// </summary>
public string DisplayCountry
{
get { return GetDisplayCountry(new Locale().Id); }
}
/// <summary>
/// Gets the country name suitable for display for the specified locale.
/// </summary>
/// <param name="displayLocale">The display locale</param>
public string GetDisplayCountry(Locale displayLocale)
{
return GetString(NativeMethods.uloc_getDisplayCountry, Id, displayLocale.Id);
}
/// <summary>
/// Gets the full name for the UI's locale.
/// </summary>
public string DisplayName
{
get { return GetDisplayName(new Locale().Id); }
}
/// <summary>
/// Gets the full name suitable for display for the specified locale.
/// </summary>
/// <param name="displayLocale">The display locale</param>
public string GetDisplayName(Locale displayLocale)
{
return GetString(NativeMethods.uloc_getDisplayName, Id, displayLocale.Id);
}
/// <summary>
/// Gets the Locale's <see cref="Id"/> as a string.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Id;
}
/// <summary>
/// Gets a list of all available locales.
/// </summary>
public static List<Locale> AvailableLocales
{
get
{
var locales = new List<Locale>();
for (int i = 0; i < NativeMethods.uloc_countAvailable(); i++)
locales.Add(new Locale(Marshal.PtrToStringAnsi(NativeMethods.uloc_getAvailable(i))));
return locales;
}
}
/// <summary>
/// Creates a Locale with the given Locale id.
/// </summary>
/// <param name="localeId">Locale id</param>
public static implicit operator Locale(string localeId)
{
return new Locale(localeId);
}
/// <summary>
/// Gets the locale for the specified Win32 LCID value
/// </summary>
/// <param name="lcid">the Win32 LCID to translate </param>
/// <returns>The locale for the specified Win32 LCID value, or <c>null</c> in the
/// case of an error.</returns>
public static Locale GetLocaleForLCID(int lcid)
{
var localeId = GetString(NativeMethods.uloc_getLocaleForLCID, lcid);
return !string.IsNullOrEmpty(localeId) ? new Locale(localeId) : null;
}
#region ICU wrapper methods
private delegate int GetStringMethod<in T>(T localeId, IntPtr name,
int nameCapacity, out ErrorCode err);
private delegate int GetStringDisplayMethod(string localeID, string displayLocaleID, IntPtr name,
int nameCapacity, out ErrorCode err);
private static string GetString<T>(GetStringMethod<T> method, T localeId)
{
return NativeMethods.GetAnsiString((ptr, length) =>
{
length = method(localeId, ptr, length, out var err);
return new Tuple<ErrorCode, int>(err, length);
});
}
private static string GetString(GetStringDisplayMethod method, string localeId, string displayLocaleId)
{
return NativeMethods.GetUnicodeString((ptr, length) =>
{
length = method(localeId, displayLocaleId, ptr, length, out var err);
return new Tuple<ErrorCode, int>(err, length);
});
}
/// <summary>
/// Gets the full name for the specified locale.
/// </summary>
private static string Canonicalize(string localeID)
{
return GetString(NativeMethods.uloc_canonicalize, localeID);
}
#endregion
}
}
| |
using System;
using System.Collections;
using HalconDotNet;
namespace ViewROI
{
public delegate void GCDelegate(string val);
/// <summary>
/// This class contains the graphical context of an HALCON object. The
/// set of graphical modes is defined by the hashlist 'graphicalSettings'.
/// If the list is empty, then there is no difference to the graphical
/// setting defined by the system by default. Otherwise, the provided
/// HALCON window is adjusted according to the entries of the supplied
/// graphical context (when calling applyContext())
/// </summary>
public class GraphicsContext
{
/// <summary>
/// Graphical mode for the output color (see dev_set_color)
/// </summary>
public const string GC_COLOR = "Color";
/// <summary>
/// Graphical mode for the multi-color output (see dev_set_colored)
/// </summary>
public const string GC_COLORED = "Colored";
/// <summary>
/// Graphical mode for the line width (see set_line_width)
/// </summary>
public const string GC_LINEWIDTH = "LineWidth";
/// <summary>
/// Graphical mode for the drawing (see set_draw)
/// </summary>
public const string GC_DRAWMODE = "DrawMode";
/// <summary>
/// Graphical mode for the drawing shape (see set_shape)
/// </summary>
public const string GC_SHAPE = "Shape";
/// <summary>
/// Graphical mode for the LUT (lookup table) (see set_lut)
/// </summary>
public const string GC_LUT = "Lut";
/// <summary>
/// Graphical mode for the painting (see set_paint)
/// </summary>
public const string GC_PAINT = "Paint";
/// <summary>
/// Graphical mode for the line style (see set_line_style)
/// </summary>
public const string GC_LINESTYLE = "LineStyle";
/// <summary>
/// Hashlist containing entries for graphical modes (defined by GC_*),
/// which is then linked to some HALCON object to describe its
/// graphical context.
/// </summary>
private Hashtable graphicalSettings;
/// <summary>
/// Backup of the last graphical context applied to the window.
/// </summary>
public Hashtable stateOfSettings;
private IEnumerator iterator;
/// <summary>
/// Option to delegate messages from the graphical context
/// to some observer class
/// </summary>
public GCDelegate gcNotification;
/// <summary>
/// Creates a graphical context with no initial
/// graphical modes
/// </summary>
public GraphicsContext()
{
graphicalSettings = new Hashtable(10, 0.2f);
gcNotification = new GCDelegate(dummy);
stateOfSettings = new Hashtable(10, 0.2f);
}
/// <summary>
/// Creates an instance of the graphical context with
/// the modes defined in the hashtable 'settings'
/// </summary>
/// <param name="settings">
/// List of modes, which describes the graphical context
/// </param>
public GraphicsContext(Hashtable settings)
{
graphicalSettings = settings;
gcNotification = new GCDelegate(dummy);
stateOfSettings = new Hashtable(10, 0.2f);
}
/// <summary>Applies graphical context to the HALCON window</summary>
/// <param name="window">Active HALCON window</param>
/// <param name="cContext">
/// List that contains graphical modes for window
/// </param>
public void applyContext(HWindow window, Hashtable cContext)
{
string key = "";
string valS = "";
int valI = -1;
HTuple valH = null;
iterator = cContext.Keys.GetEnumerator();
try
{
while (iterator.MoveNext())
{
key = (string)iterator.Current;
if (stateOfSettings.Contains(key) &&
stateOfSettings[key] == cContext[key])
continue;
switch (key)
{
case GC_COLOR:
valS = (string)cContext[key];
window.SetColor(valS);
if (stateOfSettings.Contains(GC_COLORED))
stateOfSettings.Remove(GC_COLORED);
break;
case GC_COLORED:
valI = (int)cContext[key];
window.SetColored(valI);
if (stateOfSettings.Contains(GC_COLOR))
stateOfSettings.Remove(GC_COLOR);
break;
case GC_DRAWMODE:
valS = (string)cContext[key];
window.SetDraw(valS);
break;
case GC_LINEWIDTH:
valI = (int)cContext[key];
window.SetLineWidth(valI);
break;
case GC_LUT:
valS = (string)cContext[key];
window.SetLut(valS);
break;
case GC_PAINT:
valS = (string)cContext[key];
window.SetPaint(valS);
break;
case GC_SHAPE:
valS = (string)cContext[key];
window.SetShape(valS);
break;
case GC_LINESTYLE:
valH = (HTuple)cContext[key];
window.SetLineStyle(valH);
break;
default:
break;
}
if (valI != -1)
{
if (stateOfSettings.Contains(key))
stateOfSettings[key] = valI;
else
stateOfSettings.Add(key, valI);
valI = -1;
}
else if (valS != "")
{
if (stateOfSettings.Contains(key))
stateOfSettings[key] = valI;
else
stateOfSettings.Add(key, valI);
valS = "";
}
else if (valH != null)
{
if (stateOfSettings.Contains(key))
stateOfSettings[key] = valI;
else
stateOfSettings.Add(key, valI);
valH = null;
}
}//while
}
catch (HOperatorException e)
{
gcNotification(e.Message);
return;
}
}
/// <summary>Sets a value for the graphical mode GC_COLOR</summary>
/// <param name="val">
/// A single color, e.g. "blue", "green" ...etc.
/// </param>
public void setColorAttribute(string val)
{
if (graphicalSettings.ContainsKey(GC_COLORED))
graphicalSettings.Remove(GC_COLORED);
addValue(GC_COLOR, val);
}
/// <summary>Sets a value for the graphical mode GC_COLORED</summary>
/// <param name="val">
/// The colored mode, which can be either "colored3" or "colored6"
/// or "colored12"
/// </param>
public void setColoredAttribute(int val)
{
if (graphicalSettings.ContainsKey(GC_COLOR))
graphicalSettings.Remove(GC_COLOR);
addValue(GC_COLORED, val);
}
/// <summary>Sets a value for the graphical mode GC_DRAWMODE</summary>
/// <param name="val">
/// One of the possible draw modes: "margin" or "fill"
/// </param>
public void setDrawModeAttribute(string val)
{
addValue(GC_DRAWMODE, val);
}
/// <summary>Sets a value for the graphical mode GC_LINEWIDTH</summary>
/// <param name="val">
/// The line width, which can range from 1 to 50
/// </param>
public void setLineWidthAttribute(int val)
{
addValue(GC_LINEWIDTH, val);
}
/// <summary>Sets a value for the graphical mode GC_LUT</summary>
/// <param name="val">
/// One of the possible modes of look up tables. For
/// further information on particular setups, please refer to the
/// Reference Manual entry of the operator set_lut.
/// </param>
public void setLutAttribute(string val)
{
addValue(GC_LUT, val);
}
/// <summary>Sets a value for the graphical mode GC_PAINT</summary>
/// <param name="val">
/// One of the possible paint modes. For further
/// information on particular setups, please refer refer to the
/// Reference Manual entry of the operator set_paint.
/// </param>
public void setPaintAttribute(string val)
{
addValue(GC_PAINT, val);
}
/// <summary>Sets a value for the graphical mode GC_SHAPE</summary>
/// <param name="val">
/// One of the possible shape modes. For further
/// information on particular setups, please refer refer to the
/// Reference Manual entry of the operator set_shape.
/// </param>
public void setShapeAttribute(string val)
{
addValue(GC_SHAPE, val);
}
/// <summary>Sets a value for the graphical mode GC_LINESTYLE</summary>
/// <param name="val">
/// A line style mode, which works
/// identical to the input for the HDevelop operator
/// 'set_line_style'. For particular information on this
/// topic, please refer to the Reference Manual entry of the operator
/// set_line_style.
/// </param>
public void setLineStyleAttribute(HTuple val)
{
addValue(GC_LINESTYLE, val);
}
/// <summary>
/// Adds a value to the hashlist 'graphicalSettings' for the
/// graphical mode described by the parameter 'key'
/// </summary>
/// <param name="key">
/// A graphical mode defined by the constant GC_*
/// </param>
/// <param name="val">
/// Defines the value as an int for this graphical
/// mode 'key'
/// </param>
private void addValue(string key, int val)
{
if (graphicalSettings.ContainsKey(key))
graphicalSettings[key] = val;
else
graphicalSettings.Add(key, val);
}
/// <summary>
/// Adds a value to the hashlist 'graphicalSettings' for the
/// graphical mode, described by the parameter 'key'
/// </summary>
/// <param name="key">
/// A graphical mode defined by the constant GC_*
/// </param>
/// <param name="val">
/// Defines the value as a string for this
/// graphical mode 'key'
/// </param>
private void addValue(string key, string val)
{
if (graphicalSettings.ContainsKey(key))
graphicalSettings[key] = val;
else
graphicalSettings.Add(key, val);
}
/// <summary>
/// Adds a value to the hashlist 'graphicalSettings' for the
/// graphical mode, described by the parameter 'key'
/// </summary>
/// <param name="key">
/// A graphical mode defined by the constant GC_*
/// </param>
/// <param name="val">
/// Defines the value as a HTuple for this
/// graphical mode 'key'
/// </param>
private void addValue(string key, HTuple val)
{
if (graphicalSettings.ContainsKey(key))
graphicalSettings[key] = val;
else
graphicalSettings.Add(key, val);
}
/// <summary>
/// Clears the list of graphical settings.
/// There will be no graphical changes made prior
/// before drawing objects, since there are no
/// graphical entries to be applied to the window.
/// </summary>
public void clear()
{
graphicalSettings.Clear();
}
/// <summary>
/// Returns an exact clone of this graphicsContext instance
/// </summary>
public GraphicsContext copy()
{
return new GraphicsContext((Hashtable)this.graphicalSettings.Clone());
}
/// <summary>
/// If the hashtable contains the key, the corresponding
/// hashtable value is returned
/// </summary>
/// <param name="key">
/// One of the graphical keys starting with GC_*
/// </param>
public object getGraphicsAttribute(string key)
{
if (graphicalSettings.ContainsKey(key))
return graphicalSettings[key];
return null;
}
/// <summary>
/// Returns a copy of the hashtable that carries the
/// entries for the current graphical context
/// </summary>
/// <returns> current graphical context </returns>
public Hashtable copyContextList()
{
return (Hashtable)graphicalSettings.Clone();
}
/********************************************************************/
public void dummy(string val) { }
}//end of class
}//end of namespace
| |
// 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.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.HtmlEditor.Linking;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor.Autoreplace;
using OpenLiveWriter.PostEditor.LiveClipboard;
using OpenLiveWriter.PostEditor.Configuration.Accounts;
using OpenLiveWriter.SpellChecker;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor
{
/// <summary>
/// Class for handling preferences
/// </summary>
public class PreferencesHandler
{
/// <summary>
/// The array of preferences panel types.
/// </summary>
private static Type[] preferencesPanelTypes;
/// <summary>
/// The name to preferences panel type table.
/// </summary>
private static Hashtable preferencesPanelTypeTable;
public static PreferencesHandler Instance
{
get
{
if (_instance == null)
_instance = new PreferencesHandler();
return _instance;
}
}
private static PreferencesHandler _instance;
/// <summary>
/// A version of show preferences that allows the caller to specify which
/// panel should be selected when the dialog opens
/// </summary>
/// <param name="selectedPanelName">The selected panel name.</param>
public void ShowPreferences(IWin32Window owner, string selectedPanelName)
{
LoadPreferencesPanels();
Type type;
if (selectedPanelName == null || selectedPanelName.Length == 0)
type = null;
else
type = (Type)preferencesPanelTypeTable[selectedPanelName.ToLower(CultureInfo.InvariantCulture)];
ShowPreferences(owner, null, type);
}
/// <summary>
/// A version of show preferences that allows the caller to specify which
/// panel should be selected when the dialog opens
/// </summary>
/// <param name="selectedPanelType"></param>
public void ShowPreferences(IWin32Window owner, IBlogPostEditingSite editingSite, Type selectedPanelType)
{
// Load preferences panels.
LoadPreferencesPanels();
// Show the preferences form.
using (new WaitCursor())
{
using (PreferencesForm preferencesForm = new PreferencesForm())
{
// Set the PreferencesPanel entries.
for (int i = 0; i < preferencesPanelTypes.Length; i++)
{
// Add the entry.
Type type = preferencesPanelTypes[i];
PreferencesPanel panel = Activator.CreateInstance(type) as PreferencesPanel;
if (editingSite != null && panel is IBlogPostEditingSitePreferences)
{
(panel as IBlogPostEditingSitePreferences).EditingSite = editingSite;
}
preferencesForm.SetEntry(i, panel);
// Select it, if requested.
if (type.Equals(selectedPanelType))
preferencesForm.SelectedIndex = i;
}
// Provide a default selected index if none was specified.
if (preferencesForm.SelectedIndex == -1)
preferencesForm.SelectedIndex = 0;
// Show the form.
preferencesForm.Win32Owner = owner;
preferencesForm.ShowDialog(owner);
// if we have an editing site then let it know that the account
// list may have been edited (allows it to adapt to the currently
// active weblog being deleted)
if (editingSite != null)
editingSite.NotifyWeblogAccountListEdited();
}
}
}
public void ShowWebProxyPreferences(IWin32Window owner)
{
// Show the preferences form.
using (new WaitCursor())
{
using (PreferencesForm preferencesForm = new PreferencesForm())
{
preferencesForm.Text = Res.Get(StringId.ProxyPrefTitle);
preferencesForm.SetEntry(0, new WebProxyPreferencesPanel());
preferencesForm.SelectedIndex = 0;
preferencesForm.Win32Owner = owner;
preferencesForm.ShowDialog(owner);
}
}
}
/// <summary>
/// Helper to load the preferences panels.
/// </summary>
private static void LoadPreferencesPanels()
{
// If preferences panels have been loaded already, return.
if (preferencesPanelTypes != null)
return;
Type type;
ArrayList types = new ArrayList();
preferencesPanelTypeTable = new Hashtable();
// Writer Preferences
type = typeof(PostEditorPreferencesPanel);
preferencesPanelTypeTable["preferences"] = type;
types.Add(type);
type = typeof(EditingPreferencesPanel);
preferencesPanelTypeTable["editing"] = type;
types.Add(type);
type = typeof(WeblogAccountPreferencesPanel);
preferencesPanelTypeTable["accounts"] = type;
types.Add(type);
// Spelling preferences.
type = typeof(SpellingPreferencesPanel);
preferencesPanelTypeTable["spelling"] = type;
types.Add(type);
//glossary management
type = typeof(GlossaryPreferencesPanel);
preferencesPanelTypeTable["glossary"] = type;
types.Add(type);
type = typeof(AutoreplacePreferencesPanel);
preferencesPanelTypeTable["autoreplace"] = type;
//types.Add(type);
if (ApplicationDiagnostics.TestMode || LiveClipboardManager.LiveClipboardFormatHandlers.Length > 0)
{
type = typeof(LiveClipboardPreferencesPanel);
preferencesPanelTypeTable["liveclipboard"] = type;
types.Add(type);
}
// Plugin preferences
type = typeof(PluginsPreferencesPanel);
preferencesPanelTypeTable["plugins"] = type;
types.Add(type);
// WebProxy preferences
type = typeof(WebProxyPreferencesPanel);
preferencesPanelTypeTable["webproxy"] = type;
types.Add(type);
type = typeof(PingPreferencesPanel);
preferencesPanelTypeTable["pings"] = type;
types.Add(type);
type = typeof(PrivacyPreferencesPanel);
preferencesPanelTypeTable["privacy"] = type;
types.Add(type);
// Set the preferences panels type array.
preferencesPanelTypes = (Type[])types.ToArray(typeof(Type));
}
}
internal interface IBlogPostEditingSitePreferences
{
IBlogPostEditingSite EditingSite { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.Localization;
using Orchard.Packaging.Events;
using Orchard.Packaging.Extensions;
using Orchard.Packaging.GalleryServer;
using Orchard.Packaging.Models;
using Orchard.Packaging.Services;
using Orchard.Packaging.ViewModels;
using Orchard.Security;
using Orchard.Themes;
using Orchard.UI.Admin;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using Orchard.Utility.Extensions;
using ILogger = Orchard.Logging.ILogger;
using NullLogger = Orchard.Logging.NullLogger;
namespace Orchard.Packaging.Controllers {
[OrchardFeature("Gallery")]
[Themed, Admin]
public class GalleryController : Controller {
private readonly ShellSettings _shellSettings;
private readonly IPackagingSourceManager _packagingSourceManager;
private readonly IExtensionDisplayEventHandler _extensionDisplayEventHandler;
private readonly IExtensionManager _extensionManager;
public GalleryController(
IEnumerable<IExtensionDisplayEventHandler> extensionDisplayEventHandlers,
ShellSettings shellSettings,
IPackagingSourceManager packagingSourceManager,
IExtensionManager extensionManager,
IOrchardServices services) {
_shellSettings = shellSettings;
_packagingSourceManager = packagingSourceManager;
_extensionDisplayEventHandler = extensionDisplayEventHandlers.FirstOrDefault();
_extensionManager = extensionManager;
Services = services;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
}
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public ActionResult Sources() {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list sources")))
return new HttpUnauthorizedResult();
return View(new PackagingSourcesViewModel {
Sources = _packagingSourceManager.GetSources(),
});
}
[HttpPost]
public ActionResult Remove(int id) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to remove sources")))
return new HttpUnauthorizedResult();
_packagingSourceManager.RemoveSource(id);
Services.Notifier.Information(T("The feed has been removed successfully."));
return RedirectToAction("Sources");
}
public ActionResult AddSource() {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources")))
return new HttpUnauthorizedResult();
return View(new PackagingAddSourceViewModel());
}
[HttpPost]
public ActionResult AddSource(string url) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources")))
return new HttpUnauthorizedResult();
if (!String.IsNullOrEmpty(url)) {
if (!url.StartsWith("http")) {
ModelState.AddModelError("Url", T("The Url is not valid").Text);
}
}
else if (String.IsNullOrWhiteSpace(url)) {
ModelState.AddModelError("Url", T("Url is required").Text);
}
string title = null;
// try to load the feed
try {
XNamespace atomns = "http://www.w3.org/2005/Atom";
var feed = XDocument.Load(url, LoadOptions.PreserveWhitespace);
var titleNode = feed.Descendants(atomns + "title").FirstOrDefault();
if (titleNode != null)
title = titleNode.Value;
if (String.IsNullOrWhiteSpace(title)) {
ModelState.AddModelError("Url", T("The feed has no title.").Text);
}
}
catch {
ModelState.AddModelError("Url", T("The url of the feed or its content is not valid.").Text);
}
if (!ModelState.IsValid)
return View(new PackagingAddSourceViewModel { Url = url });
_packagingSourceManager.AddSource(title, url);
Services.Notifier.Information(T("The feed has been added successfully."));
return RedirectToAction("Sources");
}
public ActionResult Modules(PackagingExtensionsOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list Modules")))
return new HttpUnauthorizedResult();
var pager = new Pager(Services.WorkContext.CurrentSite, pagerParameters);
return ListExtensions(options, DefaultExtensionTypes.Module, pager);
}
public ActionResult Themes(PackagingExtensionsOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list Themes")))
return new HttpUnauthorizedResult();
var pager = new Pager(Services.WorkContext.CurrentSite, pagerParameters);
return ListExtensions(options, DefaultExtensionTypes.Theme, pager);
}
protected ActionResult ListExtensions(PackagingExtensionsOptions options, string packageType, Pager pager) {
var selectedSource = _packagingSourceManager.GetSources().Where(s => s.Id == options.SourceId).FirstOrDefault();
var sources = selectedSource != null
? new[] { selectedSource }
: _packagingSourceManager.GetSources()
;
IEnumerable<PackagingEntry> extensions = null;
int totalCount = 0;
foreach (var source in sources) {
try {
Expression<Func<PublishedPackage, bool>> packagesCriteria = p => p.PackageType == packageType &&
p.IsLatestVersion &&
(string.IsNullOrEmpty(options.SearchText)
|| p.Title.Contains(options.SearchText)
|| p.Description.Contains(options.SearchText)
|| p.Tags.Contains(options.SearchText));
var sourceExtensions = _packagingSourceManager.GetExtensionList(true,
source,
packages => {
packages = packages.Where(packagesCriteria);
switch (options.Order) {
case PackagingExtensionsOrder.Downloads:
packages = packages.OrderByDescending(p => p.DownloadCount).ThenBy(p => p.Title);
break;
case PackagingExtensionsOrder.Ratings:
packages = packages.OrderByDescending(p => p.Rating).ThenBy(p => p.Title);
break;
case PackagingExtensionsOrder.Alphanumeric:
packages = packages.OrderBy(p => p.Title);
break;
}
if (pager.PageSize != 0) {
packages = packages.Skip((pager.Page - 1) * pager.PageSize).Take(pager.PageSize);
}
return packages;
}).ToArray();
// count packages separately to prevent loading everything just to count
totalCount += _packagingSourceManager.GetExtensionCount(
source,
packages => packages.Where(packagesCriteria));
extensions = extensions == null ? sourceExtensions : extensions.Concat(sourceExtensions);
// apply another paging rule in case there were multiple sources
if (sources.Count() > 1) {
switch (options.Order) {
case PackagingExtensionsOrder.Downloads:
extensions = extensions.OrderByDescending(p => p.DownloadCount).ThenBy(p => p.Title);
break;
case PackagingExtensionsOrder.Ratings:
extensions = extensions.OrderByDescending(p => p.Rating).ThenBy(p => p.Title);
break;
case PackagingExtensionsOrder.Alphanumeric:
extensions = extensions.OrderBy(p => p.Title);
break;
}
if (pager.PageSize != 0) {
extensions = extensions.Take(pager.PageSize);
}
}
}
catch (Exception exception) {
Services.Notifier.Error(T("Error loading extensions from gallery source '{0}'. {1}.", source.FeedTitle, exception.Message));
}
}
extensions = extensions ?? new PackagingEntry[0];
var pagerShape = Services.New.Pager(pager).TotalItemCount(totalCount);
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Order", options.Order);
routeData.Values.Add("Options.SearchText", options.SearchText);
routeData.Values.Add("Options.SourceId", options.SourceId);
pagerShape.RouteData(routeData);
extensions = extensions.ToList();
// Populate the notifications
IEnumerable<Tuple<ExtensionDescriptor, PackagingEntry>> extensionDescriptors = _extensionManager.AvailableExtensions()
.Join(extensions, extensionDescriptor => extensionDescriptor.Id, packaginEntry => packaginEntry.ExtensionId(),
(extensionDescriptor, packagingEntry) => new Tuple<ExtensionDescriptor, PackagingEntry>(extensionDescriptor, packagingEntry));
foreach (Tuple<ExtensionDescriptor, PackagingEntry> packagings in extensionDescriptors) {
packagings.Item2.Installed = true;
if (_extensionDisplayEventHandler != null) {
foreach (string notification in _extensionDisplayEventHandler.Displaying(packagings.Item1, ControllerContext.RequestContext)) {
packagings.Item2.Notifications.Add(notification);
}
}
}
return View(packageType == DefaultExtensionTypes.Theme ? "Themes" : "Modules", new PackagingExtensionsViewModel {
Extensions = extensions,
Sources = _packagingSourceManager.GetSources().OrderBy(s => s.FeedTitle),
Pager = pagerShape,
Options = options
});
}
}
}
| |
using System;
using NUnit.Framework;
using Braintree;
namespace Braintree.Tests
{
[TestFixture]
public class TransparentRedirectTest
{
private BraintreeGateway gateway;
private BraintreeService service;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
service = new BraintreeService(gateway.Configuration);
}
[Test]
public void Url_ReturnsCorrectUrl()
{
var host = System.Environment.GetEnvironmentVariable("GATEWAY_HOST") ?? "localhost";
var port = System.Environment.GetEnvironmentVariable("GATEWAY_PORT") ?? "3000";
var url = "http://" + host + ":" + port + "/merchants/integration_merchant_id/transparent_redirect_requests";
Assert.AreEqual(url, gateway.TransparentRedirect.Url);
}
[Test]
public void BuildTrData_BuildsAQueryStringWithApiVersion()
{
String tr_data = gateway.TransparentRedirect.BuildTrData(new TransactionRequest(), "example.com");
TestHelper.AssertIncludes("api_version=3", tr_data);
}
[Test]
public void CreateTransactionFromTransparentRedirect()
{
TransactionRequest trParams = new TransactionRequest
{
Type = TransactionType.SALE
};
TransactionRequest request = new TransactionRequest
{
Amount = SandboxValues.TransactionAmount.AUTHORIZE,
CreditCard = new TransactionCreditCardRequest
{
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2009",
}
};
String queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Transaction> result = gateway.TransparentRedirect.ConfirmTransaction(queryString);
Assert.IsTrue(result.IsSuccess());
Transaction transaction = result.Target;
Assert.AreEqual(1000.00, transaction.Amount);
Assert.AreEqual(TransactionType.SALE, transaction.Type);
Assert.AreEqual(TransactionStatus.AUTHORIZED, transaction.Status);
Assert.AreEqual(DateTime.Now.Year, transaction.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, transaction.UpdatedAt.Value.Year);
CreditCard creditCard = transaction.CreditCard;
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("05", creditCard.ExpirationMonth);
Assert.AreEqual("2009", creditCard.ExpirationYear);
Assert.AreEqual("05/2009", creditCard.ExpirationDate);
}
[Test]
public void CreateCustomerFromTransparentRedirect()
{
CustomerRequest trParams = new CustomerRequest
{
FirstName = "John"
};
CustomerRequest request = new CustomerRequest
{
LastName = "Doe"
};
String queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
[Test]
public void UpdateCustomerFromTransparentRedirect()
{
var createRequest = new CustomerRequest
{
FirstName = "Miranda",
LastName = "Higgenbottom"
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
CustomerRequest trParams = new CustomerRequest
{
CustomerId = createdCustomer.Id,
FirstName = "Penelope"
};
CustomerRequest request = new CustomerRequest
{
LastName = "Lambert"
};
String queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
Assert.IsTrue(result.IsSuccess());
Customer updatedCustomer = gateway.Customer.Find(createdCustomer.Id);
Assert.AreEqual("Penelope", updatedCustomer.FirstName);
Assert.AreEqual("Lambert", updatedCustomer.LastName);
}
[Test]
public void CreateCreditCardFromTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest trParams = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "4111111111111111",
ExpirationDate = "10/10"
};
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "John Doe"
};
String queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard creditCard = result.Target;
Assert.AreEqual("John Doe", creditCard.CardholderName);
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("10/2010", creditCard.ExpirationDate);
}
[Test]
public void UpdateCreditCardFromTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5105105105105100",
ExpirationDate = "05/12",
CardholderName = "Beverly D'angelo"
};
CreditCard createdCreditCard = gateway.CreditCard.Create(creditCardRequest).Target;
CreditCardRequest trParams = new CreditCardRequest
{
PaymentMethodToken = createdCreditCard.Token,
Number = "4111111111111111",
ExpirationDate = "10/10"
};
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "Sampsonite"
};
String queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard creditCard = gateway.CreditCard.Find(createdCreditCard.Token);
Assert.AreEqual("Sampsonite", creditCard.CardholderName);
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("10/2010", creditCard.ExpirationDate);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class NoParameterBlockTests : SharedBlockTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void DoubleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression)));
}
[Fact]
public void DoubleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void TripleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void TripleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void TripleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuadrupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuadrupleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuadrupleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuintupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuintupleElementBlockNullArgument()
{
Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuintupleElementBlockUnreadable()
{
Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
Assert.Throws<ArgumentException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SextupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), default(IEnumerable<ParameterExpression>), Expression.Constant(0)));
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), null, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), expressions));
Assert.Throws<ArgumentException>(null, (() => Expression.Block(typeof(string), expressions.ToArray())));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int)));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountZeroOnNonVariableAcceptingForms(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Empty(block.Variables);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, expressions));
Assert.Same(block, block.Update(Enumerable.Empty<ParameterExpression>(), expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory, MemberData(nameof(BlockSizes))]
public void ExpressionListBehavior(int parCount)
{
// This method contains a lot of assertions, which amount to one large assertion that
// the result of the Expressions property behaves correctly.
Expression[] exps = Enumerable.Range(0, parCount).Select(_ => Expression.Constant(0)).ToArray();
BlockExpression block = Expression.Block(exps);
ReadOnlyCollection<Expression> children = block.Expressions;
Assert.Equal(parCount, children.Count);
using (var en = children.GetEnumerator())
{
IEnumerator nonGenEn = ((IEnumerable)children).GetEnumerator();
for (int i = 0; i != parCount; ++i)
{
Assert.True(en.MoveNext());
Assert.True(nonGenEn.MoveNext());
Assert.Same(exps[i], children[i]);
Assert.Same(exps[i], en.Current);
Assert.Same(exps[i], nonGenEn.Current);
Assert.Equal(i, children.IndexOf(exps[i]));
Assert.True(children.Contains(exps[i]));
}
Assert.False(en.MoveNext());
Assert.False(nonGenEn.MoveNext());
(nonGenEn as IDisposable)?.Dispose();
}
Expression[] copyToTest = new Expression[parCount + 1];
Assert.Throws<ArgumentNullException>(() => children.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => children.CopyTo(copyToTest, -1));
Assert.All(copyToTest, Assert.Null); // assert partial copy didn't happen before exception
Assert.Throws<ArgumentException>(() => children.CopyTo(copyToTest, 2));
Assert.All(copyToTest, Assert.Null);
children.CopyTo(copyToTest, 1);
Assert.Equal(copyToTest, exps.Prepend(null));
Assert.Throws<ArgumentOutOfRangeException>("index", () => children[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => children[parCount]);
Assert.Equal(-1, children.IndexOf(Expression.Parameter(typeof(int))));
Assert.False(children.Contains(Expression.Parameter(typeof(int))));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateToNullArguments(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Throws<ArgumentNullException>("expressions", () => block.Update(null, null));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDoesntRepeatEnumeration(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, new RunOnceEnumerable<Expression>(expressions)));
Assert.NotSame(
block,
block.Update(null, new RunOnceEnumerable<Expression>(PadBlock(blockSize - 1, Expression.Constant(1)))));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDifferentSizeReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, block.Update(null, block.Expressions.Prepend(Expression.Empty())));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateAnyExpressionDifferentReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
Expression[] expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
for (int i = 0; i != expressions.Length; ++i)
{
Expression[] newExps = new Expression[expressions.Length];
expressions.CopyTo(newExps, 0);
newExps[i] = Expression.Constant(1);
Assert.NotSame(block, block.Update(null, newExps));
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. 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 System.IO;
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.ToolPackage;
using Microsoft.DotNet.Tools.Tool.Install;
using Microsoft.DotNet.Tools.Tests.ComponentMocks;
using Microsoft.DotNet.Tools.Test.Utilities;
using Microsoft.DotNet.ShellShim;
using Microsoft.Extensions.DependencyModel.Tests;
using Microsoft.Extensions.EnvironmentAbstractions;
using Xunit;
using Parser = Microsoft.DotNet.Cli.Parser;
using System.Runtime.InteropServices;
using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Install.LocalizableStrings;
using System.Text.Json;
namespace Microsoft.DotNet.Tests.Commands.Tool
{
public class ToolInstallGlobalOrToolPathCommandTests
{
private readonly IFileSystem _fileSystem;
private readonly IToolPackageStore _toolPackageStore;
private readonly IToolPackageStoreQuery _toolPackageStoreQuery;
private readonly CreateShellShimRepository _createShellShimRepository;
private readonly CreateToolPackageStoresAndInstaller _createToolPackageStoreAndInstaller;
private readonly EnvironmentPathInstructionMock _environmentPathInstructionMock;
private readonly AppliedOption _appliedCommand;
private readonly ParseResult _parseResult;
private readonly BufferedReporter _reporter;
private readonly string _temporaryDirectory;
private readonly string _pathToPlaceShim;
private readonly string _pathToPlacePackages;
private const string PackageId = "global.tool.console.demo";
private const string PackageVersion = "1.0.4";
private const string ToolCommandName = "SimulatorCommand";
public ToolInstallGlobalOrToolPathCommandTests()
{
_reporter = new BufferedReporter();
_fileSystem = new FileSystemMockBuilder().UseCurrentSystemTemporaryDirectory().Build();
_temporaryDirectory = _fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath;
_pathToPlaceShim = Path.Combine(_temporaryDirectory, "pathToPlace");
_fileSystem.Directory.CreateDirectory(_pathToPlaceShim);
_pathToPlacePackages = _pathToPlaceShim + "Packages";
var toolPackageStoreMock = new ToolPackageStoreMock(new DirectoryPath(_pathToPlacePackages), _fileSystem);
_toolPackageStore = toolPackageStoreMock;
_toolPackageStoreQuery = toolPackageStoreMock;
_createShellShimRepository =
(nonGlobalLocation) => new ShellShimRepository(
new DirectoryPath(_pathToPlaceShim),
fileSystem: _fileSystem,
appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem),
filePermissionSetter: new NoOpFilePermissionSetter());
_environmentPathInstructionMock =
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim);
_createToolPackageStoreAndInstaller = (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, CreateToolPackageInstaller());
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId}");
_appliedCommand = result["dotnet"]["tool"]["install"];
var parser = Parser.Instance;
_parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId});
}
[Fact]
public void WhenRunWithPackageIdItShouldCreateValidShim()
{
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand,
_parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
// It is hard to simulate shell behavior. Only Assert shim can point to executable dll
_fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue();
var deserializedFakeShim = JsonSerializer.Deserialize<AppHostShellShimMakerMock.FakeShim>(
_fileSystem.File.ReadAllText(ExpectedCommandPath()));
_fileSystem.File.Exists(deserializedFakeShim.ExecutablePath).Should().BeTrue();
}
[Fact]
public void WhenRunFromToolInstallRedirectCommandWithPackageIdItShouldCreateValidShim()
{
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand,
_parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
var toolInstallCommand = new ToolInstallCommand(
_appliedCommand,
_parseResult,
toolInstallGlobalOrToolPathCommand);
toolInstallCommand.Execute().Should().Be(0);
_fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue();
}
[Fact]
public void WhenRunWithPackageIdWithSourceItShouldCreateValidShim()
{
const string sourcePath = "http://mysource.com";
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --add-source {sourcePath}");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
ParseResult parseResult =
Parser.Instance.ParseFrom("dotnet tool", new[] { "install", "-g", PackageId, "--add-source", sourcePath });
var toolToolPackageInstaller = CreateToolPackageInstaller(
feeds: new List<MockFeed> {
new MockFeed
{
Type = MockFeedType.ImplicitAdditionalFeed,
Uri = sourcePath,
Packages = new List<MockFeedPackage>
{
new MockFeedPackage
{
PackageId = PackageId,
Version = PackageVersion,
ToolCommandName = ToolCommandName,
}
}
}
});
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand,
parseResult,
(location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolToolPackageInstaller),
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
// It is hard to simulate shell behavior. Only Assert shim can point to executable dll
_fileSystem.File.Exists(ExpectedCommandPath())
.Should().BeTrue();
var deserializedFakeShim =
JsonSerializer.Deserialize<AppHostShellShimMakerMock.FakeShim>(
_fileSystem.File.ReadAllText(ExpectedCommandPath()));
_fileSystem.File.Exists(deserializedFakeShim.ExecutablePath).Should().BeTrue();
}
[Fact]
public void WhenRunWithPackageIdItShouldShowPathInstruction()
{
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand,
_parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter.Lines.First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText);
}
[Fact]
public void WhenRunWithPackageIdPackageFormatIsNotFullySupportedItShouldShowPathInstruction()
{
const string Warning = "WARNING";
var injectedWarnings = new Dictionary<PackageId, IEnumerable<string>>()
{
[new PackageId(PackageId)] = new List<string>() { Warning }
};
var toolPackageInstaller = new ToolPackageInstallerMock(
fileSystem: _fileSystem,
store: _toolPackageStore,
projectRestorer: new ProjectRestorerMock(
fileSystem: _fileSystem,
reporter: _reporter),
warningsMap: injectedWarnings);
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
_appliedCommand,
_parseResult,
(location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller),
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter.Lines.First().Should().Be(Warning.Yellow());
_reporter.Lines.Skip(1).First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText);
}
[Fact]
public void GivenFailedPackageInstallWhenRunWithPackageIdItShouldFail()
{
const string ErrorMessage = "Simulated error";
var toolPackageInstaller =
CreateToolPackageInstaller(
installCallback: () => throw new ToolPackageException(ErrorMessage));
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
_appliedCommand,
_parseResult,
(location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller),
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
Action a = () => toolInstallGlobalOrToolPathCommand.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(
ErrorMessage +
Environment.NewLine +
string.Format(LocalizableStrings.ToolInstallationFailedWithRestoreGuidance, PackageId));
_fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse();
}
[Fact]
public void GivenCreateShimItShouldHaveNoBrokenFolderOnDisk()
{
_fileSystem.File.CreateEmptyFile(ExpectedCommandPath()); // Create conflict shim
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
_appliedCommand,
_parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
Action a = () => toolInstallGlobalOrToolPathCommand.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(string.Format(
CommonLocalizableStrings.ShellShimConflict,
ToolCommandName));
_fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse();
}
[Fact]
public void GivenInCorrectToolConfigurationWhenRunWithPackageIdItShouldFail()
{
var toolPackageInstaller =
CreateToolPackageInstaller(
installCallback: () => throw new ToolConfigurationException("Simulated error"));
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
_appliedCommand,
_parseResult,
(location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller),
_createShellShimRepository,
_environmentPathInstructionMock,
_reporter);
Action a = () => toolInstallGlobalOrToolPathCommand.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(
string.Format(
LocalizableStrings.InvalidToolConfiguration,
"Simulated error") + Environment.NewLine +
string.Format(LocalizableStrings.ToolInstallationFailedContactAuthor, PackageId)
);
}
[Fact]
public void WhenRunWithPackageIdItShouldShowSuccessMessage()
{
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
_appliedCommand,
_parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter
.Lines
.Should()
.Equal(string.Format(
LocalizableStrings.InstallationSucceeded,
ToolCommandName,
PackageId,
PackageVersion).Green());
}
[Fact]
public void WhenRunWithInvalidVersionItShouldThrow()
{
const string invalidVersion = "!NotValidVersion!";
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version {invalidVersion}");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
appliedCommand,
result,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
Action action = () => toolInstallGlobalOrToolPathCommand.Execute();
action
.ShouldThrow<GracefulException>()
.WithMessage(string.Format(
LocalizableStrings.InvalidNuGetVersionRange,
invalidVersion));
}
[Fact]
public void WhenRunWithExactVersionItShouldSucceed()
{
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version {PackageVersion}");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
appliedCommand,
result,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter
.Lines
.Should()
.Equal(string.Format(
LocalizableStrings.InstallationSucceeded,
ToolCommandName,
PackageId,
PackageVersion).Green());
}
[Fact]
public void WhenRunWithValidVersionRangeItShouldSucceed()
{
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version [1.0,2.0]");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
appliedCommand,
result,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter
.Lines
.Should()
.Equal(string.Format(
LocalizableStrings.InstallationSucceeded,
ToolCommandName,
PackageId,
PackageVersion).Green());
}
[Fact]
public void WhenRunWithoutAMatchingRangeItShouldFail()
{
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version [5.0,10.0]");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
appliedCommand,
result,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
Action a = () => toolInstallGlobalOrToolPathCommand.Execute();
a.ShouldThrow<GracefulException>().And.Message
.Should().Contain(
LocalizableStrings.ToolInstallationRestoreFailed +
Environment.NewLine + string.Format(LocalizableStrings.ToolInstallationFailedWithRestoreGuidance, PackageId));
_fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse();
}
[Fact]
public void WhenRunWithValidVersionWildcardItShouldSucceed()
{
ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version 1.0.*");
AppliedOption appliedCommand = result["dotnet"]["tool"]["install"];
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(
appliedCommand,
result,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true),
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter
.Lines
.Should()
.Equal(string.Format(
LocalizableStrings.InstallationSucceeded,
ToolCommandName,
PackageId,
PackageVersion).Green());
}
[Fact]
public void WhenRunWithPackageIdAndBinPathItShouldNoteHaveEnvironmentPathInstruction()
{
var result = Parser.Instance.Parse($"dotnet tool install --tool-path /tmp/folder {PackageId}");
var appliedCommand = result["dotnet"]["tool"]["install"];
var parser = Parser.Instance;
var parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId});
var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand,
parseResult,
_createToolPackageStoreAndInstaller,
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim),
_reporter);
toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0);
_reporter.Lines.Should().NotContain(l => l.Contains(EnvironmentPathInstructionMock.MockInstructionText));
}
[Fact]
public void AndPackagedShimIsProvidedWhenRunWithPackageIdItCreateShimUsingPackagedShim()
{
var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty;
var prepackagedShimPath = Path.Combine (_temporaryDirectory, ToolCommandName + extension);
var tokenToIdentifyPackagedShim = "packagedShim";
_fileSystem.File.WriteAllText(prepackagedShimPath, tokenToIdentifyPackagedShim);
var result = Parser.Instance.Parse($"dotnet tool install --tool-path /tmp/folder {PackageId}");
var appliedCommand = result["dotnet"]["tool"]["install"];
var parser = Parser.Instance;
var parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId});
var packagedShimsMap = new Dictionary<PackageId, IReadOnlyList<FilePath>>
{
[new PackageId(PackageId)] = new[] {new FilePath(prepackagedShimPath)}
};
var installCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand,
parseResult,
(location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, new ToolPackageInstallerMock(
fileSystem: _fileSystem,
store: _toolPackageStore,
packagedShimsMap: packagedShimsMap,
projectRestorer: new ProjectRestorerMock(
fileSystem: _fileSystem,
reporter: _reporter))),
_createShellShimRepository,
new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim),
_reporter);
installCommand.Execute().Should().Be(0);
_fileSystem.File.ReadAllText(ExpectedCommandPath()).Should().Be(tokenToIdentifyPackagedShim);
}
private IToolPackageInstaller CreateToolPackageInstaller(
List<MockFeed> feeds = null,
Action installCallback = null)
{
return new ToolPackageInstallerMock(
fileSystem: _fileSystem,
store: _toolPackageStore,
projectRestorer: new ProjectRestorerMock(
fileSystem: _fileSystem,
reporter: _reporter,
feeds: feeds),
installCallback: installCallback);
}
private string ExpectedCommandPath()
{
var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty;
return Path.Combine(
_pathToPlaceShim,
ToolCommandName + extension);
}
private class NoOpFilePermissionSetter : IFilePermissionSetter
{
public void SetUserExecutionPermission(string path)
{
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System;
using System.Linq;
/// <summary>
/// This script shows how to call the Insert command on a database using simplified class-based
/// methods or by calling the SQL statements directly. Transactions are shown in the functions that
/// insert three times to show how to speed up your data.
///
/// In this example we will not overwrite the working database since we are updating the data. If
/// we were to overwrite, then changes would be lost each time the scene is run again.
/// </summary>
public class InsertCommand : MonoBehaviour {
// The list of player stats from the database
private List<PlayerStats> _playerStatsList;
// These variables will be used to store data from the GUI interface
private string _newPlayerName;
private string _newPlayerTotalKills;
private string _newPlayerPoints;
// reference to our db manager object
public SimpleSQL.SimpleSQLManager dbManager;
// reference to our output text object
public GUIText outputText;
void Start()
{
// clear out the output text since we are using GUI in this example
outputText.text = "";
// reset the GUI and reload
ResetGUI();
}
void OnGUI()
{
GUILayout.BeginVertical();
GUILayout.Space(10.0f);
GUILayout.BeginHorizontal();
GUILayout.Space(10.0f);
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.Label("Player Name:", GUILayout.Width(100.0f));
_newPlayerName = GUILayout.TextField(_newPlayerName, GUILayout.Width(200.0f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Total Kills:", GUILayout.Width(100.0f));
_newPlayerTotalKills = GUILayout.TextField(_newPlayerTotalKills, GUILayout.Width(200.0f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Points:", GUILayout.Width(100.0f));
_newPlayerPoints = GUILayout.TextField(_newPlayerPoints, GUILayout.Width(200.0f));
GUILayout.EndHorizontal();
int totalKills;
int points;
if (!int.TryParse(_newPlayerTotalKills, out totalKills))
totalKills = 0;
if (!int.TryParse(_newPlayerPoints, out points))
points = 0;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Insert", GUILayout.Width(100.0f)))
{
SavePlayerStats_Simple(_newPlayerName, totalKills, points);
ResetGUI();
}
GUILayout.Label("OR", GUILayout.Width(30.0f));
if (GUILayout.Button("Insert Query", GUILayout.Width(100.0f)))
{
SavePlayerStats_Query(_newPlayerName, totalKills, points);
ResetGUI();
}
GUILayout.Label("OR", GUILayout.Width(30.0f));
if (GUILayout.Button("Insert 3 Times", GUILayout.Width(200.0f)))
{
SavePlayerStats_SimpleThreeTimes(_newPlayerName, totalKills, points);
ResetGUI();
}
GUILayout.Label("OR", GUILayout.Width(30.0f));
if (GUILayout.Button("Insert 3 Times Query", GUILayout.Width(200.0f)))
{
SavePlayerStats_QueryThreeTimes(_newPlayerName, totalKills, points);
ResetGUI();
}
GUILayout.EndHorizontal();
GUILayout.Space(20.0f);
GUILayout.BeginHorizontal();
GUILayout.Label("Player", GUILayout.Width(200.0f));
GUILayout.Label("Total Kills", GUILayout.Width(150.0f));
GUILayout.Label("Points", GUILayout.Width(150.0f));
GUILayout.EndHorizontal();
GUILayout.Label("-----------------------------------------------------------------------------------------------------------------------------------------");
foreach (PlayerStats playerStats in _playerStatsList)
{
GUILayout.BeginHorizontal();
GUILayout.Label(playerStats.PlayerName, GUILayout.Width(200.0f));
GUILayout.Label(playerStats.TotalKills.ToString(), GUILayout.Width(150.0f));
GUILayout.Label(playerStats.Points.ToString(), GUILayout.Width(150.0f));
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
private void ResetGUI()
{
// Reset the temporary GUI variables
_newPlayerName = "";
_newPlayerTotalKills = "";
_newPlayerPoints = "";
// Loads the player stats from the database using Linq
_playerStatsList = new List<PlayerStats> (from ps in dbManager.Table<PlayerStats> () select ps);
}
/// <summary>
/// Saves the player stats by using the PlayerStats class structure. No need for SQL here.
/// </summary>
/// <param name='playerName'>
/// Player name.
/// </param>
/// <param name='totalKills'>
/// Total kills.
/// </param>
/// <param name='points'>
/// Points.
/// </param>
private void SavePlayerStats_Simple(string playerName, int totalKills, int points)
{
// Initialize our PlayerStats class
PlayerStats playerStats = new PlayerStats { PlayerName = playerName, TotalKills = totalKills, Points = points };
// Insert our PlayerStats into the database
dbManager.Insert(playerStats);
}
/// <summary>
/// Saves the player stats by executing a SQL statement. Note that no data is returned, this only modifies the table
/// </summary>
/// <param name='playerName'>
/// Player name.
/// </param>
/// <param name='totalKills'>
/// Total kills.
/// </param>
/// <param name='points'>
/// Points.
/// </param>
private void SavePlayerStats_Query(string playerName, int totalKills, int points)
{
// Call our SQL statement using ? to bind our variables
dbManager.Execute("INSERT INTO PlayerStats (PlayerName, TotalKills, Points) VALUES (?, ?, ?)", playerName, totalKills, points);
}
/// <summary>
/// Saves the player stats three times, using a collection of PlayerStats and inserting all at once. This example uses
/// transactions which can vastly reduce the amount of time spent updating data when you have a lot of records to insert.
/// </summary>
/// <param name='playerName'>
/// Player name.
/// </param>
/// <param name='totalKills'>
/// Total kills.
/// </param>
/// <param name='points'>
/// Points.
/// </param>
private void SavePlayerStats_SimpleThreeTimes(string playerName, int totalKills, int points)
{
// set up our playerStats variable to store data
PlayerStats playerStats;
// set up our collection of playerStats to pass to the database
List<PlayerStats> playerStatsCollection = new List<PlayerStats>();
// add player stats to the collection
playerStats = new PlayerStats { PlayerName = playerName, TotalKills = totalKills, Points = points };
playerStatsCollection.Add (playerStats);
// add player stats to the collection
playerStats = new PlayerStats { PlayerName = playerName, TotalKills = totalKills, Points = points };
playerStatsCollection.Add (playerStats);
// add player stats to the collection
playerStats = new PlayerStats { PlayerName = playerName, TotalKills = totalKills, Points = points };
playerStatsCollection.Add (playerStats);
// insert all the player stats at one time by passing the collection
dbManager.InsertAll(playerStatsCollection);
}
/// <summary>
/// Saves the player stats three times using a SQL statement. The calls are made inside of a transaction
/// by using BeginTransaction and Commit. Transactions vastly reduce the amount of time it takes
/// to save multiple records.
/// </summary>
/// <param name='playerName'>
/// Player name.
/// </param>
/// <param name='totalKills'>
/// Total kills.
/// </param>
/// <param name='points'>
/// Points.
/// </param>
private void SavePlayerStats_QueryThreeTimes(string playerName, int totalKills, int points)
{
// set up our insert SQL statement with ? parameters
string sql = "INSERT INTO PlayerStats (PlayerName, TotalKills, Points) VALUES (?, ?, ?)";
// start a transaction
dbManager.BeginTransaction();
// execute the SQL statement three times
dbManager.Execute(sql, playerName, totalKills, points);
dbManager.Execute(sql, playerName, totalKills, points);
dbManager.Execute(sql, playerName, totalKills, points);
// commit our transaction to the database
dbManager.Commit();
}
}
| |
// 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 System.Linq;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
using System.IO;
using System.Diagnostics;
namespace Microsoft.Research.CodeAnalysis
{
/// <summary>
/// The precondition discharger
/// </summary>
public interface IPreconditionInference
{
bool ShouldAddAssumeFalse { get; }
bool TryInferConditions(ProofObligation obl, ICodeFixesManager codefixesManager, out InferredConditions conditions);
}
/// <summary>
/// The manager for candidate preconditions
/// </summary>
[ContractClass(typeof(IPreconditionDispatcherContracts))]
public interface IPreconditionDispatcher
{
/// <summary>
/// Add the preconditions to the list of current preconditions
/// </summary>
ProofOutcome AddPreconditions(ProofObligation obl, IEnumerable<BoxedExpression> preconditions, ProofOutcome originalOutcome);
/// <summary>
/// Returns the list of precondition for this method
/// </summary>
IEnumerable<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>> GeneratePreconditions();
/// <summary>
/// Suggest the precondition.
/// Returns how many preconditions have been suggested
/// </summary>
int SuggestPreconditions(bool treatSuggestionsAsWarnings, bool forceSuggestionOutput);
/// <summary>
/// Infer the precondition.
/// Returns how many preconditions have been propagated to the callers
/// </summary>
/// <param name="asPrecondition">if true, try to propagate as precondition, otherwise as assume</param>
int PropagatePreconditions(bool asPrecondition);
int NumberOfWarnings { get; }
}
public class PreconditionInferenceManager
{
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.Inference != null);
Contract.Invariant(this.Dispatch != null);
}
public readonly IPreconditionInference Inference;
public readonly IPreconditionDispatcher Dispatch;
static private PreconditionInferenceManager dummy; // Thread-safe
static public PreconditionInferenceManager Dummy
{
get
{
if (dummy == null)
{
dummy = new PreconditionInferenceManager(new DummyIPreconditionInference(), new DummyIPreconditionDispatcher());
}
return dummy;
}
}
public PreconditionInferenceManager(IPreconditionInference Inference, IPreconditionDispatcher Dispatcher)
{
Contract.Requires(Inference != null);
Contract.Requires(Dispatcher != null);
this.Inference = Inference;
this.Dispatch = Dispatcher;
}
#region Dummy implementations of the interfaces
private class DummyIPreconditionInference : IPreconditionInference
{
public bool TryInferConditions(ProofObligation obl, ICodeFixesManager codefixesManager, out InferredConditions preConditions)
{
preConditions = null;
return false;
}
public bool ShouldAddAssumeFalse
{
get { return false; }
}
}
private class DummyIPreconditionDispatcher : IPreconditionDispatcher
{
public ProofOutcome AddPreconditions(ProofObligation obl, IEnumerable<BoxedExpression> preconditions, ProofOutcome originalOutcome)
{
return originalOutcome;
}
public IEnumerable<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>> GeneratePreconditions()
{
return Enumerable.Empty<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>>();
}
public int SuggestPreconditions(bool treatSuggestionsAsWarnings, bool forceSuggestionOutput)
{
return 0;
}
public int PropagatePreconditions(bool asPrecondition)
{
return 0;
}
public int NumberOfWarnings
{
get { return 0; }
}
}
#endregion
}
#region Contracts for the interfaces
[ContractClassFor(typeof(IPreconditionDispatcher))]
internal abstract class IPreconditionDispatcherContracts
: IPreconditionDispatcher
{
public ProofOutcome AddPreconditions(ProofObligation obl, IEnumerable<BoxedExpression> preconditions, ProofOutcome originalOutcome)
{
Contract.Requires(obl != null);
Contract.Requires(preconditions != null);
return ProofOutcome.Top;
}
public IEnumerable<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>> GeneratePreconditions()
{
Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>>>() != null);
return null;
}
public int SuggestPreconditions(bool treatSuggestionsAsWarnings, bool forceSuggestionOutput)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return 0;
}
public int PropagatePreconditions(bool asPrecondition)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return 0;
}
public int NumberOfWarnings
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return 0;
}
}
}
#endregion
#region Aggressive (yet unsound) Precondition Inference: Try to read preconditions in the prestate
public class AggressivePreconditionInference<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
: IPreconditionInference
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
where LogOptions : IFrameworkLogOptions
{
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.MethodDriver != null);
}
#endregion
#region State
protected readonly IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> MethodDriver;
#endregion
#region Constructor
public AggressivePreconditionInference(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> MethodDriver)
{
Contract.Requires(MethodDriver != null);
this.MethodDriver = MethodDriver;
}
#endregion
#region IPreconditionDischarger Members
virtual public bool TryInferConditions(ProofObligation obl, ICodeFixesManager codefixesManager, out InferredConditions preConditions)
{
var preConds = PreconditionSuggestion.ExpressionsInPreState(obl.ConditionForPreconditionInference, this.MethodDriver.Context, this.MethodDriver.MetaDataDecoder, obl.PC, allowedKinds: ExpressionInPreStateKind.All);
preConditions = /*preConds == null ? null : */ preConds.Where(pre => pre.hasVariables).AsInferredPreconditions(isSufficient: true);
return /*preConditions != null && */ preConditions.Any();
}
#endregion
#region Overridden
public bool ShouldAddAssumeFalse
{
get { return false; }
}
public override string ToString()
{
return "Aggressive precondition inference";
}
#endregion
}
#endregion
#region Profiler for precondition Inference
[ContractVerification(true)]
public class PreconditionInferenceProfiler
: IPreconditionInference
{
#region state
readonly private IPreconditionInference inner;
[ThreadStatic]
static private int inferred;
[ThreadStatic]
static private TimeSpan inferenceTime;
[ThreadStatic]
static private int totalMethodsWithPreconditons;
[ThreadStatic]
static private int totalMethodsWithNecessaryPreconditions;
#endregion
#region invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(inner != null);
Contract.Invariant(inferred >= 0);
Contract.Invariant(totalMethodsWithPreconditons >= 0);
}
#endregion
public PreconditionInferenceProfiler(IPreconditionInference inner)
{
Contract.Requires(inner != null);
Contract.Assume(inferred >= 0, "it's a static variable: We believe at construction that other objects left it >= 0");
this.inner = inner;
Contract.Assume(totalMethodsWithPreconditons >= 0, "static invariant");
}
public bool TryInferConditions(ProofObligation obl, ICodeFixesManager codefixesManager, out InferredConditions preConditions)
{
var watch = new CustomStopwatch();
watch.Start();
var result = inner.TryInferConditions(obl, codefixesManager, out preConditions);
watch.Stop();
inferenceTime += watch.Elapsed;
if (preConditions == null)
{
return false;
}
if (result) inferred += preConditions.Count();
return result;
}
public bool ShouldAddAssumeFalse
{
get { return inner.ShouldAddAssumeFalse; }
}
static public void NotifyMethodWithAPrecondition()
{
totalMethodsWithPreconditons++;
}
static public void NotifyCheckInferredRequiresResult(uint tops)
{
totalMethodsWithNecessaryPreconditions += tops == 0 ? 1 : 0;
}
static public void DumpStatistics(IOutput output)
{
Contract.Requires(output != null);
if (totalMethodsWithPreconditons > 0)
{
output.WriteLine("Methods with necessary preconditions: {0}", totalMethodsWithPreconditons);
if (totalMethodsWithNecessaryPreconditions > 0)
{
output.WriteLine("Methods where preconditions were also sufficient: {0}", totalMethodsWithNecessaryPreconditions);
}
if (inferred > 0)
{
output.WriteLine("Discovered {0} new candidate preconditions in {1}", inferred, inferenceTime);
}
}
}
}
#endregion
#region Profiler for precondition Dispatching
public class PreconditionDispatcherProfiler
: IPreconditionDispatcher
{
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(inner != null);
Contract.Invariant(filtered >= 0);
}
#endregion
#region State
private readonly IPreconditionDispatcher inner;
private bool statisticsAlreadyCollected;
[ThreadStatic]
private static int filtered;
#endregion
#region Constructor
public PreconditionDispatcherProfiler(IPreconditionDispatcher dispatcher)
{
Contract.Requires(dispatcher != null);
Contract.Assume(filtered >= 0, "it's a static variable: We believe at construction that other objects left it >= 0");
inner = dispatcher;
statisticsAlreadyCollected = false;
}
#endregion
#region Statistics
public static void DumpStatistics(IOutput output)
{
Contract.Requires(output != null);
output.WriteLine("Retained {0} preconditions after filtering", filtered);
}
#endregion
#region Implementations
public ProofOutcome AddPreconditions(ProofObligation obl, IEnumerable<BoxedExpression> preconditions, ProofOutcome originalOutcome)
{
return inner.AddPreconditions(obl, preconditions, originalOutcome);
}
public IEnumerable<KeyValuePair<BoxedExpression, IEnumerable<MinimalProofObligation>>> GeneratePreconditions()
{
var result = inner.GeneratePreconditions();
AddStatistics(result.Count());
return result;
}
public int SuggestPreconditions(bool treatSuggestionsAsWarnings, bool forceSuggestionOutput)
{
return AddStatistics(inner.SuggestPreconditions(treatSuggestionsAsWarnings, forceSuggestionOutput));
}
public int PropagatePreconditions(bool asPrecondition)
{
return AddStatistics(inner.PropagatePreconditions(asPrecondition));
}
public int NumberOfWarnings
{
get { return inner.NumberOfWarnings; }
}
#endregion
#region private methods
private int AddStatistics(int howmany)
{
Contract.Requires(howmany >= 0);
Contract.Ensures(Contract.Result<int>() == howmany);
if (!statisticsAlreadyCollected)
{
filtered += howmany;
statisticsAlreadyCollected = true;
}
return howmany;
}
private int AddStatisticsForObjectInvariants(int howmany)
{
// TODO: stats for object invariants
return howmany;
}
#endregion
}
#endregion
}
| |
/*
DBFReader
Class for reading the records assuming that the given
InputStream comtains DBF data.
This file is part of DotNetDBF packege.
original author (javadbf): anil@linuxense.com 2004/03/31
License: LGPL (http://www.gnu.org/copyleft/lesser.html)
ported to C# (DotNetDBF): Jay Tuley <jay+dotnetdbf@tuley.name> 6/28/2007
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Linq;
namespace DotNetDBF
{
public class DBFReader : DBFBase, IDisposable
{
private BinaryReader _dataInputStream;
private DBFHeader _header;
private string _dataMemoLoc;
private int[] _selectFields = new int[]{};
private int[] _orderedSelectFields = new int[] { };
/* Class specific variables */
private bool isClosed = true;
/**
Initializes a DBFReader object.
When this constructor returns the object
will have completed reading the hader (meta date) and
header information can be quried there on. And it will
be ready to return the first row.
@param InputStream where the data is read from.
*/
public void SetSelectFields(params string[] aParams)
{
_selectFields =
aParams.Select(
it =>
Array.FindIndex(_header.FieldArray,
jt => jt.Name.Equals(it, StringComparison.InvariantCultureIgnoreCase))).ToArray();
_orderedSelectFields = _selectFields.OrderBy(it => it).ToArray();
}
public DBFField[] GetSelectFields()
{
return _selectFields.Any()
? _selectFields.Select(it => _header.FieldArray[it]).ToArray()
: _header.FieldArray;
}
public DBFReader(string anIn, string charEncoding)
{
try
{
if (!string.IsNullOrEmpty(charEncoding))
{
CharEncoding = Encoding.GetEncoding(charEncoding);
}
_dataInputStream = new BinaryReader(
File.Open(anIn,
FileMode.Open,
FileAccess.Read,
FileShare.Read)
);
var dbtPath = Path.ChangeExtension(anIn, "dbt");
if (File.Exists(dbtPath))
{
_dataMemoLoc = dbtPath;
}
isClosed = false;
_header = new DBFHeader();
_header.Read(_dataInputStream);
/* it might be required to leap to the start of records at times */
int t_dataStartIndex = _header.HeaderLength
- (32 + (32 * _header.FieldArray.Length))
- 1;
if (t_dataStartIndex > 0)
{
_dataInputStream.ReadBytes((t_dataStartIndex));
}
}
catch (IOException ex)
{
throw new DBFException("Failed To Read DBF", ex);
}
}
public DBFReader(Stream anIn)
{
try
{
_dataInputStream = new BinaryReader(anIn);
isClosed = false;
_header = new DBFHeader();
_header.Read(_dataInputStream);
/* it might be required to leap to the start of records at times */
int t_dataStartIndex = _header.HeaderLength
- (32 + (32 * _header.FieldArray.Length))
- 1;
if (t_dataStartIndex > 0)
{
_dataInputStream.ReadBytes((t_dataStartIndex));
}
}
catch (IOException e)
{
throw new DBFException("Failed To Read DBF", e);
}
}
/**
Returns the number of records in the DBF.
*/
public int RecordCount
{
get { return _header.NumberOfRecords; }
}
/**
Returns the asked Field. In case of an invalid index,
it returns a ArrayIndexOutofboundsException.
@param index. Index of the field. Index of the first field is zero.
*/
public DBFField[] Fields
{
get { return _header.FieldArray; }
}
#region IDisposable Members
/// <summary>Performs application-defined tasks associated with freeing, releasing,
/// or resetting unmanaged resources.</summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
Close();
}
#endregion
public string DataMemoLoc
{
get
{
return _dataMemoLoc;
}set
{
_dataMemoLoc = value;
}
}
public override String ToString()
{
StringBuilder sb =
new StringBuilder(_header.Year + "/" + _header.Month + "/"
+ _header.Day + "\n"
+ "Total records: " + _header.NumberOfRecords +
"\nHeader length: " + _header.HeaderLength +
"");
for (int i = 0; i < _header.FieldArray.Length; i++)
{
sb.Append(_header.FieldArray[i].Name);
sb.Append("\n");
}
return sb.ToString();
}
public void Close()
{
_dataInputStream.Close();
isClosed = true;
}
/**
Reads the returns the next row in the DBF stream.
@returns The next row as an Object array. Types of the elements
these arrays follow the convention mentioned in the class description.
*/
public Object[] NextRecord()
{
return NextRecord(_selectFields, _orderedSelectFields);
}
internal Object[] NextRecord(IEnumerable<int> selectIndexes, IList<int> sortedIndexes)
{
if (isClosed)
{
throw new DBFException("Source is not open");
}
IList<int> tOrderdSelectIndexes = sortedIndexes;
var recordObjects = new Object[_header.FieldArray.Length];
try
{
bool isDeleted = false;
do
{
if (isDeleted)
{
_dataInputStream.ReadBytes(_header.RecordLength - 1);
}
int t_byte = _dataInputStream.ReadByte();
if (t_byte == DBFFieldType.EndOfData)
{
return null;
}
isDeleted = (t_byte == '*');
} while (isDeleted);
int j = 0;
int k = -1;
for (int i = 0; i < _header.FieldArray.Length; i++)
{
if (tOrderdSelectIndexes.Count == j && j != 0
|| (tOrderdSelectIndexes.Count > j && tOrderdSelectIndexes[j] > i && tOrderdSelectIndexes[j] != k))
{
_dataInputStream.BaseStream.Seek(_header.FieldArray[i].FieldLength, SeekOrigin.Current);
continue;
}
if (tOrderdSelectIndexes.Count > j)
k = tOrderdSelectIndexes[j];
j++;
switch (_header.FieldArray[i].DataType)
{
case NativeDbType.Char:
var b_array = new byte[
_header.FieldArray[i].FieldLength
];
_dataInputStream.Read(b_array, 0, b_array.Length);
//StringBuilder sb = new StringBuilder();
//for (int c = 0; c < b_array.Length && b_array[c] != 0; c++)
//{
// sb.Append((char)b_array[c]);
//}
//recordObjects[i] = sb.ToString().TrimEnd();
recordObjects[i] = CharEncoding.GetString(b_array).TrimEnd();
//recordObjects[i] = Encoding.GetEncoding("ISO-8859-1").GetString(b_array).TrimEnd();
break;
case NativeDbType.Date:
byte[] t_byte_year = new byte[4];
_dataInputStream.Read(t_byte_year,
0,
t_byte_year.Length);
byte[] t_byte_month = new byte[2];
_dataInputStream.Read(t_byte_month,
0,
t_byte_month.Length);
byte[] t_byte_day = new byte[2];
_dataInputStream.Read(t_byte_day,
0,
t_byte_day.Length);
try
{
var tYear = CharEncoding.GetString(t_byte_year);
var tMonth = CharEncoding.GetString(t_byte_month);
var tDay = CharEncoding.GetString(t_byte_day);
int tIntYear, tIntMonth, tIntDay;
if (Int32.TryParse(tYear, out tIntYear) &&
Int32.TryParse(tMonth, out tIntMonth) &&
Int32.TryParse(tDay, out tIntDay))
{
recordObjects[i] = new DateTime(
tIntYear,
tIntMonth,
tIntDay);
}
else
{
recordObjects[i] = null;
}
}
catch (ArgumentOutOfRangeException)
{
/* this field may be empty or may have improper value set */
recordObjects[i] = null;
}
break;
case NativeDbType.Float:
try
{
byte[] t_float = new byte[
_header.FieldArray[i].FieldLength
];
_dataInputStream.Read(t_float, 0, t_float.Length);
String tParsed = CharEncoding.GetString(t_float);
var tLast = tParsed.Substring(tParsed.Length - 1);
if (tParsed.Length > 0
&& tLast != " "
&& tLast != DBFFieldType.Unknown)
{
//recordObjects[i] = Double.Parse(tParsed, NumberStyles.Float | NumberStyles.AllowLeadingWhite);
recordObjects[i] = GlobalcachingApplication.Utils.Conversion.StringToDouble(tParsed);
}
else
{
recordObjects[i] = null;
}
}
catch (FormatException e)
{
throw new DBFException("Failed to parse Float",
e);
}
break;
case NativeDbType.Numeric:
try
{
byte[] t_numeric = new byte[
_header.FieldArray[i].FieldLength
];
_dataInputStream.Read(t_numeric,
0,
t_numeric.Length);
string tParsed =
CharEncoding.GetString(t_numeric);
var tLast = tParsed.Substring(tParsed.Length - 1);
if (tParsed.Length > 0
&& tLast != " "
&& tLast != DBFFieldType.Unknown)
{
//recordObjects[i] = Decimal.Parse(tParsed, NumberStyles.Float | NumberStyles.AllowLeadingWhite);
recordObjects[i] = GlobalcachingApplication.Utils.Conversion.StringToDouble(tParsed);
}
else
{
recordObjects[i] = null;
}
}
catch (FormatException e)
{
throw new DBFException(
"Failed to parse Number", e);
}
break;
case NativeDbType.Logical:
byte t_logical = _dataInputStream.ReadByte();
//todo find out whats really valid
if (t_logical == 'Y' || t_logical == 't'
|| t_logical == 'T'
|| t_logical == 't')
{
recordObjects[i] = true;
}
else if (t_logical == DBFFieldType.UnknownByte)
{
recordObjects[i] = DBNull.Value;
}else
{
recordObjects[i] = false;
}
break;
case NativeDbType.Memo:
if(string.IsNullOrEmpty(_dataMemoLoc))
throw new Exception("Memo Location Not Set");
var tRawMemoPointer = _dataInputStream.ReadBytes(_header.FieldArray[i].FieldLength);
var tMemoPoiner = CharEncoding.GetString(tRawMemoPointer);
if(string.IsNullOrEmpty(tMemoPoiner))
{
recordObjects[i] = DBNull.Value;
break;
}
long tBlock;
if(!long.TryParse(tMemoPoiner, out tBlock))
{ //Because Memo files can vary and are often the least importat data,
//we will return null when it doesn't match our format.
recordObjects[i] = DBNull.Value;
break;
}
recordObjects[i] = new MemoValue(tBlock, this, _dataMemoLoc);
break;
default:
_dataInputStream.ReadBytes(_header.FieldArray[i].FieldLength);
recordObjects[i] = DBNull.Value;
break;
}
}
}
catch (EndOfStreamException)
{
return null;
}
catch (IOException e)
{
throw new DBFException("Problem Reading File", e);
}
return selectIndexes.Any() ? selectIndexes.Select(it => recordObjects[it]).ToArray() : recordObjects;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Dalssoft.DiagramNet
{
/// <summary>
/// This class is the controller for RectangleElement
/// </summary>
internal class RectangleController: IController, IMoveController, IResizeController
{
//parent element
protected BaseElement el;
//Move vars.
protected Point dragOffset = new Point(0);
protected bool isDragging = false;
protected bool canMove = true;
//Resize vars.
protected const int selCornerSize = 3;
protected RectangleElement[] selectionCorner = new RectangleElement[9];
protected CornerPosition selCorner = CornerPosition.Nothing;
protected bool canResize = true;
public RectangleController(BaseElement element)
{
el = element;
//Create corners
for(int i = 0; i < selectionCorner.Length; i++)
{
selectionCorner[i] = new RectangleElement(0, 0, selCornerSize * 2, selCornerSize * 2);
selectionCorner[i].BorderColor = Color.Black;
selectionCorner[i].FillColor1 = Color.White;
selectionCorner[i].FillColor2 = Color.Empty;
}
}
#region IController Members
public BaseElement OwnerElement
{
get
{
return el;
}
}
public virtual bool HitTest(Point p)
{
GraphicsPath gp = new GraphicsPath();
Matrix mtx = new Matrix();
Point elLocation = el.Location;
Size elSize = el.Size;
gp.AddRectangle(new Rectangle(elLocation.X,
elLocation.Y,
elSize.Width,
elSize.Height));
gp.Transform(mtx);
return gp.IsVisible(p);
}
public virtual bool HitTest(Rectangle r)
{
GraphicsPath gp = new GraphicsPath();
Matrix mtx = new Matrix();
Point elLocation = el.Location;
Size elSize = el.Size;
gp.AddRectangle(new Rectangle(elLocation.X,
elLocation.Y,
elSize.Width,
elSize.Height));
gp.Transform(mtx);
Rectangle retGp = Rectangle.Round(gp.GetBounds());
return r.Contains (retGp);
}
public virtual void DrawSelection(Graphics g)
{
int border = 3;
Point elLocation = el.Location;
Size elSize = el.Size;
Rectangle r = BaseElement.GetUnsignedRectangle(
new Rectangle(
elLocation.X - border, elLocation.Y - border,
elSize.Width + (border * 2), elSize.Height + (border * 2)));
HatchBrush brush = new HatchBrush(HatchStyle.SmallCheckerBoard, Color.LightGray, Color.Transparent);
Pen p = new Pen(brush, border);
g.DrawRectangle(p, r);
p.Dispose();
brush.Dispose();
}
#endregion
#region IMoveController Members
void IMoveController.Start(Point posStart)
{
Point elLocation = el.Location;
dragOffset.X = elLocation.X - posStart.X;
dragOffset.Y = elLocation.Y - posStart.Y;
isDragging = true;
}
void IMoveController.Move(Point posCurrent)
{
if (isDragging)
{
Point dragPointEl = posCurrent;
dragPointEl.Offset(dragOffset.X, dragOffset.Y) ;
if (dragPointEl.X < 0) dragPointEl.X = 0;
if (dragPointEl.Y < 0) dragPointEl.Y = 0;
el.Location = dragPointEl;
}
}
void IMoveController.End()
{
isDragging = false;
}
bool IMoveController.IsMoving
{
get
{
return isDragging;
}
}
bool IMoveController.CanMove
{
get
{
return canMove;
}
}
#endregion
#region IResizeController Members
public RectangleElement[] Corners
{
get
{
return selectionCorner;
}
}
void IResizeController.UpdateCornersPos()
{
// Update selection corner rectangle
Rectangle rec = new Rectangle(el.Location, el.Size);
selectionCorner[(int) CornerPosition.TopLeft].Location = new Point(rec.Location.X - selCornerSize, rec.Location.Y - selCornerSize);
selectionCorner[(int) CornerPosition.TopRight].Location = new Point(rec.Location.X + rec.Size.Width - selCornerSize, rec.Location.Y - selCornerSize);
selectionCorner[(int) CornerPosition.TopCenter].Location = new Point(rec.Location.X + rec.Size.Width / 2 - selCornerSize, rec.Location.Y - selCornerSize);
selectionCorner[(int) CornerPosition.BottomLeft].Location = new Point(rec.Location.X - selCornerSize, rec.Location.Y + rec.Size.Height - selCornerSize);
selectionCorner[(int) CornerPosition.BottomRight].Location = new Point(rec.Location.X + rec.Size.Width - selCornerSize, rec.Location.Y + rec.Size.Height - selCornerSize);
selectionCorner[(int) CornerPosition.BottomCenter].Location = new Point(rec.Location.X + rec.Size.Width / 2 - selCornerSize, rec.Location.Y + rec.Size.Height - selCornerSize);
selectionCorner[(int) CornerPosition.MiddleLeft].Location = new Point(rec.Location.X - selCornerSize, rec.Location.Y + rec.Size.Height / 2 - selCornerSize);
selectionCorner[(int) CornerPosition.MiddleCenter].Location = new Point(rec.Location.X + rec.Size.Width / 2 - selCornerSize, rec.Location.Y + rec.Size.Height / 2 - selCornerSize);
selectionCorner[(int) CornerPosition.MiddleRight].Location = new Point(rec.Location.X + rec.Size.Width - selCornerSize, rec.Location.Y + rec.Size.Height / 2 - selCornerSize);
}
CornerPosition IResizeController.HitTestCorner(Point p)
{
for(int i = 0; i < selectionCorner.Length; i++)
{
IController ctrl = ((IControllable) selectionCorner[i]).GetController();
if (ctrl.HitTest(p))
return (CornerPosition) i;
}
return CornerPosition.Nothing;
}
void IResizeController.Start(Point posStart, CornerPosition corner)
{
selCorner = corner;
dragOffset.X = selectionCorner[(int) selCorner].Location.X - posStart.X;
dragOffset.Y = selectionCorner[(int) selCorner].Location.Y - posStart.Y;
}
void IResizeController.Resize(Point posCurrent)
{
RectangleElement corner = selectionCorner[(int) selCorner];
Point loc;
Point dragPointEl = posCurrent;
dragPointEl.Offset(dragOffset.X, dragOffset.Y);
if (dragPointEl.X < 0) dragPointEl.X = 0;
if (dragPointEl.Y < 0) dragPointEl.Y = 0;
switch (selCorner)
{
case CornerPosition.TopLeft:
corner.Location = dragPointEl;
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(el.Size.Width + (el.Location.X - loc.X),
el.Size.Height + (el.Location.Y - loc.Y));
el.Location = loc;
break;
case CornerPosition.TopCenter:
corner.Location = new Point(corner.Location.X, dragPointEl.Y);
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(el.Size.Width,
el.Size.Height + (el.Location.Y - loc.Y));
el.Location = new Point(el.Location.X, loc.Y);
break;
case CornerPosition.TopRight:
corner.Location = dragPointEl;
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(loc.X - el.Location.X,
el.Size.Height - (loc.Y - el.Location.Y));
el.Location = new Point(el.Location.X, loc.Y);
break;
case CornerPosition.MiddleLeft:
corner.Location = new Point(dragPointEl.X, corner.Location.Y);
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(el.Size.Width + (el.Location.X - loc.X),
el.Size.Height);
el.Location = new Point(loc.X, el.Location.Y);
break;
case CornerPosition.MiddleRight:
corner.Location = new Point(dragPointEl.X, corner.Location.Y);
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(loc.X - el.Location.X,
el.Size.Height);
break;
case CornerPosition.BottomLeft:
corner.Location = dragPointEl;
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(el.Size.Width - (loc.X - el.Location.X),
loc.Y - el.Location.Y);
el.Location = new Point(loc.X, el.Location.Y);
break;
case CornerPosition.BottomCenter:
corner.Location = new Point(corner.Location.X, dragPointEl.Y);
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(el.Size.Width,
loc.Y - el.Location.Y);
break;
case CornerPosition.BottomRight:
corner.Location = dragPointEl;
loc = new Point(corner.Location.X + corner.Size.Width / 2, corner.Location.Y + corner.Size.Height / 2);
el.Size = new Size(loc.X - el.Location.X,
loc.Y - el.Location.Y);
break;
}
}
void IResizeController.End(Point posEnd)
{
if ((el.Size.Height < 0) || (el.Size.Width < 0))
{
Rectangle urec = el.GetUnsignedRectangle();
el.Location = urec.Location;
el.Size = urec.Size;
}
selCorner = CornerPosition.Nothing;
dragOffset = Point.Empty;
}
bool IResizeController.IsResizing
{
get
{
return (selCorner != CornerPosition.Nothing);
}
}
bool IResizeController.CanResize
{
get
{
return canResize;
}
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/clouderrorreporting/v1beta1/error_group_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.ErrorReporting.V1Beta1 {
/// <summary>Holder for reflection information generated from google/devtools/clouderrorreporting/v1beta1/error_group_service.proto</summary>
public static partial class ErrorGroupServiceReflection {
#region Descriptor
/// <summary>File descriptor for google/devtools/clouderrorreporting/v1beta1/error_group_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ErrorGroupServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkVnb29nbGUvZGV2dG9vbHMvY2xvdWRlcnJvcnJlcG9ydGluZy92MWJldGEx",
"L2Vycm9yX2dyb3VwX3NlcnZpY2UucHJvdG8SK2dvb2dsZS5kZXZ0b29scy5j",
"bG91ZGVycm9ycmVwb3J0aW5nLnYxYmV0YTEaHGdvb2dsZS9hcGkvYW5ub3Rh",
"dGlvbnMucHJvdG8aOGdvb2dsZS9kZXZ0b29scy9jbG91ZGVycm9ycmVwb3J0",
"aW5nL3YxYmV0YTEvY29tbW9uLnByb3RvIiUKD0dldEdyb3VwUmVxdWVzdBIS",
"Cgpncm91cF9uYW1lGAEgASgJIlwKElVwZGF0ZUdyb3VwUmVxdWVzdBJGCgVn",
"cm91cBgBIAEoCzI3Lmdvb2dsZS5kZXZ0b29scy5jbG91ZGVycm9ycmVwb3J0",
"aW5nLnYxYmV0YTEuRXJyb3JHcm91cDKOAwoRRXJyb3JHcm91cFNlcnZpY2US",
"tAEKCEdldEdyb3VwEjwuZ29vZ2xlLmRldnRvb2xzLmNsb3VkZXJyb3JyZXBv",
"cnRpbmcudjFiZXRhMS5HZXRHcm91cFJlcXVlc3QaNy5nb29nbGUuZGV2dG9v",
"bHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJldGExLkVycm9yR3JvdXAiMYLT",
"5JMCKxIpL3YxYmV0YTEve2dyb3VwX25hbWU9cHJvamVjdHMvKi9ncm91cHMv",
"Kn0SwQEKC1VwZGF0ZUdyb3VwEj8uZ29vZ2xlLmRldnRvb2xzLmNsb3VkZXJy",
"b3JyZXBvcnRpbmcudjFiZXRhMS5VcGRhdGVHcm91cFJlcXVlc3QaNy5nb29n",
"bGUuZGV2dG9vbHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJldGExLkVycm9y",
"R3JvdXAiOILT5JMCMhopL3YxYmV0YTEve2dyb3VwLm5hbWU9cHJvamVjdHMv",
"Ki9ncm91cHMvKn06BWdyb3VwQvcBCi9jb20uZ29vZ2xlLmRldnRvb2xzLmNs",
"b3VkZXJyb3JyZXBvcnRpbmcudjFiZXRhMUIWRXJyb3JHcm91cFNlcnZpY2VQ",
"cm90b1ABWl5nb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz",
"L2RldnRvb2xzL2Nsb3VkZXJyb3JyZXBvcnRpbmcvdjFiZXRhMTtjbG91ZGVy",
"cm9ycmVwb3J0aW5nqgIjR29vZ2xlLkNsb3VkLkVycm9yUmVwb3J0aW5nLlYx",
"QmV0YTHKAiNHb29nbGVcQ2xvdWRcRXJyb3JSZXBvcnRpbmdcVjFiZXRhMWIG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.ErrorReporting.V1Beta1.CommonReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.GetGroupRequest), global::Google.Cloud.ErrorReporting.V1Beta1.GetGroupRequest.Parser, new[]{ "GroupName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.UpdateGroupRequest), global::Google.Cloud.ErrorReporting.V1Beta1.UpdateGroupRequest.Parser, new[]{ "Group" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A request to return an individual group.
/// </summary>
public sealed partial class GetGroupRequest : pb::IMessage<GetGroupRequest> {
private static readonly pb::MessageParser<GetGroupRequest> _parser = new pb::MessageParser<GetGroupRequest>(() => new GetGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroupServiceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest(GetGroupRequest other) : this() {
groupName_ = other.groupName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest Clone() {
return new GetGroupRequest(this);
}
/// <summary>Field number for the "group_name" field.</summary>
public const int GroupNameFieldNumber = 1;
private string groupName_ = "";
/// <summary>
/// [Required] The group resource name. Written as
/// <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
/// Call
/// <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
/// <code>groupStats.list</code></a> to return a list of groups belonging to
/// this project.
///
/// Example: <code>projects/my-project-123/groups/my-group</code>
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GroupName {
get { return groupName_; }
set {
groupName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GroupName != other.GroupName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GroupName.Length != 0) hash ^= GroupName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (GroupName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GroupName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GroupName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetGroupRequest other) {
if (other == null) {
return;
}
if (other.GroupName.Length != 0) {
GroupName = other.GroupName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
GroupName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A request to replace the existing data for the given group.
/// </summary>
public sealed partial class UpdateGroupRequest : pb::IMessage<UpdateGroupRequest> {
private static readonly pb::MessageParser<UpdateGroupRequest> _parser = new pb::MessageParser<UpdateGroupRequest>(() => new UpdateGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroupServiceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest(UpdateGroupRequest other) : this() {
Group = other.group_ != null ? other.Group.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest Clone() {
return new UpdateGroupRequest(this);
}
/// <summary>Field number for the "group" field.</summary>
public const int GroupFieldNumber = 1;
private global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup group_;
/// <summary>
/// [Required] The group which replaces the resource on the server.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup Group {
get { return group_; }
set {
group_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Group, other.Group)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (group_ != null) hash ^= Group.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (group_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Group);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (group_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateGroupRequest other) {
if (other == null) {
return;
}
if (other.group_ != null) {
if (group_ == null) {
group_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup();
}
Group.MergeFrom(other.Group);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (group_ == null) {
group_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorGroup();
}
input.ReadMessage(group_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
namespace Discord
{
//Based on https://github.com/dotnet/corefx/blob/d0dc5fc099946adc1035b34a8b1f6042eddb0c75/src/System.Threading.Tasks.Parallel/src/System/Threading/PlatformHelper.cs
//Copyright (c) .NET Foundation and Contributors
internal static class ConcurrentHashSet
{
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000;
private static volatile int s_processorCount;
private static volatile int s_lastProcessorCountRefreshTicks;
public static int DefaultConcurrencyLevel
{
get
{
int now = Environment.TickCount;
if (s_processorCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS)
{
s_processorCount = Environment.ProcessorCount;
s_lastProcessorCountRefreshTicks = now;
}
return s_processorCount;
}
}
}
//Based on https://github.com/dotnet/corefx/blob/master/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs
//Copyright (c) .NET Foundation and Contributors
[DebuggerDisplay("Count = {Count}")]
internal class ConcurrentHashSet<T> : IReadOnlyCollection<T>
{
private sealed class Tables
{
internal readonly Node[] _buckets;
internal readonly object[] _locks;
internal volatile int[] _countPerLock;
internal Tables(Node[] buckets, object[] locks, int[] countPerLock)
{
_buckets = buckets;
_locks = locks;
_countPerLock = countPerLock;
}
}
private sealed class Node
{
internal readonly T _value;
internal volatile Node _next;
internal readonly int _hashcode;
internal Node(T key, int hashcode, Node next)
{
_value = key;
_next = next;
_hashcode = hashcode;
}
}
private const int DefaultCapacity = 31;
private const int MaxLockNumber = 1024;
private static int GetBucket(int hashcode, int bucketCount)
{
int bucketNo = (hashcode & 0x7fffffff) % bucketCount;
return bucketNo;
}
private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
{
bucketNo = (hashcode & 0x7fffffff) % bucketCount;
lockNo = bucketNo % lockCount;
}
private static int DefaultConcurrencyLevel => ConcurrentHashSet.DefaultConcurrencyLevel;
private volatile Tables _tables;
private readonly IEqualityComparer<T> _comparer;
private readonly bool _growLockArray;
private int _budget;
public int Count
{
get
{
int count = 0;
int acquiredLocks = 0;
try
{
AcquireAllLocks(ref acquiredLocks);
for (int i = 0; i < _tables._countPerLock.Length; i++)
count += _tables._countPerLock[i];
}
finally { ReleaseLocks(0, acquiredLocks); }
return count;
}
}
public bool IsEmpty
{
get
{
int acquiredLocks = 0;
try
{
// Acquire all locks
AcquireAllLocks(ref acquiredLocks);
for (int i = 0; i < _tables._countPerLock.Length; i++)
{
if (_tables._countPerLock[i] != 0)
return false;
}
}
finally { ReleaseLocks(0, acquiredLocks); }
return true;
}
}
public ReadOnlyCollection<T> Values
{
get
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
List<T> values = new List<T>();
for (int i = 0; i < _tables._buckets.Length; i++)
{
Node current = _tables._buckets[i];
while (current != null)
{
values.Add(current._value);
current = current._next;
}
}
return new ReadOnlyCollection<T>(values);
}
finally { ReleaseLocks(0, locksAcquired); }
}
}
public ConcurrentHashSet()
: this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer<T>.Default) { }
public ConcurrentHashSet(int concurrencyLevel, int capacity)
: this(concurrencyLevel, capacity, false, EqualityComparer<T>.Default) { }
public ConcurrentHashSet(IEnumerable<T> collection)
: this(collection, EqualityComparer<T>.Default) { }
public ConcurrentHashSet(IEqualityComparer<T> comparer)
: this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) { }
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is <c>null</c></exception>
public ConcurrentHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
: this(comparer)
{
if (collection == null) throw new ArgumentNullException(paramName: nameof(collection));
InitializeFromCollection(collection);
}
/// <exception cref="ArgumentNullException">
/// <paramref name="collection" /> or <paramref name="comparer" /> is <c>null</c>
/// </exception>
public ConcurrentHashSet(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer)
: this(concurrencyLevel, DefaultCapacity, false, comparer)
{
if (collection == null) throw new ArgumentNullException(paramName: nameof(collection));
if (comparer == null) throw new ArgumentNullException(paramName: nameof(comparer));
InitializeFromCollection(collection);
}
public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer)
: this(concurrencyLevel, capacity, false, comparer) { }
internal ConcurrentHashSet(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<T> comparer)
{
if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException(paramName: nameof(concurrencyLevel));
if (capacity < 0) throw new ArgumentOutOfRangeException(paramName: nameof(capacity));
if (comparer == null) throw new ArgumentNullException(paramName: nameof(comparer));
if (capacity < concurrencyLevel)
capacity = concurrencyLevel;
object[] locks = new object[concurrencyLevel];
for (int i = 0; i < locks.Length; i++)
locks[i] = new object();
int[] countPerLock = new int[locks.Length];
Node[] buckets = new Node[capacity];
_tables = new Tables(buckets, locks, countPerLock);
_comparer = comparer;
_growLockArray = growLockArray;
_budget = buckets.Length / locks.Length;
}
private void InitializeFromCollection(IEnumerable<T> collection)
{
foreach (var value in collection)
{
if (value == null) throw new ArgumentNullException(paramName: "key");
if (!TryAddInternal(value, _comparer.GetHashCode(value), false))
throw new ArgumentException();
}
if (_budget == 0)
_budget = _tables._buckets.Length / _tables._locks.Length;
}
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c></exception>
public bool ContainsKey(T value)
{
if (value == null) throw new ArgumentNullException(paramName: "key");
return ContainsKeyInternal(value, _comparer.GetHashCode(value));
}
private bool ContainsKeyInternal(T value, int hashcode)
{
Tables tables = _tables;
int bucketNo = GetBucket(hashcode, tables._buckets.Length);
Node n = Volatile.Read(ref tables._buckets[bucketNo]);
while (n != null)
{
if (hashcode == n._hashcode && _comparer.Equals(n._value, value))
return true;
n = n._next;
}
return false;
}
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c></exception>
public bool TryAdd(T value)
{
if (value == null) throw new ArgumentNullException(paramName: "key");
return TryAddInternal(value, _comparer.GetHashCode(value), true);
}
private bool TryAddInternal(T value, int hashcode, bool acquireLock)
{
while (true)
{
Tables tables = _tables;
GetBucketAndLockNo(hashcode, out int bucketNo, out int lockNo, tables._buckets.Length, tables._locks.Length);
bool resizeDesired = false;
bool lockTaken = false;
try
{
if (acquireLock)
Monitor.Enter(tables._locks[lockNo], ref lockTaken);
if (tables != _tables)
continue;
Node prev = null;
for (Node node = tables._buckets[bucketNo]; node != null; node = node._next)
{
if (hashcode == node._hashcode && _comparer.Equals(node._value, value))
return false;
prev = node;
}
Volatile.Write(ref tables._buckets[bucketNo], new Node(value, hashcode, tables._buckets[bucketNo]));
checked { tables._countPerLock[lockNo]++; }
if (tables._countPerLock[lockNo] > _budget)
resizeDesired = true;
}
finally
{
if (lockTaken)
Monitor.Exit(tables._locks[lockNo]);
}
if (resizeDesired)
GrowTable(tables);
return true;
}
}
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c></exception>
public bool TryRemove(T value)
{
if (value == null) throw new ArgumentNullException(paramName: "key");
return TryRemoveInternal(value);
}
private bool TryRemoveInternal(T value)
{
int hashcode = _comparer.GetHashCode(value);
while (true)
{
Tables tables = _tables;
GetBucketAndLockNo(hashcode, out int bucketNo, out int lockNo, tables._buckets.Length, tables._locks.Length);
lock (tables._locks[lockNo])
{
if (tables != _tables)
continue;
Node prev = null;
for (Node curr = tables._buckets[bucketNo]; curr != null; curr = curr._next)
{
if (hashcode == curr._hashcode && _comparer.Equals(curr._value, value))
{
if (prev == null)
Volatile.Write(ref tables._buckets[bucketNo], curr._next);
else
prev._next = curr._next;
value = curr._value;
tables._countPerLock[lockNo]--;
return true;
}
prev = curr;
}
}
value = default(T);
return false;
}
}
public void Clear()
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
Tables newTables = new Tables(new Node[DefaultCapacity], _tables._locks, new int[_tables._countPerLock.Length]);
_tables = newTables;
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
public IEnumerator<T> GetEnumerator()
{
Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
Node current = Volatile.Read(ref buckets[i]);
while (current != null)
{
yield return current._value;
current = current._next;
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private void GrowTable(Tables tables)
{
const int MaxArrayLength = 0X7FEFFFFF;
int locksAcquired = 0;
try
{
AcquireLocks(0, 1, ref locksAcquired);
if (tables != _tables)
return;
long approxCount = 0;
for (int i = 0; i < tables._countPerLock.Length; i++)
approxCount += tables._countPerLock[i];
if (approxCount < tables._buckets.Length / 4)
{
_budget = 2 * _budget;
if (_budget < 0)
_budget = int.MaxValue;
return;
}
int newLength = 0;
bool maximizeTableSize = false;
try
{
checked
{
newLength = tables._buckets.Length * 2 + 1;
while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
newLength += 2;
if (newLength > MaxArrayLength)
maximizeTableSize = true;
}
}
catch (OverflowException)
{
maximizeTableSize = true;
}
if (maximizeTableSize)
{
newLength = MaxArrayLength;
_budget = int.MaxValue;
}
AcquireLocks(1, tables._locks.Length, ref locksAcquired);
object[] newLocks = tables._locks;
if (_growLockArray && tables._locks.Length < MaxLockNumber)
{
newLocks = new object[tables._locks.Length * 2];
Array.Copy(tables._locks, 0, newLocks, 0, tables._locks.Length);
for (int i = tables._locks.Length; i < newLocks.Length; i++)
newLocks[i] = new object();
}
Node[] newBuckets = new Node[newLength];
int[] newCountPerLock = new int[newLocks.Length];
for (int i = 0; i < tables._buckets.Length; i++)
{
Node current = tables._buckets[i];
while (current != null)
{
Node next = current._next;
GetBucketAndLockNo(current._hashcode, out int newBucketNo, out int newLockNo, newBuckets.Length, newLocks.Length);
newBuckets[newBucketNo] = new Node(current._value, current._hashcode, newBuckets[newBucketNo]);
checked { newCountPerLock[newLockNo]++; }
current = next;
}
}
_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
_tables = new Tables(newBuckets, newLocks, newCountPerLock);
}
finally { ReleaseLocks(0, locksAcquired); }
}
private void AcquireAllLocks(ref int locksAcquired)
{
AcquireLocks(0, 1, ref locksAcquired);
AcquireLocks(1, _tables._locks.Length, ref locksAcquired);
}
private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
{
object[] locks = _tables._locks;
for (int i = fromInclusive; i < toExclusive; i++)
{
bool lockTaken = false;
try
{
Monitor.Enter(locks[i], ref lockTaken);
}
finally
{
if (lockTaken)
locksAcquired++;
}
}
}
private void ReleaseLocks(int fromInclusive, int toExclusive)
{
for (int i = fromInclusive; i < toExclusive; i++)
Monitor.Exit(_tables._locks[i]);
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel.Design;
namespace System.Windows.Forms
{
[Editor("System.Windows.Forms.RibbonItemCollectionEditor", typeof(UITypeEditor))]
public class RibbonItemCollection
: List<RibbonItem>, IList
{
#region Fields
private Ribbon _owner;
private RibbonTab _ownerTab;
private RibbonPanel _ownerPanel;
#endregion
#region Ctor
/// <summary>
/// Creates a new ribbon item collection
/// </summary>
internal RibbonItemCollection()
{
}
#endregion
#region Properties
/// <summary>
/// Gets the Ribbon owner of this collection
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Ribbon Owner
{
get
{
return _owner;
}
}
/// <summary>
/// Gets the RibbonPanel where this item is located
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonPanel OwnerPanel
{
get
{
return _ownerPanel;
}
}
/// <summary>
/// Gets the RibbonTab that contains this item
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonTab OwnerTab
{
get
{
return _ownerTab;
}
}
#endregion
#region Overrides
/// <summary>
/// Adds the specified item to the collection
/// </summary>
public virtual new void Add(RibbonItem item)
{
item.SetOwner(Owner);
item.SetOwnerPanel(OwnerPanel);
item.SetOwnerTab(OwnerTab);
base.Add(item);
}
/// <summary>
/// Adds the specified range of items
/// </summary>
/// <param name="items">Items to add</param>
public virtual new void AddRange(IEnumerable<RibbonItem> items)
{
foreach (RibbonItem item in items)
{
item.SetOwner(Owner);
item.SetOwnerPanel(OwnerPanel);
item.SetOwnerTab(OwnerTab);
}
base.AddRange(items);
}
/// <summary>
/// Inserts the specified item at the desired index
/// </summary>
/// <param name="index">Desired index of the item</param>
/// <param name="item">Item to insert</param>
public virtual new void Insert(int index, RibbonItem item)
{
item.SetOwner(Owner);
item.SetOwnerPanel(OwnerPanel);
item.SetOwnerTab(OwnerTab);
base.Insert(index, item);
}
#endregion
#region Methods
/// <summary>
/// Gets the left of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsLeft(IEnumerable<RibbonItem> items)
{
if (Count == 0) return 0;
int min = int.MaxValue;
foreach (RibbonItem item in items)
{
if (item.Bounds.X < min)
{
min = item.Bounds.X;
}
}
return min;
}
/// <summary>
/// Gets the right of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsRight(IEnumerable<RibbonItem> items)
{
if (Count == 0) return 0;
int max = int.MinValue; ;
foreach (RibbonItem item in items)
{
if (item.Bounds.Right > max)
{
max = item.Bounds.Right;
}
}
return max;
}
/// <summary>
/// Gets the top of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsTop(IEnumerable<RibbonItem> items)
{
if (Count == 0) return 0;
int min = int.MaxValue;
foreach (RibbonItem item in items)
{
if (item.Bounds.Y < min)
{
min = item.Bounds.Y;
}
}
return min;
}
/// <summary>
/// Gets the bottom of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsBottom(IEnumerable<RibbonItem> items)
{
if (Count == 0) return 0;
int max = int.MinValue;
foreach (RibbonItem item in items)
{
if (item.Bounds.Bottom > max)
{
max = item.Bounds.Bottom;
}
}
return max;
}
/// <summary>
/// Gets the width of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsWidth(IEnumerable<RibbonItem> items)
{
return GetItemsRight(items) - GetItemsLeft(items);
}
/// <summary>
/// Gets the height of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsHeight(IEnumerable<RibbonItem> items)
{
return GetItemsBottom(items) - GetItemsTop(items);
}
/// <summary>
/// Gets the bounds of items as a group of shapes
/// </summary>
/// <returns></returns>
internal Rectangle GetItemsBounds(IEnumerable<RibbonItem> items)
{
return Rectangle.FromLTRB(GetItemsLeft(items), GetItemsTop(items), GetItemsRight(items), GetItemsBottom(items));
}
/// <summary>
/// Gets the left of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsLeft()
{
if (Count == 0) return 0;
int min = int.MaxValue;
foreach (RibbonItem item in this)
{
if (item.Bounds.X < min)
{
min = item.Bounds.X;
}
}
return min;
}
/// <summary>
/// Gets the right of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsRight()
{
if (Count == 0) return 0;
int max = int.MinValue; ;
foreach (RibbonItem item in this)
{
if (item.Visible && item.Bounds.Right > max)
{
max = item.Bounds.Right;
}
}
if (max == int.MinValue) { max = 0; }
return max;
}
/// <summary>
/// Gets the top of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsTop()
{
if (Count == 0) return 0;
int min = int.MaxValue;
foreach (RibbonItem item in this)
{
if (item.Bounds.Y < min)
{
min = item.Bounds.Y;
}
}
return min;
}
/// <summary>
/// Gets the bottom of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsBottom()
{
if (Count == 0) return 0;
int max = int.MinValue;
foreach (RibbonItem item in this)
{
if (item.Visible && item.Bounds.Bottom > max)
{
max = item.Bounds.Bottom;
}
}
if (max == int.MinValue) { max = 0; }
return max;
}
/// <summary>
/// Gets the width of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsWidth()
{
return GetItemsRight() - GetItemsLeft();
}
/// <summary>
/// Gets the height of items as a group of shapes
/// </summary>
/// <returns></returns>
internal int GetItemsHeight()
{
return GetItemsBottom() - GetItemsTop();
}
/// <summary>
/// Gets the bounds of items as a group of shapes
/// </summary>
/// <returns></returns>
internal Rectangle GetItemsBounds()
{
return Rectangle.FromLTRB(GetItemsLeft(), GetItemsTop(), GetItemsRight(), GetItemsBottom());
}
/// <summary>
/// Moves the bounds of items as a group of shapes
/// </summary>
/// <param name="p"></param>
internal void MoveTo(Point p)
{
MoveTo(this, p);
}
/// <summary>
/// Moves the bounds of items as a group of shapes
/// </summary>
/// <param name="p"></param>
internal void MoveTo(IEnumerable<RibbonItem> items, Point p)
{
Rectangle oldBounds = GetItemsBounds(items);
foreach (RibbonItem item in items)
{
int dx = item.Bounds.X - oldBounds.Left;
int dy = item.Bounds.Y - oldBounds.Top;
item.SetBounds(new Rectangle(new Point(p.X + dx, p.Y + dy), item.Bounds.Size));
}
}
/// <summary>
/// Centers the items on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsInto(Rectangle rectangle)
{
CenterItemsInto(this, rectangle);
}
/// <summary>
/// Centers the items vertically on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsVerticallyInto(Rectangle rectangle)
{
CenterItemsVerticallyInto(this, rectangle);
}
/// <summary>
/// Centers the items horizontally on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsHorizontallyInto(Rectangle rectangle)
{
CenterItemsHorizontallyInto(this, rectangle);
}
/// <summary>
/// Centers the items on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsInto(IEnumerable<RibbonItem> items, Rectangle rectangle)
{
int x = rectangle.Left + (rectangle.Width - GetItemsWidth()) / 2;
int y = rectangle.Top + (rectangle.Height - GetItemsHeight()) / 2;
MoveTo(items, new Point(x, y));
}
/// <summary>
/// Centers the items vertically on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsVerticallyInto(IEnumerable<RibbonItem> items, Rectangle rectangle)
{
int x = GetItemsLeft(items);
int y = rectangle.Top + (rectangle.Height - GetItemsHeight(items)) / 2;
MoveTo(items, new Point(x, y));
}
/// <summary>
/// Centers the items horizontally on the specified rectangle
/// </summary>
/// <param name="rectangle"></param>
internal void CenterItemsHorizontallyInto(IEnumerable<RibbonItem> items, Rectangle rectangle)
{
int x = rectangle.Left + (rectangle.Width - GetItemsWidth(items)) / 2;
int y = GetItemsTop(items);
MoveTo(items, new Point(x, y));
}
/// <summary>
/// Sets the owner Ribbon of the collection
/// </summary>
/// <param name="owner"></param>
internal void SetOwner(Ribbon owner)
{
_owner = owner;
foreach (RibbonItem item in this)
{
item.SetOwner(owner);
}
}
/// <summary>
/// Sets the owner Tab of the collection
/// </summary>
/// <param name="tab"></param>
internal void SetOwnerTab(RibbonTab tab)
{
_ownerTab = tab;
foreach (RibbonItem item in this)
{
item.SetOwnerTab(tab);
}
}
/// <summary>
/// Sets the owner panel of the collection
/// </summary>
/// <param name="panel"></param>
internal void SetOwnerPanel(RibbonPanel panel)
{
_ownerPanel = panel;
foreach (RibbonItem item in this)
{
item.SetOwnerPanel(panel);
}
}
#endregion
#region IList
int IList.Add(object item)
{
RibbonItem ri = item as RibbonItem;
if (ri == null)
return -1;
this.Add(ri);
return this.Count - 1;
}
void IList.Insert(int index, object item)
{
RibbonItem ri = item as RibbonItem;
if (ri == null)
return;
this.Insert(index, ri);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// The call site (class name, method name and source information).
/// </summary>
[LayoutRenderer("callsite")]
[ThreadAgnostic]
public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace
{
/// <summary>
/// Initializes a new instance of the <see cref="CallSiteLayoutRenderer" /> class.
/// </summary>
public CallSiteLayoutRenderer()
{
this.ClassName = true;
this.MethodName = true;
this.CleanNamesOfAnonymousDelegates = false;
#if !SILVERLIGHT
this.FileName = false;
this.IncludeSourcePath = true;
#endif
}
/// <summary>
/// Gets or sets a value indicating whether to render the class name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool ClassName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to render the method name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool MethodName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the method name will be cleaned up if it is detected as an anonymous delegate.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool CleanNamesOfAnonymousDelegates { get; set; }
/// <summary>
/// Gets or sets the number of frames to skip.
/// </summary>
[DefaultValue(0)]
public int SkipFrames { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to render the source file name and line number.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source file path.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(true)]
public bool IncludeSourcePath { get; set; }
#endif
/// <summary>
/// Gets the level of stack trace information required by the implementing class.
/// </summary>
StackTraceUsage IUsesStackTrace.StackTraceUsage
{
get
{
#if !SILVERLIGHT
if (this.FileName)
{
return StackTraceUsage.Max;
}
#endif
return StackTraceUsage.WithoutSource;
}
}
/// <summary>
/// Renders the call site and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
StackFrame frame = logEvent.StackTrace != null ? logEvent.StackTrace.GetFrame(logEvent.UserStackFrameNumber + SkipFrames) : null;
if (frame != null)
{
MethodBase method = frame.GetMethod();
if (this.ClassName)
{
if (method.DeclaringType != null)
{
string className = method.DeclaringType.FullName;
if (this.CleanNamesOfAnonymousDelegates)
{
// NLog.UnitTests.LayoutRenderers.CallSiteTests+<>c__DisplayClassa
if (className.Contains("+<>"))
{
int index = className.IndexOf("+<>");
className = className.Substring(0, index);
}
}
builder.Append(className);
}
else
{
builder.Append("<no type>");
}
}
if (this.MethodName)
{
if (this.ClassName)
{
builder.Append(".");
}
if (method != null)
{
string methodName = method.Name;
if (this.CleanNamesOfAnonymousDelegates)
{
// Clean up the function name if it is an anonymous delegate
// <.ctor>b__0
// <Main>b__2
if (methodName.Contains("__") == true && methodName.StartsWith("<") == true && methodName.Contains(">") == true)
{
int startIndex = methodName.IndexOf('<') + 1;
int endIndex = methodName.IndexOf('>');
methodName = methodName.Substring(startIndex, endIndex - startIndex);
}
}
builder.Append(methodName);
}
else
{
builder.Append("<no method>");
}
}
#if !SILVERLIGHT
if (this.FileName)
{
string fileName = frame.GetFileName();
if (fileName != null)
{
builder.Append("(");
if (this.IncludeSourcePath)
{
builder.Append(fileName);
}
else
{
builder.Append(Path.GetFileName(fileName));
}
builder.Append(":");
builder.Append(frame.GetFileLineNumber());
builder.Append(")");
}
}
#endif
}
}
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer 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 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer 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.
// -----
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace fxpa
{
/// <summary>
/// Provides a more comprehensible, user friendly and flexible way of interfacing and object.
/// </summary>
public partial class CustomPropertiesControl : UserControl
{
protected List<Control> propertiesControls = new List<Control>();
protected const int InterControlMargin = 5;
bool _isReadOnly = false;
public bool IsReadOnly
{
get { return _isReadOnly; }
set { _isReadOnly = value; }
}
protected int _startingYLocation = 0;
IPropertyContainer _selectedObject;
public IPropertyContainer SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
UpdateUI();
}
}
List<string> _filteringPropertiesNames = new List<string>();
/// <summary>
/// Properties with those names will not be displayed.
/// </summary>
public List<string> FilteringPropertiesNames
{
get { return _filteringPropertiesNames; }
}
/// <summary>
///
/// </summary>
public CustomPropertiesControl()
{
InitializeComponent();
//_filteringPropertiesNames.Add("Enabled");
}
private void CustomPropertiesControl_Load(object sender, EventArgs e)
{
_startingYLocation = InterControlMargin;
}
protected virtual void OnUpdateUI(int startingYValue)
{
}
/// <summary>
/// Main UI logic function.
/// </summary>
/// <returns>Y axis value of the dynamic last control.</returns>
protected void UpdateUI()
{
int lastYValue = _startingYLocation; // checkBoxEnabled.Bottom + InterControlMargin;
//lastYValue = Math.Max(checkBoxEnabled.Bottom + InterControlMargin, _startingYLocation);
if (this.DesignMode)
{
return;
}
// Clear existing indicator custom parameters controls.
foreach (Control control in propertiesControls)
{
control.Parent = null;
control.Tag = null;
control.Dispose();
}
propertiesControls.Clear();
if (SelectedObject == null)
{
OnUpdateUI(lastYValue);
return;
}
// Gather indicator custom parameters.
Type type = SelectedObject.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
Dictionary<string, PropertyInfo> actualProperties = new Dictionary<string, PropertyInfo>();
// Filter properties.
foreach (PropertyInfo info in properties)
{
if (_filteringPropertiesNames.Contains(info.Name) == false)
{
if (actualProperties.ContainsKey(info.Name) == false)
{// Also if a parent and child define same property, with "new" only show childs.
actualProperties.Add(info.Name, info);
}
}
}
// Handle default properties of the SelectedObject class.
foreach (PropertyInfo info in actualProperties.Values)
{
if (info.CanRead == false)
{// We do not process write only properties.
continue;
}
Type propertyType = info.PropertyType;
bool isReadOnly = info.CanWrite == false || IsReadOnly;
object value = info.GetValue(SelectedObject, null);
Type underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{// Unwrap nullable properties.
propertyType = underlyingType;
if (value == null)
{// Nullable enums with null values not displayed.
continue;
}
}
AddDynamicPropertyValueControl(info.Name, propertyType, value, info, isReadOnly, ref lastYValue);
}
// Handle dynamic generic properties of the indicator as well.
foreach (string name in SelectedObject.GetPropertiesNames())
{
AddDynamicPropertyValueControl(name, SelectedObject.GetPropertyType(name), SelectedObject.GetPropertyValue(name), name, IsReadOnly, ref lastYValue);
}
OnUpdateUI(lastYValue);
}
/// <summary>
/// Helper to create the corresponding label.
/// </summary>
protected void AddDynamicPropertyLabel(string labelTitle, ref int yLocation)
{
Label label = new Label();
label.Text = labelTitle;
label.Top = yLocation;
label.AutoSize = true;
this.Controls.Add(label);
yLocation = label.Bottom + InterControlMargin;
propertiesControls.Add(label);
}
/// <summary>
/// Helper to create the corresponding control.
/// </summary>
protected void AddDynamicPropertyValueControl(string propertyName, Type propertyType, object value, object tag, bool isReadOnly, ref int yLocation)
{
Control control = null;
if (propertyType.IsEnum)
{
AddDynamicPropertyLabel(propertyName, ref yLocation);
string stringValue = value.ToString();
ComboBox propertyValuesComboBox = new ComboBox();
control = propertyValuesComboBox;
propertyValuesComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
propertyValuesComboBox.Enabled = !isReadOnly;
string[] names = Enum.GetNames(propertyType);
propertyValuesComboBox.Items.AddRange(names);
for (int i = 0; i < propertyValuesComboBox.Items.Count; i++)
{
if (propertyValuesComboBox.Items[i].ToString() == stringValue)
{
propertyValuesComboBox.SelectedIndex = i;
break;
}
}
//propertyValuesComboBox.Top = yLocation;
propertyValuesComboBox.Tag = tag;
propertyValuesComboBox.SelectedIndexChanged += new EventHandler(propertyValues_SelectedIndexChanged);
}
if (propertyType == typeof(string))
{
AddDynamicPropertyLabel(propertyName, ref yLocation);
TextBox textBox = new TextBox();
textBox.Text = (string)value;
textBox.Enabled = !isReadOnly;
textBox.Tag = tag;
//textBox.Top = yLocation;
control = textBox;
textBox.TextChanged += new EventHandler(textBox_TextChanged);
}
if (propertyType == typeof(double)
|| propertyType == typeof(float)
|| propertyType == typeof(int)
|| propertyType == typeof(short)
|| propertyType == typeof(long))
{
AddDynamicPropertyLabel(propertyName, ref yLocation);
NumericUpDown propertyValueNumeric = new NumericUpDown();
control = propertyValueNumeric;
propertyValueNumeric.ReadOnly = isReadOnly;
// Enabled also needed, since readonly only blocks text, not up down buttons.
propertyValueNumeric.Enabled = !isReadOnly;
propertyValueNumeric.Minimum = decimal.MinValue;
propertyValueNumeric.Maximum = decimal.MaxValue;
propertyValueNumeric.Value = decimal.Parse(value.ToString());
propertyValueNumeric.Tag = tag;
//propertyValueNumeric.Top = yLocation;
propertyValueNumeric.ValueChanged += new EventHandler(propertyValue_ValueChanged);
}
else if (propertyType == typeof(bool))
{
CheckBox propertyValue = new CheckBox();
control = propertyValue;
propertyValue.Checked = (bool)value;
propertyValue.Text = propertyName;
propertyValue.Enabled = !isReadOnly;
//propertyValue.Top = yLocation;
propertyValue.Tag = tag;
propertyValue.CheckedChanged += new EventHandler(propertyValue_CheckedChanged);
}
else if (propertyType == typeof(Pen))
{
PenControl penControl = new PenControl();
control = penControl;
penControl.BorderStyle = BorderStyle.FixedSingle;
penControl.Pen = (Pen)value;
penControl.PenChangedEvent += new PenControl.PenChangedDelegate(penControl_PenChangedEvent);
penControl.Tag = tag;
penControl.PenName = propertyName;
penControl.ReadOnly = IsReadOnly;
//penControl.Top = yLocation;
}
else
{
//SystemMonitor.Error("Failed to display indicator property type [" + propertyType.Name + "].");
}
if (control != null)
{
control.Top = yLocation;
propertiesControls.Add(control);
this.Controls.Add(control);
yLocation = control.Bottom + InterControlMargin;
control.Width = this.Width - InterControlMargin;
this.Height = control.Bottom;
}
}
/// <summary>
/// Helper.
/// </summary>
protected Type GetPropertyTypeByTag(object tag)
{
if (tag is string)
{// Is generic dynamic property.
return _selectedObject.GetPropertyType(tag as string);
}
// Is normal property.
PropertyInfo info = (PropertyInfo)tag;
if (Nullable.GetUnderlyingType(info.PropertyType) != null)
{// Is nullable, establish underlying.
return Nullable.GetUnderlyingType(info.PropertyType);
}
else
{// Direct aquisition.
return info.PropertyType;
}
}
/// <summary>
///
/// </summary>
public void penControl_PenChangedEvent(PenControl control)
{
SetObjectPropertyValueByTag(control.Tag, control.Pen);
}
void textBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
SetObjectPropertyValueByTag(textBox.Tag, textBox.Text);
}
/// <summary>
///
/// </summary>
protected virtual void propertyValues_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox propertyValuesComboBox = (ComboBox)sender;
if (propertyValuesComboBox.SelectedIndex < 0)
{
return;
}
object newValue = Enum.Parse(GetPropertyTypeByTag(propertyValuesComboBox.Tag), propertyValuesComboBox.SelectedItem.ToString());
SetObjectPropertyValueByTag(propertyValuesComboBox.Tag, newValue);
}
void propertyValue_ValueChanged(object sender, EventArgs e)
{
NumericUpDown propertyValueNumeric = (NumericUpDown)sender;
Type propertyType = GetPropertyTypeByTag(propertyValueNumeric.Tag);
// Since numeric may display different types of values, and the type info is lost in entering,
// now extract it back to pass properly to the indicator.
object value = null;
if (propertyType == typeof(int))
{
value = (int)propertyValueNumeric.Value;
}
else if (propertyType == typeof(double))
{
value = (double)propertyValueNumeric.Value;
}
else if (propertyType == typeof(Single))
{
value = (Single)propertyValueNumeric.Value;
}
else if (propertyType == typeof(long))
{
value = (long)propertyValueNumeric.Value;
}
else
{
//SystemMonitor.Error("Unsupported input type in numeric box.");
}
SetObjectPropertyValueByTag(propertyValueNumeric.Tag, value);
}
/// <summary>
/// Helper.
/// </summary>
void SetObjectPropertyValueByTag(object tag, object value)
{
if (tag is string)
{// This is a dynamic generic property.
_selectedObject.SetPropertyValue(tag as string, value);
}
else if (tag is PropertyInfo)
{// Direct property of the indicator.
((PropertyInfo)tag).SetValue(_selectedObject, value, null);
}
else
{
//SystemMonitor.Error("Unrecognized tag type for indicator property.");
}
_selectedObject.PropertyChanged();
}
void propertyValue_CheckedChanged(object sender, EventArgs e)
{
CheckBox propertyValueCheckbox = (CheckBox)sender;
SetObjectPropertyValueByTag(propertyValueCheckbox.Tag, propertyValueCheckbox.Checked);
}
private void checkBoxEnabled_CheckedChanged(object sender, EventArgs e)
{
//_selectedObject.Enabled = checkBoxEnabled.Checked;
}
private void CustomPropertiesControl_SizeChanged(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
control.Width = this.Width - InterControlMargin;
}
}
}
}
| |
using UnityEngine.Rendering;
namespace UnityEngine.PostProcessing
{
using SSRResolution = ScreenSpaceReflectionModel.SSRResolution;
using SSRReflectionBlendType = ScreenSpaceReflectionModel.SSRReflectionBlendType;
public sealed class ScreenSpaceReflectionComponent : PostProcessingComponentCommandBuffer<ScreenSpaceReflectionModel>
{
static class Uniforms
{
internal static readonly int _RayStepSize = Shader.PropertyToID("_RayStepSize");
internal static readonly int _AdditiveReflection = Shader.PropertyToID("_AdditiveReflection");
internal static readonly int _BilateralUpsampling = Shader.PropertyToID("_BilateralUpsampling");
internal static readonly int _TreatBackfaceHitAsMiss = Shader.PropertyToID("_TreatBackfaceHitAsMiss");
internal static readonly int _AllowBackwardsRays = Shader.PropertyToID("_AllowBackwardsRays");
internal static readonly int _TraceBehindObjects = Shader.PropertyToID("_TraceBehindObjects");
internal static readonly int _MaxSteps = Shader.PropertyToID("_MaxSteps");
internal static readonly int _FullResolutionFiltering = Shader.PropertyToID("_FullResolutionFiltering");
internal static readonly int _HalfResolution = Shader.PropertyToID("_HalfResolution");
internal static readonly int _HighlightSuppression = Shader.PropertyToID("_HighlightSuppression");
internal static readonly int _PixelsPerMeterAtOneMeter = Shader.PropertyToID("_PixelsPerMeterAtOneMeter");
internal static readonly int _ScreenEdgeFading = Shader.PropertyToID("_ScreenEdgeFading");
internal static readonly int _ReflectionBlur = Shader.PropertyToID("_ReflectionBlur");
internal static readonly int _MaxRayTraceDistance = Shader.PropertyToID("_MaxRayTraceDistance");
internal static readonly int _FadeDistance = Shader.PropertyToID("_FadeDistance");
internal static readonly int _LayerThickness = Shader.PropertyToID("_LayerThickness");
internal static readonly int _SSRMultiplier = Shader.PropertyToID("_SSRMultiplier");
internal static readonly int _FresnelFade = Shader.PropertyToID("_FresnelFade");
internal static readonly int _FresnelFadePower = Shader.PropertyToID("_FresnelFadePower");
internal static readonly int _ReflectionBufferSize = Shader.PropertyToID("_ReflectionBufferSize");
internal static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
internal static readonly int _InvScreenSize = Shader.PropertyToID("_InvScreenSize");
internal static readonly int _ProjInfo = Shader.PropertyToID("_ProjInfo");
internal static readonly int _CameraClipInfo = Shader.PropertyToID("_CameraClipInfo");
internal static readonly int _ProjectToPixelMatrix = Shader.PropertyToID("_ProjectToPixelMatrix");
internal static readonly int _WorldToCameraMatrix = Shader.PropertyToID("_WorldToCameraMatrix");
internal static readonly int _CameraToWorldMatrix = Shader.PropertyToID("_CameraToWorldMatrix");
internal static readonly int _Axis = Shader.PropertyToID("_Axis");
internal static readonly int _CurrentMipLevel = Shader.PropertyToID("_CurrentMipLevel");
internal static readonly int _NormalAndRoughnessTexture = Shader.PropertyToID("_NormalAndRoughnessTexture");
internal static readonly int _HitPointTexture = Shader.PropertyToID("_HitPointTexture");
internal static readonly int _BlurTexture = Shader.PropertyToID("_BlurTexture");
internal static readonly int _FilteredReflections = Shader.PropertyToID("_FilteredReflections");
internal static readonly int _FinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture");
internal static readonly int _TempTexture = Shader.PropertyToID("_TempTexture");
}
// Unexposed variables
bool k_HighlightSuppression = false;
bool k_TraceBehindObjects = true;
bool k_TreatBackfaceHitAsMiss = false;
bool k_BilateralUpsample = true;
enum PassIndex
{
RayTraceStep = 0,
CompositeFinal = 1,
Blur = 2,
CompositeSSR = 3,
MinMipGeneration = 4,
HitPointToReflections = 5,
BilateralKeyPack = 6,
BlitDepthAsCSZ = 7,
PoissonBlur = 8,
}
readonly int[] m_ReflectionTextures = new int[5];
// Not really needed as SSR only works in deferred right now
public override DepthTextureMode GetCameraFlags()
{
return DepthTextureMode.Depth;
}
public override bool active
{
get
{
return model.enabled
&& context.isGBufferAvailable
&& !context.interrupted;
}
}
public override void OnEnable()
{
m_ReflectionTextures[0] = Shader.PropertyToID("_ReflectionTexture0");
m_ReflectionTextures[1] = Shader.PropertyToID("_ReflectionTexture1");
m_ReflectionTextures[2] = Shader.PropertyToID("_ReflectionTexture2");
m_ReflectionTextures[3] = Shader.PropertyToID("_ReflectionTexture3");
m_ReflectionTextures[4] = Shader.PropertyToID("_ReflectionTexture4");
}
public override string GetName()
{
return "Screen Space Reflection";
}
public override CameraEvent GetCameraEvent()
{
return CameraEvent.AfterFinalPass;
}
public override void PopulateCommandBuffer(CommandBuffer cb)
{
var settings = model.settings;
var camera = context.camera;
// Material setup
int downsampleAmount = (settings.reflection.reflectionQuality == SSRResolution.High) ? 1 : 2;
var rtW = context.width / downsampleAmount;
var rtH = context.height / downsampleAmount;
float sWidth = context.width;
float sHeight = context.height;
float sx = sWidth / 2f;
float sy = sHeight / 2f;
var material = context.materialFactory.Get("Hidden/Post FX/Screen Space Reflection");
material.SetInt(Uniforms._RayStepSize, settings.reflection.stepSize);
material.SetInt(Uniforms._AdditiveReflection, settings.reflection.blendType == SSRReflectionBlendType.Additive ? 1 : 0);
material.SetInt(Uniforms._BilateralUpsampling, k_BilateralUpsample ? 1 : 0);
material.SetInt(Uniforms._TreatBackfaceHitAsMiss, k_TreatBackfaceHitAsMiss ? 1 : 0);
material.SetInt(Uniforms._AllowBackwardsRays, settings.reflection.reflectBackfaces ? 1 : 0);
material.SetInt(Uniforms._TraceBehindObjects, k_TraceBehindObjects ? 1 : 0);
material.SetInt(Uniforms._MaxSteps, settings.reflection.iterationCount);
material.SetInt(Uniforms._FullResolutionFiltering, 0);
material.SetInt(Uniforms._HalfResolution, (settings.reflection.reflectionQuality != SSRResolution.High) ? 1 : 0);
material.SetInt(Uniforms._HighlightSuppression, k_HighlightSuppression ? 1 : 0);
// The height in pixels of a 1m object if viewed from 1m away.
float pixelsPerMeterAtOneMeter = sWidth / (-2f * Mathf.Tan(camera.fieldOfView / 180f * Mathf.PI * 0.5f));
material.SetFloat(Uniforms._PixelsPerMeterAtOneMeter, pixelsPerMeterAtOneMeter);
material.SetFloat(Uniforms._ScreenEdgeFading, settings.screenEdgeMask.intensity);
material.SetFloat(Uniforms._ReflectionBlur, settings.reflection.reflectionBlur);
material.SetFloat(Uniforms._MaxRayTraceDistance, settings.reflection.maxDistance);
material.SetFloat(Uniforms._FadeDistance, settings.intensity.fadeDistance);
material.SetFloat(Uniforms._LayerThickness, settings.reflection.widthModifier);
material.SetFloat(Uniforms._SSRMultiplier, settings.intensity.reflectionMultiplier);
material.SetFloat(Uniforms._FresnelFade, settings.intensity.fresnelFade);
material.SetFloat(Uniforms._FresnelFadePower, settings.intensity.fresnelFadePower);
var P = camera.projectionMatrix;
var projInfo = new Vector4(
-2f / (sWidth * P[0]),
-2f / (sHeight * P[5]),
(1f - P[2]) / P[0],
(1f + P[6]) / P[5]
);
var cameraClipInfo = float.IsPositiveInfinity(camera.farClipPlane) ?
new Vector3(camera.nearClipPlane, -1f, 1f) :
new Vector3(camera.nearClipPlane * camera.farClipPlane, camera.nearClipPlane - camera.farClipPlane, camera.farClipPlane);
material.SetVector(Uniforms._ReflectionBufferSize, new Vector2(rtW, rtH));
material.SetVector(Uniforms._ScreenSize, new Vector2(sWidth, sHeight));
material.SetVector(Uniforms._InvScreenSize, new Vector2(1f / sWidth, 1f / sHeight));
material.SetVector(Uniforms._ProjInfo, projInfo); // used for unprojection
material.SetVector(Uniforms._CameraClipInfo, cameraClipInfo);
var warpToScreenSpaceMatrix = new Matrix4x4();
warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0f, 0f, sx));
warpToScreenSpaceMatrix.SetRow(1, new Vector4(0f, sy, 0f, sy));
warpToScreenSpaceMatrix.SetRow(2, new Vector4(0f, 0f, 1f, 0f));
warpToScreenSpaceMatrix.SetRow(3, new Vector4(0f, 0f, 0f, 1f));
var projectToPixelMatrix = warpToScreenSpaceMatrix * P;
material.SetMatrix(Uniforms._ProjectToPixelMatrix, projectToPixelMatrix);
material.SetMatrix(Uniforms._WorldToCameraMatrix, camera.worldToCameraMatrix);
material.SetMatrix(Uniforms._CameraToWorldMatrix, camera.worldToCameraMatrix.inverse);
// Command buffer setup
var intermediateFormat = context.isHdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
const int maxMip = 5;
var kNormalAndRoughnessTexture = Uniforms._NormalAndRoughnessTexture;
var kHitPointTexture = Uniforms._HitPointTexture;
var kBlurTexture = Uniforms._BlurTexture;
var kFilteredReflections = Uniforms._FilteredReflections;
var kFinalReflectionTexture = Uniforms._FinalReflectionTexture;
var kTempTexture = Uniforms._TempTexture;
// RGB: Normals, A: Roughness.
// Has the nice benefit of allowing us to control the filtering mode as well.
cb.GetTemporaryRT(kNormalAndRoughnessTexture, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
cb.GetTemporaryRT(kHitPointTexture, rtW, rtH, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
for (int i = 0; i < maxMip; ++i)
{
// We explicitly interpolate during bilateral upsampling.
cb.GetTemporaryRT(m_ReflectionTextures[i], rtW >> i, rtH >> i, 0, FilterMode.Bilinear, intermediateFormat);
}
cb.GetTemporaryRT(kFilteredReflections, rtW, rtH, 0, k_BilateralUpsample ? FilterMode.Point : FilterMode.Bilinear, intermediateFormat);
cb.GetTemporaryRT(kFinalReflectionTexture, rtW, rtH, 0, FilterMode.Point, intermediateFormat);
cb.Blit(BuiltinRenderTextureType.CameraTarget, kNormalAndRoughnessTexture, material, (int)PassIndex.BilateralKeyPack);
cb.Blit(BuiltinRenderTextureType.CameraTarget, kHitPointTexture, material, (int)PassIndex.RayTraceStep);
cb.Blit(BuiltinRenderTextureType.CameraTarget, kFilteredReflections, material, (int)PassIndex.HitPointToReflections);
cb.Blit(kFilteredReflections, m_ReflectionTextures[0], material, (int)PassIndex.PoissonBlur);
for (int i = 1; i < maxMip; ++i)
{
int inputTex = m_ReflectionTextures[i - 1];
int lowMip = i;
cb.GetTemporaryRT(kBlurTexture, rtW >> lowMip, rtH >> lowMip, 0, FilterMode.Bilinear, intermediateFormat);
cb.SetGlobalVector(Uniforms._Axis, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
cb.SetGlobalFloat(Uniforms._CurrentMipLevel, i - 1.0f);
cb.Blit(inputTex, kBlurTexture, material, (int)PassIndex.Blur);
cb.SetGlobalVector(Uniforms._Axis, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
inputTex = m_ReflectionTextures[i];
cb.Blit(kBlurTexture, inputTex, material, (int)PassIndex.Blur);
cb.ReleaseTemporaryRT(kBlurTexture);
}
cb.Blit(m_ReflectionTextures[0], kFinalReflectionTexture, material, (int)PassIndex.CompositeSSR);
cb.GetTemporaryRT(kTempTexture, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Bilinear, intermediateFormat);
cb.Blit(BuiltinRenderTextureType.CameraTarget, kTempTexture, material, (int)PassIndex.CompositeFinal);
cb.Blit(kTempTexture, BuiltinRenderTextureType.CameraTarget);
cb.ReleaseTemporaryRT(kTempTexture);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// 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.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
// This scenario declares support for a calculator service.
// Remote clients (including this sample on another machine) can supply:
// - Operands 1 and 2
// - an operator (+,-,*,/)
// and get a result
public sealed partial class Scenario3_ServerForeground : Page
{
private MainPage rootPage = MainPage.Current;
GattServiceProvider serviceProvider;
private GattLocalCharacteristic op1Characteristic;
private int operand1Received = 0;
private GattLocalCharacteristic op2Characteristic;
private int operand2Received = 0;
private GattLocalCharacteristic operatorCharacteristic;
CalculatorOperators operatorReceived = 0;
private GattLocalCharacteristic resultCharacteristic;
private int resultVal = 0;
private bool peripheralSupported;
private enum CalculatorCharacteristics
{
Operand1 = 1,
Operand2 = 2,
Operator = 3
}
private enum CalculatorOperators
{
Add = 1,
Subtract = 2,
Multiply = 3,
Divide = 4
}
#region UI Code
public Scenario3_ServerForeground()
{
InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
peripheralSupported = await CheckPeripheralRoleSupportAsync();
if (peripheralSupported)
{
ServerPanel.Visibility = Visibility.Visible;
}
else
{
PeripheralWarning.Visibility = Visibility.Visible;
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (serviceProvider != null)
{
if (serviceProvider.AdvertisementStatus != GattServiceProviderAdvertisementStatus.Stopped)
{
serviceProvider.StopAdvertising();
}
serviceProvider = null;
}
}
private async void PublishButton_ClickAsync()
{
// Server not initialized yet - initialize it and start publishing
if (serviceProvider == null)
{
var serviceStarted = await ServiceProviderInitAsync();
if (serviceStarted)
{
rootPage.NotifyUser("Service successfully started", NotifyType.StatusMessage);
PublishButton.Content = "Stop Service";
}
else
{
rootPage.NotifyUser("Service not started", NotifyType.ErrorMessage);
}
}
else
{
// BT_Code: Stops advertising support for custom GATT Service
serviceProvider.StopAdvertising();
serviceProvider = null;
PublishButton.Content = "Start Service";
}
}
private async void UpdateUX()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
switch (operatorReceived)
{
case CalculatorOperators.Add:
OperationText.Text = "+";
break;
case CalculatorOperators.Subtract:
OperationText.Text = "-";
break;
case CalculatorOperators.Multiply:
OperationText.Text = "*";
break;
case CalculatorOperators.Divide:
OperationText.Text = "/";
break;
default:
OperationText.Text = "INV";
break;
}
Operand1Text.Text = operand1Received.ToString();
Operand2Text.Text = operand2Received.ToString();
resultVal = ComputeResult();
ResultText.Text = resultVal.ToString();
});
}
#endregion
private async Task<bool> CheckPeripheralRoleSupportAsync()
{
// BT_Code: New for Creator's Update - Bluetooth adapter has properties of the local BT radio.
var localAdapter = await BluetoothAdapter.GetDefaultAsync();
if (localAdapter != null)
{
return localAdapter.IsPeripheralRoleSupported;
}
else
{
// Bluetooth is not turned on
return false;
}
}
/// <summary>
/// Uses the relevant Service/Characteristic UUIDs to initialize, hook up event handlers and start a service on the local system.
/// </summary>
/// <returns></returns>
private async Task<bool> ServiceProviderInitAsync()
{
// BT_Code: Initialize and starting a custom GATT Service using GattServiceProvider.
GattServiceProviderResult serviceResult = await GattServiceProvider.CreateAsync(Constants.CalcServiceUuid);
if (serviceResult.Error == BluetoothError.Success)
{
serviceProvider = serviceResult.ServiceProvider;
}
else
{
rootPage.NotifyUser($"Could not create service provider: {serviceResult.Error}", NotifyType.ErrorMessage);
return false;
}
GattLocalCharacteristicResult result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op1CharacteristicUuid, Constants.gattOperandParameters);
if (result.Error == BluetoothError.Success)
{
op1Characteristic = result.Characteristic;
}
else
{
rootPage.NotifyUser($"Could not create operand1 characteristic: {result.Error}", NotifyType.ErrorMessage);
return false;
}
op1Characteristic.WriteRequested += Op1Characteristic_WriteRequestedAsync;
result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op2CharacteristicUuid, Constants.gattOperandParameters);
if (result.Error == BluetoothError.Success)
{
op2Characteristic = result.Characteristic;
}
else
{
rootPage.NotifyUser($"Could not create operand2 characteristic: {result.Error}", NotifyType.ErrorMessage);
return false;
}
op2Characteristic.WriteRequested += Op2Characteristic_WriteRequestedAsync;
result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.OperatorCharacteristicUuid, Constants.gattOperatorParameters);
if (result.Error == BluetoothError.Success)
{
operatorCharacteristic = result.Characteristic;
}
else
{
rootPage.NotifyUser($"Could not create operator characteristic: {result.Error}", NotifyType.ErrorMessage);
return false;
}
operatorCharacteristic.WriteRequested += OperatorCharacteristic_WriteRequestedAsync;
// Add presentation format - 32-bit unsigned integer, with exponent 0, the unit is unitless, with no company description
GattPresentationFormat intFormat = GattPresentationFormat.FromParts(
GattPresentationFormatTypes.UInt32,
PresentationFormats.Exponent,
Convert.ToUInt16(PresentationFormats.Units.Unitless),
Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
PresentationFormats.Description);
Constants.gattResultParameters.PresentationFormats.Add(intFormat);
result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ResultCharacteristicUuid, Constants.gattResultParameters);
if (result.Error == BluetoothError.Success)
{
resultCharacteristic = result.Characteristic;
}
else
{
rootPage.NotifyUser($"Could not create result characteristic: {result.Error}", NotifyType.ErrorMessage);
return false;
}
resultCharacteristic.ReadRequested += ResultCharacteristic_ReadRequestedAsync;
resultCharacteristic.SubscribedClientsChanged += ResultCharacteristic_SubscribedClientsChanged;
// BT_Code: Indicate if your sever advertises as connectable and discoverable.
GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
{
// IsConnectable determines whether a call to publish will attempt to start advertising and
// put the service UUID in the ADV packet (best effort)
IsConnectable = peripheralSupported,
// IsDiscoverable determines whether a remote device can query the local device for support
// of this service
IsDiscoverable = true
};
serviceProvider.AdvertisementStatusChanged += ServiceProvider_AdvertisementStatusChanged;
serviceProvider.StartAdvertising(advParameters);
return true;
}
private void ResultCharacteristic_SubscribedClientsChanged(GattLocalCharacteristic sender, object args)
{
rootPage.NotifyUser($"New device subscribed. New subscribed count: {sender.SubscribedClients.Count}", NotifyType.StatusMessage);
}
private void ServiceProvider_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
{
// Created - The default state of the advertisement, before the service is published for the first time.
// Stopped - Indicates that the application has canceled the service publication and its advertisement.
// Started - Indicates that the system was successfully able to issue the advertisement request.
// Aborted - Indicates that the system was unable to submit the advertisement request, or it was canceled due to resource contention.
rootPage.NotifyUser($"New Advertisement Status: {sender.AdvertisementStatus}", NotifyType.StatusMessage);
}
private async void ResultCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
{
// BT_Code: Process a read request.
using (args.GetDeferral())
{
// Get the request information. This requires device access before an app can access the device's request.
GattReadRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
rootPage.NotifyUser("Access to device not allowed", NotifyType.ErrorMessage);
return;
}
var writer = new DataWriter();
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteInt32(resultVal);
// Can get details about the request such as the size and offset, as well as monitor the state to see if it has been completed/cancelled externally.
// request.Offset
// request.Length
// request.State
// request.StateChanged += <Handler>
// Gatt code to handle the response
request.RespondWithValue(writer.DetachBuffer());
}
}
private int ComputeResult()
{
Int32 computedValue = 0;
switch (operatorReceived)
{
case CalculatorOperators.Add:
computedValue = operand1Received + operand2Received;
break;
case CalculatorOperators.Subtract:
computedValue = operand1Received - operand2Received;
break;
case CalculatorOperators.Multiply:
computedValue = operand1Received * operand2Received;
break;
case CalculatorOperators.Divide:
if (operand2Received == 0 || (operand1Received == -0x80000000 && operand2Received == -1))
{
rootPage.NotifyUser("Division overflow", NotifyType.ErrorMessage);
}
else
{
computedValue = operand1Received / operand2Received;
}
break;
default:
rootPage.NotifyUser("Invalid Operator", NotifyType.ErrorMessage);
break;
}
NotifyClientDevices(computedValue);
return computedValue;
}
private async void NotifyClientDevices(int computedValue)
{
var writer = new DataWriter();
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteInt32(computedValue);
// BT_Code: Returns a collection of all clients that the notification was attempted and the result.
IReadOnlyList<GattClientNotificationResult> results = await resultCharacteristic.NotifyValueAsync(writer.DetachBuffer());
rootPage.NotifyUser($"Sent value {computedValue} to clients.", NotifyType.StatusMessage);
foreach (var result in results)
{
// An application can iterate through each registered client that was notified and retrieve the results:
//
// result.SubscribedClient: The details on the remote client.
// result.Status: The GattCommunicationStatus
// result.ProtocolError: iff Status == GattCommunicationStatus.ProtocolError
}
}
private async void Op1Characteristic_WriteRequestedAsync(GattLocalCharacteristic sender, GattWriteRequestedEventArgs args)
{
// BT_Code: Processing a write request.
using (args.GetDeferral())
{
// Get the request information. This requires device access before an app can access the device's request.
GattWriteRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
return;
}
ProcessWriteCharacteristic(request, CalculatorCharacteristics.Operand1);
}
}
private async void Op2Characteristic_WriteRequestedAsync(GattLocalCharacteristic sender, GattWriteRequestedEventArgs args)
{
using (args.GetDeferral())
{
// Get the request information. This requires device access before an app can access the device's request.
GattWriteRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
return;
}
ProcessWriteCharacteristic(request, CalculatorCharacteristics.Operand2);
}
}
private async void OperatorCharacteristic_WriteRequestedAsync(GattLocalCharacteristic sender, GattWriteRequestedEventArgs args)
{
using (args.GetDeferral())
{
// Get the request information. This requires device access before an app can access the device's request.
GattWriteRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
return;
}
ProcessWriteCharacteristic(request, CalculatorCharacteristics.Operator);
}
}
/// <summary>
/// BT_Code: Processing a write request.Takes in a GATT Write request and updates UX based on opcode.
/// </summary>
/// <param name="request"></param>
/// <param name="opCode">Operand (1 or 2) and Operator (3)</param>
private void ProcessWriteCharacteristic(GattWriteRequest request, CalculatorCharacteristics opCode)
{
if (request.Value.Length != 4)
{
// Input is the wrong length. Respond with a protocol error if requested.
if (request.Option == GattWriteOption.WriteWithResponse)
{
request.RespondWithProtocolError(GattProtocolError.InvalidAttributeValueLength);
}
return;
}
var reader = DataReader.FromBuffer(request.Value);
reader.ByteOrder = ByteOrder.LittleEndian;
int val = reader.ReadInt32();
switch (opCode)
{
case CalculatorCharacteristics.Operand1:
operand1Received = val;
break;
case CalculatorCharacteristics.Operand2:
operand2Received = val;
break;
case CalculatorCharacteristics.Operator:
if (!Enum.IsDefined(typeof(CalculatorOperators), val))
{
if (request.Option == GattWriteOption.WriteWithResponse)
{
request.RespondWithProtocolError(GattProtocolError.InvalidPdu);
}
return;
}
operatorReceived = (CalculatorOperators)val;
break;
}
// Complete the request if needed
if (request.Option == GattWriteOption.WriteWithResponse)
{
request.Respond();
}
UpdateUX();
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="State.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine.States
{
using System;
using System.Collections.Generic;
using Appccelerate.StateMachine.Machine.ActionHolders;
using Appccelerate.StateMachine.Machine.Transitions;
/// <summary>
/// A state of the state machine.
/// A state can be a sub-state or super-state of another state.
/// </summary>
/// <typeparam name="TState">The type of the state id.</typeparam>
/// <typeparam name="TEvent">The type of the event id.</typeparam>
public class State<TState, TEvent>
: IState<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
/// <summary>
/// Collection of the sub-states of this state.
/// </summary>
private readonly List<IState<TState, TEvent>> subStates;
/// <summary>
/// Collection of transitions that start in this state (<see cref="ITransition{TState,TEvent}.Source"/> is equal to this state).
/// </summary>
private readonly TransitionDictionary<TState, TEvent> transitions;
private readonly IStateMachineInformation<TState, TEvent> stateMachineInformation;
private readonly IExtensionHost<TState, TEvent> extensionHost;
/// <summary>
/// The level of this state within the state hierarchy [1..maxLevel]
/// </summary>
private int level;
/// <summary>
/// The super-state of this state. Null for states with <see cref="level"/> equal to 1.
/// </summary>
private IState<TState, TEvent> superState;
/// <summary>
/// The initial sub-state of this state.
/// </summary>
private IState<TState, TEvent> initialState;
/// <summary>
/// The <see cref="HistoryType"/> of this state.
/// </summary>
private HistoryType historyType = HistoryType.None;
/// <summary>
/// Initializes a new instance of the <see cref="State<TState, TEvent>"/> class.
/// </summary>
/// <param name="id">The unique id of this state.</param>
/// <param name="stateMachineInformation">The state machine information.</param>
/// <param name="extensionHost">The extension host.</param>
public State(TState id, IStateMachineInformation<TState, TEvent> stateMachineInformation, IExtensionHost<TState, TEvent> extensionHost)
{
this.Id = id;
this.level = 1;
this.stateMachineInformation = stateMachineInformation;
this.extensionHost = extensionHost;
this.subStates = new List<IState<TState, TEvent>>();
this.transitions = new TransitionDictionary<TState, TEvent>(this);
this.EntryActions = new List<IActionHolder>();
this.ExitActions = new List<IActionHolder>();
}
/// <summary>
/// Gets or sets the last active state of this state.
/// </summary>
/// <value>The last state of the active.</value>
public IState<TState, TEvent> LastActiveState { get; set; }
/// <summary>
/// Gets the unique id of this state.
/// </summary>
/// <value>The id of this state.</value>
public TState Id { get; private set; }
/// <summary>
/// Gets the entry actions.
/// </summary>
/// <value>The entry actions.</value>
public IList<IActionHolder> EntryActions { get; private set; }
/// <summary>
/// Gets the exit actions.
/// </summary>
/// <value>The exit action.</value>
public IList<IActionHolder> ExitActions { get; private set; }
/// <summary>
/// Gets or sets the initial sub state of this state.
/// </summary>
/// <value>The initial sub state of this state.</value>
public IState<TState, TEvent> InitialState
{
get
{
return this.initialState;
}
set
{
this.CheckInitialStateIsNotThisInstance(value);
this.CheckInitialStateIsASubState(value);
this.initialState = this.LastActiveState = value;
}
}
/// <summary>
/// Gets or sets the super-state of this state.
/// </summary>
/// <remarks>
/// The <see cref="Level"/> of this state is changed accordingly to the super-state.
/// </remarks>
/// <value>The super-state of this super.</value>
public IState<TState, TEvent> SuperState
{
get
{
return this.superState;
}
set
{
this.CheckSuperStateIsNotThisInstance(value);
this.superState = value;
this.SetInitialLevel();
}
}
/// <summary>
/// Gets or sets the level of this state in the state hierarchy.
/// When set then the levels of all sub-states are changed accordingly.
/// </summary>
/// <value>The level.</value>
public int Level
{
get
{
return this.level;
}
set
{
this.level = value;
this.SetLevelOfSubStates();
}
}
/// <summary>
/// Gets or sets the history type of this state.
/// </summary>
/// <value>The type of the history.</value>
public HistoryType HistoryType
{
get { return this.historyType; }
set { this.historyType = value; }
}
/// <summary>
/// Gets the sub-states of this state.
/// </summary>
/// <value>The sub-states of this state.</value>
public ICollection<IState<TState, TEvent>> SubStates
{
get { return this.subStates; }
}
/// <summary>
/// Gets the transitions that start in this state.
/// </summary>
/// <value>The transitions.</value>
public ITransitionDictionary<TState, TEvent> Transitions
{
get { return this.transitions; }
}
/// <summary>
/// Goes recursively up the state hierarchy until a state is found that can handle the event.
/// </summary>
/// <param name="context">The event context.</param>
/// <returns>The result of the transition.</returns>
public ITransitionResult<TState, TEvent> Fire(ITransitionContext<TState, TEvent> context)
{
Ensure.ArgumentNotNull(context, "context");
ITransitionResult<TState, TEvent> result = TransitionResult<TState, TEvent>.NotFired;
var transitionsForEvent = this.transitions[context.EventId.Value];
if (transitionsForEvent != null)
{
foreach (ITransition<TState, TEvent> transition in transitionsForEvent)
{
result = transition.Fire(context);
if (result.Fired)
{
return result;
}
}
}
if (this.SuperState != null)
{
result = this.SuperState.Fire(context);
}
return result;
}
public void Entry(ITransitionContext<TState, TEvent> context)
{
Ensure.ArgumentNotNull(context, "context");
context.AddRecord(this.Id, RecordType.Enter);
this.ExecuteEntryActions(context);
}
public void Exit(ITransitionContext<TState, TEvent> context)
{
Ensure.ArgumentNotNull(context, "context");
context.AddRecord(this.Id, RecordType.Exit);
this.ExecuteExitActions(context);
this.SetThisStateAsLastStateOfSuperState();
}
public IState<TState, TEvent> EnterByHistory(ITransitionContext<TState, TEvent> context)
{
IState<TState, TEvent> result = this;
switch (this.HistoryType)
{
case HistoryType.None:
result = this.EnterHistoryNone(context);
break;
case HistoryType.Shallow:
result = this.EnterHistoryShallow(context);
break;
case HistoryType.Deep:
result = this.EnterHistoryDeep(context);
break;
}
return result;
}
public IState<TState, TEvent> EnterShallow(ITransitionContext<TState, TEvent> context)
{
this.Entry(context);
return this.initialState == null ?
this :
this.initialState.EnterShallow(context);
}
public IState<TState, TEvent> EnterDeep(ITransitionContext<TState, TEvent> context)
{
this.Entry(context);
return this.LastActiveState == null ?
this :
this.LastActiveState.EnterDeep(context);
}
public override string ToString()
{
return this.Id.ToString();
}
private static void HandleException(Exception exception, ITransitionContext<TState, TEvent> context)
{
context.OnExceptionThrown(exception);
}
/// <summary>
/// Sets the initial level depending on the level of the super state of this instance.
/// </summary>
private void SetInitialLevel()
{
this.Level = this.superState != null ? this.superState.Level + 1 : 1;
}
/// <summary>
/// Sets the level of all sub states.
/// </summary>
private void SetLevelOfSubStates()
{
foreach (var state in this.subStates)
{
state.Level = this.level + 1;
}
}
private void ExecuteEntryActions(ITransitionContext<TState, TEvent> context)
{
foreach (var actionHolder in this.EntryActions)
{
this.ExecuteEntryAction(actionHolder, context);
}
}
private void ExecuteEntryAction(IActionHolder actionHolder, ITransitionContext<TState, TEvent> context)
{
try
{
actionHolder.Execute(context.EventArgument);
}
catch (Exception exception)
{
this.HandleEntryActionException(context, exception);
}
}
private void HandleEntryActionException(ITransitionContext<TState, TEvent> context, Exception exception)
{
this.extensionHost.ForEach(
extension =>
extension.HandlingEntryActionException(
this.stateMachineInformation, this, context, ref exception));
HandleException(exception, context);
this.extensionHost.ForEach(
extension =>
extension.HandledEntryActionException(
this.stateMachineInformation, this, context, exception));
}
private void ExecuteExitActions(ITransitionContext<TState, TEvent> context)
{
foreach (var actionHolder in this.ExitActions)
{
this.ExecuteExitAction(actionHolder, context);
}
}
private void ExecuteExitAction(IActionHolder actionHolder, ITransitionContext<TState, TEvent> context)
{
try
{
actionHolder.Execute(context.EventArgument);
}
catch (Exception exception)
{
this.HandleExitActionException(context, exception);
}
}
private void HandleExitActionException(ITransitionContext<TState, TEvent> context, Exception exception)
{
this.extensionHost.ForEach(
extension =>
extension.HandlingExitActionException(
this.stateMachineInformation, this, context, ref exception));
HandleException(exception, context);
this.extensionHost.ForEach(
extension =>
extension.HandledExitActionException(
this.stateMachineInformation, this, context, exception));
}
/// <summary>
/// Sets this instance as the last state of this instance's super state.
/// </summary>
private void SetThisStateAsLastStateOfSuperState()
{
if (this.superState != null)
{
this.superState.LastActiveState = this;
}
}
private IState<TState, TEvent> EnterHistoryDeep(ITransitionContext<TState, TEvent> context)
{
return this.LastActiveState != null
?
this.LastActiveState.EnterDeep(context)
:
this;
}
private IState<TState, TEvent> EnterHistoryShallow(ITransitionContext<TState, TEvent> context)
{
return this.LastActiveState != null
?
this.LastActiveState.EnterShallow(context)
:
this;
}
private IState<TState, TEvent> EnterHistoryNone(ITransitionContext<TState, TEvent> context)
{
return this.initialState != null
?
this.initialState.EnterShallow(context)
:
this;
}
/// <summary>
/// Throws an exception if the new super state is this instance.
/// </summary>
/// <param name="newSuperState">The value.</param>
// ReSharper disable once UnusedParameter.Local
private void CheckSuperStateIsNotThisInstance(IState<TState, TEvent> newSuperState)
{
if (this == newSuperState)
{
throw new ArgumentException(StatesExceptionMessages.StateCannotBeItsOwnSuperState(this.ToString()));
}
}
/// <summary>
/// Throws an exception if the new initial state is this instance.
/// </summary>
/// <param name="newInitialState">The value.</param>
// ReSharper disable once UnusedParameter.Local
private void CheckInitialStateIsNotThisInstance(IState<TState, TEvent> newInitialState)
{
if (this == newInitialState)
{
throw new ArgumentException(StatesExceptionMessages.StateCannotBeTheInitialSubStateToItself(this.ToString()));
}
}
/// <summary>
/// Throws an exception if the new initial state is not a sub-state of this instance.
/// </summary>
/// <param name="value">The value.</param>
private void CheckInitialStateIsASubState(IState<TState, TEvent> value)
{
if (value.SuperState != this)
{
throw new ArgumentException(StatesExceptionMessages.StateCannotBeTheInitialStateOfSuperStateBecauseItIsNotADirectSubState(value.ToString(), this.ToString()));
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using Epi.Collections;
using System.IO;
using System.Text;
using Epi.Data;
using System.Globalization;
using Epi.Data.Office.Forms;
namespace Epi.Data.Office
{
/// <summary>
/// Concrete Microsoft Access 2007 database implementation
/// </summary>
public partial class Access2007Database : OleDbDatabase
{
/// <summary>
/// Default Constructor
/// </summary>
public Access2007Database() : base() { }
#region Database Implementation
/// <summary>
/// Set Access database file path
/// </summary>
/// <param name="filePath"></param>
public override void SetDataSourceFilePath(string filePath)
{
this.ConnectionString = filePath;
}
/// <summary>
/// Returns the full name of the data source
/// </summary>
public override string FullName // Implements Database.FullName
{
get
{
return "[MS Access] " + Location ?? "";
}
}
/// <summary>
/// Compact the database
/// << may only apply to Access databases >>
/// </summary>
public override bool CompactDatabase()
{
bool success = true;
Type typeJRO = Type.GetTypeFromProgID("JRO.JetEngine");
if (typeJRO == null)
{
throw new InvalidOperationException("JRO.JetEngine can not be created... please check if it is installed");
}
object JRO = Activator.CreateInstance(typeJRO);
string dataSource = DataSource;
string dataSource_Temp = dataSource.Insert(dataSource.LastIndexOf('.'),"_Temp");
object[] paramObjects = new object[]
{
OleConnectionString,
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"" + dataSource_Temp + "\";Jet OLEDB:Engine Type=5"
};
try
{
JRO.GetType().InvokeMember
(
"CompactDatabase",
System.Reflection.BindingFlags.InvokeMethod,
null,
JRO,
paramObjects
);
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(JRO);
JRO = null;
}
if (success)
{
System.IO.File.Delete(dataSource);
System.IO.File.Move(dataSource_Temp, dataSource);
}
return success;
}
/// <summary>
/// Adds a column to the table
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="column">The column</param>
/// <returns>Boolean</returns>
public override bool AddColumn(string tableName, TableColumn column)
{
StringBuilder sb = new StringBuilder();
sb.Append("ALTER TABLE ");
sb.Append(tableName);
sb.Append(" ADD COLUMN ");
sb.Append(column.Name);
sb.Append(" ");
sb.Append(GetDbSpecificColumnType(column.DataType));
if (column.Length != null)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
sb.Append(") ");
}
ExecuteNonQuery(CreateQuery(sb.ToString()));
return false;
}
protected override OleDbConnection GetNativeConnection(string connectionString)
{
OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
oleDBCnnStrBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
return new OleDbConnection(oleDBCnnStrBuilder.ToString());
}
/// <summary>
/// Creates a table with the given columns
/// </summary>
/// <param name="tableName">Table name to be created</param>
/// <param name="columns">List of columns</param>
public override void CreateTable(string tableName, List<TableColumn> columns)
{
StringBuilder sb = new StringBuilder();
sb.Append("create table ");
sb.Append(Util.InsertInSquareBrackets(tableName));
sb.Append(" ( ");
foreach (TableColumn column in columns)
{
if (column.Name.ToLowerInvariant() != "uniquekey")
{
if (column.IsIdentity)
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
sb.Append(" COUNTER ");
}
else
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value > 255)
{
sb.Append("memo");
}
else
{
sb.Append(GetDbSpecificColumnType(column.DataType));
}
}
}
else
{
//UniqueKey exists
sb.Append("[");
sb.Append(column.Name);
sb.Append("] counter ");
}
if (column.Length != null)
{
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value <= 255 && column.Length.Value > 0)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
sb.Append(") ");
}
}
if (!column.AllowNull)
{
sb.Append(" NOT ");
}
sb.Append(" null ");
if (column.IsPrimaryKey)
{
sb.Append(" constraint");
sb.Append(" PK_");
sb.Append(column.Name);
sb.Append("_");
sb.Append(tableName);
sb.Append(" primary key ");
}
if (!string.IsNullOrEmpty(column.ForeignKeyColumnName) && !string.IsNullOrEmpty(column.ForeignKeyTableName))
{
sb.Append(" references ");
sb.Append(column.ForeignKeyTableName);
sb.Append("([");
sb.Append(column.ForeignKeyColumnName);
sb.Append("]) ");
if (column.CascadeDelete)
{
sb.Append(" on delete cascade");
}
}
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
sb.Append(") ");
ExecuteNonQuery(CreateQuery(sb.ToString()));
}
#endregion
#region Private Members
/// <summary>
/// Gets the database-specific column data type.
/// </summary>
/// <param name="dataType">An extension of the System.Data.DbType that adds StringLong (Text, Memo) data type that Epi Info commonly uses.</param>
/// <returns>Database-specific column data type.</returns>
public override string GetDbSpecificColumnType(GenericDbColumnType dataType)
{
switch (dataType)
{
case GenericDbColumnType.AnsiString:
case GenericDbColumnType.AnsiStringFixedLength:
return AccessColumnType.Text;
case GenericDbColumnType.Binary:
return "binary";
case GenericDbColumnType.Boolean:
return AccessColumnType.YesNo; // "yesno";
case GenericDbColumnType.Byte:
return "byte";
case GenericDbColumnType.Currency:
return AccessColumnType.Currency; // "CURRENCY";
case GenericDbColumnType.Date:
case GenericDbColumnType.DateTime:
case GenericDbColumnType.Time:
return "datetime";
case GenericDbColumnType.Decimal:
case GenericDbColumnType.Double:
return "double";
case GenericDbColumnType.Guid:
return "GUID";
case GenericDbColumnType.Int16:
case GenericDbColumnType.UInt16:
return "SHORT";
case GenericDbColumnType.Int32:
case GenericDbColumnType.UInt32:
return "integer";
case GenericDbColumnType.Int64:
case GenericDbColumnType.UInt64:
return "LONG";
case GenericDbColumnType.Object:
case GenericDbColumnType.Image:
return "LONGBINARY";
case GenericDbColumnType.SByte:
return "byte";
case GenericDbColumnType.Single:
return "single";
case GenericDbColumnType.String:
case GenericDbColumnType.StringFixedLength:
return "text";
case GenericDbColumnType.StringLong:
case GenericDbColumnType.Xml:
return "MEMO";
case GenericDbColumnType.VarNumeric:
return "double";
default:
throw new GeneralException("genericDbColumnType is unknown");
// return "text";
}
}
/// <summary>
/// Read only attribute of connection description
/// </summary>
public override string ConnectionDescription
{
get { return "Microsoft Access Database: " + Location; }
}
/// <summary>
/// Connection String attribute
/// </summary>
public override string ConnectionString
{
get
{
return base.ConnectionString;
}
set
{
string connectionString;
if (Util.IsFilePath(value))
{
connectionString = Access2007Database.BuildConnectionString(value, "");
}
else
{
connectionString = value;
}
//we can't test the connection now because the database
// may not be existant (yet)
base.ConnectionString = connectionString;
}
}
#endregion
/// <summary>
/// Gets table schema information about an OLE database
/// </summary>
/// <returns>DataTable with schema information</returns>
//This function has been fixed in parent class, It should work for all database type // zack 1/30/08
//public override DataTable GetTableSchema()
//{
//DataTable schema = base.GetSchema("Tables");
//foreach (DataRow row in schema.Rows)
//{
// // TODO: This isn't asbolute, should be replaced with search on...
// // exact system table names
// if (row[ColumnNames.SCHEMA_TABLE_NAME].ToString().StartsWith("MSys", true, CultureInfo.InvariantCulture))
// {
// row.Delete();
// }
//}
//schema.AcceptChanges();
// return schema;
//}
public static string BuildConnectionString(string filePath, string password)
{
StringBuilder builder = new StringBuilder();
if (filePath.EndsWith(".accdb", true, System.Globalization.CultureInfo.InvariantCulture))
{
builder.Append("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
}
builder.Append(EncodeOleDbConnectionStringValue(filePath));
builder.Append(";");
builder.Append("User Id=admin;Password=;");
if (!string.IsNullOrEmpty(password))
{
builder.Append("Jet OLEDB:Database Password=");
builder.Append(EncodeOleDbConnectionStringValue(password));
builder.Append(";");
}
// sanity check
OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
return connectionBuilder.ToString();
}
/// <summary>
/// Builds a connection string using default parameters given a database name
/// </summary>
/// <param name="databaseName">Name of the database</param>
/// <returns>A connection string</returns>
public static string BuildDefaultConnectionString(string databaseName)
{
return BuildConnectionString(Configuration.GetNewInstance().Directories.Project + "\\" + databaseName + ".accdb", string.Empty);
}
/// <summary>
/// Returns Code Table names for the project
/// </summary>
/// <param name="project">Project</param>
/// <returns>DataTable</returns>
public override DataTable GetCodeTableNamesForProject(Project project)
{
List<string> tables = project.GetDataTableList();
DataSets.TableSchema.TablesDataTable codeTables = project.GetCodeTableList();
foreach (DataSets.TableSchema.TablesRow row in codeTables)
{
tables.Add(row.TABLE_NAME);
}
DataTable bindingTable = new DataTable();
bindingTable.Columns.Add(ColumnNames.NAME);
foreach (string table in tables)
{
if (!string.IsNullOrEmpty(table))
{
if (project.CollectedData.TableExists(table))
{
bindingTable.Rows.Add(new string[] { table });
}
}
}
return bindingTable;
}
/// <summary>
/// Returns code table list
/// </summary>
/// <param name="db">IDbDriver</param>
/// <returns>Epi.DataSets.TableSchema.TablesDataTable</returns>
public override Epi.DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db)
{
DataSets.TableSchema.TablesDataTable tables = db.GetTableSchema();
//remove tables without prefix "code"
DataRow[] rowsFiltered = tables.Select("TABLE_NAME not like 'code%'");
foreach (DataRow rowFiltered in rowsFiltered)
{
tables.Rows.Remove(rowFiltered);
}
foreach (DataRow row in tables)
{
if (String.IsNullOrEmpty(row.ItemArray[2].ToString()))
{
//remove a row with an empty string
tables.Rows.Remove(row);
}
}
DataRow[] rowsCode = tables.Select("TABLE_NAME like 'code%'");
return tables;
}
/// <summary>
/// Identify Database
/// Note: This will need to be revisited
/// </summary>
/// <returns></returns>
public override string IdentifyDatabase()
{
return "ACCESS";
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
namespace System.Management
{
// We use this class to prevent the accidental returning of a boxed value type to a caller
// If we store a boxed value type in a private field, and return it to the caller through a public
// property or method, the call can potentially change its value. The GetSafeObject method does two things
// 1) If the value is a primitive, we know that it will implement IConvertible. IConvertible.ToType will
// copy a boxed primitive
// 2) In the case of a boxed non-primitive value type, or simply a reference type, we call
// RuntimeHelpers.GetObjectValue. This returns reference types right back to the caller, but if passed
// a boxed non-primitive value type, it will return a boxed copy. We cannot use GetObjectValue for primitives
// because its implementation does not copy boxed primitives.
class ValueTypeSafety
{
public static object GetSafeObject(object theValue)
{
if(null == theValue)
return null;
else if(theValue.GetType().IsPrimitive)
return ((IConvertible)theValue).ToType(typeof(object), null);
else
return RuntimeHelpers.GetObjectValue(theValue);
}
}
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents information about a WMI property.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample displays all properties that qualifies the "DeviceID" property
/// // in Win32_LogicalDisk.DeviceID='C' instance.
/// class Sample_PropertyData
/// {
/// public static int Main(string[] args) {
/// ManagementObject disk =
/// new ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"");
/// PropertyData diskProperty = disk.Properties["DeviceID"];
/// Console.WriteLine("Name: " + diskProperty.Name);
/// Console.WriteLine("Type: " + diskProperty.Type);
/// Console.WriteLine("Value: " + diskProperty.Value);
/// Console.WriteLine("IsArray: " + diskProperty.IsArray);
/// Console.WriteLine("IsLocal: " + diskProperty.IsLocal);
/// Console.WriteLine("Origin: " + diskProperty.Origin);
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample displays all properties that qualifies the "DeviceID" property
/// ' in Win32_LogicalDisk.DeviceID='C' instance.
/// Class Sample_PropertyData
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID=""C:""")
/// Dim diskProperty As PropertyData = disk.Properties("DeviceID")
/// Console.WriteLine("Name: " & diskProperty.Name)
/// Console.WriteLine("Type: " & diskProperty.Type)
/// Console.WriteLine("Value: " & diskProperty.Value)
/// Console.WriteLine("IsArray: " & diskProperty.IsArray)
/// Console.WriteLine("IsLocal: " & diskProperty.IsLocal)
/// Console.WriteLine("Origin: " & diskProperty.Origin)
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class PropertyData
{
private ManagementBaseObject parent; //need access to IWbemClassObject pointer to be able to refresh property info
//and get property qualifiers
private string propertyName;
private object propertyValue;
private long propertyNullEnumValue = 0;
private int propertyType;
private int propertyFlavor;
private QualifierDataCollection qualifiers;
internal PropertyData(ManagementBaseObject parent, string propName)
{
this.parent = parent;
this.propertyName = propName;
qualifiers = null;
RefreshPropertyInfo();
}
//This private function is used to refresh the information from the Wmi object before returning the requested data
private void RefreshPropertyInfo()
{
propertyValue = null; // Needed so we don't leak this in/out parameter...
int status = parent.wbemObject.Get_(propertyName, 0, ref propertyValue, ref propertyType, ref propertyFlavor);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para>Gets or sets the name of the property.</para>
/// </summary>
/// <value>
/// A string containing the name of the
/// property.
/// </value>
public string Name
{ //doesn't change for this object so we don't need to refresh
get { return propertyName != null ? propertyName : ""; }
}
/// <summary>
/// <para>Gets or sets the current value of the property.</para>
/// </summary>
/// <value>
/// An object containing the value of the
/// property.
/// </value>
public object Value
{
get {
RefreshPropertyInfo();
return ValueTypeSafety.GetSafeObject(MapWmiValueToValue(propertyValue,
(CimType)(propertyType & ~(int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY),
(0 != (propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY))));
}
set {
RefreshPropertyInfo();
object newValue = MapValueToWmiValue(value,
(CimType)(propertyType & ~(int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY),
(0 != (propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY)));
int status = parent.wbemObject.Put_(propertyName, 0, ref newValue, 0);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
//if succeeded and this object has a path, update the path to reflect the new key value
//NOTE : we could only do this for key properties but since it's not trivial to find out
// whether this property is a key or not, we just do it for any property
else
if (parent.GetType() == typeof(ManagementObject))
((ManagementObject)parent).Path.UpdateRelativePath((string)parent["__RELPATH"]);
}
}
/// <summary>
/// <para>Gets or sets the CIM type of the property.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.CimType'/> value
/// representing the CIM type of the property.</para>
/// </value>
public CimType Type {
get {
RefreshPropertyInfo();
return (CimType)(propertyType & ~(int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY);
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the property has been defined in the current WMI class.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the property has been defined
/// in the current WMI class; otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsLocal
{
get {
RefreshPropertyInfo();
return ((propertyFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_ORIGIN_PROPAGATED) != 0) ? false : true ; }
}
/// <summary>
/// <para>Gets or sets a value indicating whether the property is an array.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the property is an array; otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsArray
{
get {
RefreshPropertyInfo();
return ((propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY) != 0);}
}
/// <summary>
/// <para>Gets or sets the name of the WMI class in the hierarchy in which the property was introduced.</para>
/// </summary>
/// <value>
/// A string containing the name of the
/// originating WMI class.
/// </value>
public string Origin
{
get {
string className = null;
int status = parent.wbemObject.GetPropertyOrigin_(propertyName, out className);
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_OBJECT)
className = string.Empty; // Interpret as an unspecified property - return ""
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return className;
}
}
/// <summary>
/// <para>Gets or sets the set of qualifiers defined on the property.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents
/// the set of qualifiers defined on the property.</para>
/// </value>
public QualifierDataCollection Qualifiers
{
get {
if (qualifiers == null)
qualifiers = new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier);
return qualifiers;
}
}
internal long NullEnumValue
{
get {
return propertyNullEnumValue;
}
set {
propertyNullEnumValue = value;
}
}
/// <summary>
/// Takes a property value returned from WMI and maps it to an
/// appropriate managed code representation.
/// </summary>
/// <param name="wmiValue"> </param>
/// <param name="type"> </param>
/// <param name="isArray"> </param>
internal static object MapWmiValueToValue(object wmiValue, CimType type, bool isArray)
{
object val = null;
if ((System.DBNull.Value != wmiValue) && (null != wmiValue))
{
if (isArray)
{
Array wmiValueArray = (Array)wmiValue;
int length = wmiValueArray.Length;
switch (type)
{
case CimType.UInt16:
val = new ushort [length];
for (int i = 0; i < length; i++)
((ushort[])val) [i] = (ushort)((int)(wmiValueArray.GetValue(i)));
break;
case CimType.UInt32:
val = new uint [length];
for (int i = 0; i < length; i++)
((uint[])val)[i] = (uint)((int)(wmiValueArray.GetValue(i)));
break;
case CimType.UInt64:
val = new ulong [length];
for (int i = 0; i < length; i++)
((ulong[])val) [i] = Convert.ToUInt64((string)(wmiValueArray.GetValue(i)),(IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(ulong)));
break;
case CimType.SInt8:
val = new sbyte [length];
for (int i = 0; i < length; i++)
((sbyte[])val) [i] = (sbyte)((short)(wmiValueArray.GetValue(i)));
break;
case CimType.SInt64:
val = new long [length];
for (int i = 0; i < length; i++)
((long[])val) [i] = Convert.ToInt64((string)(wmiValueArray.GetValue(i)),(IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(long)));
break;
case CimType.Char16:
val = new char [length];
for (int i = 0; i < length; i++)
((char[])val) [i] = (char)((short)(wmiValueArray.GetValue(i)));
break;
case CimType.Object:
val = new ManagementBaseObject [length];
for (int i = 0; i < length; i++)
((ManagementBaseObject[])val) [i] = new ManagementBaseObject(new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(wmiValueArray.GetValue(i))));
break;
default:
val = wmiValue;
break;
}
}
else
{
switch (type)
{
case CimType.SInt8:
val = (sbyte)((short)wmiValue);
break;
case CimType.UInt16:
val = (ushort)((int)wmiValue);
break;
case CimType.UInt32:
val = (uint)((int)wmiValue);
break;
case CimType.UInt64:
val = Convert.ToUInt64((string)wmiValue,(IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(ulong)));
break;
case CimType.SInt64:
val = Convert.ToInt64((string)wmiValue,(IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(long)));
break;
case CimType.Char16:
val = (char)((short)wmiValue);
break;
case CimType.Object:
val = new ManagementBaseObject(new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(wmiValue)));
break;
default:
val = wmiValue;
break;
}
}
}
return val;
}
/// <summary>
/// Takes a managed code value, together with a desired property
/// </summary>
/// <param name="val"> </param>
/// <param name="type"> </param>
/// <param name="isArray"> </param>
internal static object MapValueToWmiValue(object val, CimType type, bool isArray)
{
object wmiValue = System.DBNull.Value;
CultureInfo culInfo = CultureInfo.InvariantCulture;
if (null != val)
{
if (isArray)
{
Array valArray = (Array)val;
int length = valArray.Length;
switch (type)
{
case CimType.SInt8:
wmiValue = new short [length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = (short)Convert.ToSByte(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(sbyte)));
break;
case CimType.UInt8:
if (val is byte[])
wmiValue = val;
else
{
wmiValue = new byte [length];
for (int i = 0; i < length; i++)
((byte[])wmiValue)[i] = Convert.ToByte(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(byte)));
}
break;
case CimType.SInt16:
if (val is short[])
wmiValue = val;
else
{
wmiValue = new short [length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = Convert.ToInt16(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(short)));
}
break;
case CimType.UInt16:
wmiValue = new int [length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = (int)(Convert.ToUInt16(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(ushort))));
break;
case CimType.SInt32:
if (val is int[])
wmiValue = val;
else
{
wmiValue = new int [length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = Convert.ToInt32(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(int)));
}
break;
case CimType.UInt32:
wmiValue = new int [length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = (int)(Convert.ToUInt32(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(uint))));
break;
case CimType.SInt64:
wmiValue = new string [length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (Convert.ToInt64(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(System.Int64)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
break;
case CimType.UInt64:
wmiValue = new string [length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (Convert.ToUInt64(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(System.UInt64)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
break;
case CimType.Real32:
if (val is float[])
wmiValue = val;
else
{
wmiValue = new float [length];
for (int i = 0; i < length; i++)
((float[])(wmiValue))[i] = Convert.ToSingle(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(float)));
}
break;
case CimType.Real64:
if (val is double[])
wmiValue = val;
else
{
wmiValue = new double [length];
for (int i = 0; i < length; i++)
((double[])(wmiValue))[i] = Convert.ToDouble(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(double)));
}
break;
case CimType.Char16:
wmiValue = new short [length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = (short)Convert.ToChar(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(char)));
break;
case CimType.String:
case CimType.DateTime:
case CimType.Reference:
if (val is string[])
wmiValue = val;
else
{
wmiValue = new string [length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (valArray.GetValue(i)).ToString();
}
break;
case CimType.Boolean:
if (val is bool[])
wmiValue = val;
else
{
wmiValue = new bool [length];
for (int i = 0; i < length; i++)
((bool[])(wmiValue))[i] = Convert.ToBoolean(valArray.GetValue(i),(IFormatProvider)culInfo.GetFormat(typeof(bool)));
}
break;
case CimType.Object:
wmiValue = new IWbemClassObject_DoNotMarshal[length];
for (int i = 0; i < length; i++)
{
((IWbemClassObject_DoNotMarshal[])(wmiValue))[i] = (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(((ManagementBaseObject)valArray.GetValue(i)).wbemObject));
}
break;
default:
wmiValue = val;
break;
}
}
else
{
switch (type)
{
case CimType.SInt8:
wmiValue = (short)Convert.ToSByte(val,(IFormatProvider)culInfo.GetFormat(typeof(short)));
break;
case CimType.UInt8:
wmiValue = Convert.ToByte(val,(IFormatProvider)culInfo.GetFormat(typeof(byte)));
break;
case CimType.SInt16:
wmiValue = Convert.ToInt16(val,(IFormatProvider)culInfo.GetFormat(typeof(short)));
break;
case CimType.UInt16:
wmiValue = (int)(Convert.ToUInt16(val,(IFormatProvider)culInfo.GetFormat(typeof(ushort))));
break;
case CimType.SInt32:
wmiValue = Convert.ToInt32(val,(IFormatProvider)culInfo.GetFormat(typeof(int)));
break;
case CimType.UInt32:
wmiValue = (int)Convert.ToUInt32(val,(IFormatProvider)culInfo.GetFormat(typeof(uint)));
break;
case CimType.SInt64:
wmiValue = (Convert.ToInt64(val,(IFormatProvider)culInfo.GetFormat(typeof(System.Int64)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
break;
case CimType.UInt64:
wmiValue = (Convert.ToUInt64(val,(IFormatProvider)culInfo.GetFormat(typeof(System.UInt64)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
break;
case CimType.Real32:
wmiValue = Convert.ToSingle(val,(IFormatProvider)culInfo.GetFormat(typeof(float)));
break;
case CimType.Real64:
wmiValue = Convert.ToDouble(val,(IFormatProvider)culInfo.GetFormat(typeof(double)));
break;
case CimType.Char16:
wmiValue = (short)Convert.ToChar(val,(IFormatProvider)culInfo.GetFormat(typeof(char)));
break;
case CimType.String:
case CimType.DateTime:
case CimType.Reference:
wmiValue = val.ToString();
break;
case CimType.Boolean:
wmiValue = Convert.ToBoolean(val,(IFormatProvider)culInfo.GetFormat(typeof(bool)));
break;
case CimType.Object:
if (val is ManagementBaseObject)
{
wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject) val).wbemObject);
}
else
{
wmiValue = val;
}
break;
default:
wmiValue = val;
break;
}
}
}
return wmiValue;
}
internal static object MapValueToWmiValue(object val, out bool isArray, out CimType type)
{
object wmiValue = System.DBNull.Value;
CultureInfo culInfo = CultureInfo.InvariantCulture;
isArray = false;
type = 0;
if (null != val)
{
isArray = val.GetType().IsArray;
Type valueType = val.GetType();
if (isArray)
{
Type elementType = valueType.GetElementType();
// Casting primitive types to object[] is not allowed
if (elementType.IsPrimitive)
{
if (elementType == typeof(byte))
{
byte[] arrayValue = (byte[])val;
int length = arrayValue.Length;
type = CimType.UInt8;
wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])wmiValue) [i] = ((IConvertible)((System.Byte)(arrayValue[i]))).ToInt16(null);
}
else if (elementType == typeof(sbyte))
{
sbyte[] arrayValue = (sbyte[])val;
int length = arrayValue.Length;
type = CimType.SInt8;
wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])wmiValue) [i] = ((IConvertible)((System.SByte)(arrayValue[i]))).ToInt16(null);
}
else if (elementType == typeof(bool))
{
type = CimType.Boolean;
wmiValue = (bool[])val;
}
else if (elementType == typeof(ushort))
{
ushort[] arrayValue = (ushort[])val;
int length = arrayValue.Length;
type = CimType.UInt16;
wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])wmiValue) [i] = ((IConvertible)((System.UInt16)(arrayValue[i]))).ToInt32(null);
}
else if (elementType == typeof(short))
{
type = CimType.SInt16;
wmiValue = (short[])val;
}
else if (elementType == typeof(int))
{
type = CimType.SInt32;
wmiValue = (int[])val;
}
else if (elementType == typeof(uint))
{
uint[] arrayValue = (uint[])val;
int length = arrayValue.Length;
type = CimType.UInt32;
wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])wmiValue) [i] = ((System.UInt32)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(uint)));
}
else if (elementType == typeof(ulong))
{
ulong[] arrayValue = (ulong[])val;
int length = arrayValue.Length;
type = CimType.UInt64;
wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])wmiValue) [i] = ((System.UInt64)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
}
else if (elementType == typeof(long))
{
long[] arrayValue = (long[])val;
int length = arrayValue.Length;
type = CimType.SInt64;
wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])wmiValue) [i] = ((long)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
}
else if (elementType == typeof(float))
{
type = CimType.Real32;
wmiValue = (float[])val;
}
else if (elementType == typeof(double))
{
type = CimType.Real64;
wmiValue = (double[])val;
}
else if (elementType == typeof(char))
{
char[] arrayValue = (char[])val;
int length = arrayValue.Length;
type = CimType.Char16;
wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])wmiValue) [i] = ((IConvertible)((System.Char)(arrayValue[i]))).ToInt16(null);
}
}
else
{
// Non-primitive types
if (elementType == typeof(string))
{
type = CimType.String;
wmiValue = (string[])val;
}
else
{
// Check for an embedded object array
if (val is ManagementBaseObject[])
{
Array valArray = (Array)val;
int length = valArray.Length;
type = CimType.Object;
wmiValue = new IWbemClassObject_DoNotMarshal[length];
for (int i = 0; i < length; i++)
{
((IWbemClassObject_DoNotMarshal[])(wmiValue))[i] = (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(((ManagementBaseObject)valArray.GetValue(i)).wbemObject));
}
}
}
}
}
else // Non-array values
{
if (valueType == typeof(ushort))
{
type = CimType.UInt16;
wmiValue = ((IConvertible)((System.UInt16)val)).ToInt32(null);
}
else if (valueType == typeof(uint))
{
type = CimType.UInt32;
if (((uint)val & 0x80000000) != 0)
wmiValue = Convert.ToString(val,(IFormatProvider)culInfo.GetFormat(typeof(uint)));
else
wmiValue = Convert.ToInt32(val,(IFormatProvider)culInfo.GetFormat(typeof(int)));
}
else if (valueType == typeof(ulong))
{
type = CimType.UInt64;
wmiValue = ((System.UInt64)val).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
}
else if (valueType == typeof(sbyte))
{
type = CimType.SInt8;
wmiValue = ((IConvertible)((System.SByte)val)).ToInt16(null);
}
else if (valueType == typeof(byte))
{
type = CimType.UInt8;
wmiValue = val;
}
else if (valueType == typeof(short))
{
type = CimType.SInt16;
wmiValue = val;
}
else if (valueType == typeof(int))
{
type = CimType.SInt32;
wmiValue = val;
}
else if (valueType == typeof(long))
{
type = CimType.SInt64;
wmiValue = val.ToString();
}
else if (valueType == typeof(bool))
{
type = CimType.Boolean;
wmiValue = val;
}
else if (valueType == typeof(float))
{
type = CimType.Real32;
wmiValue = val;
}
else if (valueType == typeof(double))
{
type = CimType.Real64;
wmiValue = val;
}
else if (valueType == typeof(char))
{
type = CimType.Char16;
wmiValue = ((IConvertible)((System.Char)val)).ToInt16(null);
}
else if (valueType == typeof(string))
{
type = CimType.String;
wmiValue = val;
}
else
{
// Check for an embedded object
if (val is ManagementBaseObject)
{
type = CimType.Object;
wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject) val).wbemObject);
}
}
}
}
return wmiValue;
}
}//PropertyData
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/folio_check_cash_payment.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Folio {
/// <summary>Holder for reflection information generated from folio/folio_check_cash_payment.proto</summary>
public static partial class FolioCheckCashPaymentReflection {
#region Descriptor
/// <summary>File descriptor for folio/folio_check_cash_payment.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FolioCheckCashPaymentReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiRmb2xpby9mb2xpb19jaGVja19jYXNoX3BheW1lbnQucHJvdG8SEWhvbG1z",
"LnR5cGVzLmZvbGlvGhhmb2xpby9wYXltZW50X3R5cGUucHJvdG8aH2dvb2ds",
"ZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8aIGlhbS9zdGFmZl9tZW1iZXJf",
"aW5kaWNhdG9yLnByb3RvGh9wcmltaXRpdmUvbW9uZXRhcnlfYW1vdW50LnBy",
"b3RvGi5mb2xpby9mb2xpb19jaGVja19jYXNoX3BheW1lbnRfaW5kaWNhdG9y",
"LnByb3RvIsoCChVGb2xpb0NoZWNrQ2FzaFBheW1lbnQSNQoGYW1vdW50GAEg",
"ASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50EhMK",
"C2lzX2NhbmNlbGVkGAIgASgIEjQKDHBheW1lbnRfdHlwZRgDIAEoDjIeLmhv",
"bG1zLnR5cGVzLmZvbGlvLlBheW1lbnRUeXBlEjoKC3JlY2VpdmVkX2J5GAQg",
"ASgLMiUuaG9sbXMudHlwZXMuaWFtLlN0YWZmTWVtYmVySW5kaWNhdG9yEi0K",
"CXBvc3RlZF9hdBgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAS",
"RAoJZW50aXR5X2lkGAYgASgLMjEuaG9sbXMudHlwZXMuZm9saW8uRm9saW9D",
"aGVja0Nhc2hQYXltZW50SW5kaWNhdG9yQhSqAhFIT0xNUy5UeXBlcy5Gb2xp",
"b2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Folio.PaymentTypeReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::HOLMS.Types.IAM.StaffMemberIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Folio.FolioCheckCashPayment), global::HOLMS.Types.Folio.FolioCheckCashPayment.Parser, new[]{ "Amount", "IsCanceled", "PaymentType", "ReceivedBy", "PostedAt", "EntityId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class FolioCheckCashPayment : pb::IMessage<FolioCheckCashPayment> {
private static readonly pb::MessageParser<FolioCheckCashPayment> _parser = new pb::MessageParser<FolioCheckCashPayment>(() => new FolioCheckCashPayment());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FolioCheckCashPayment> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Folio.FolioCheckCashPaymentReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioCheckCashPayment() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioCheckCashPayment(FolioCheckCashPayment other) : this() {
Amount = other.amount_ != null ? other.Amount.Clone() : null;
isCanceled_ = other.isCanceled_;
paymentType_ = other.paymentType_;
ReceivedBy = other.receivedBy_ != null ? other.ReceivedBy.Clone() : null;
PostedAt = other.postedAt_ != null ? other.PostedAt.Clone() : null;
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioCheckCashPayment Clone() {
return new FolioCheckCashPayment(this);
}
/// <summary>Field number for the "amount" field.</summary>
public const int AmountFieldNumber = 1;
private global::HOLMS.Types.Primitive.MonetaryAmount amount_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount Amount {
get { return amount_; }
set {
amount_ = value;
}
}
/// <summary>Field number for the "is_canceled" field.</summary>
public const int IsCanceledFieldNumber = 2;
private bool isCanceled_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsCanceled {
get { return isCanceled_; }
set {
isCanceled_ = value;
}
}
/// <summary>Field number for the "payment_type" field.</summary>
public const int PaymentTypeFieldNumber = 3;
private global::HOLMS.Types.Folio.PaymentType paymentType_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Folio.PaymentType PaymentType {
get { return paymentType_; }
set {
paymentType_ = value;
}
}
/// <summary>Field number for the "received_by" field.</summary>
public const int ReceivedByFieldNumber = 4;
private global::HOLMS.Types.IAM.StaffMemberIndicator receivedBy_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.IAM.StaffMemberIndicator ReceivedBy {
get { return receivedBy_; }
set {
receivedBy_ = value;
}
}
/// <summary>Field number for the "posted_at" field.</summary>
public const int PostedAtFieldNumber = 5;
private global::Google.Protobuf.WellKnownTypes.Timestamp postedAt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp PostedAt {
get { return postedAt_; }
set {
postedAt_ = value;
}
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 6;
private global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FolioCheckCashPayment);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FolioCheckCashPayment other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Amount, other.Amount)) return false;
if (IsCanceled != other.IsCanceled) return false;
if (PaymentType != other.PaymentType) return false;
if (!object.Equals(ReceivedBy, other.ReceivedBy)) return false;
if (!object.Equals(PostedAt, other.PostedAt)) return false;
if (!object.Equals(EntityId, other.EntityId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (amount_ != null) hash ^= Amount.GetHashCode();
if (IsCanceled != false) hash ^= IsCanceled.GetHashCode();
if (PaymentType != 0) hash ^= PaymentType.GetHashCode();
if (receivedBy_ != null) hash ^= ReceivedBy.GetHashCode();
if (postedAt_ != null) hash ^= PostedAt.GetHashCode();
if (entityId_ != null) hash ^= EntityId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (amount_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Amount);
}
if (IsCanceled != false) {
output.WriteRawTag(16);
output.WriteBool(IsCanceled);
}
if (PaymentType != 0) {
output.WriteRawTag(24);
output.WriteEnum((int) PaymentType);
}
if (receivedBy_ != null) {
output.WriteRawTag(34);
output.WriteMessage(ReceivedBy);
}
if (postedAt_ != null) {
output.WriteRawTag(42);
output.WriteMessage(PostedAt);
}
if (entityId_ != null) {
output.WriteRawTag(50);
output.WriteMessage(EntityId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (amount_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Amount);
}
if (IsCanceled != false) {
size += 1 + 1;
}
if (PaymentType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PaymentType);
}
if (receivedBy_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReceivedBy);
}
if (postedAt_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PostedAt);
}
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FolioCheckCashPayment other) {
if (other == null) {
return;
}
if (other.amount_ != null) {
if (amount_ == null) {
amount_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
Amount.MergeFrom(other.Amount);
}
if (other.IsCanceled != false) {
IsCanceled = other.IsCanceled;
}
if (other.PaymentType != 0) {
PaymentType = other.PaymentType;
}
if (other.receivedBy_ != null) {
if (receivedBy_ == null) {
receivedBy_ = new global::HOLMS.Types.IAM.StaffMemberIndicator();
}
ReceivedBy.MergeFrom(other.ReceivedBy);
}
if (other.postedAt_ != null) {
if (postedAt_ == null) {
postedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
PostedAt.MergeFrom(other.PostedAt);
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (amount_ == null) {
amount_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(amount_);
break;
}
case 16: {
IsCanceled = input.ReadBool();
break;
}
case 24: {
paymentType_ = (global::HOLMS.Types.Folio.PaymentType) input.ReadEnum();
break;
}
case 34: {
if (receivedBy_ == null) {
receivedBy_ = new global::HOLMS.Types.IAM.StaffMemberIndicator();
}
input.ReadMessage(receivedBy_);
break;
}
case 42: {
if (postedAt_ == null) {
postedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(postedAt_);
break;
}
case 50: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator();
}
input.ReadMessage(entityId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public static partial class TimeSpanTests
{
private static IEnumerable<object[]> MultiplicationTestData()
{
yield return new object[] {new TimeSpan(2, 30, 0), 2.0, new TimeSpan(5, 0, 0)};
yield return new object[] {new TimeSpan(14, 2, 30, 0), 192.0, TimeSpan.FromDays(2708)};
yield return new object[] {TimeSpan.FromDays(366), Math.PI, new TimeSpan(993446995288779)};
yield return new object[] {TimeSpan.FromDays(366), -Math.E, new TimeSpan(-859585952922633)};
yield return new object[] {TimeSpan.FromDays(29.530587981), 13.0, TimeSpan.FromDays(383.897643819444)};
yield return new object[] {TimeSpan.FromDays(-29.530587981), -12.0, TimeSpan.FromDays(354.367055833333)};
yield return new object[] {TimeSpan.FromDays(-29.530587981), 0.0, TimeSpan.Zero};
yield return new object[] {TimeSpan.MaxValue, 0.5, TimeSpan.FromTicks((long)(long.MaxValue * 0.5))};
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void Multiplication(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(expected, timeSpan * factor);
Assert.Equal(expected, factor * timeSpan);
}
[Fact]
public static void OverflowingMultiplication()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue * 1.000000001);
Assert.Throws<OverflowException>(() => -1.000000001 * TimeSpan.MaxValue);
}
[Fact]
public static void NaNMultiplication()
{
AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1) * double.NaN);
AssertExtensions.Throws<ArgumentException>("factor", () => double.NaN * TimeSpan.FromDays(1));
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(factor, expected / timeSpan, 14);
double divisor = 1.0 / factor;
Assert.Equal(expected, timeSpan / divisor);
}
[Fact]
public static void DivideByZero()
{
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1) / 0);
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1) / 0);
Assert.Throws<OverflowException>(() => TimeSpan.Zero / 0);
Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1) / TimeSpan.Zero);
Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1) / TimeSpan.Zero);
Assert.True(double.IsNaN(TimeSpan.Zero / TimeSpan.Zero));
}
[Fact]
public static void NaNDivision()
{
AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1) / double.NaN);
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void NamedMultiplication(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(expected, timeSpan.Multiply(factor));
}
[Fact]
public static void NamedOverflowingMultiplication()
{
Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Multiply(1.000000001));
}
[Fact]
public static void NamedNaNMultiplication()
{
AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1).Multiply(double.NaN));
}
[Theory, MemberData(nameof(MultiplicationTestData))]
public static void NamedDivision(TimeSpan timeSpan, double factor, TimeSpan expected)
{
Assert.Equal(factor, expected.Divide(timeSpan), 14);
double divisor = 1.0 / factor;
Assert.Equal(expected, timeSpan.Divide(divisor));
}
[Fact]
public static void NamedDivideByZero()
{
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1).Divide(0));
Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1).Divide(0));
Assert.Throws<OverflowException>(() => TimeSpan.Zero.Divide(0));
Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1).Divide(TimeSpan.Zero));
Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1).Divide(TimeSpan.Zero));
Assert.True(double.IsNaN(TimeSpan.Zero.Divide(TimeSpan.Zero)));
}
[Fact]
public static void NamedNaNDivision()
{
AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN));
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Span(string inputString, IFormatProvider provider, TimeSpan expected)
{
ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
TimeSpan result;
Assert.Equal(expected, TimeSpan.Parse(input, provider));
Assert.True(TimeSpan.TryParse(input, out result, provider));
Assert.Equal(expected, result);
// Also negate
if (!char.IsWhiteSpace(input[0]))
{
input = ("-" + inputString).AsReadOnlySpan();
expected = -expected;
Assert.Equal(expected, TimeSpan.Parse(input, provider));
Assert.True(TimeSpan.TryParse(input, out result, provider));
Assert.Equal(expected, result);
}
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType)
{
if (inputString != null)
{
Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsReadOnlySpan(), provider));
Assert.False(TimeSpan.TryParse(inputString.AsReadOnlySpan(), out TimeSpan result, provider));
Assert.Equal(TimeSpan.Zero, result);
}
}
[Theory]
[MemberData(nameof(ParseExact_Valid_TestData))]
public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected)
{
ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
TimeSpan result;
Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US")));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G")
{
// TimeSpanStyles is interpreted only for custom formats
Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result, TimeSpanStyles.AssumeNegative));
Assert.Equal(expected.Negate(), result);
}
else
{
// Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse
Assert.Equal(expected, TimeSpan.Parse(input));
Assert.True(TimeSpan.TryParse(input, out result));
Assert.Equal(expected, result);
}
}
[Theory]
[MemberData(nameof(ParseExact_Invalid_TestData))]
public static void ParseExactTest__Span_Invalid(string inputString, string format, Type exceptionType)
{
if (inputString != null)
{
Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US")));
TimeSpan result;
Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), new[] { format }, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
}
}
[Fact]
public static void ParseExactMultiple_Span_InvalidNullEmptyFormats()
{
TimeSpan result;
AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null));
Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null, out result));
Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), new string[0], null));
Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), new string[0], null, out result));
}
[Theory]
[MemberData(nameof(ToString_MemberData))]
public static void TryFormat_Valid(TimeSpan input, string format, string expected)
{
int charsWritten;
Span<char> dst;
dst = new char[expected.Length - 1];
Assert.False(input.TryFormat(dst, out charsWritten, format));
Assert.Equal(0, charsWritten);
dst = new char[expected.Length];
Assert.True(input.TryFormat(dst, out charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(dst));
dst = new char[expected.Length + 1];
Assert.True(input.TryFormat(dst, out charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1)));
Assert.Equal(0, dst[dst.Length - 1]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.