context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesPutWarmer3
{
public partial class IndicesPutWarmer3YamlTests
{
public class IndicesPutWarmer3AllPathOptionsYamlBase : YamlTestsBase
{
public IndicesPutWarmer3AllPathOptionsYamlBase() : base()
{
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index1", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index2", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("foo", null));
//do cluster.health
this.Do(()=> _client.ClusterHealth(nv=>nv
.AddQueryString("wait_for_status", @"yellow")
));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerPerIndex2Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerPerIndex2Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("test_index1", "warmer", _body));
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("test_index2", "warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerInAllIndex3Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerInAllIndex3Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("_all", "warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//match _response.foo.warmers.warmer.source.query.match_all:
this.IsMatch(_response.foo.warmers.warmer.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerInIndex4Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerInIndex4Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("*", "warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//match _response.foo.warmers.warmer.source.query.match_all:
this.IsMatch(_response.foo.warmers.warmer.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerPrefixIndex5Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerPrefixIndex5Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("test_index*", "warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerInListOfIndices6Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerInListOfIndices6Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmer("test_index1,test_index2", "warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//is_false _response.foo;
this.IsFalse(_response.foo);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerWithBlankIndex7Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerWithBlankIndex7Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmerForAll("warmer", _body));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "*"));
//match _response.test_index1.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.warmer.source.query.match_all, new {});
//match _response.test_index2.warmers.warmer.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.warmer.source.query.match_all, new {});
//match _response.foo.warmers.warmer.source.query.match_all:
this.IsMatch(_response.foo.warmers.warmer.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class PutWarmerWithMissingName8Tests : IndicesPutWarmer3AllPathOptionsYamlBase
{
[Test]
public void PutWarmerWithMissingName8Test()
{
//do indices.put_warmer
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.IndicesPutWarmerForAll("", _body), shouldCatch: @"param");
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public sealed partial class DataMisalignedException : System.Exception
{
public DataMisalignedException() { }
public DataMisalignedException(string message) { }
public DataMisalignedException(string message, System.Exception innerException) { }
}
public partial class DllNotFoundException : System.TypeLoadException
{
public DllNotFoundException() { }
public DllNotFoundException(string message) { }
public DllNotFoundException(string message, System.Exception inner) { }
}
}
namespace System.Runtime.InteropServices
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ArrayWithOffset
{
public ArrayWithOffset(object array, int offset) { throw new System.NotImplementedException(); }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Runtime.InteropServices.ArrayWithOffset obj) { return default(bool); }
public object GetArray() { return default(object); }
public override int GetHashCode() { return default(int); }
public int GetOffset() { return default(int); }
public static bool operator ==(System.Runtime.InteropServices.ArrayWithOffset a, System.Runtime.InteropServices.ArrayWithOffset b) { return default(bool); }
public static bool operator !=(System.Runtime.InteropServices.ArrayWithOffset a, System.Runtime.InteropServices.ArrayWithOffset b) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1037), Inherited = false)]
public sealed partial class BestFitMappingAttribute : System.Attribute
{
public bool ThrowOnUnmappableChar;
public BestFitMappingAttribute(bool BestFitMapping) { }
public bool BestFitMapping { get { return default(bool); } }
}
public enum CallingConvention
{
Cdecl = 2,
StdCall = 3,
ThisCall = 4,
Winapi = 1,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2), Inherited = false)]
public sealed partial class DefaultCharSetAttribute : System.Attribute
{
public DefaultCharSetAttribute(System.Runtime.InteropServices.CharSet charSet) { }
public System.Runtime.InteropServices.CharSet CharSet { get { return default(System.Runtime.InteropServices.CharSet); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2048))]
public sealed partial class DefaultParameterValueAttribute : System.Attribute
{
public DefaultParameterValueAttribute(object value) { }
public object Value { get { return default(object); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited = false)]
public sealed partial class DllImportAttribute : System.Attribute
{
public bool BestFitMapping;
public System.Runtime.InteropServices.CallingConvention CallingConvention;
public System.Runtime.InteropServices.CharSet CharSet;
public string EntryPoint;
public bool ExactSpelling;
public bool PreserveSig;
public bool SetLastError;
public bool ThrowOnUnmappableChar;
public DllImportAttribute(string dllName) { }
public string Value { get { return default(string); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(5149), Inherited = false)]
public sealed partial class GuidAttribute : System.Attribute
{
public GuidAttribute(string guid) { }
public string Value { get { return default(string); } }
}
public sealed partial class HandleCollector
{
public HandleCollector(string name, int initialThreshold) { }
public HandleCollector(string name, int initialThreshold, int maximumThreshold) { }
public int Count { get { return default(int); } }
public int InitialThreshold { get { return default(int); } }
public int MaximumThreshold { get { return default(int); } }
public string Name { get { return default(string); } }
public void Add() { }
public void Remove() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2048), Inherited = false)]
public sealed partial class InAttribute : System.Attribute
{
public InAttribute() { }
}
public static partial class PInvokeMarshal
{
public static readonly int SystemDefaultCharSize;
public static readonly int SystemMaxDBCSCharSize;
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr AllocateMemory(int sizeInBytes) { return default(System.IntPtr); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("DestroyStructure(IntPtr, Type) may be unavailable in future releases. Instead, use DestroyStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296520")]
[System.Security.SecurityCriticalAttribute]
public static void DestroyStructure(System.IntPtr ptr, System.Type structureType) { }
[System.Security.SecurityCriticalAttribute]
public static void DestroyStructure<T>(System.IntPtr ptr) { }
[System.Security.SecurityCriticalAttribute]
public static void FreeMemory(System.IntPtr ptr) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("GetDelegateForFunctionPointer(IntPtr, Type) may be unavailable in future releases. Instead, use GetDelegateForFunctionPointer<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296521")]
[System.Security.SecurityCriticalAttribute]
public static System.Delegate GetDelegateForFunctionPointer(System.IntPtr ptr, System.Type delegateType) { return default(System.Delegate); }
[System.Security.SecurityCriticalAttribute]
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(System.IntPtr ptr) { return default(TDelegate); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("GetFunctionPointerForDelegate(Delegate) may be unavailable in future releases. Instead, use GetFunctionPointerForDelegate<T>(T). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296522")]
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetFunctionPointerForDelegate(System.Delegate d) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static int GetLastError() { return default(int); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("OffsetOf(Type, string) may be unavailable in future releases. Instead, use OffsetOf<T>(string). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296511")]
public static System.IntPtr OffsetOf(System.Type type, string fieldName) { return default(System.IntPtr); }
public static System.IntPtr OffsetOf<T>(string fieldName) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static string PtrToStringAnsi(System.IntPtr ptr) { return default(string); }
[System.Security.SecurityCriticalAttribute]
public static string PtrToStringAnsi(System.IntPtr ptr, int len) { return default(string); }
[System.Security.SecurityCriticalAttribute]
public static string PtrToStringUTF16(System.IntPtr ptr) { return default(string); }
[System.Security.SecurityCriticalAttribute]
public static string PtrToStringUTF16(System.IntPtr ptr, int len) { return default(string); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512")]
[System.Security.SecurityCriticalAttribute]
public static void PtrToStructure(System.IntPtr ptr, object structure) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513")]
[System.Security.SecurityCriticalAttribute]
public static object PtrToStructure(System.IntPtr ptr, System.Type structureType) { return default(object); }
[System.Security.SecurityCriticalAttribute]
public static T PtrToStructure<T>(System.IntPtr ptr) { return default(T); }
[System.Security.SecurityCriticalAttribute]
public static void PtrToStructure<T>(System.IntPtr ptr, T structure) { }
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr ReallocateMemory(System.IntPtr ptr, int sizeInBytes) { return default(System.IntPtr); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("SizeOf(Object) may be unavailable in future releases. Instead, use SizeOf<T>(). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296514")]
public static int SizeOf(object structure) { return default(int); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("SizeOf(Type) may be unavailable in future releases. Instead, use SizeOf<T>(). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296515")]
public static int SizeOf(System.Type type) { return default(int); }
public static int SizeOf<T>() { return default(int); }
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr StringToAllocatedMemoryAnsi(string s) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr StringToAllocatedMemoryUTF16(string s) { return default(System.IntPtr); }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("StructureToPtr(Object, IntPtr, Boolean) may be unavailable in future releases. Instead, use StructureToPtr<T>(T, IntPtr, Boolean). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296516")]
[System.Security.SecurityCriticalAttribute]
public static void StructureToPtr(object structure, System.IntPtr ptr, bool fDeleteOld) { }
[System.Security.SecurityCriticalAttribute]
public static void StructureToPtr<T>(T structure, System.IntPtr ptr, bool fDeleteOld) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("UnsafeAddrOfPinnedArrayElement(Array, Int32) may be unavailable in future releases. Instead, use UnsafeAddrOfPinnedArrayElement<T>(T[], Int32). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296517")]
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr UnsafeAddrOfPinnedArrayElement(System.Array arr, int index) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static System.IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { return default(System.IntPtr); }
[System.Security.SecurityCriticalAttribute]
public static void ZeroFreeMemoryAnsi(System.IntPtr s) { }
[System.Security.SecurityCriticalAttribute]
public static void ZeroFreeMemoryUTF16(System.IntPtr s) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(10496), Inherited = false)]
public sealed partial class MarshalAsAttribute : System.Attribute
{
public System.Runtime.InteropServices.UnmanagedType ArraySubType;
public int IidParameterIndex;
public string MarshalCookie;
public string MarshalType;
public System.Type MarshalTypeRef;
public System.Runtime.InteropServices.VarEnum SafeArraySubType;
public System.Type SafeArrayUserDefinedSubType;
public int SizeConst;
public short SizeParamIndex;
public MarshalAsAttribute(short unmanagedType) { }
public MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType unmanagedType) { }
public System.Runtime.InteropServices.UnmanagedType Value { get { return default(System.Runtime.InteropServices.UnmanagedType); } }
}
public partial class MarshalDirectiveException : System.Exception
{
public MarshalDirectiveException() { }
public MarshalDirectiveException(string message) { }
public MarshalDirectiveException(string message, System.Exception inner) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2048), Inherited = false)]
public sealed partial class OptionalAttribute : System.Attribute
{
public OptionalAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64), Inherited = false)]
public sealed partial class PreserveSigAttribute : System.Attribute
{
public PreserveSigAttribute() { }
}
[System.Security.SecurityCriticalAttribute]
public abstract partial class SafeBuffer : System.Runtime.InteropServices.SafeHandle
{
protected SafeBuffer(bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
// Added because SafeHandleZeroOrMinusOneIsInvalid is removed
public override bool IsInvalid { get { return default(bool); } }
[System.CLSCompliantAttribute(false)]
public ulong ByteLength { get { return default(ulong); } }
[System.CLSCompliantAttribute(false)]
public unsafe void AcquirePointer(ref byte* pointer) { }
[System.CLSCompliantAttribute(false)]
public void Initialize(uint numElements, uint sizeOfEachElement) { }
[System.CLSCompliantAttribute(false)]
public void Initialize(ulong numBytes) { }
[System.CLSCompliantAttribute(false)]
public void Initialize<T>(uint numElements) where T : struct { }
[System.CLSCompliantAttribute(false)]
public T Read<T>(ulong byteOffset) where T : struct { return default(T); }
[System.CLSCompliantAttribute(false)]
public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { }
public void ReleasePointer() { }
[System.CLSCompliantAttribute(false)]
public void Write<T>(ulong byteOffset, T value) where T : struct { }
[System.CLSCompliantAttribute(false)]
public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4096), AllowMultiple = false, Inherited = false)]
public sealed partial class UnmanagedFunctionPointerAttribute : System.Attribute
{
public bool BestFitMapping;
public System.Runtime.InteropServices.CharSet CharSet;
public bool SetLastError;
public bool ThrowOnUnmappableChar;
public UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention callingConvention) { }
public System.Runtime.InteropServices.CallingConvention CallingConvention { get { return default(System.Runtime.InteropServices.CallingConvention); } }
}
public enum UnmanagedType
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as AnsiBStr may be unavailable in future releases.")]
AnsiBStr = 35,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling arbitrary types may be unavailable in future releases. Please specify the type you wish to marshal as.")]
AsAny = 40,
Bool = 2,
BStr = 19,
ByValArray = 30,
ByValTStr = 23,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as Currency may be unavailable in future releases.")]
Currency = 15,
Error = 45,
FunctionPtr = 38,
HString = 47,
I1 = 3,
I2 = 5,
I4 = 7,
I8 = 9,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as IDispatch may be unavailable in future releases.")]
IDispatch = 26,
IInspectable = 46,
Interface = 28,
IUnknown = 25,
LPArray = 42,
LPStr = 20,
LPStruct = 43,
LPTStr = 22,
LPWStr = 21,
R4 = 11,
R8 = 12,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as SafeArray may be unavailable in future releases.")]
SafeArray = 29,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Applying UnmanagedType.Struct is unnecessary when marshalling a struct. Support for UnmanagedType.Struct when marshalling a reference type may be unavailable in future releases.")]
Struct = 27,
SysInt = 31,
SysUInt = 32,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as TBstr may be unavailable in future releases.")]
TBStr = 36,
U1 = 4,
U2 = 6,
U4 = 8,
U8 = 10,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as VariantBool may be unavailable in future releases.")]
VariantBool = 37,
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling as VBByRefString may be unavailable in future releases.")]
VBByRefStr = 34,
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("Marshalling VARIANTs may be unavailable in future releases.")]
public enum VarEnum
{
VT_ARRAY = 8192,
VT_BLOB = 65,
VT_BLOB_OBJECT = 70,
VT_BOOL = 11,
VT_BSTR = 8,
VT_BYREF = 16384,
VT_CARRAY = 28,
VT_CF = 71,
VT_CLSID = 72,
VT_CY = 6,
VT_DATE = 7,
VT_DECIMAL = 14,
VT_DISPATCH = 9,
VT_EMPTY = 0,
VT_ERROR = 10,
VT_FILETIME = 64,
VT_HRESULT = 25,
VT_I1 = 16,
VT_I2 = 2,
VT_I4 = 3,
VT_I8 = 20,
VT_INT = 22,
VT_LPSTR = 30,
VT_LPWSTR = 31,
VT_NULL = 1,
VT_PTR = 26,
VT_R4 = 4,
VT_R8 = 5,
VT_RECORD = 36,
VT_SAFEARRAY = 27,
VT_STORAGE = 67,
VT_STORED_OBJECT = 69,
VT_STREAM = 66,
VT_STREAMED_OBJECT = 68,
VT_UI1 = 17,
VT_UI2 = 18,
VT_UI4 = 19,
VT_UI8 = 21,
VT_UINT = 23,
VT_UNKNOWN = 13,
VT_USERDEFINED = 29,
VT_VARIANT = 12,
VT_VECTOR = 4096,
VT_VOID = 24,
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.AspNetCore.Http;
using NakedFramework.Facade.Contexts;
using NakedFramework.Facade.Interface;
using NakedFramework.Facade.Translation;
using NakedFramework.Rest.Snapshot.Constants;
using NakedFramework.Rest.Snapshot.RelTypes;
using NakedFramework.Rest.Snapshot.Utility;
namespace NakedFramework.Rest.Snapshot.Representation;
[DataContract]
public class ObjectRepresentation : Representation {
protected ObjectRepresentation(IFrameworkFacade frameworkFacade, HttpRequest req, ObjectContextFacade objectContext, RestControlFlags flags)
: base(frameworkFacade.OidStrategy, flags) {
var objectUri = GetHelper(frameworkFacade.OidStrategy, req, objectContext);
SetScalars(objectContext);
SelfRelType = objectContext.Specification.IsService ? new ServiceRelType(RelValues.Self, objectUri) : new ObjectRelType(RelValues.Self, objectUri);
SetLinksAndMembers(frameworkFacade, req, objectContext);
SetExtensions(objectContext.Target);
SetHeader(objectContext);
}
[DataMember(Name = JsonPropertyNames.Title)]
public string Title { get; set; }
[DataMember(Name = JsonPropertyNames.Links)]
public LinkRepresentation[] Links { get; set; }
[DataMember(Name = JsonPropertyNames.Extensions)]
public MapRepresentation Extensions { get; set; }
[DataMember(Name = JsonPropertyNames.Members)]
public MapRepresentation Members { get; set; }
private static UriMtHelper GetHelper(IOidStrategy oidStrategy, HttpRequest req, ObjectContextFacade objectContext) => new(oidStrategy, req, objectContext.Target);
private static bool IsProtoPersistent(IObjectFacade objectFacade) => objectFacade.IsTransient;
private static bool IsForm(IObjectFacade objectFacade) => objectFacade.IsViewModelEditView;
private void SetScalars(ObjectContextFacade objectContext) => Title = objectContext.Target.TitleString;
private void SetHeader(ObjectContextFacade objectContext) {
Caching = objectContext.Specification.IsService ? CacheType.NonExpiring : CacheType.Transactional;
SetEtag(objectContext.Target);
}
private LinkRepresentation[] CreateIsOfTypeLinks(HttpRequest req, ObjectContextFacade objectContext) {
var spec = objectContext.Target.Specification;
return new[] {
LinkRepresentation.Create(OidStrategy, new TypeActionRelType(new UriMtHelper(OidStrategy, req, spec), WellKnownIds.IsSubtypeOf), Flags,
new OptionalProperty(JsonPropertyNames.Id, WellKnownIds.IsSubtypeOf),
new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.SuperType, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.Value, null, typeof(object))))))),
LinkRepresentation.Create(OidStrategy, new TypeActionRelType(new UriMtHelper(OidStrategy, req, spec), WellKnownIds.IsSupertypeOf), Flags,
new OptionalProperty(JsonPropertyNames.Id, WellKnownIds.IsSupertypeOf),
new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.SubType, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.Value, null, typeof(object)))))))
};
}
private void SetLinksAndMembers(IFrameworkFacade frameworkFacade, HttpRequest req, ObjectContextFacade objectContext) {
var tempLinks = new List<LinkRepresentation>();
if (!objectContext.Mutated && !IsProtoPersistent(objectContext.Target)) {
tempLinks.Add(LinkRepresentation.Create(OidStrategy, SelfRelType, Flags));
}
// custom isSub/SupertypeOf links
tempLinks.AddRange(CreateIsOfTypeLinks(req, objectContext));
SetMembers(frameworkFacade, objectContext, req, tempLinks);
Links = tempLinks.ToArray();
}
private void SetMembers(IFrameworkFacade frameworkFacade, ObjectContextFacade objectContext, HttpRequest req, List<LinkRepresentation> tempLinks) {
var visiblePropertiesAndCollections = objectContext.VisibleProperties;
if (!Flags.BlobsClobs) {
// filter any blobs and clobs
visiblePropertiesAndCollections = visiblePropertiesAndCollections.Where(vp => !RestUtils.IsBlobOrClob(vp.Specification)).ToArray();
}
var visibleProperties = visiblePropertiesAndCollections.Where(p => !p.Property.IsCollection).ToArray();
if (!IsProtoPersistent(objectContext.Target) && !IsForm(objectContext.Target) && visibleProperties.Any(p => p.Property.IsUsable(objectContext.Target).IsAllowed)) {
var ids = visibleProperties.Where(p => p.Property.IsUsable(objectContext.Target).IsAllowed && !p.Property.IsInline).Select(p => p.Id).ToArray();
var props = ids.Select(s => new OptionalProperty(s, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.Value, null, typeof(object))))).ToArray();
var helper = GetHelper(OidStrategy, req, objectContext);
var modifyLink = LinkRepresentation.Create(OidStrategy, new ObjectRelType(RelValues.Update, helper) { Method = RelMethod.Put }, Flags,
new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(props)));
tempLinks.Add(modifyLink);
}
if (IsProtoPersistent(objectContext.Target)) {
var ids = objectContext.Target.Specification.Properties.Where(p => !p.IsCollection && !p.IsInline).ToDictionary(p => p.Id, p => {
var useDate = p.IsDateOnly;
return GetPropertyValue(frameworkFacade, req, p, objectContext.Target, Flags, true, useDate);
}).ToArray();
var props = ids.Select(kvp => new OptionalProperty(kvp.Key, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.Value, kvp.Value)))).ToArray();
var argMembers = new OptionalProperty(JsonPropertyNames.Members, MapRepresentation.Create(props));
var args = new List<OptionalProperty> { argMembers };
var persistLink = LinkRepresentation.Create(OidStrategy, new ObjectsRelType(RelValues.Persist, new UriMtHelper(OidStrategy, req, objectContext.Target.Specification)) { Method = RelMethod.Post }, Flags,
new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(args.ToArray())));
tempLinks.Add(persistLink);
}
var properties = visiblePropertiesAndCollections.Select(p => InlineMemberAbstractRepresentation.Create(frameworkFacade, req, p, Flags, false)).ToArray();
ActionContextFacade[] visibleActions;
if (IsProtoPersistent(objectContext.Target)) {
visibleActions = Array.Empty<ActionContextFacade>();
}
else if (IsForm(objectContext.Target)) {
visibleActions = objectContext.VisibleActions.Where(af => af.Action.ParameterCount == 0).ToArray();
}
else {
visibleActions = FilterLocallyContributedActions(objectContext.VisibleActions, visiblePropertiesAndCollections.Where(p => p.Property.IsCollection).ToArray());
}
var actions = visibleActions.Select(a => InlineActionRepresentation.Create(OidStrategy, req, a, Flags)).ToArray();
var allMembers = properties.Union(actions);
Members = RestUtils.CreateMap(allMembers.ToDictionary(m => m.Id, m => (object)m));
}
private static ActionContextFacade[] FilterLocallyContributedActions(ActionContextFacade[] actions, PropertyContextFacade[] collections) {
var lcas = collections.SelectMany(c => c.Target.Specification.GetLocallyContributedActions(c.Property.ElementSpecification, c.Property.Id));
return actions.Where(a => !lcas.Select(lca => lca.Id).Contains(a.Id)).ToArray();
}
private static IDictionary<string, object> GetCustomExtensions(IObjectFacade objectFacade) {
InteractionMode mode;
if (objectFacade.IsNotPersistent && !objectFacade.IsViewModel) {
mode = InteractionMode.NotPersistent;
}
else if (objectFacade.IsTransient) {
mode = InteractionMode.Transient;
}
else if (objectFacade.IsViewModelEditView) {
mode = InteractionMode.Form;
}
else {
mode = InteractionMode.Persistent;
}
return new Dictionary<string, object> {
[JsonPropertyNames.InteractionMode] = mode.ToString().ToLower()
};
}
private void SetExtensions(IObjectFacade objectFacade) => Extensions = GetExtensions(objectFacade);
private MapRepresentation GetExtensions(IObjectFacade objectFacade) =>
RestUtils.GetExtensions(
objectFacade.Specification.SingularName,
objectFacade.Specification.Description(objectFacade),
objectFacade.Specification.PluralName,
objectFacade.Specification.DomainTypeName(OidStrategy),
objectFacade.Specification.IsService,
null,
null,
null,
null,
null,
null,
objectFacade.PresentationHint,
objectFacade.RestExtension,
GetCustomExtensions(objectFacade),
null,
null,
OidStrategy,
false);
public static ObjectRepresentation Create(IFrameworkFacade frameworkFacade, IObjectFacade target, HttpRequest req, RestControlFlags flags) {
var oc = frameworkFacade.GetObject(target);
return Create(frameworkFacade, oc, req, flags);
}
public static ObjectRepresentation Create(IFrameworkFacade frameworkFacade, ObjectContextFacade objectContext, HttpRequest req, RestControlFlags flags) {
if (objectContext.Target != null && (objectContext.Specification.IsService || !IsProtoPersistent(objectContext.Target))) {
return CreateObjectWithOptionals(frameworkFacade, objectContext, req, flags);
}
return new ObjectRepresentation(frameworkFacade, req, objectContext, flags);
}
private static ObjectRepresentation CreateObjectWithOptionals(IFrameworkFacade frameworkFacade, ObjectContextFacade objectContext, HttpRequest req, RestControlFlags flags) {
var oid = frameworkFacade.OidStrategy.OidTranslator.GetOidTranslation(objectContext.Target);
var props = new List<OptionalProperty>();
if (objectContext.Specification.IsService) {
props.Add(new OptionalProperty(JsonPropertyNames.ServiceId, oid.DomainType));
}
else {
props.Add(new OptionalProperty(JsonPropertyNames.InstanceId, oid.InstanceId));
props.Add(new OptionalProperty(JsonPropertyNames.DomainType, oid.DomainType));
}
return CreateWithOptionals<ObjectRepresentation>(new object[] { frameworkFacade, req, objectContext, flags }, props);
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// 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.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.Firebird;
using FluentMigrator.Runner.Processors.MySql;
using FluentMigrator.Runner.Processors.Postgres;
using FluentMigrator.Runner.Processors.Sqlite;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Runner.Versioning;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Integration.Migrations.Tagged;
using FluentMigrator.Tests.Unit;
using FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3;
using FluentMigrator.Tests.Integration.Migrations.Invalid;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Integration
{
[TestFixture]
[Category("Integration")]
public class MigrationRunnerTests : IntegrationTestBase
{
private IRunnerContext _runnerContext;
private IMigrationInfo CreateMigrationFor(long version, string versionName = null)
{
return new MigrationInfo(version, versionName, TransactionBehavior.Default, new VersionMigration(null));
}
[SetUp]
public void SetUp()
{
_runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
}
[Test]
public void CanRunMigration()
{
ExecuteWithSupportedProcessors(processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeTrue();
// This is a hack until MigrationVersionRunner and MigrationRunner are refactored and merged together
//processor.CommitTransaction();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeFalse();
});
}
[Test]
public void CanSilentlyFail()
{
try
{
var processorOptions = new Mock<IMigrationProcessorOptions>();
processorOptions.SetupGet(x => x.PreviewOnly).Returns(false);
var processor = new Mock<IMigrationProcessor>();
processor.Setup(x => x.Process(It.IsAny<CreateForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Process(It.IsAny<DeleteForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Options).Returns(processorOptions.Object);
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor.Object) { SilentlyFail = true };
runner.Up(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
runner.Down(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0);
}, false);
}
}
[Test]
public void CanApplyForeignKeyConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeFalse();
}, false, typeof(SqliteProcessor));
}
[Test]
public void CanApplyForeignKeyConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConventionWithSchema());
processor.ConstraintExists("TestSchema", "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConventionWithSchema());
}, false, new []{typeof(SqliteProcessor), typeof(FirebirdProcessor)});
}
[Test]
public void CanApplyIndexConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
});
}
[Test]
public void CanApplyIndexConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists("TestSchema", "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists("TestSchema", "Users").ShouldBeFalse();
});
}
[Test]
public void CanCreateAndDropIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanCreateAndDropIndexWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
}, false, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanRenameTable()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
processor.TableExists(null, "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigration());
processor.TableExists(null, "TestTable'3").ShouldBeFalse();
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable'3").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameColumn()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
}, true, typeof(SqliteProcessor));
}
[Test]
public void CanRenameColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
}, true, typeof(SqliteProcessor), typeof(FirebirdProcessor));
}
[Test]
public void CanLoadMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(MigrationRunnerTests).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.MigrationLoader.LoadMigrations().ShouldNotBeNull();
});
}
[Test]
public void CanLoadVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(TestMigration).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.VersionLoader.VersionInfo.ShouldNotBeNull();
});
}
[Test]
public void CanRunMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(1)).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(2)).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(3)).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(4)).ShouldBeTrue();
runner.VersionLoader.VersionInfo.Latest().ShouldBe("4-0");
runner.RollbackToVersion(0, false);
});
}
[Test]
public void CanMigrateASpecificVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
try
{
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(1)).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0, false);
}
});
}
[Test]
public void CanMigrateASpecificVersionDown()
{
try
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(1)).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.MigrateDown(0, false);
testRunner.VersionLoader.VersionInfo.HasAppliedMigration(CreateMigrationFor(1)).ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
}, false, typeof(SqliteProcessor));
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0, false);
}, false);
}
}
[Test]
public void RollbackAllShouldRemoveVersionInfoTable()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(2);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeTrue();
});
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.RollbackToVersion(0);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeFalse();
});
}
[Test]
public void MigrateUpWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp();
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpSpecificVersionWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1);
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpWithTaggedMigrationsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0);
}
});
}
[Test]
public void MigrateUpWithTaggedMigrationsAndUsingMultipleTagsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA", "TenantB" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0);
}
});
}
[Test]
public void MigrateUpWithDifferentTaggedShouldIgnoreConcreteOfTagged()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantB" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeTrue();
}
finally
{
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0);
}
});
}
[Test]
public void MigrateDownWithDifferentTagsToMigrateUpShouldApplyMatchedMigrations()
{
var assembly = typeof(TenantATable).Assembly;
var migrationsNamespace = typeof(TenantATable).Namespace;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = migrationsNamespace,
};
// Excluded SqliteProcessor as it errors on DB cleanup (RollbackToVersion).
ExecuteWithSupportedProcessors(processor =>
{
try
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
runnerContext.Tags = new[] { "TenantB" };
new MigrationRunner(assembly, runnerContext, processor).MigrateDown(0, false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeFalse();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeFalse();
}
finally
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0, false);
}
}, true, typeof(SqliteProcessor));
}
[Test]
public void VersionInfoCreationScriptsOnlyGeneratedOnceInPreviewMode()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processorOptions = new ProcessorOptions { PreviewOnly = true };
var outputSql = new StringWriter();
var announcer = new TextWriterAnnouncer(outputSql){ ShowSql = true };
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), announcer, processorOptions, new SqlServerDbFactory());
try
{
var asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(announcer)
{
Namespace = "FluentMigrator.Tests.Integration.Migrations",
PreviewOnly = true
};
var runner = new MigrationRunner(asm, runnerContext, processor);
runner.MigrateUp(1, false);
processor.CommitTransaction();
string schemaName = new TestVersionTableMetaData().SchemaName;
var schemaAndTableName = string.Format("\\[{0}\\]\\.\\[{1}\\]", schemaName, TestVersionTableMetaData.TABLENAME);
var outputSqlString = outputSql.ToString();
var createSchemaMatches = new Regex(string.Format("CREATE SCHEMA \\[{0}\\]", schemaName)).Matches(outputSqlString).Count;
var createTableMatches = new Regex("CREATE TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
var createIndexMatches = new Regex("CREATE UNIQUE CLUSTERED INDEX \\[" + TestVersionTableMetaData.UNIQUEINDEXNAME + "\\] ON " + schemaAndTableName).Matches(outputSqlString).Count;
var alterTableMatches = new Regex("ALTER TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
System.Console.WriteLine(outputSqlString);
createSchemaMatches.ShouldBe(1);
createTableMatches.ShouldBe(1);
alterTableMatches.ShouldBe(1);
createIndexMatches.ShouldBe(1);
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void ValidateVersionOrderShouldDoNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SqliteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp(3);
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
Assert.DoesNotThrow(migrationRunner.ValidateVersionOrder);
}, false, excludedProcessors);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
}
[Test(Description = "*** This does not apply to Defi implementation since we want to apply even if it is out of order.")]
public void ValidateVersionOrderShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SqliteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
VersionOrderInvalidException caughtException = null;
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp();
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.ValidateVersionOrder();
}, false, excludedProcessors);
}
catch (VersionOrderInvalidException ex)
{
caughtException = ex;
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
caughtException.ShouldNotBeNull();
caughtException.InvalidMigrations.Count().ShouldBe(1);
var keyValuePair = caughtException.InvalidMigrations.First();
keyValuePair.Value.Version.ShouldBe(200909060935);
keyValuePair.Value.Migration.ShouldBeOfType<UserEmail>();
}
[Test]
public void CanCreateSequence()
{
ExecuteWithSqlServer2012(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence");
runner.Down(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence").ShouldBeFalse();
}, true);
}
[Test]
public void CanCreateSequenceWithSchema()
{
Action<IMigrationProcessor> action = processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSequence());
processor.SequenceExists("TestSchema", "TestSequence");
runner.Down(new TestCreateSequence());
processor.SequenceExists("TestSchema", "TestSequence").ShouldBeFalse();
};
ExecuteWithSqlServer2012(
action,true);
ExecuteWithPostgres(action, IntegrationTestOptions.Postgres, true);
}
[Test]
public void CanAlterColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Up(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Up(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeTrue();
runner.Down(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTablesSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Up(new TestAlterSchema());
processor.TableExists("NewSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestAlterSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanCreateUniqueConstraint()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor)});
}
[Test]
public void CanCreateUniqueConstraintWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanInsertData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
DataSet ds = processor.ReadTableData(null, "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanInsertDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
DataSet ds = processor.ReadTableData("TestSchema", "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanUpdateData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestUpdateData());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(1);
upDs.Tables[0].Rows[0][1].ShouldBe("Updated");
runner.Down(new TestUpdateData());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanDeleteData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
runner.Up(new TestDeleteData());
DataSet upDs = processor.ReadTableData(null, "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteData());
DataSet downDs = processor.ReadTableData(null, "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanDeleteDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestDeleteDataWithSchema());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteDataWithSchema());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanReverseCreateIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeTrue();
runner.Down(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanExecuteSql()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestExecuteSql());
runner.Down(new TestExecuteSql());
}, true, new[] { typeof(FirebirdProcessor) });
}
private static MigrationRunner SetupMigrationRunner(IMigrationProcessor processor)
{
Assembly asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
return new MigrationRunner(asm, runnerContext, processor);
}
private static void CleanupTestSqlServerDatabase(SqlConnection connection, SqlServerProcessor origProcessor)
{
if (origProcessor.WasCommitted)
{
connection.Close();
var cleanupProcessor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner cleanupRunner = SetupMigrationRunner(cleanupProcessor);
cleanupRunner.RollbackToVersion(0);
}
else
{
origProcessor.RollbackTransaction();
}
}
}
internal class TestForeignKeyNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestIndexNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").OnColumn("GroupId");
Delete.Table("Users");
}
}
internal class TestForeignKeySilentFailure : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey("FK_Foo").FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.ForeignKey("FK_Foo").OnTable("Users");
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestCreateAndDropTableMigration : Migration
{
public override void Up()
{
Create.Table("TestTable")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").AsBoolean().Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").ForeignColumn("TestTableId")
.ToTable("TestTable").PrimaryColumn("Id");
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2");
Delete.Table("TestTable");
}
}
internal class TestRenameTableMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").To("TestTable'3");
}
}
internal class TestRenameColumnMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigration : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable");
}
}
internal class TestForeignKeyNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.InSchema("TestSchema")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").InSchema("TestSchema").ForeignColumn("GroupId").ToTable("Groups").InSchema("TestSchema").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users").InSchema("TestSchema");
Delete.Table("Groups").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestIndexNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").InSchema("TestSchema").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").InSchema("TestSchema").OnColumn("GroupId");
Delete.Table("Users").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestCreateAndDropTableMigrationWithSchema : Migration
{
public override void Up()
{
Create.Table("TestTable")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").InSchema("TestSchema").ForeignColumn("TestTableId")
.ToTable("TestTable").InSchema("TestSchema").PrimaryColumn("Id");
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2").InSchema("TestSchema");
Delete.Table("TestTable").InSchema("TestSchema");
}
}
internal class TestRenameTableMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").InSchema("TestSchema").To("TestTable'3");
}
}
internal class TestRenameColumnMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").InSchema("TestSchema").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigrationWithSchema : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema");
}
}
internal class TestCreateSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
}
public override void Down()
{
Delete.Schema("TestSchema");
}
}
internal class TestCreateSequence : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence");
}
}
internal class TestCreateSequenceWithSchema : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").InSchema("TestSchema").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence").InSchema("TestSchema");
}
}
internal class TestAlterColumnWithSchema: Migration
{
public override void Up()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsAnsiString(100).Nullable();
}
public override void Down()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
}
}
internal class TestAlterTableWithSchema : Migration
{
public override void Up()
{
Alter.Table("TestTable2").InSchema("TestSchema").AddColumn("NewColumn").AsInt32().WithDefaultValue(1);
}
public override void Down()
{
Delete.Column("NewColumn").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestAlterSchema : Migration
{
public override void Up()
{
Create.Schema("NewSchema");
Alter.Table("TestTable").InSchema("TestSchema").ToSchema("NewSchema");
}
public override void Down()
{
Alter.Table("TestTable").InSchema("NewSchema").ToSchema("TestSchema");
Delete.Schema("NewSchema");
}
}
internal class TestCreateUniqueConstraint : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2");
}
}
internal class TestCreateUniqueConstraintWithSchema : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestUpdateData : Migration
{
public override void Up()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Updated" }).AllRows();
}
public override void Down()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Test" }).AllRows();
}
}
internal class TestDeleteData : Migration
{
public override void Up()
{
Delete.FromTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
}
internal class TestDeleteDataWithSchema :Migration
{
public override void Up()
{
Delete.FromTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test"});
}
public override void Down()
{
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
}
internal class TestCreateIndexWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.Index().OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name2").Ascending();
}
}
internal class TestExecuteSql : Migration
{
public override void Up()
{
Execute.Sql("select 1");
}
public override void Down()
{
Execute.Sql("select 2");
}
}
}
| |
using System;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Trigger the "blur" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur()
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "change" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change()
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "focus" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus()
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0})")]
public virtual jQuery FocusIn(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0})")]
public virtual jQuery FocusIn(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0},{1})")]
public virtual jQuery FocusIn(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0},{1})")]
public virtual jQuery FocusIn(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "select" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select()
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "submit" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit()
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(object eventData, Action handler)
{
return null;
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Collections;
namespace Sanford.Collections
{
/// <summary>
/// Represents a collection of key-and-value pairs.
/// </summary>
/// <remarks>
/// The SkipList class is an implementation of the IDictionary interface. It
/// is based on the data structure created by William Pugh.
/// </remarks>
public class SkipList : IDictionary
{
#region SkipList Members
#region Constants
// Maximum level any node in a skip list can have
private const int MaxLevel = 32;
// Probability factor used to determine the node level
private const double Probability = 0.5;
#endregion
#region Fields
// The skip list header. It also serves as the NIL node.
private Node header = new Node(MaxLevel);
// Comparer for comparing keys.
private IComparer comparer;
// Random number generator for generating random node levels.
private Random random = new Random();
// Current maximum list level.
private int listLevel;
// Current number of elements in the skip list.
private int count;
// Version of the skip list. Used for validation checks with
// enumerators.
private long version = 0;
#endregion
/// <summary>
/// Initializes a new instance of the SkipList class that is empty and
/// is sorted according to the IComparable interface implemented by
/// each key added to the SkipList.
/// </summary>
/// <remarks>
/// Each key must implement the IComparable interface to be capable of
/// comparisons with every other key in the SortedList. The elements
/// are sorted according to the IComparable implementation of each key
/// added to the SkipList.
/// </remarks>
public SkipList()
{
// Initialize the skip list.
Initialize();
}
/// <summary>
/// Initializes a new instance of the SkipList class that is empty and
/// is sorted according to the specified IComparer interface.
/// </summary>
/// <param name="comparer">
/// The IComparer implementation to use when comparing keys.
/// </param>
/// <remarks>
/// The elements are sorted according to the specified IComparer
/// implementation. If comparer is a null reference, the IComparable
/// implementation of each key is used; therefore, each key must
/// implement the IComparable interface to be capable of comparisons
/// with every other key in the SkipList.
/// </remarks>
public SkipList(IComparer comparer)
{
// Initialize comparer with the client provided comparer.
this.comparer = comparer;
// Initialize the skip list.
Initialize();
}
/// <summary>
/// Destructor.
/// </summary>
~SkipList()
{
Clear();
}
#region Private Helper Methods
/// <summary>
/// Initializes the SkipList.
/// </summary>
private void Initialize()
{
listLevel = 1;
count = 0;
// When the list is empty, make sure all forward references in the
// header point back to the header. This is important because the
// header is used as the sentinel to mark the end of the skip list.
for(int i = 0; i < MaxLevel; i++)
{
header.forward[i] = header;
}
}
/// <summary>
/// Returns a level value for a new SkipList node.
/// </summary>
/// <returns>
/// The level value for a new SkipList node.
/// </returns>
private int GetNewLevel()
{
int level = 1;
// Determines the next node level.
while(random.NextDouble() < Probability && level < MaxLevel &&
level <= listLevel)
{
level++;
}
return level;
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key)
{
Node curr;
Node[] dummy = new Node[MaxLevel];
return Search(key, out curr, dummy);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key, out Node curr)
{
Node[] dummy = new Node[MaxLevel];
return Search(key, out curr, dummy);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key, Node[] update)
{
Node curr;
return Search(key, out curr, update);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key, out Node curr, Node[] update)
{
// Make sure key isn't null.
if(key == null)
{
throw new ArgumentNullException("An attempt was made to pass a null key to a SkipList.");
}
bool result;
// Check to see if we will search with a comparer.
if(comparer != null)
{
result = SearchWithComparer(key, out curr, update);
}
// Else we're using the IComparable interface.
else
{
result = SearchWithComparable(key, out curr, update);
}
return result;
}
/// <summary>
/// Search for the specified key using a comparer.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool SearchWithComparer(object key, out Node curr,
Node[] update)
{
bool found = false;
// Start from the beginning of the skip list.
curr = header;
// Work our way down from the top of the skip list to the bottom.
for(int i = listLevel - 1; i >= 0; i--)
{
// While we haven't reached the end of the skip list and the
// current key is less than the search key.
while(curr.forward[i] != header &&
comparer.Compare(curr.forward[i].Entry.Key, key) < 0)
{
// Move forward in the skip list.
curr = curr.forward[i];
}
// Keep track of each node where we move down a level. This
// will be used later to rearrange node references when
// inserting or deleting a new element.
update[i] = curr;
}
// Move ahead in the skip list. If the new key doesn't already
// exist in the skip list, this should put us at either the end of
// the skip list or at a node with a key greater than the search key.
// If the new key already exists in the skip list, this should put
// us at a node with a key equal to the search key.
curr = curr.forward[0];
// If we haven't reached the end of the skip list and the
// current key is equal to the search key.
if(curr != header && comparer.Compare(key, curr.Entry.Key) == 0)
{
// Indicate that we've found the search key.
found = true;
}
return found;
}
/// <summary>
/// Search for the specified key using the IComparable interface
/// implemented by each key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
/// <remarks>
/// Assumes each key inserted into the SkipList implements the
/// IComparable interface.
///
/// If the specified key is in the SkipList, the curr parameter will
/// reference the node with the key. If the specified key is not in the
/// SkipList, the curr paramater will either hold the node with the
/// first key value greater than the specified key or it will have the
/// same value as the header indicating that the search reached the end
/// of the SkipList.
/// </remarks>
private bool SearchWithComparable(object key, out Node curr,
Node[] update)
{
// Make sure key is comparable.
if(!(key is IComparable))
{
throw new ArgumentException("The SkipList was set to use the IComparable interface and an attempt was made to add a key that does not support this interface.");
}
bool found = false;
IComparable comp;
// Begin at the start of the skip list.
curr = header;
// Work our way down from the top of the skip list to the bottom.
for(int i = listLevel - 1; i >= 0; i--)
{
// Get the comparable interface for the current key.
comp = (IComparable)curr.forward[i].Key;
// While we haven't reached the end of the skip list and the
// current key is less than the search key.
while(curr.forward[i] != header && comp.CompareTo(key) < 0)
{
// Move forward in the skip list.
curr = curr.forward[i];
// Get the comparable interface for the current key.
comp = (IComparable)curr.forward[i].Key;
}
// Keep track of each node where we move down a level. This
// will be used later to rearrange node references when
// inserting a new element.
update[i] = curr;
}
// Move ahead in the skip list. If the new key doesn't already
// exist in the skip list, this should put us at either the end of
// the skip list or at a node with a key greater than the search key.
// If the new key already exists in the skip list, this should put
// us at a node with a key equal to the search key.
curr = curr.forward[0];
// Get the comparable interface for the current key.
comp = (IComparable)curr.Key;
// If we haven't reached the end of the skip list and the
// current key is equal to the search key.
if(curr != header && comp.CompareTo(key) == 0)
{
// Indicate that we've found the search key.
found = true;
}
return found;
}
/// <summary>
/// Inserts a key/value pair into the SkipList.
/// </summary>
/// <param name="key">
/// The key to insert into the SkipList.
/// </param>
/// <param name="val">
/// The value to insert into the SkipList.
/// </param>
/// <param name="update">
/// An array of nodes holding references to places in the SkipList in
/// which the search for the place to insert the new key/value pair
/// dropped down one level.
/// </param>
private void Insert(object key, object val, Node[] update)
{
// Get the level for the new node.
int newLevel = GetNewLevel();
// If the level for the new node is greater than the skip list
// level.
if(newLevel > listLevel)
{
// Make sure our update references above the current skip list
// level point to the header.
for(int i = listLevel; i < newLevel; i++)
{
update[i] = header;
}
// The current skip list level is now the new node level.
listLevel = newLevel;
}
// Create the new node.
Node newNode = new Node(newLevel, key, val);
// Insert the new node into the skip list.
for(int i = 0; i < newLevel; i++)
{
// The new node forward references are initialized to point to
// our update forward references which point to nodes further
// along in the skip list.
newNode.forward[i] = update[i].forward[i];
// Take our update forward references and point them towards
// the new node.
update[i].forward[i] = newNode;
}
// Keep track of the number of nodes in the skip list.
count++;
// Indicate that the skip list has changed.
version++;
}
#endregion
#endregion
#region Node Class
/// <summary>
/// Represents a node in the SkipList.
/// </summary>
private class Node : IDisposable
{
#region Fields
// References to nodes further along in the skip list.
public Node[] forward;
// Node key.
private Object key;
// Node value.
private Object val;
#endregion
/// <summary>
/// Initializes an instant of a Node with its node level.
/// </summary>
/// <param name="level">
/// The node level.
/// </param>
public Node(int level)
{
forward = new Node[level];
}
/// <summary>
/// Initializes an instant of a Node with its node level and
/// key/value pair.
/// </summary>
/// <param name="level">
/// The node level.
/// </param>
/// <param name="key">
/// The key for the node.
/// </param>
/// <param name="val">
/// The value for the node.
/// </param>
public Node(int level, object key, object val)
{
forward = new Node[level];
Key = key;
Value = val;
}
/// <summary>
/// Key property.
/// </summary>
public Object Key
{
get
{
return key;
}
set
{
key = value;
}
}
/// <summary>
/// Value property.
/// </summary>
public Object Value
{
get
{
return val;
}
set
{
val = value;
}
}
/// <summary>
/// Node dictionary Entry property - contains key/value pair.
/// </summary>
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(Key, Value);
}
}
#region IDisposable Members
/// <summary>
/// Disposes the Node.
/// </summary>
public void Dispose()
{
for(int i = 0; i < forward.Length; i++)
{
forward[i] = null;
}
}
#endregion
}
#endregion
#region SkipListEnumerator Class
/// <summary>
/// Enumerates the elements of a skip list.
/// </summary>
private class SkipListEnumerator : IDictionaryEnumerator
{
#region SkipListEnumerator Members
#region Fields
// The skip list to enumerate.
private SkipList list;
// The current node.
private Node current;
// The version of the skip list we are enumerating.
private long version;
// Keeps track of previous move result so that we can know
// whether or not we are at the end of the skip list.
private bool moveResult = true;
#endregion
/// <summary>
/// Initializes an instance of a SkipListEnumerator.
/// </summary>
/// <param name="list"></param>
public SkipListEnumerator(SkipList list)
{
this.list = list;
version = list.version;
current = list.header;
}
#endregion
#region IDictionaryEnumerator Members
/// <summary>
/// Gets both the key and the value of the current dictionary
/// entry.
/// </summary>
public DictionaryEntry Entry
{
get
{
DictionaryEntry entry;
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version != list.version)
{
throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator.");
}
// Make sure we are not before the beginning or beyond the
// end of the skip list.
else if(current == list.header)
{
throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator.");
}
// Finally, all checks have passed. Get the current entry.
else
{
entry = current.Entry;
}
return entry;
}
}
/// <summary>
/// Gets the key of the current dictionary entry.
/// </summary>
public object Key
{
get
{
object key = Entry.Key;
return key;
}
}
/// <summary>
/// Gets the value of the current dictionary entry.
/// </summary>
public object Value
{
get
{
object val = Entry.Value;
return val;
}
}
#endregion
#region IEnumerator Members
/// <summary>
/// Advances the enumerator to the next element of the skip list.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next
/// element; false if the enumerator has passed the end of the
/// skip list.
/// </returns>
public bool MoveNext()
{
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version == list.version)
{
// If the result of the previous move operation was true
// we can still move forward in the skip list.
if(moveResult)
{
// Move forward in the skip list.
current = current.forward[0];
// If we are at the end of the skip list.
if(current == list.header)
{
// Indicate that we've reached the end of the skip
// list.
moveResult = false;
}
}
}
// Else this version of the enumerator doesn't match that of
// the skip list. The skip list has been modified since the
// creation of the enumerator.
else
{
throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator.");
}
return moveResult;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before
/// the first element in the skip list.
/// </summary>
public void Reset()
{
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version == list.version)
{
current = list.header;
moveResult = true;
}
// Else this version of the enumerator doesn't match that of
// the skip list. The skip list has been modified since the
// creation of the enumerator.
else
{
throw new InvalidOperationException("SkipListEnumerator is no longer valid. The SkipList has been modified since the creation of this enumerator.");
}
}
/// <summary>
/// Gets the current element in the skip list.
/// </summary>
public object Current
{
get
{
return Entry;
}
}
#endregion
}
#endregion
#region IDictionary Members
/// <summary>
/// Adds an element with the provided key and value to the SkipList.
/// </summary>
/// <param name="key">
/// The Object to use as the key of the element to add.
/// </param>
/// <param name="value">
/// The Object to use as the value of the element to add.
/// </param>
public void Add(object key, object value)
{
Node[] update = new Node[MaxLevel];
// If key does not already exist in the skip list.
if(!Search(key, update))
{
// Inseart key/value pair into the skip list.
Insert(key, value, update);
}
// Else throw an exception. The IDictionary Add method throws an
// exception if an attempt is made to add a key that already
// exists in the skip list.
else
{
throw new ArgumentException("An attempt was made to add an element in which the key of the element already exists in the SkipList.");
}
}
/// <summary>
/// Removes all elements from the SkipList.
/// </summary>
public void Clear()
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
Node prev;
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Keep track of the previous node.
prev = curr;
// Move forward in the skip list.
curr = curr.forward[0];
// Dispose of the previous node.
prev.Dispose();
}
// Initialize skip list and indicate that it has been changed.
Initialize();
version++;
}
/// <summary>
/// Determines whether the SkipList contains an element with the
/// specified key.
/// </summary>
/// <param name="key">
/// The key to locate in the SkipList.
/// </param>
/// <returns>
/// true if the SkipList contains an element with the key; otherwise,
/// false.
/// </returns>
public bool Contains(object key)
{
return Search(key);
}
/// <summary>
/// Returns an IDictionaryEnumerator for the SkipList.
/// </summary>
/// <returns>
/// An IDictionaryEnumerator for the SkipList.
/// </returns>
public IDictionaryEnumerator GetEnumerator()
{
return new SkipListEnumerator(this);
}
/// <summary>
/// Removes the element with the specified key from the SkipList.
/// </summary>
/// <param name="key">
/// The key of the element to remove.
/// </param>
public void Remove(object key)
{
Node[] update = new Node[MaxLevel];
Node curr;
if(Search(key, out curr, update))
{
// Take the forward references that point to the node to be
// removed and reassign them to the nodes that come after it.
for(int i = 0; i < listLevel &&
update[i].forward[i] == curr; i++)
{
update[i].forward[i] = curr.forward[i];
}
curr.Dispose();
// After removing the node, we may need to lower the current
// skip list level if the node had the highest level of all of
// the nodes.
while(listLevel > 1 && header.forward[listLevel - 1] == header)
{
listLevel--;
}
// Keep track of the number of nodes.
count--;
// Indicate that the skip list has changed.
version++;
}
}
/// <summary>
/// Gets a value indicating whether the SkipList has a fixed size.
/// </summary>
public bool IsFixedSize
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the IDictionary is read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets or sets the element with the specified key. This is the
/// indexer for the SkipList.
/// </summary>
public object this[object key]
{
get
{
object val = null;
Node curr;
if(Search(key, out curr))
{
val = curr.Entry.Value;
}
return val;
}
set
{
Node[] update = new Node[MaxLevel];
Node curr;
// If the search key already exists in the skip list.
if(Search(key, out curr, update))
{
// Replace the current value with the new value.
curr.Value = value;
// Indicate that the skip list has changed.
version++;
}
// Else the key doesn't exist in the skip list.
else
{
// Insert the key and value into the skip list.
Insert(key, value, update);
}
}
}
/// <summary>
/// Gets an ICollection containing the keys of the SkipList.
/// </summary>
public ICollection Keys
{
get
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// Create a collection to hold the keys.
ArrayList collection = new ArrayList();
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Add the key to the collection.
collection.Add(curr.Entry.Key);
// Move forward in the skip list.
curr = curr.forward[0];
}
return collection;
}
}
/// <summary>
/// Gets an ICollection containing the values of the SkipList.
/// </summary>
public ICollection Values
{
get
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// Create a collection to hold the values.
ArrayList collection = new ArrayList();
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Add the value to the collection.
collection.Add(curr.Entry.Value);
// Move forward in the skip list.
curr = curr.forward[0];
}
return collection;
}
}
#endregion
#region ICollection Members
/// <summary>
/// Copies the elements of the SkipList to an Array, starting at a
/// particular Array index.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements
/// copied from SkipList.
/// </param>
/// <param name="index">
/// The zero-based index in array at which copying begins.
/// </param>
public void CopyTo(Array array, int index)
{
// Make sure array isn't null.
if(array == null)
{
throw new ArgumentNullException("An attempt was made to pass a null array to the CopyTo method of a SkipList.");
}
// Make sure index is not negative.
else if(index < 0)
{
throw new ArgumentOutOfRangeException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList.");
}
// Array bounds checking.
else if(index >= array.Length)
{
throw new ArgumentException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList.");
}
// Make sure that the number of elements in the skip list is not
// greater than the available space from index to the end of the
// array.
else if((array.Length - index) < Count)
{
throw new ArgumentException("An attempt was made to pass an out of range index to the CopyTo method of a SkipList.");
}
// Else copy elements from skip list into array.
else
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Copy current value into array.
array.SetValue(curr.Entry.Value, index);
// Move forward in the skip list and array.
curr = curr.forward[0];
index++;
}
}
}
/// <summary>
/// Gets the number of elements contained in the SkipList.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets a value indicating whether access to the SkipList is
/// synchronized (thread-safe).
/// </summary>
public bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the
/// SkipList.
/// </summary>
public object SyncRoot
{
get
{
return this;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through the SkipList.
/// </summary>
/// <returns>
/// An IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new SkipListEnumerator(this);
}
#endregion
}
}
| |
using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
//@@@
public static partial class Symbol
{
/// <summary>
/// ASYMKEY_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/asymkey-id-transact-sql
/// </summary>
/// <param name="asym_key_name">asym_key_name.</param>
/// <returns>kye id.</returns>
[FuncStyleConverter]
public static int? AsymKey_Id(string asym_key_name) => throw new InvalitContextException(nameof(AsymKey_Id));
/// <summary>
/// ASYMKEYPROPERTY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/asymkeyproperty-transact-sql
/// </summary>
/// <param name="key_id">key_id.</param>
/// <param name="param">algorithm_desc or string_sid or sid.</param>
/// <returns>the properties of an asymmetric key.</returns>
[FuncStyleConverter]
public static object AsymKeyProperty(int? key_id, string param) => throw new InvalitContextException(nameof(AsymKeyProperty));
/// <summary>
/// CERTPROPERTY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/certproperty-transact-sql
/// </summary>
/// <param name="cert_id">cert_id.</param>
/// <param name="PropertyName">PropertyName.</param>
/// <returns>property.</returns>
[FuncStyleConverter]
public static object CertProperty(int? cert_id, string PropertyName) => throw new InvalitContextException(nameof(CertProperty));
/// <summary>
/// CERT_ID.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/cert-id-transact-sql
/// </summary>
/// <param name="cert_name">cert_name.</param>
/// <returns>id.</returns>
[FuncStyleConverter]
public static int? Cert_Id(string cert_name) => throw new InvalitContextException(nameof(Cert_Id));
/// <summary>
/// CRYPT_GEN_RANDOM.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sql
/// </summary>
/// <param name="length">length.</param>
/// <param name="seed">seed.</param>
/// <returns>a cryptographic random number generated by the Crypto API (CAPI). The output is a hexadecimal number of the specified number of bytes.</returns>
[FuncStyleConverter]
public static byte[] Crypt_Gen_Random(int length, byte[] seed) => throw new InvalitContextException(nameof(Crypt_Gen_Random));
/// <summary>
/// DECRYPTBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbyasymkey-transact-sql.
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByAsymKey(int? Asym_Key_ID, string ciphertext) => throw new InvalitContextException(nameof(DecryptByAsymKey));
/// <summary>
/// DECRYPTBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbyasymkey-transact-sql.
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="password">password.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByAsymKey(int? Asym_Key_ID, string ciphertext, string password) => throw new InvalitContextException(nameof(DecryptByAsymKey));
/// <summary>
/// DECRYPTBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbycert-transact-sql
/// </summary>
/// <param name="certificate_ID">certificate_ID.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByCert(int? certificate_ID, string ciphertext) => throw new InvalitContextException(nameof(DecryptByCert));
/// <summary>
/// DECRYPTBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbycert-transact-sql
/// </summary>
/// <param name="certificate_ID">certificate_ID.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="password">password.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByCert(int? certificate_ID, string ciphertext, string password) => throw new InvalitContextException(nameof(DecryptByCert));
/// <summary>
/// DECRYPTBYKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykey-transact-sql
/// </summary>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKey(string ciphertext) => throw new InvalitContextException(nameof(DecryptByKey));
/// <summary>
/// DECRYPTBYKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykey-transact-sql
/// </summary>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="add_authenticator">add_authenticator.</param>
/// <param name="authenticator">authenticator.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKey(string ciphertext, int add_authenticator, byte[] authenticator) => throw new InvalitContextException(nameof(DecryptByKey));
/// <summary>
/// DECRYPTBYKEYAUTOASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykeyautoasymkey-transact-sql
/// </summary>
/// <param name="akey_ID">akey_ID.</param>
/// <param name="akey_password">akey_password.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKeyAutoAsymKey(int? akey_ID, string akey_password, object ciphertext) => throw new InvalitContextException(nameof(DecryptByKeyAutoAsymKey));
/// <summary>
/// DECRYPTBYKEYAUTOASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykeyautoasymkey-transact-sql
/// </summary>
/// <param name="akey_ID">akey_ID.</param>
/// <param name="akey_password">akey_password.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="add_authenticator">add_authenticator.</param>
/// <param name="authenticator">authenticator.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKeyAutoAsymKey(int? akey_ID, string akey_password, object ciphertext, int add_authenticator, byte[] authenticator) => throw new InvalitContextException(nameof(DecryptByKeyAutoAsymKey));
/// <summary>
/// DECRYPTBYKEYAUTOCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykeyautocert-transact-sql
/// </summary>
/// <param name="cert_ID">cert_ID.</param>
/// <param name="cert_password">cert_password.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKeyAutoCert(int? cert_ID, string cert_password, object ciphertext) => throw new InvalitContextException(nameof(DecryptByKeyAutoCert));
/// <summary>
/// DECRYPTBYKEYAUTOCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykeyautocert-transact-sql
/// </summary>
/// <param name="cert_ID">cert_ID.</param>
/// <param name="cert_password">cert_password.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="add_authenticator">add_authenticator.</param>
/// <param name="authenticator">authenticator.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByKeyAutoCert(int? cert_ID, string cert_password, object ciphertext, int add_authenticator, byte[] authenticator) => throw new InvalitContextException(nameof(DecryptByKeyAutoCert));
/// <summary>
/// DECRYPTBYPASSPHRASE.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbypassphrase-transact-sql
/// </summary>
/// <param name="passphrase">passphrase.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByPassphrase(string passphrase, string ciphertext) => throw new InvalitContextException(nameof(DecryptByPassphrase));
/// <summary>
/// DECRYPTBYPASSPHRASE.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbypassphrase-transact-sql
/// </summary>
/// <param name="passphrase">passphrase.</param>
/// <param name="ciphertext">ciphertext.</param>
/// <param name="add_authenticator">add_authenticator.</param>
/// <param name="authenticator">authenticator.</param>
/// <returns>decrypts data.</returns>
[FuncStyleConverter]
public static byte[] DecryptByPassphrase(string passphrase, string ciphertext, int add_authenticator, byte[] authenticator) => throw new InvalitContextException(nameof(DecryptByPassphrase));
/// <summary>
/// ENCRYPTBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbyasymkey-transact-sql
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="plaintext">plaintext.</param>
/// <returns>encrypts data.</returns>
[FuncStyleConverter]
public static byte[] EncryptByAsymKey(int? Asym_Key_ID, string plaintext) => throw new InvalitContextException(nameof(EncryptByAsymKey));
/// <summary>
/// ENCRYPTBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbycert-transact-sql
/// </summary>
/// <param name="certificate_ID">certificate_ID.</param>
/// <param name="plaintext">plaintex.t</param>
/// <returns>encrypts data.</returns>
[FuncStyleConverter]
public static byte[] EncryptByCert(int? certificate_ID, string plaintext) => throw new InvalitContextException(nameof(EncryptByCert));
/// <summary>
/// ENCRYPTBYKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbykey-transact-sql
/// </summary>
/// <param name="key_GUID">key_GUID.</param>
/// <param name="param">add_authenticator or authenticator.</param>
/// <returns>encrypts data.</returns>
[FuncStyleConverter]
public static byte[] EncryptByKey(object key_GUID, object param) => throw new InvalitContextException(nameof(EncryptByKey));
/// <summary>
/// ENCRYPTBYPASSPHRASE.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbypassphrase-transact-sql
/// </summary>
/// <param name="passphrase">passphrase.</param>
/// <param name="cleartext">cleartext.</param>
/// <returns>encrypts data.</returns>
[FuncStyleConverter]
public static byte[] EncryptByPassphrase(string passphrase, string cleartext) => throw new InvalitContextException(nameof(EncryptByPassphrase));
/// <summary>
/// ENCRYPTBYPASSPHRASE.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbypassphrase-transact-sql
/// </summary>
/// <param name="passphrase">passphrase.</param>
/// <param name="cleartext">cleartext.</param>
/// <param name="add_authenticator">add_authenticator.</param>
/// <param name="authenticator">authenticator.</param>
/// <returns>encrypts data.</returns>
[FuncStyleConverter]
public static byte[] EncryptByPassphrase(string passphrase, string cleartext, int add_authenticator, byte[] authenticator) => throw new InvalitContextException(nameof(EncryptByPassphrase));
/// <summary>
/// HASHBYTES.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/hashbytes-transact-sql
/// </summary>
/// <param name="algorithm">algorithm.</param>
/// <param name="input">input.</param>
/// <returns>hash.</returns>
[FuncStyleConverter]
public static byte[] HashBytes(string algorithm, object input) => throw new InvalitContextException(nameof(HashBytes));
/// <summary>
/// IS_OBJECTSIGNED.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/is-objectsigned-transact-sql
/// </summary>
/// <param name="obj">obj.</param>
/// <param name="object_id">object_id.</param>
/// <param name="class">class.</param>
/// <param name="param">param.</param>
/// <returns>Indicates whether an object is signed by a specified certificate or asymmetric key.</returns>
[FuncStyleConverter]
public static byte[] Is_ObjectSigned(string obj, int? object_id, object @class, object param) => throw new InvalitContextException(nameof(Is_ObjectSigned));
/// <summary>
/// Key_GUID.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/key-guid-transact-sql
/// </summary>
/// <returns>the GUID of a symmetric key in the database.</returns>
[FuncStyleConverter]
public static object Key_Guid(string Key_Name) => throw new InvalitContextException(nameof(Key_Guid));
/// <summary>
/// KEY_ID.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/key-id-transact-sql
/// </summary>
/// <param name="Key_Name">Key_Name.</param>
/// <returns>id.</returns>
[FuncStyleConverter]
public static int? Key_Id(string Key_Name) => throw new InvalitContextException(nameof(Key_Id));
/// <summary>
/// KEY_NAME.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/key-name-transact-sql
/// </summary>
/// <param name="param">ciphertext or key_guid.</param>
/// <returns>name.</returns>
[FuncStyleConverter]
public static string Key_Name(object param) => throw new InvalitContextException(nameof(Key_Name));
/// <summary>
/// SIGNBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/signbyasymkey-transact-sql
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="plaintext">plaintext.</param>
/// <returns>bytes.</returns>
[FuncStyleConverter]
public static byte[] SignByAsymKey(int? Asym_Key_ID, string plaintext) => throw new InvalitContextException(nameof(SignByAsymKey));
/// <summary>
/// SIGNBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/signbyasymkey-transact-sql
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="plaintext">plaintext.</param>
/// <param name="password">password.</param>
/// <returns>bytes.</returns>
[FuncStyleConverter]
public static byte[] SignByAsymKey(int? Asym_Key_ID, string plaintext, string password) => throw new InvalitContextException(nameof(SignByAsymKey));
/// <summary>
/// SIGNBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/signbycert-transact-sql
/// </summary>
/// <param name="certificate_ID">certificate_ID.</param>
/// <param name="plaintext">plaintext.</param>
/// <returns>bytes.</returns>
[FuncStyleConverter]
public static byte[] SignByCert(int? certificate_ID, string plaintext) => throw new InvalitContextException(nameof(SignByCert));
/// <summary>
/// SIGNBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/signbycert-transact-sql
/// </summary>
/// <param name="certificate_ID">certificate_ID.</param>
/// <param name="plaintext">plaintext.</param>
/// <param name="password">password.</param>
/// <returns>bytes.</returns>
[FuncStyleConverter]
public static byte[] SignByCert(int? certificate_ID, string plaintext, string password) => throw new InvalitContextException(nameof(SignByCert));
/// <summary>
/// SYMKEYPROPERTY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/symkeyproperty-transact-sql
/// </summary>
/// <param name="Key_ID">Key_ID.</param>
/// <param name="param">algorithm_desc or string_sid or sid.</param>
/// <returns>the algorithm of a symmetric key created from an EKM module.</returns>
[FuncStyleConverter]
public static object SymKeyProperty(int? Key_ID, string param) => throw new InvalitContextException(nameof(SymKeyProperty));
/// <summary>
/// VERIFYSIGNEDBYCERT.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/verifysignedbycert-transact-sql
/// </summary>
/// <param name="Cert_ID">Cert_ID.</param>
/// <param name="signed_data">signed_data.</param>
/// <param name="signature">signature.</param>
/// <returns>1 when signed data is unchanged; otherwise 0.</returns>
[FuncStyleConverter]
public static int VerifySignedByCert(int? Cert_ID, object signed_data, object signature) => throw new InvalitContextException(nameof(VerifySignedByCert));
/// <summary>
/// VERIFYSIGNEDBYASYMKEY.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/verifysignedbyasymkey-transact-sql
/// </summary>
/// <param name="Asym_Key_ID">Asym_Key_ID.</param>
/// <param name="clear_text">clear_text.</param>
/// <param name="signature">signature.</param>
/// <returns>1 when the signatures match; otherwise 0.</returns>
[FuncStyleConverter]
public static int VerifySignedByAsymKey(int? Asym_Key_ID, string clear_text, object signature) => throw new InvalitContextException(nameof(VerifySignedByAsymKey));
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Xml;
using System.Diagnostics;
namespace Nixxis.Client
{
public class BaseQualificationItem : IComparer<BaseQualificationItem>
{
private string m_Id;
private string m_Parent;
private string m_Description;
private int m_DisplayOrder;
private bool m_Argued;
private int m_Positive;
private bool m_PositiveUpdatable;
private int m_Action;
protected BaseQualificationItem()
{
}
internal BaseQualificationItem(string id, string description, string parent, int displayOrder, bool argued, int positive, bool positiveUpdatable, int action)
{
m_Id = id;
m_Description = description;
m_Parent = parent;
m_DisplayOrder = displayOrder;
m_Argued = argued;
m_Positive = positive;
m_PositiveUpdatable = positiveUpdatable;
m_Action = action;
}
internal BaseQualificationItem(BaseQualificationItem bqi)
{
m_Id = bqi.m_Id;
m_Description = bqi.m_Description;
m_Parent = bqi.Parent;
m_DisplayOrder = bqi.m_DisplayOrder;
m_Argued = bqi.m_Argued;
m_Positive = bqi.m_Positive;
m_PositiveUpdatable = bqi.m_PositiveUpdatable;
m_Action = bqi.m_Action;
}
public string Id
{
get
{
return m_Id;
}
}
internal string Parent
{
get
{
return m_Parent;
}
}
public string Description
{
get
{
return m_Description;
}
}
public bool Argued
{
get
{
return m_Argued;
}
}
public int Positive
{
get
{
return m_Positive;
}
}
public bool PositiveUpdatable
{
get
{
return m_PositiveUpdatable;
}
}
public int Action
{
get
{
return m_Action;
}
}
#region IComparer<BaseQualificationItem> Members
public int Compare(BaseQualificationItem x, BaseQualificationItem y)
{
return x.m_DisplayOrder.CompareTo(y.m_DisplayOrder);
}
#endregion
}
public class QualificationInfo : BaseQualificationItem
{
private class ActivityInfo
{
public string Id;
public int Revision;
public string QualificationId;
public DateTime LastUpdate = DateTime.Now;
internal QualificationInfo m_Q;
internal SortedDictionary<string, BaseQualificationItem> m_BaseQualifications = new SortedDictionary<string, BaseQualificationItem>();
}
private BaseQualificationItem m_bqi;
public BaseQualificationItem Qualification
{
get { return m_bqi; }
set { m_bqi = value; }
}
private static SortedDictionary<string, ActivityInfo> m_ActivityReferences = new SortedDictionary<string, ActivityInfo>();
public static QualificationInfo FromActivityId(HttpLink link, string activityId)
{
ActivityInfo A = null;
string ActivityKey = activityId;
int ActivityRevision = 0;
string QualificationId = string.Empty;
int Sep = activityId.IndexOf('.');
if (Sep > 0)
{
ActivityKey = activityId.Substring(0, Sep);
Int32.TryParse(activityId.Substring(Sep + 1), out ActivityRevision);
}
if (m_ActivityReferences.TryGetValue(activityId, out A))
{
m_ActivityReferences.Remove(activityId);
A = null;
}
if(A == null)
{
if (link != null)
{
ResponseData Data = link.GetResponseData(link.BuildRequest("~getinfo", null, string.Concat(((int)InfoCodes.Qualifications).ToString(), "\r\n", activityId)));
if (Data != null && Data.Valid)
{
A = new ActivityInfo();
foreach (KeyValuePair<string, string> Pair in Data)
{
if (Pair.Key.Equals("ActivityQualification"))
{
string[] Details = Pair.Value.Split(new char[] { ';' });
A.Id = Details[0];
if (Details.Length > 1)
A.QualificationId = Details[1];
else
A.QualificationId = string.Empty;
if (Details.Length > 2)
A.Revision = Convert.ToInt32(Details[2]);
else
A.Revision = ActivityRevision;
if (m_ActivityReferences.ContainsKey(A.Id))
m_ActivityReferences.Remove(A.Id);
m_ActivityReferences.Add(A.Id, A);
}
else if(Pair.Key.StartsWith("_"))
{
string[] Details = Pair.Value.Split(new char[] { ';' }, 10);
BaseQualificationItem QItem = new BaseQualificationItem(Pair.Key.Substring(1), Microsoft.JScript.GlobalObject.unescape(Details[9]), Details[1], Convert.ToInt32(Details[0]), (Convert.ToInt32(Details[2]) > 0), Convert.ToInt32(Details[3]), (Convert.ToInt32(Details[4]) > 0), Convert.ToInt32(Details[5]));
if (A.m_BaseQualifications.ContainsKey(QItem.Id))
A.m_BaseQualifications.Remove(QItem.Id);
A.m_BaseQualifications.Add(QItem.Id, QItem);
}
}
A.m_Q = new QualificationInfo(A.m_BaseQualifications[A.QualificationId]);
FillChildren(A, A.m_Q);
}
}
}
if (A == null)
return null;
return A.m_Q;
}
private static void FillChildren(ActivityInfo A, QualificationInfo parent)
{
parent.m_QualiChilds.Clear();
foreach (KeyValuePair<string, BaseQualificationItem> kvp in A.m_BaseQualifications)
{
if (kvp.Value.Parent == parent.Id)
{
QualificationInfo NewInfo = new QualificationInfo(kvp.Value);
parent.m_QualiChilds.Add(NewInfo);
FillChildren(A, NewInfo);
}
}
parent.m_QualiChilds.Sort(parent);
}
private List<BaseQualificationItem> m_QualiChilds = new List<BaseQualificationItem>();
public List<BaseQualificationItem> ListQualification
{
get { return m_QualiChilds; }
}
public static QualificationInfo FromActivityId(string activityId)
{
return FromActivityId(null, activityId);
}
private QualificationInfo(BaseQualificationItem bqi) : base(bqi)
{
}
public QualificationInfo()
{
}
}
public class ActivityInfo
{
private string m_ActivityId;
private string m_CampaignId;
private bool m_IsSearchMode;
private string m_Description;
private string m_CampaignDescription;
public ActivityInfo(string id, bool isSearchMode, string campaignId, string campaignDescription, string description)
{
m_ActivityId = id;
m_IsSearchMode = isSearchMode;
m_Description = description;
m_CampaignId = campaignId;
m_CampaignDescription = campaignDescription;
}
public string ActivityId
{
get
{
return m_ActivityId;
}
}
public bool IsSearchMode
{
get
{
return m_IsSearchMode;
}
}
public string CampaignId
{
get
{
return m_CampaignId;
}
}
public string Description
{
get
{
return m_Description;
}
}
public string CampaignDescription
{
get
{
return m_CampaignDescription;
}
}
public void InternalRefresh(bool isSearchMode, string description)
{
m_IsSearchMode = isSearchMode;
m_Description = description;
}
}
public class ActivityCollection : KeyedCollection<string, ActivityInfo>
{
protected override string GetKeyForItem(ActivityInfo item)
{
return item.ActivityId;
}
}
public class ExternalAgentInfo
{
public string AgentId { get; private set; }
public string Description { get; private set; }
public string Account { get; private set; }
public string State { get; private set; }
public ExternalAgentInfo(string agentId, string account, string description, string state)
{
AgentId = agentId;
Account = account;
Description = description;
State = state;
}
}
public class ExternalAgentCollection : KeyedCollection<string, ExternalAgentInfo>
{
protected override string GetKeyForItem(ExternalAgentInfo item)
{
return item.AgentId;
}
}
public class PauseCodeInfo
{
private string m_PauseCodeId;
private string m_Description;
public PauseCodeInfo(string pauseCodeId, string description)
{
m_PauseCodeId = pauseCodeId;
m_Description = description;
}
public string PauseCodeId
{
get
{
return m_PauseCodeId;
}
}
public string Description
{
get
{
return m_Description;
}
}
public void InternalRefresh(string description)
{
m_Description = description;
}
public override string ToString()
{
return Description;
}
}
public class PauseCodeCollection : KeyedCollection<string, PauseCodeInfo>
{
protected override string GetKeyForItem(PauseCodeInfo item)
{
return item.PauseCodeId;
}
}
public class ContactInfo : IContactInfo, IScriptControl2, INotifyPropertyChanged, IDisposable//, ITypedList
{
private string m_Id;
protected HttpLink m_ClientLink;
private bool m_RequestAgentAction = false;
private char m_MediaCode;
private char m_State;
private DateTime m_Appearance = DateTime.Now;
private DateTime m_LastStateChange;
private string m_ContactDuration, m_StateDuration;
private string m_From;
private string m_To;
private string m_UUI;
private string m_Language;
private string m_Activity;
private string m_Queue;
private string m_Direction;
private string m_Context;
private string m_Script;
private string m_CustomerId;
private string m_CustomerDescription;
private string m_ContactListId;
private string m_ContentLink;
private int m_ContentType;
private string m_ContentHandler;
private string m_Campaign;
private ContactHistory m_History;
private SendOrPostCallback m_SendOrPostPropertyChanged;
public bool RequestAgentAction
{
get
{
return m_RequestAgentAction;
}
set
{
m_RequestAgentAction = value; OnPropertyChanged(new PropertyChangedEventArgs("RequestAgentAction"));
}
}
public string ContentHandler
{
get
{
return m_ContentHandler;
}
set
{
m_ContentHandler = value;
OnPropertyChanged(new PropertyChangedEventArgs("ContentHandler"));
}
}
public string ContentLink
{
get
{
return m_ContentLink;
}
set
{
m_ContentLink = value;
OnPropertyChanged(new PropertyChangedEventArgs("ContentLink"));
}
}
// 0 = Default
// 1 = Chat | 64 = SMS alphabet & size
// | 128 = SMS x 3
//
public int ContentType
{
get
{
return m_ContentType;
}
set
{
m_ContentType = value;
OnPropertyChanged(new PropertyChangedEventArgs("ContentType"));
}
}
public string ContactListId
{
get
{
return m_ContactListId;
}
internal set
{
m_ContactListId = value;
OnPropertyChanged(new PropertyChangedEventArgs("ContactListId"));
}
}
public string Campaign
{
get
{
return m_Campaign;
}
internal set
{
m_Campaign = value;
OnPropertyChanged(new PropertyChangedEventArgs("Campaign"));
}
}
private object m_UserData;
private ContactInfo()
{
}
public ContactInfo(HttpLink clientLink, char media, string id, string script = null)
{
m_ClientLink = clientLink;
m_MediaCode = media;
m_State = ' ';
m_Id = id;
m_LastStateChange = DateTime.Now;
m_Script = script;
m_SendOrPostPropertyChanged = new SendOrPostCallback(SendOrPostPropertyChanged);
}
protected ContactInfo(ContactInfo cinfo) : this(cinfo.m_ClientLink, cinfo.MediaCode, cinfo.Id)
{
this.Update(cinfo);
}
public string Id
{
get
{
return m_Id;
}
internal set
{
m_Id = value;
OnPropertyChanged(new PropertyChangedEventArgs("Id"));
}
}
public char MediaCode
{
get
{
return m_MediaCode;
}
internal set
{
m_MediaCode = value;
OnPropertyChanged(new PropertyChangedEventArgs("MediaCode"));
OnPropertyChanged(new PropertyChangedEventArgs("Media"));
}
}
public ContactMedia Media
{
get
{
switch (m_MediaCode)
{
case 'V':
return ContactMedia.Voice;
case 'M':
return ContactMedia.Mail;
case 'C':
return ContactMedia.Chat;
}
return ContactMedia.Unknown;
}
}
public char State
{
get
{
return m_State;
}
internal set
{
if (m_State != value)
{
m_State = value;
m_LastStateChange = DateTime.Now;
OnPropertyChanged(new PropertyChangedEventArgs("State"));
OnPropertyChanged(new PropertyChangedEventArgs("StateDescription"));
OnPropertyChanged(new PropertyChangedEventArgs("LastStateChange"));
OnPropertyChanged(new PropertyChangedEventArgs("StateDuration"));
}
}
}
public string StateDescription
{
get
{
switch (m_State)
{
case 'A':
return Strings.ContactState_Alerting;
case 'P':
return Strings.ContactState_Preview;
case 'C':
return Strings.ContactState_Connected;
case 'D':
return Strings.ContactState_Disconnected;
case 'X':
return Strings.ContactState_Closing;
case 'H':
return Strings.ContactState_OnHold;
}
return m_State.ToString();
}
}
internal void TimerCallbackHandler(object state)
{
string Elapsed = DateTime.Now.Subtract(m_Appearance).ToString("hh\\:mm\\:ss");
if (m_ContactDuration != Elapsed)
{
m_ContactDuration = Elapsed;
OnPropertyChanged(new PropertyChangedEventArgs("ContactDuration"));
}
Elapsed = DateTime.Now.Subtract(m_LastStateChange).ToString("hh\\:mm\\:ss");
if (m_StateDuration != Elapsed)
{
m_StateDuration = Elapsed;
OnPropertyChanged(new PropertyChangedEventArgs("StateDuration"));
}
}
public string ContactDuration
{
get
{
return m_ContactDuration;
}
}
public string StateDuration
{
get
{
return m_StateDuration;
}
}
public DateTime LastStateChange
{
get
{
return m_LastStateChange;
}
}
public DateTime Appearance
{
get
{
return m_Appearance;
}
}
public string From
{
get
{
return m_From;
}
internal set
{
m_From = value;
OnPropertyChanged(new PropertyChangedEventArgs("From"));
}
}
public string To
{
get
{
return m_To;
}
internal set
{
m_To = value;
OnPropertyChanged(new PropertyChangedEventArgs("To"));
}
}
public string UUI
{
get
{
return m_UUI;
}
internal set
{
m_UUI = value;
OnPropertyChanged(new PropertyChangedEventArgs("UUI"));
}
}
public string Language
{
get
{
return m_Language;
}
internal set
{
m_Language = value;
OnPropertyChanged(new PropertyChangedEventArgs("Language"));
}
}
public string Activity
{
get
{
return m_Activity;
}
internal set
{
m_Activity = value;
OnPropertyChanged(new PropertyChangedEventArgs("Activity"));
}
}
public string Queue
{
get
{
return m_Queue;
}
internal set
{
m_Queue = value;
OnPropertyChanged(new PropertyChangedEventArgs("Queue"));
}
}
public string Direction
{
get
{
return m_Direction;
}
internal set
{
m_Direction = value;
OnPropertyChanged(new PropertyChangedEventArgs("Direction"));
}
}
public string Context
{
get
{
return m_Context;
}
internal set
{
m_Context = value;
OnPropertyChanged(new PropertyChangedEventArgs("Context"));
}
}
public string Script
{
get
{
return m_Script;
}
internal set
{
m_Script = value;
OnPropertyChanged(new PropertyChangedEventArgs("Script"));
}
}
public string CustomerId
{
get
{
return m_CustomerId;
}
internal set
{
m_CustomerId = value;
OnPropertyChanged(new PropertyChangedEventArgs("CustomerId"));
}
}
public string CustomerDescription
{
get
{
return m_CustomerDescription;
}
internal set
{
m_CustomerDescription = value;
OnPropertyChanged(new PropertyChangedEventArgs("CustomerDescription"));
}
}
public void SetCustomerId(string customerId)
{
m_CustomerId = customerId;
m_ClientLink.SetCustomerId(m_Id, customerId);
OnPropertyChanged(new PropertyChangedEventArgs("CustomerId"));
if (ContactContentChanged != null)
{
try
{
ContactContentChanged(this);
}
catch
{
}
}
}
public void SetCustomerDescription(string customerDescription)
{
m_CustomerDescription = customerDescription;
m_ClientLink.SetCustomerDescription(m_Id, customerDescription);
OnPropertyChanged(new PropertyChangedEventArgs("CustomerDescription"));
if (ContactContentChanged != null)
{
try
{
ContactContentChanged(this);
}
catch
{
}
}
}
public void SetContactListId(string id)
{
m_ContactListId = id;
m_ClientLink.SetContactListId(m_Id, id);
OnPropertyChanged(new PropertyChangedEventArgs("ContactListId"));
if (ContactContentChanged != null)
{
try
{
ContactContentChanged(this);
}
catch
{
}
}
}
public string GetPrivateInfo(string key)
{
ResponseData Data = m_ClientLink.GetResponseData(m_ClientLink.BuildRequest("~getinfo&fmt=uri", null, string.Concat(((int)InfoCodes.ContactProperty).ToString(), "\r\n", m_Id, "\r\n", key)));
if (Data != null && Data.Valid)
{
foreach (string Key in Data.Keys)
return Key;
return "";
}
return null;
}
public void SetPrivateInfo(string key, string value)
{
ResponseData Data = m_ClientLink.GetResponseData(m_ClientLink.BuildRequest("~setinfo&fmt=uri", null, string.Concat(((int)InfoCodes.ContactProperty).ToString(), "\r\n", m_Id, "\r\n", key, "\r\n", Microsoft.JScript.GlobalObject.escape(value))));
}
public System.Xml.XmlDocument GetContextData()
{
return GetContextData(0);
}
public System.Xml.XmlDocument GetContextData(int historyLength)
{
ResponseData Data = m_ClientLink.GetResponseData(m_ClientLink.BuildRequest("~getinfo&fmt=uri", null, string.Concat(((int)InfoCodes.ContextData).ToString(), "\r\n", m_Id, "\r\n", historyLength.ToString())), true);
if (Data != null && Data.Valid && !string.IsNullOrEmpty(Data.RawResponse))
{
System.Xml.XmlDocument Doc = new System.Xml.XmlDocument();
try
{
Doc.LoadXml(Data.RawResponse);
}
catch
{
Doc = null;
}
return Doc;
}
return null;
}
public System.Xml.XmlDocument UpdateContextData(System.Xml.XmlDocument data)
{
return UpdateContextData(data.OuterXml);
}
public System.Xml.XmlDocument UpdateContextData(string data)
{
ResponseData Data = m_ClientLink.GetResponseData(m_ClientLink.BuildRequest("~setinfo&fmt=uri", null, string.Concat(((int)InfoCodes.ContextData).ToString(), "\r\n", m_Id, "\r\n", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(data)))), true);
if (Data != null && Data.Valid && !string.IsNullOrEmpty(Data.RawResponse))
{
System.Xml.XmlDocument Doc = new System.Xml.XmlDocument();
try
{
Doc.LoadXml(Data.RawResponse);
}
catch
{
Doc = null;
}
return Doc;
}
return null;
}
public ContactHistory GetHistory()
{
if (m_History != null && m_History.Count > 0)
return m_History;
XmlDocument doc = GetContextData(100);
m_History = new ContactHistory();
if (doc != null)
{
XmlNode mainNode = doc.SelectSingleNode(@"contextdata/history");
if (mainNode != null)
{
foreach (XmlNode historyItem in mainNode.ChildNodes)
{
if (historyItem.Name.Equals("contact", StringComparison.InvariantCultureIgnoreCase))
{
ContactHistoryItem history = new ContactHistoryItem();
history.CurrentContactId = this.Id;
history.ContactId = historyItem.Attributes["id"] == null ? string.Empty : historyItem.Attributes["id"].Value;
if (!string.IsNullOrEmpty(history.ContactId))
{
foreach (XmlNode item in historyItem.ChildNodes)
{
#region XML Info
try
{
if (item.Name.Equals("ContactId", StringComparison.InvariantCultureIgnoreCase))
{
history.ContactId = item.InnerXml;
}
else if (item.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase))
{
history.ContactId = item.InnerXml;
}
else if (item.Name.Equals("LocalDateTime", StringComparison.InvariantCultureIgnoreCase))
{
history.LocalDateTime = DateTime.Parse(item.InnerXml);
}
else if (item.Name.Equals("ContactTime", StringComparison.InvariantCultureIgnoreCase))
{
history.ContactTime = item.InnerXml;
}
else if (item.Name.Equals("Media", StringComparison.InvariantCultureIgnoreCase))
{
history.Media = item.InnerXml;
}
else if (item.Name.Equals("Direction", StringComparison.InvariantCultureIgnoreCase))
{
history.Direction = item.InnerXml;
}
else if (item.Name.Equals("SetupTime", StringComparison.InvariantCultureIgnoreCase))
{
history.SetupTime = new TimeSpan(0, 0, int.Parse(item.InnerXml));
}
else if (item.Name.Equals("ComTime", StringComparison.InvariantCultureIgnoreCase))
{
history.ComTime = new TimeSpan(0, 0, int.Parse(item.InnerXml));
}
else if (item.Name.Equals("QueueTime", StringComparison.InvariantCultureIgnoreCase))
{
history.QueueTime = new TimeSpan(0, 0, int.Parse(item.InnerXml));
}
else if (item.Name.Equals("TalkTime", StringComparison.InvariantCultureIgnoreCase))
{
history.TalkTime = new TimeSpan(0, 0, int.Parse(item.InnerXml));
}
else if (item.Name.Equals("Activity", StringComparison.InvariantCultureIgnoreCase))
{
history.Activity = item.InnerXml;
history.ActivityId = item.Attributes["id"].Value;
}
else if (item.Name.Equals("Qualification", StringComparison.InvariantCultureIgnoreCase))
{
history.Qualification = item.InnerXml;
history.QualificationId = item.Attributes["id"] == null ? string.Empty : item.Attributes["id"].Value;
}
else if (item.Name.Equals("QualifiedBy", StringComparison.InvariantCultureIgnoreCase))
{
history.QualifiedBy = item.InnerXml;
history.QualifiedById = item.Attributes["id"] == null ? string.Empty : item.Attributes["id"].Value;
}
else if (item.Name.Equals("Recording", StringComparison.InvariantCultureIgnoreCase))
{
history.RecordingId = item.Attributes["id"] == null ? string.Empty : item.Attributes["id"].Value;
history.RecordingMarker = new TimeSpan(0, 0, 0, 0, int.Parse(item.Attributes["marker"] == null ? "0" : item.Attributes["marker"].Value));
}
}
catch (Exception error)
{
System.Diagnostics.Trace.WriteLine("Error processing XML for history of contact: " + error.ToString());
}
#endregion
}
m_History.Add(history);
}
}
}
}
}
return m_History;
}
public object UserData
{
get
{
return m_UserData;
}
set
{
m_UserData = value;
OnPropertyChanged(new PropertyChangedEventArgs("UserData"));
}
}
public virtual bool Update(ContactInfo newInfo)
{
bool Updated = false;
bool IsPreview = (m_State == 'P') ? true : false;
if (newInfo.From != null && newInfo.From != this.From)
{
m_From = newInfo.From;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("From"));
}
if (newInfo.To != null && newInfo.To != this.To)
{
m_To = newInfo.To;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("To"));
}
if (newInfo.UUI != null && newInfo.UUI != this.UUI)
{
m_UUI = newInfo.UUI;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("UUI"));
}
if (newInfo.Language != null && newInfo.Language != this.Language)
{
m_Language = newInfo.Language;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Language"));
}
if (newInfo.Activity != null && newInfo.Activity != this.Activity)
{
if (!IsPreview)
{
m_Activity = newInfo.Activity;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Activity"));
}
}
if (newInfo.Queue != null && newInfo.Queue != this.Queue)
{
m_Queue = newInfo.Queue;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Queue"));
}
if (newInfo.Direction != null && newInfo.Direction != this.Direction)
{
m_Direction = newInfo.Direction;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Direction"));
}
if (newInfo.Context != null && newInfo.Context != this.Context)
{
m_Context = newInfo.Context;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Context"));
}
if (newInfo.Script != null && newInfo.Script != this.Script)
{
m_Script = newInfo.Script;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Script"));
}
if (newInfo.ContentLink != null && newInfo.ContentLink != this.ContentLink)
{
m_ContentLink = newInfo.ContentLink;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("ContentLink"));
}
if (newInfo.ContentHandler != null && newInfo.ContentHandler != this.ContentHandler)
{
m_ContentHandler = newInfo.ContentHandler;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("ContentHandler"));
}
if (newInfo.ContentType != 0 && newInfo.ContentType != this.ContentType)
{
m_ContentType = newInfo.ContentType;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("ContentType"));
}
if (newInfo.ContactListId != null && newInfo.ContactListId != this.ContactListId)
{
m_ContactListId = newInfo.ContactListId;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("ContactListId"));
}
if (newInfo.CustomerId != null && newInfo.CustomerId != this.CustomerId)
{
m_CustomerId = newInfo.CustomerId;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("CustomerId"));
}
if (newInfo.CustomerDescription != null && newInfo.CustomerDescription != this.CustomerDescription)
{
m_CustomerDescription = newInfo.CustomerDescription;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("CustomerDescription"));
}
if (string.IsNullOrEmpty(m_CustomerDescription) && !string.IsNullOrEmpty(m_CustomerId))
{
m_CustomerDescription = m_CustomerId;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("CustomerDescription"));
}
if (newInfo.Campaign != null && newInfo.Campaign != this.Campaign)
{
if (!IsPreview)
{
m_Campaign = newInfo.Campaign;
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Campaign"));
}
}
if (string.IsNullOrWhiteSpace(m_Script) && m_Direction == "O" && (string.IsNullOrWhiteSpace(m_Activity) || m_Activity.Length < 32) && !string.IsNullOrWhiteSpace(m_ClientLink.ClientSettings["manualCallScript"]))
{
m_Script = m_ClientLink.ClientSettings["manualCallScript"];
Updated = true;
OnPropertyChanged(new PropertyChangedEventArgs("Script"));
}
if (Updated)
{
if (ContactContentChanged != null)
{
try
{
ContactContentChanged(this);
}
catch
{
}
}
}
return Updated;
}
#region IScriptControl2 Members
public bool NewCall(string destination, ContactMedia media)
{
return NewCall(destination, media, null, null, null, null, null);
}
public bool NewCall(string destination, ContactMedia media, string contactId, string activity, string customerId, string contactListId, string onBehalfOf)
{
switch (media)
{
case ContactMedia.Voice:
System.Diagnostics.Debug.WriteLine(string.Format("New call to {0} for contact {1}", destination, contactId), "Scripting");
m_ClientLink.Commands.VoiceNewCall.Execute(
destination,
contactId,
(string.IsNullOrEmpty(activity)) ? null : string.Concat("AcId=", activity),
(string.IsNullOrEmpty(customerId)) ? null : string.Concat("CuId=", customerId),
(string.IsNullOrEmpty(contactListId)) ? null : string.Concat("LiId=", contactListId),
(string.IsNullOrEmpty(onBehalfOf)) ? null : string.Concat("OnBehalf=", onBehalfOf));
return true;
}
return false;
}
public bool Redial(string destination)
{
return NewCall(destination, this.Media, this.Id, this.Activity, this.CustomerId, this.ContactListId, null);
}
public bool SetTextContent(string content)
{
if (Media == ContactMedia.Mail)
{
throw new NotImplementedException();
}
return false;
}
public string GetTextContent()
{
if (Media == ContactMedia.Mail)
{
throw new NotImplementedException();
}
return null;
}
public bool Close(bool sendTextContent)
{
if (Media == ContactMedia.Mail && sendTextContent)
{
throw new NotImplementedException();
}
m_ClientLink.Commands.TerminateContact.Execute(m_Id);
return true;
}
public bool Close(bool sendTextContent, TerminateBehavior terminateBehavior)
{
if (terminateBehavior == TerminateBehavior.ForcePause)
m_ClientLink.Commands.Pause.Execute();
m_ClientLink.Commands.TerminateContact.Execute(m_Id);
if (terminateBehavior == TerminateBehavior.ForceReady && m_ClientLink.AutoReady < 0)
{
m_ClientLink.Commands.WaitForCall.Execute();
m_ClientLink.Commands.WaitForChat.Execute();
m_ClientLink.Commands.WaitForMail.Execute();
}
return true;
}
public IAgentInfo AgentInfo
{
get
{
return m_ClientLink;
}
}
public IScriptContainer ScriptContainer
{
get
{
return m_ClientLink.EventControl as IScriptContainer;
}
}
public System.Collections.Specialized.NameValueCollection ClientSettings
{
get
{
return m_ClientLink.ClientSettings;
}
}
public event ContactContentChangedDelegate ContactContentChanged;
#endregion
#region IScriptControl Members
public bool NewCall(string destination)
{
return NewCall(destination, ContactMedia.Voice, null, null, null, null, null);
}
public bool Hold()
{
switch (Media)
{
case ContactMedia.Voice:
m_ClientLink.Commands.VoiceHold.Execute(Id);
return true;
case ContactMedia.Chat:
m_ClientLink.Commands.ChatHold.Execute(Id);
return true;
}
return false;
}
public bool Retrieve()
{
switch (Media)
{
case ContactMedia.Voice:
m_ClientLink.Commands.VoiceRetrieve.Execute(Id);
return true;
case ContactMedia.Chat:
m_ClientLink.Commands.ChatRetrieve.Execute(Id);
return true;
}
return false;
}
public bool Hangup()
{
switch (Media)
{
case ContactMedia.Voice:
m_ClientLink.Commands.VoiceHangup.Execute(Id);
return true;
case ContactMedia.Chat:
m_ClientLink.Commands.ChatHangup.Execute(Id);
return true;
}
return false;
}
public bool Transfer()
{
switch (Media)
{
case ContactMedia.Voice:
m_ClientLink.Commands.VoiceTransfer.Execute(Id);
return true;
}
return false;
}
public bool Transfer(TransferFailureBehavior failureBehavior)
{
return Transfer();
}
public bool Forward(string destination)
{
switch (Media)
{
case ContactMedia.Voice:
m_ClientLink.Commands.VoiceForward.Execute(destination, Id);
return true;
case ContactMedia.Chat:
m_ClientLink.Commands.ChatForward.Execute(destination, Id);
return true;
case ContactMedia.Mail:
m_ClientLink.Commands.MailForward.Execute(destination, Id);
return true;
}
return false;
}
public bool Forward(string destination, TransferFailureBehavior failureBehavior)
{
return Forward(destination);
}
public bool Qualify(QualificationInfo qualification)
{
m_ClientLink.SetQualification(Id, qualification.Id, null, null);
return true;
}
public bool Qualify(string qualificationId)
{
m_ClientLink.SetQualification(Id, qualificationId, null, null);
return true;
}
public bool Qualify(string qualificationId, DateTime callbackTime, string callbackNumber)
{
m_ClientLink.SetQualification(Id, qualificationId, callbackTime.ToString("yyyyMMddHHmm"), callbackNumber);
return true;
}
public bool Close()
{
return Close(false);
}
public bool Close(TerminateBehavior terminateBehavior)
{
return Close(false, terminateBehavior);
}
public event ContactStateChangedDelegate ContactStateChanged;
#endregion
protected void SendOrPostPropertyChanged(object state)
{
if(PropertyChanged != null)
{
PropertyChanged(this, (PropertyChangedEventArgs)state);
}
}
protected void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
m_ClientLink.Invoke(PropertyChanged, this, args);
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void Dispose()
{
}
}
public class ContactInfoText : ContactInfo
{
protected PredefinedTextCollection m_PredefinedTextCollection;
public ContactInfoText(ContactInfo cinfo): base(cinfo)
{
}
public PredefinedTextCollection PredefinedTexts
{
get
{
if (m_PredefinedTextCollection == null)
{
m_PredefinedTextCollection = m_ClientLink.GetPredefinedTexts(Activity);
}
return m_PredefinedTextCollection;
}
}
}
public class ContactInfoVoice : ContactInfo
{
public ContactInfoVoice(ContactInfo cinfo): base(cinfo)
{
this.Update(cinfo);
}
}
public class ContactInfoMail : MailMessage
{
public ContactInfoMail(ContactInfo cinfo)
: base(cinfo)
{ }
}
public class MailMessage : ContactInfoText
{
private string m_MailReceivedText;
private string m_MailToStartReplyText;
private string m_MailCreationTime;
private System.Collections.Specialized.NameValueCollection m_ResponseData = new System.Collections.Specialized.NameValueCollection();
private List<ReceivedAttachmentItem> m_Attachments=null;
public List<ReceivedAttachmentItem> InfosAttachments { get { return m_Attachments; } }
public bool IsFakeMail { get; internal set; }
public MailMessage Message
{
get
{
return this;
}
}
public MailMessage(ContactInfo cinfo): base(cinfo)
{
if ((cinfo.ContentType & 1) == 1)
{
IsFakeMail = true;
}
else
{
this.Subject = this.UUI;
string[] urlsplit = m_ClientLink.BaseUri.AbsoluteUri.Split('/');
string url = urlsplit[0] + "//" + urlsplit[2] + ContentLink;
HttpWebRequest wr;
wr = WebRequest.Create(url + "responsedata") as HttpWebRequest;
wr.Method = "GET";
try
{
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
{
using (Stream objStream = response.GetResponseStream())
{
string[] DataParts = new StreamReader(objStream).ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string DataPart in DataParts)
{
string[] ValueParts = DataPart.Split(new char[] { '=' }, 2);
if (ValueParts.Length == 2)
{
m_ResponseData.Add(ValueParts[0], ValueParts[1]);
}
}
}
}
}
catch (Exception e)
{
}
wr = WebRequest.Create(url + "draft2") as HttpWebRequest;
wr.Method = "GET";
try
{
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
{
using (Stream objStream = response.GetResponseStream())
{
string[] DraftParts = new StreamReader(objStream).ReadToEnd().Split(new char[] { '/' }, 2);
if (!string.IsNullOrEmpty(DraftParts[0]))
{
string[] AttList = DraftParts[0].Split(',');
foreach (string AttId in AttList)
{
int Pos = AttId.IndexOf(':');
if (Pos > 0)
{
AttachmentItem Item = new AttachmentItem();
Item.Id = AttId.Substring(0, Pos);
Item.DescriptionAttachment = AttId.Substring(Pos + 1);
Item.InitialChecked = true;
AttachCollection.Insert(0, Item);
}
else
{
foreach (AttachmentItem Item in AttachCollection)
{
if (Item.Id == AttId)
Item.InitialChecked = true;
}
}
}
}
m_MailToStartReplyText = DraftParts[1];
}
}
}
catch (Exception e)
{
}
CreateInfosAttachments();
}
this.Update(cinfo);
}
public System.Collections.Specialized.NameValueCollection ResponseData
{
get
{
return m_ResponseData;
}
}
private void CreateInfosAttachments()
{
if (m_Attachments == null)
{
m_Attachments = new List<ReceivedAttachmentItem>();
string[] urlsplit = m_ClientLink.BaseUri.AbsoluteUri.Split('/');
string UrlMailData = urlsplit[0] + "//" + urlsplit[2] + ContentLink + "data";
HttpWebRequest wr = WebRequest.Create(UrlMailData) as HttpWebRequest;
wr.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
try
{
using (Stream objStream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(objStream);
while (!sr.EndOfStream)
{
string[] data = sr.ReadLine().Split('=');
if (data[0] == "attachment")
{
ReceivedAttachmentItem attItem = new ReceivedAttachmentItem();
string[] TabAtt = data[1].Split('&');
attItem.Id = TabAtt[0];
attItem.FileName = Microsoft.JScript.GlobalObject.unescape(TabAtt[1]);
m_Attachments.Add(attItem);
}
}
}
}
finally
{
response.Close();
}
}
catch (Exception e)
{
}
}
}
private AttachmentCollection m_AttachmentCollection;
public string Subject { get; internal set; }
public string MailCreationTime
{
get
{
if (IsFakeMail)
return "";
if (m_MailCreationTime == null)
{
string[] urlsplit = m_ClientLink.BaseUri.AbsoluteUri.Split('/');
string UrlMailData = urlsplit[0] + "//" + urlsplit[2] + ContentLink + "data";
HttpWebRequest wr = WebRequest.Create(UrlMailData) as HttpWebRequest;
wr.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
try
{
using (Stream objStream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(objStream);
while (!sr.EndOfStream)
{
string[] data = sr.ReadLine().Split('=');
if (data[0] == "CreationTime")
{
m_MailCreationTime = Microsoft.JScript.GlobalObject.unescape(data[1]);
}
}
}
}
finally
{
response.Close();
}
}
catch (Exception e)
{
}
}
return m_MailCreationTime;
}
}
public string MailToStartReplyText
{
get
{
if (IsFakeMail)
return "";
if (m_MailToStartReplyText == null)
{
//TO BE DONE ON THE SERVER SIDE BECAUSE NOW THE URL RETURN A BAD FORMAT
}
return m_MailToStartReplyText;
}
}
public string MailReceivedText
{
get
{
if (IsFakeMail)
return "";
if (m_MailReceivedText == null)
{
string[] urlsplit = m_ClientLink.BaseUri.AbsoluteUri.Split('/');
string url= urlsplit[0]+"//"+urlsplit[2]+ ContentLink + "htmlbody";
HttpWebRequest wr = WebRequest.Create(url) as HttpWebRequest;
wr.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
try
{
using (Stream objStream = response.GetResponseStream())
{
m_MailReceivedText = new StreamReader(objStream).ReadToEnd();
}
}
finally
{
response.Close();
}
}
catch (Exception e)
{
}
}
return m_MailReceivedText;
}
}
public AttachmentCollection AttachCollection
{
get
{
if (IsFakeMail)
return null;
if (m_AttachmentCollection == null)
{
m_AttachmentCollection = m_ClientLink.GetAttachments(Activity);
}
return m_AttachmentCollection;
}
}
#region Added by Tom
public string OriginalMessageUrl
{
get
{
string[] urlsplit = m_ClientLink.BaseUri.AbsoluteUri.Split('/');
return urlsplit[0] + "//" + urlsplit[2] + ContentLink + "htmlbody";
}
}
public string ReplyTo
{
get
{
return this.ResponseData["To"] ?? this.From;
}
set
{
if (this.ResponseData["To"] == null)
this.ResponseData.Add("To", value);
else
this.ResponseData["To"] = value;
}
}
public string ReplyFrom
{
get
{
return this.ResponseData["From"] ?? this.To;
}
set
{
if (this.ResponseData["From"] == null)
this.ResponseData.Add("From", value);
else
this.ResponseData["From"] = value;
}
}
public string ReplySubject
{
get
{
return this.ResponseData["Subject"] ?? "RE: " + this.Subject;
}
set
{
if (this.ResponseData["Subject"] == null)
this.ResponseData.Add("Subject", value);
else
this.ResponseData["Subject"] = value;
}
}
#endregion
}
public class ContactInfoChat : ContactInfoText
{
private ChatConversation m_Conversation;
public ChatConversation Conversation
{
get { return m_Conversation; }
}
public ContactInfoChat(ContactInfo cinfo): base(cinfo)
{
}
public override bool Update(ContactInfo newInfo)
{
bool Result = base.Update(newInfo);
if (m_Conversation == null && !string.IsNullOrEmpty(this.ContentLink))
{
string ConversationId = string.Empty;
int ConvIndex = this.ContentLink.IndexOf("conversationid=", StringComparison.OrdinalIgnoreCase);
if (ConvIndex >= 0)
{
int ConvEnd = this.ContentLink.IndexOf('&', ConvIndex);
if (ConvEnd >= 0)
ConversationId = this.ContentLink.Substring(ConvIndex + 15, ConvEnd - (ConvIndex + 15));
else
ConversationId = this.ContentLink.Substring(ConvIndex + 15);
}
m_Conversation = new ChatConversation(m_ClientLink.LinkNetworkType, new Uri(m_ClientLink.BaseUri, this.ContentLink).ToString(), ConversationId, m_ClientLink.AgentId, m_ClientLink.SyncContext);
m_Conversation.Join();
}
else if (m_Conversation == null) ContactRoute.DiagnosticHelpers.DebugIfPossible();
return Result;
}
public override void Dispose()
{
if (State == 'X' && m_Conversation != null)
{
m_Conversation.Close();
m_Conversation = null;
}
base.Dispose();
}
public void Say(string message)
{
m_Conversation.Say(message);
}
public void Leave()
{
m_Conversation.Leave(null);
}
}
public delegate void AddChatMessageHandler(int lineType, string from, string to, string message);
public class PredefinedTextItem
{
private string m_Id;
public string Id
{
get { return m_Id; }
set { m_Id = value; }
}
private string m_Text;
public string Text
{
get { return m_Text; }
set { m_Text = value; }
}
private string m_FullText;
public string FullText
{
get { return m_FullText; }
set { m_FullText = value; }
}
public PredefinedTextItem()
{
}
}
public class AttachmentItem
{
public string Id { get; internal set; }
public string DescriptionAttachment { get; internal set; }
public string CampaignId { get; internal set; }
public int CompatibleMedias { get; internal set; }
public string Language { get; internal set; }
public string Location { get; internal set; }
public bool LocationIsLocal { get; internal set; }
public bool InlineDisposition { get; internal set; }
public string Target { get; internal set; }
public bool InitialChecked { get; internal set; }
public AttachmentItem()
{
}
public AttachmentItem(string localFile)
{
Id = localFile.ToLower();
DescriptionAttachment = Path.GetFileName(localFile);
LocationIsLocal = true;
Location = localFile;
}
}
public class PredefinedTextCollection : System.Collections.ObjectModel.KeyedCollection<string, PredefinedTextItem>
{
protected override string GetKeyForItem(PredefinedTextItem item)
{
return item.Id;
}
}
public class AttachmentCollection : System.Collections.ObjectModel.KeyedCollection<string, AttachmentItem>
{
protected override string GetKeyForItem(AttachmentItem item)
{
return item.Id;
}
}
public class ReceivedAttachmentItem
{
public string Id { get; internal set; }
public string FileName { get; internal set; }
public string PhysicalFile { get; set; }
}
public class ChatMessageLine
{
public int LineType { get; internal set; }
public string From { get; internal set; }
public string To { get; internal set; }
public string Message { get; internal set; }
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Runner.Generators.Hana;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Hana
{
[TestFixture]
[Category("Hana")]
public class HanaColumnTests : BaseColumnTests
{
protected HanaGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new HanaGenerator();
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" MyDomainType NULL);");
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" MyDomainType NULL);");
}
[Test]
public override void CanAlterColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.Column.IsNullable = null;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ALTER (\"TestColumn1\" NVARCHAR(20));");
}
[Test]
public override void CanAlterColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.Column.IsNullable = null;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ALTER (\"TestColumn1\" NVARCHAR(20));");
}
[Test]
public override void CanCreateAutoIncrementColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ALTER (\"TestColumn1\" INTEGER GENERATED ALWAYS AS IDENTITY);");
}
[Test]
public override void CanCreateAutoIncrementColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ALTER (\"TestColumn1\" INTEGER GENERATED ALWAYS AS IDENTITY);");
}
[Test]
public override void CanCreateColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" NVARCHAR(5));");
}
[Test]
public override void CanCreateColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" NVARCHAR(5));");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndCustomSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema");
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE ""TestTable1"" ADD (""TestColumn1"" DATETIME NULL);" + Environment.NewLine +
@"UPDATE ""TestTable1"" SET ""TestColumn1"" = CURRENT_TIMESTAMP WHERE 1 = 1;");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndDefaultSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression();
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE ""TestTable1"" ADD (""TestColumn1"" DATETIME NULL);" + Environment.NewLine +
@"UPDATE ""TestTable1"" SET ""TestColumn1"" = CURRENT_TIMESTAMP WHERE 1 = 1;");
}
[Test]
public override void CanCreateDecimalColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" DECIMAL(19,2));");
}
[Test]
public void CanCreateBooleanColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateBooleanColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" BOOLEAN);");
}
[Test]
public override void CanCreateDecimalColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD (\"TestColumn1\" DECIMAL(19,2));");
}
[Test]
public override void CanDropColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP (\"TestColumn1\");");
}
[Test]
public override void CanDropColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP (\"TestColumn1\");");
}
[Test]
public override void CanDropMultipleColumnsWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP (\"TestColumn1\"); ALTER TABLE \"TestTable1\" DROP (\"TestColumn2\");");
}
[Test]
public override void CanDropMultipleColumnsWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP (\"TestColumn1\"); ALTER TABLE \"TestTable1\" DROP (\"TestColumn2\");");
}
[Test]
public override void CanRenameColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("RENAME COLUMN \"TestTable1\".\"TestColumn1\" TO \"TestColumn2\";");
}
[Test]
public override void CanRenameColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("RENAME COLUMN \"TestTable1\".\"TestColumn1\" TO \"TestColumn2\";");
}
}
}
| |
/*
* DelegateSerializationHolder.cs - Implementation of the
* "System.DelegateSerializationHolder" 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
{
#if CONFIG_SERIALIZATION
using System.Runtime.Serialization;
using System.Reflection;
using System.Private;
// This class is used as a proxy to stand in for delegate objects.
// This class must be named "System.DelegateSerializationHolder" for
// compatibility with other serialization implementations.
internal class DelegateSerializationHolder : ISerializable, IObjectReference
{
// Entry class that is used to hold the information about a delegate.
[Serializable]
internal class DelegateEntry
{
public String type;
public String assembly;
public Object target;
public String targetTypeAssembly;
public String targetTypeName;
public String methodName;
public DelegateEntry delegateEntry;
// Convert a delegate serialization entry into a delegate.
public Delegate ToDelegate()
{
Assembly assem;
Type delegateType;
Type targetType;
// Validate the entry state.
if(methodName == null || methodName.Length == 0)
{
throw new SerializationException
(_("Serialize_StateMissing"));
}
// Fetch the delegate type.
assem = FormatterServices.GetAssemblyByName(assembly);
if(assem == null)
{
throw new SerializationException
(_("Serialize_UnknownAssembly"));
}
delegateType = assem.GetType(type);
if(delegateType == null)
{
throw new SerializationException
(_("Serialize_StateMissing"));
}
// Fetch the target type.
assem = FormatterServices.GetAssemblyByName
(targetTypeAssembly);
if(assem == null)
{
throw new SerializationException
(_("Serialize_UnknownAssembly"));
}
targetType = assem.GetType(targetTypeName);
if(targetType == null)
{
throw new SerializationException
(_("Serialize_StateMissing"));
}
// Check that the target is an instance of
// the specified target type.
if(target != null)
{
if(!targetType.IsInstanceOfType(target))
{
throw new SerializationException
(_("Serialize_DelegateTargetMismatch"));
}
}
// Create the Delegate.
Delegate del;
if(target != null)
{
del = Delegate.CreateDelegate
(delegateType, target, methodName);
}
else
{
del = Delegate.CreateDelegate
(delegateType, targetType, methodName);
}
// Fail if the method is non-public.
MethodInfo method = del.Method;
if(method != null && !(method.IsPublic))
{
throw new SerializationException
(_("Serialize_DelegateNotPublic"));
}
return del;
}
}; // class DelegateEntry
// Internal state.
private DelegateEntry entry;
// Constructor.
public DelegateSerializationHolder(SerializationInfo info,
StreamingContext context)
{
if(info == null)
{
throw new ArgumentNullException("info");
}
bool needsResolve = false;
try
{
// Try the new serialization format first.
entry = (DelegateEntry)(info.GetValue
("Delegate", typeof(DelegateEntry)));
needsResolve = true;
}
catch(Exception)
{
// Try the old-style serialization format (deprecated).
entry = new DelegateEntry();
entry.type = info.GetString("DelegateType");
entry.assembly = info.GetString("DelegateAssembly");
entry.target = info.GetValue("Target", typeof(Object));
entry.targetTypeAssembly =
info.GetString("TargetTypeAssembly");
entry.targetTypeName = info.GetString("TargetTypeName");
entry.methodName = info.GetString("MethodName");
}
// Resolve targets specified as field names.
if(needsResolve)
{
DelegateEntry e = entry;
while(e != null)
{
if(e.target is String)
{
e.target = info.GetValue
((String)(e.target), typeof(Object));
}
e = e.delegateEntry;
}
}
}
// Serialize a delegate object.
internal static DelegateEntry Serialize
(SerializationInfo info, int listPosition,
Type delegateType, Object target, MethodBase method)
{
// Create the new delegate entry block.
DelegateEntry entry = new DelegateEntry();
entry.type = delegateType.FullName;
entry.assembly = delegateType.Assembly.FullName;
entry.target = target;
entry.targetTypeAssembly =
method.ReflectedType.Assembly.FullName;
entry.targetTypeName = method.ReflectedType.FullName;
entry.methodName = method.Name;
// Add the block if this is the first in the list.
if(info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate", entry, typeof(DelegateEntry));
}
// Add the target object to the top level of the info block.
// Needed to get around order of fixup problems in some
// third party serialization implementations.
if(target != null)
{
String name = "target" + listPosition.ToString();
info.AddValue(name, target, typeof(Object));
entry.target = name;
}
// Return the entry to the caller so that we can chain
// multiple entries together for multicast delegates.
return entry;
}
// Serialize a multicast delegate object.
internal static void SerializeMulticast
(SerializationInfo info, MulticastDelegate del)
{
DelegateEntry entry, next;
int index = 0;
// Serialize the first entry on the multicast list.
entry = Serialize(info, index++, del.GetType(), del.target,
MethodBase.GetMethodFromHandle(del.method));
// Serialize the rest of the multicast chain.
del = del.prev;
while(del != null)
{
next = Serialize
(info, index++, del.GetType(), del.target,
MethodBase.GetMethodFromHandle(del.method));
entry.delegateEntry = next;
entry = next;
del = del.prev;
}
}
// Implement the ISerializable interface.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// This method should never be called.
throw new NotSupportedException();
}
// Implement the IObjectReference interface.
public Object GetRealObject(StreamingContext context)
{
// Get the first delegate in the chain.
Delegate del = entry.ToDelegate();
// Bail out early if this is a unicast delegate.
if(!(del is MulticastDelegate) || entry.delegateEntry == null)
{
return del;
}
// Build the multicast delegate chain.
Delegate end = del;
Delegate newDelegate;
DelegateEntry e = entry.delegateEntry;
while(e != null)
{
newDelegate = e.ToDelegate();
if(newDelegate.GetType() != del.GetType())
{
throw new SerializationException
(_("Arg_DelegateMismatch"));
}
((MulticastDelegate)end).prev =
(newDelegate as MulticastDelegate);
end = newDelegate;
e = e.delegateEntry;
}
return del;
}
}; // class DelegateSerializationHolder
#endif // CONFIG_SERIALIZATION
}; // namespace System
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.ServiceModel.Administration;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.ServiceModel.Configuration;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Threading;
using System.Transactions;
using System.Runtime.CompilerServices;
using System.Globalization;
[AttributeUsage(ServiceModelAttributeTargets.CallbackBehavior)]
public sealed class CallbackBehaviorAttribute : Attribute, IEndpointBehavior
{
ConcurrencyMode concurrencyMode = ConcurrencyMode.Single;
bool includeExceptionDetailInFaults = false;
bool validateMustUnderstand = true;
bool ignoreExtensionDataObject = DataContractSerializerDefaults.IgnoreExtensionDataObject;
int maxItemsInObjectGraph = DataContractSerializerDefaults.MaxItemsInObjectGraph;
bool automaticSessionShutdown = true;
bool useSynchronizationContext = true;
internal static IsolationLevel DefaultIsolationLevel = IsolationLevel.Unspecified;
IsolationLevel transactionIsolationLevel = DefaultIsolationLevel;
bool isolationLevelSet = false;
TimeSpan transactionTimeout = TimeSpan.Zero;
string transactionTimeoutString;
bool transactionTimeoutSet = false;
public bool AutomaticSessionShutdown
{
get { return this.automaticSessionShutdown; }
set { this.automaticSessionShutdown = value; }
}
public IsolationLevel TransactionIsolationLevel
{
get { return this.transactionIsolationLevel; }
set
{
switch (value)
{
case IsolationLevel.Serializable:
case IsolationLevel.RepeatableRead:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.Snapshot:
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.transactionIsolationLevel = value;
isolationLevelSet = true;
}
}
internal bool IsolationLevelSet
{
get { return this.isolationLevelSet; }
}
public bool IncludeExceptionDetailInFaults
{
get { return this.includeExceptionDetailInFaults; }
set { this.includeExceptionDetailInFaults = value; }
}
public ConcurrencyMode ConcurrencyMode
{
get { return this.concurrencyMode; }
set
{
if (!ConcurrencyModeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.concurrencyMode = value;
}
}
public string TransactionTimeout
{
get { return transactionTimeoutString; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
try
{
TimeSpan timeout = TimeSpan.Parse(value, CultureInfo.InvariantCulture);
if (timeout < TimeSpan.Zero)
{
string message = SR.GetString(SR.SFxTimeoutOutOfRange0);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, message));
}
this.transactionTimeout = timeout;
this.transactionTimeoutString = value;
this.transactionTimeoutSet = true;
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxTimeoutInvalidStringFormat), "value", e));
}
catch (OverflowException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
}
}
internal bool TransactionTimeoutSet
{
get { return this.transactionTimeoutSet; }
}
public bool UseSynchronizationContext
{
get { return this.useSynchronizationContext; }
set { this.useSynchronizationContext = value; }
}
public bool ValidateMustUnderstand
{
get { return validateMustUnderstand; }
set { validateMustUnderstand = value; }
}
public bool IgnoreExtensionDataObject
{
get { return ignoreExtensionDataObject; }
set { ignoreExtensionDataObject = value; }
}
public int MaxItemsInObjectGraph
{
get { return maxItemsInObjectGraph; }
set { maxItemsInObjectGraph = value; }
}
[MethodImpl(MethodImplOptions.NoInlining)]
void SetIsolationLevel(ChannelDispatcher channelDispatcher)
{
if (channelDispatcher == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher");
}
channelDispatcher.TransactionIsolationLevel = this.transactionIsolationLevel;
}
void IEndpointBehavior.Validate(ServiceEndpoint serviceEndpoint)
{
}
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection parameters)
{
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime clientRuntime)
{
if (!serviceEndpoint.Contract.IsDuplex())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.SFxCallbackBehaviorAttributeOnlyOnDuplex, serviceEndpoint.Contract.Name)));
}
DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime;
dispatchRuntime.ValidateMustUnderstand = validateMustUnderstand;
dispatchRuntime.ConcurrencyMode = this.concurrencyMode;
dispatchRuntime.ChannelDispatcher.IncludeExceptionDetailInFaults = this.includeExceptionDetailInFaults;
dispatchRuntime.AutomaticInputSessionShutdown = this.automaticSessionShutdown;
if (!this.useSynchronizationContext)
{
dispatchRuntime.SynchronizationContext = null;
}
dispatchRuntime.ChannelDispatcher.TransactionTimeout = transactionTimeout;
if (isolationLevelSet)
{
SetIsolationLevel(dispatchRuntime.ChannelDispatcher);
}
DataContractSerializerServiceBehavior.ApplySerializationSettings(serviceEndpoint, this.ignoreExtensionDataObject, this.maxItemsInObjectGraph);
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.SFXEndpointBehaviorUsedOnWrongSide, typeof(CallbackBehaviorAttribute).Name)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AzureLinkboard.Web.Api.Areas.HelpPage.ModelDescriptions;
using AzureLinkboard.Web.Api.Areas.HelpPage.Models;
namespace AzureLinkboard.Web.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Text;
using System.Threading.Tasks;
using Orleans;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace Tester.CodeGenTests
{
/// <summary>
/// Summary description for GrainClientTest
/// </summary>
[TestCategory("BVT"), TestCategory("CodeGen")]
public class GeneratorGrainTest : HostedTestClusterEnsureDefaultStarted
{
public GeneratorGrainTest(DefaultClusterFixture fixture) : base(fixture)
{
}
[Fact]
public async Task GeneratorGrainControlFlow()
{
var grainName = typeof(GeneratorTestGrain).FullName;
IGeneratorTestGrain grain = this.GrainFactory.GetGrain<IGeneratorTestGrain>(GetRandomGrainId(), grainName);
bool isNull = await grain.StringIsNullOrEmpty();
Assert.True(isNull);
await grain.StringSet("Begin");
isNull = await grain.StringIsNullOrEmpty();
Assert.False(isNull);
MemberVariables members = await grain.GetMemberVariables();
Assert.Equal("Begin", members.stringVar);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes("ByteBegin");
string str = "StringBegin";
MemberVariables memberVariables = new MemberVariables(bytes, str, ReturnCode.Fail);
await grain.SetMemberVariables(memberVariables);
members = await grain.GetMemberVariables();
ASCIIEncoding enc = new ASCIIEncoding();
Assert.Equal("ByteBegin", enc.GetString(members.byteArray));
Assert.Equal("StringBegin", members.stringVar);
Assert.Equal(ReturnCode.Fail, members.code);
}
[Fact]
public async Task GeneratorDerivedGrain1ControlFlow()
{
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
bool isNull = await grain.StringIsNullOrEmpty();
Assert.True(isNull);
await grain.StringSet("Begin");
isNull = await grain.StringIsNullOrEmpty();
Assert.False(isNull);
MemberVariables members = await grain.GetMemberVariables();
Assert.Equal("Begin", members.stringVar);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes("ByteBegin");
string str = "StringBegin";
MemberVariables memberVariables = new MemberVariables(bytes, str, ReturnCode.Fail);
await grain.SetMemberVariables(memberVariables);
members = await grain.GetMemberVariables();
ASCIIEncoding enc = new ASCIIEncoding();
Assert.Equal("ByteBegin", enc.GetString(members.byteArray));
Assert.Equal("StringBegin", members.stringVar);
Assert.Equal(ReturnCode.Fail, members.code);
}
[Fact]
public async Task GeneratorDerivedGrain2ControlFlow()
{
var grainName = typeof(GeneratorTestDerivedGrain2).FullName;
IGeneratorTestDerivedGrain2 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain2>(GetRandomGrainId(), grainName);
bool boolPromise = await grain.StringIsNullOrEmpty();
Assert.True(boolPromise);
await grain.StringSet("Begin");
boolPromise = await grain.StringIsNullOrEmpty();
Assert.False(boolPromise);
MemberVariables members = await grain.GetMemberVariables();
Assert.Equal("Begin", members.stringVar);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes("ByteBegin");
string str = "StringBegin";
MemberVariables memberVariables = new MemberVariables(bytes, str, ReturnCode.Fail);
await grain.SetMemberVariables(memberVariables);
members = await grain.GetMemberVariables();
ASCIIEncoding enc = new ASCIIEncoding();
Assert.Equal("ByteBegin", enc.GetString(members.byteArray));
Assert.Equal("StringBegin", members.stringVar);
Assert.Equal(ReturnCode.Fail, members.code);
string strPromise = await grain.StringConcat("Begin", "Cont", "End");
Assert.Equal("BeginContEnd", strPromise);
}
[Fact]
public async Task GeneratorDerivedDerivedGrainControlFlow()
{
IGeneratorTestDerivedDerivedGrain grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
bool isNull = await grain.StringIsNullOrEmpty();
Assert.True(isNull);
await grain.StringSet("Begin");
isNull = await grain.StringIsNullOrEmpty();
Assert.False(isNull);
MemberVariables members = await grain.GetMemberVariables();
Assert.Equal("Begin", members.stringVar);
ReplaceArguments arguments = new ReplaceArguments("Begin", "End");
string strPromise = await grain.StringReplace(arguments);
Assert.Equal("End", strPromise);
strPromise = await grain.StringConcat("Begin", "Cont", "End");
Assert.Equal("BeginContEnd", strPromise);
string[] strArray = { "Begin", "Cont", "Cont", "End" };
strPromise = await grain.StringNConcat(strArray);
Assert.Equal("BeginContContEnd", strPromise);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes("ByteBegin");
string str = "StringBegin";
MemberVariables memberVariables = new MemberVariables(bytes, str, ReturnCode.Fail);
await grain.SetMemberVariables(memberVariables);
members = await grain.GetMemberVariables();
ASCIIEncoding enc = new ASCIIEncoding();
Assert.Equal("ByteBegin", enc.GetString(members.byteArray));
Assert.Equal("StringBegin", members.stringVar);
Assert.Equal(ReturnCode.Fail, members.code);
}
[Fact]
public async Task CodeGenDerivedFromCSharpInterfaceInDifferentAssembly()
{
var grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedFromCSharpInterfaceInExternalAssemblyGrain>(Guid.NewGuid());
var input = 1;
var output = await grain.Echo(input);
Assert.Equal(input, output);
}
[Fact]
public async Task GrainWithGenericMethods()
{
var grain = this.GrainFactory.GetGrain<IGrainWithGenericMethods>(Guid.NewGuid());
Assert.Equal("default string", await grain.Default());
Assert.Equal(-8, await grain.RoundTrip(8));
Assert.Equal(new[] { typeof(IGrain), typeof(string), typeof(DateTime) }, await grain.GetTypesExplicit<IGrain, string, DateTime>());
Assert.Equal(new[] { typeof(IGrain), typeof(string), typeof(DateTime) }, await grain.GetTypesInferred((IGrain)grain, default(string), default(DateTime)));
Assert.Equal(new[] { typeof(IGrain), typeof(string) }, await grain.GetTypesInferred(default(IGrain), default(string), 0));
var now = DateTime.Now;
Assert.Equal(now, await grain.RoundTrip(now));
Assert.Equal(default(DateTime), await grain.Default<DateTime>());
Assert.Equal(grain, await grain.Constraints(grain));
}
[Fact]
public async Task GenericGrainWithGenericMethods()
{
var grain = this.GrainFactory.GetGrain<IGenericGrainWithGenericMethods<int>>(Guid.NewGuid());
// The non-generic version of the method returns default(T).
Assert.Equal(0, await grain.Method(888));
// The generic version of the method returns the value provided.
var now = DateTime.Now;
Assert.Equal(now, await grain.Method(now));
}
[Fact]
public async Task GrainObserverWithGenericMethods()
{
var localObject = new ObserverWithGenericMethods();
var grain = this.GrainFactory.GetGrain<IGrainWithGenericMethods>(Guid.NewGuid());
var observer = await this.GrainFactory.CreateObjectReference<IGrainObserverWithGenericMethods>(localObject);
await grain.SetValueOnObserver(observer, "ToastedEnchiladas");
Assert.Equal("ToastedEnchiladas", await localObject.ValueTask);
}
[Fact]
public async Task GrainWithValueTaskMethod()
{
var grain = this.GrainFactory.GetGrain<IGrainWithGenericMethods>(Guid.NewGuid());
Assert.Equal(1, await grain.ValueTaskMethod(true).ConfigureAwait(false));
Assert.Equal(2, await grain.ValueTaskMethod(false).ConfigureAwait(false));
}
private class ObserverWithGenericMethods : IGrainObserverWithGenericMethods
{
private readonly TaskCompletionSource<object> valueCompletion = new TaskCompletionSource<object>();
public Task<object> ValueTask => this.valueCompletion.Task;
public void SetValue<T>(T value)
{
this.valueCompletion.SetResult(value);
}
}
[Fact, TestCategory("FSharp")]
public async Task CodeGenDerivedFromFSharpInterfaceInDifferentAssembly()
{
var grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedFromFSharpInterfaceInExternalAssemblyGrain>(Guid.NewGuid());
var input = 1;
var output = await grain.Echo(input);
Assert.Equal(input, output);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit;
using System.Collections;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Drawing.Drawing2D;
namespace Revit.SDK.Samples.SlabShapeEditing.CS
{
/// <summary>
/// window form contains one picture box to show the
/// profile of slab geometry. user can add vertex and crease.
/// User can edit slab shape via vertex and crease too.
/// </summary>
public partial class SlabShapeEditingForm : System.Windows.Forms.Form
{
enum EditorState { AddVertex, AddCrease, Select, Rotate, Null };
ExternalCommandData m_commandData; //object which contains reference of Revit Application
SlabProfile m_slabProfile; //store geometry info of selected slab
PointF m_mouseRightDownLocation; //where mouse right button down
LineTool m_lineTool; //tool use to draw crease
LineTool m_pointTool; //tool use to draw vertex
ArrayList m_graphicsPaths; //store all the GraphicsPath objects of crease and vertex.
int m_selectIndex; //index of crease and vertex which mouse hovering on.
int m_clickedIndex; //index of crease and vertex which mouse clicked.
ArrayList m_createdVertices; // new created vertices
ArrayList m_createCreases; // new created creases
SlabShapeEditor m_slabShapeEditor; //object use to edit slab shape
SlabShapeCrease m_selectedCrease; //selected crease, mouse clicked on
SlabShapeVertex m_selectedVertex; //selected vertex, mouse clicked on
EditorState editorState; //state of user's operation
Pen m_toolPen; //pen use to draw new created vertex and crease
Pen m_selectPen; // pen use to draw vertex and crease which been selected
Pen m_profilePen; // pen use to draw slab's profile
const string justNumber = "Please input numbers in textbox!"; //error message
const string selectFirst = "Please select a Vertex (or Crease) first!"; //error message
/// <summary>
/// constructor
/// </summary>
/// <param name="commandData">selected floor (or slab)</param>
/// <param name="commandData">contains reference of Revit Application</param>
public SlabShapeEditingForm(Floor floor, ExternalCommandData commandData)
{
InitializeComponent();
m_commandData = commandData;
m_slabProfile = new SlabProfile(floor, commandData);
m_slabShapeEditor = floor.SlabShapeEditor;
m_lineTool = new LineTool();
m_pointTool = new LineTool();
editorState = EditorState.AddVertex;
m_graphicsPaths = new ArrayList();
m_createdVertices = new ArrayList();
m_createCreases = new ArrayList();
m_selectIndex = -1;
m_clickedIndex = -1;
m_toolPen = new Pen(System.Drawing.Color.Blue, 2);
m_selectPen = new Pen(System.Drawing.Color.Red, 2);
m_profilePen = new Pen(System.Drawing.Color.Black, (float)(0.5));
}
/// <summary>
/// represents the geometry info for slab
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void SlabShapePictureBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
m_slabProfile.Draw2D(e.Graphics, m_profilePen);
if (EditorState.Rotate != editorState)
{
m_lineTool.Draw2D(e.Graphics, m_toolPen);
m_pointTool.DrawRectangle(e.Graphics, m_toolPen);
//draw selected beam (line) by red pen
DrawSelectedLineRed(e.Graphics, m_selectPen);
}
}
/// <summary>
/// Draw selected crease or vertex red
/// </summary>
/// <param name="graphics">Form graphics object,</param>
/// <param name="pen">Pen which used to draw lines</param>
private void DrawSelectedLineRed(Graphics graphics, Pen pen)
{
if (-1 != m_selectIndex)
{
GraphicsPath selectedPath = (GraphicsPath)m_graphicsPaths[m_selectIndex];
PointF pointF0 = (PointF)selectedPath.PathPoints.GetValue(0);
PointF pointF1 = (PointF)selectedPath.PathPoints.GetValue(1);
if (m_selectIndex < m_createCreases.Count)
{ graphics.DrawLine(pen, pointF0, pointF1); }
else { graphics.DrawRectangle(pen, pointF0.X - 2, pointF0.Y - 2, 4, 4); }
}
if (-1 != m_clickedIndex)
{
GraphicsPath clickedPath = (GraphicsPath)m_graphicsPaths[m_clickedIndex];
PointF pointF0 = (PointF)clickedPath.PathPoints.GetValue(0);
PointF pointF1 = (PointF)clickedPath.PathPoints.GetValue(1);
if (m_clickedIndex < m_createCreases.Count)
{ graphics.DrawLine(pen, pointF0, pointF1); }
else { graphics.DrawRectangle(pen, pointF0.X - 2, pointF0.Y - 2, 4, 4); }
}
}
/// <summary>
/// rotate slab and get selected vertex or crease
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void SlabShapePictureBox_MouseMove(object sender, MouseEventArgs e)
{
PointF pointF = new PointF(e.X, e.Y);
if (EditorState.AddCrease == editorState && 1 == m_lineTool.Points.Count % 2)
{ m_lineTool.MovePoint = pointF; }
else { m_lineTool.MovePoint = PointF.Empty; }
if (MouseButtons.Right == e.Button)
{
double moveX = e.Location.X - m_mouseRightDownLocation.X;
double moveY = m_mouseRightDownLocation.Y - e.Location.Y;
m_slabProfile.RotateFloor(moveY / 500, moveX / 500);
m_mouseRightDownLocation = e.Location;
}
else if (EditorState.Select == editorState)
{
for (int i = 0; i < m_graphicsPaths.Count; i++)
{
GraphicsPath path = (GraphicsPath)m_graphicsPaths[i];
if (path.IsOutlineVisible(pointF, m_toolPen))
{ m_selectIndex = i; break; }
m_selectIndex = -1;
}
}
this.SlabShapePictureBox.Refresh();
}
/// <summary>
/// get location where right button click down.
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void SlabShapePictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (MouseButtons.Right == e.Button)
{
m_mouseRightDownLocation = e.Location;
editorState = EditorState.Rotate;
m_clickedIndex = m_selectIndex = -1;
}
}
/// <summary>
/// add vertex and crease, select new created vertex and crease
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void SlabShapePictureBox_MouseClick(object sender, MouseEventArgs e)
{
if (EditorState.AddCrease == editorState)
{
if (!m_slabProfile.CanCreateVertex(new PointF(e.X, e.Y))) { return; }
m_lineTool.Points.Add(new PointF(e.X, e.Y));
int lineSize = m_lineTool.Points.Count;
if (0 == m_lineTool.Points.Count % 2)
{
m_createCreases.Add(
m_slabProfile.AddCrease((PointF)m_lineTool.Points[lineSize - 2],
(PointF)m_lineTool.Points[lineSize - 1]));
}
CreateGraphicsPath(); //create graphic path for all the vertex and crease
}
else if (EditorState.AddVertex == editorState)
{
SlabShapeVertex vertex = m_slabProfile.AddVertex(new PointF(e.X, e.Y));
if (null == vertex) { return; }
m_pointTool.Points.Add(new PointF(e.X, e.Y));
//draw point as a short line, so add two points here
m_pointTool.Points.Add(new PointF((float)(e.X + 2), (float)(e.Y + 2)));
m_createdVertices.Add(vertex);
CreateGraphicsPath(); //create graphic path for all the vertex and crease
}
else if (EditorState.Select == editorState)
{
if (m_selectIndex >= 0)
{
m_clickedIndex = m_selectIndex;
if (m_selectIndex <= m_createCreases.Count - 1)
{
m_selectedCrease = (SlabShapeCrease)(m_createCreases[m_selectIndex]);
m_selectedVertex = null;
}
else
{
//put all path (crease and vertex) in one arrayList, so reduce creases.count
int index = m_selectIndex - m_createCreases.Count;
m_selectedVertex = (SlabShapeVertex)(m_createdVertices[index]);
m_selectedCrease = null;
}
}
else { m_selectedVertex = null; m_selectedCrease = null; m_clickedIndex = -1; }
}
this.SlabShapePictureBox.Refresh();
}
/// <summary>
/// get ready to add vertex
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void PointButton_Click(object sender, EventArgs e)
{
editorState = EditorState.AddVertex;
m_slabProfile.ClearRotateMatrix();
this.SlabShapePictureBox.Cursor = Cursors.Cross;
}
/// <summary>
/// get ready to add crease
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void LineButton_Click(object sender, EventArgs e)
{
editorState = EditorState.AddCrease;
m_slabProfile.ClearRotateMatrix();
this.SlabShapePictureBox.Cursor = Cursors.Cross;
}
/// <summary>
/// get ready to move vertex and crease
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void MoveButton_Click(object sender, EventArgs e)
{
editorState = EditorState.Select;
m_slabProfile.ClearRotateMatrix();
this.SlabShapePictureBox.Cursor = Cursors.Arrow;
}
/// <summary>
/// Move vertex and crease, then update profile of slab
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void UpdateButton_Click(object sender, EventArgs e)
{
if (-1 == m_clickedIndex) { MessageBox.Show(selectFirst); return; }
double moveDistance = 0;
try { moveDistance = Convert.ToDouble(this.DistanceTextBox.Text); }
catch (Exception) { MessageBox.Show(justNumber); return; }
Transaction transaction = new Transaction(
m_commandData.Application.ActiveUIDocument.Document, "Update");
transaction.Start();
if (null != m_selectedCrease)
{ m_slabShapeEditor.ModifySubElement(m_selectedCrease, moveDistance); }
else if (null != m_selectedVertex)
{ m_slabShapeEditor.ModifySubElement(m_selectedVertex, moveDistance); }
transaction.Commit();
//re-calculate geometry info
m_slabProfile.GetSlabProfileInfo();
this.SlabShapePictureBox.Refresh();
}
/// <summary>
/// Reset slab shape
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void ResetButton_Click(object sender, EventArgs e)
{
m_slabProfile.ResetSlabShape();
m_lineTool.Points.Clear();
m_pointTool.Points.Clear();
}
/// <summary>
/// Create Graphics Path for each vertex and crease
/// </summary>
public void CreateGraphicsPath()
{
m_graphicsPaths.Clear();
//create path for all the lines draw by user
for (int i = 0; i < m_lineTool.Points.Count - 1; i += 2)
{
GraphicsPath path = new GraphicsPath();
path.AddLine((PointF)m_lineTool.Points[i], (PointF)m_lineTool.Points[i + 1]);
m_graphicsPaths.Add(path);
}
for (int i = 0; i < m_pointTool.Points.Count - 1; i += 2)
{
GraphicsPath path = new GraphicsPath();
path.AddLine((PointF)m_pointTool.Points[i], (PointF)m_pointTool.Points[i + 1]);
m_graphicsPaths.Add(path);
}
}
/// <summary>
/// set tool tip for MoveButton
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void MoveButton_MouseHover(object sender, EventArgs e)
{
this.toolTip.SetToolTip(this.MoveButton, "Select Vertex or Crease");
}
/// <summary>
/// set tool tip for PointButton
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void PointButton_MouseHover(object sender, EventArgs e)
{
this.toolTip.SetToolTip(this.PointButton, "Add Vertex");
}
/// <summary>
/// set tool tip for LineButton
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void LineButton_MouseHover(object sender, EventArgs e)
{
this.toolTip.SetToolTip(this.LineButton, "Add Crease");
}
/// <summary>
/// change cursor
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void SlabShapePictureBox_MouseHover(object sender, EventArgs e)
{
switch (editorState)
{
case EditorState.AddVertex:
this.SlabShapePictureBox.Cursor = Cursors.Cross; break;
case EditorState.AddCrease:
this.SlabShapePictureBox.Cursor = Cursors.Cross; break;
case EditorState.Select:
this.SlabShapePictureBox.Cursor = Cursors.Arrow; break;
default:
this.SlabShapePictureBox.Cursor = Cursors.Default; break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Orleans;
using Orleans.Concurrency;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
using Orleans.Runtime.Configuration;
namespace UnitTests.Grains
{
internal class StressTestGrain : Grain, IStressTestGrain
{
private string label;
private Logger logger;
public override Task OnActivateAsync()
{
if (this.GetPrimaryKeyLong() == -2)
throw new ArgumentException("Primary key cannot be -2 for this test case");
logger = base.GetLogger("StressTestGrain " + base.RuntimeIdentity);
label = this.GetPrimaryKeyLong().ToString();
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<string> GetLabel()
{
return Task.FromResult(label);
}
public Task SetLabel(string label)
{
this.label = label;
//logger.Info("SetLabel {0} received", label);
return Task.CompletedTask;
}
public Task<IStressTestGrain> GetGrainReference()
{
return Task.FromResult(this.AsReference<IStressTestGrain>());
}
public Task PingOthers(long[] others)
{
List<Task> promises = new List<Task>();
foreach (long key in others)
{
IStressTestGrain g1 = GrainFactory.GetGrain<IStressTestGrain>(key);
Task promise = g1.GetLabel();
promises.Add(promise);
}
return Task.WhenAll(promises);
}
public Task<List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>> LookUpMany(
SiloAddress destination, List<Tuple<GrainId, int>> grainAndETagList, int retries = 0)
{
var list = new List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>();
foreach (Tuple<GrainId, int> tuple in grainAndETagList)
{
GrainId id = tuple.Item1;
var reply = new List<Tuple<SiloAddress, ActivationId>>();
for (int i = 0; i < 10; i++)
{
var siloAddress = SiloAddress.New(new IPEndPoint(ClusterConfiguration.GetLocalIPAddress(),0), 0);
reply.Add(new Tuple<SiloAddress, ActivationId>(siloAddress, ActivationId.NewId()));
}
list.Add(new Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>(id, 3, reply));
}
return Task.FromResult(list);
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task Send(byte[] data)
{
return Task.CompletedTask;
}
public Task DeactivateSelf()
{
DeactivateOnIdle();
return Task.CompletedTask;
}
}
[Reentrant]
internal class ReentrantStressTestGrain : Grain, IReentrantStressTestGrain
{
private string label;
private Logger logger;
public override Task OnActivateAsync()
{
label = this.GetPrimaryKeyLong().ToString();
logger = base.GetLogger("ReentrantStressTestGrain " + base.Data.Address.ToString());
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain,
bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public async Task InterleavingConsistencyTest(int numItems)
{
TimeSpan delay = TimeSpan.FromMilliseconds(1);
SafeRandom random = new SafeRandom();
List<Task> getFileMetadataPromises = new List<Task>(numItems*2);
Dictionary<int, string> fileMetadatas = new Dictionary<int, string>(numItems*2);
for (int i = 0; i < numItems; i++)
{
int capture = i;
Func<Task> func = (
async () =>
{
await Task.Delay(random.NextTimeSpan(delay));
int fileMetadata = capture;
if ((fileMetadata%2) == 0)
{
fileMetadatas.Add(fileMetadata, fileMetadata.ToString());
}
});
getFileMetadataPromises.Add(func());
}
await Task.WhenAll(getFileMetadataPromises.ToArray());
List<Task> tagPromises = new List<Task>(fileMetadatas.Count);
foreach (KeyValuePair<int, string> keyValuePair in fileMetadatas)
{
int fileId = keyValuePair.Key;
Func<Task> func = (async () =>
{
await Task.Delay(random.NextTimeSpan(delay));
string fileMetadata = fileMetadatas[fileId];
});
tagPromises.Add(func());
}
await Task.WhenAll(tagPromises);
// sort the fileMetadatas according to fileIds.
List<string> results = new List<string>(fileMetadatas.Count);
for (int i = 0; i < numItems; i++)
{
string metadata;
if (fileMetadatas.TryGetValue(i, out metadata))
{
results.Add(metadata);
}
}
if (numItems != results.Count)
{
//throw new OrleansException(String.Format("numItems != results.Count, {0} != {1}", numItems, results.Count));
}
}
}
[Reentrant]
[StatelessWorker]
public class ReentrantLocalStressTestGrain : Grain, IReentrantLocalStressTestGrain
{
private string label;
private Logger logger;
public override Task OnActivateAsync()
{
label = this.GetPrimaryKeyLong().ToString();
logger = base.GetLogger("ReentrantLocalStressTestGrain " + base.Data.Address.ToString());
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<byte[]> Echo(byte[] data)
{
return Task.FromResult(data);
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task Ping(byte[] data)
{
return Task.CompletedTask;
}
public async Task PingWithDelay(byte[] data, TimeSpan delay)
{
await Task.Delay(delay);
}
public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableArray(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingMutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain,
bool nextGrainIsRemote)
{
if (nextGrain > 0)
{
if (nextGrainIsRemote)
{
return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain)
.PingImmutableDictionary(data, -1, false);
}
return Task.CompletedTask;
}
}
}
| |
// <copyright file="TFQMRTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Solvers.Iterative
{
/// <summary>
/// Tests of Transpose Free Quasi-Minimal Residual iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class TFQMRTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Scale it with a funny number
matrix.Multiply(Math.PI, matrix);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = Matrix<double>.Build.Sparse(100, 100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 1);
var vectorb = Vector<double>.Build.Random(order, 1);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new TFQMR();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-7);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 1);
var matrixB = Matrix<double>.Build.Random(order, order, 1);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new TFQMR();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
}
}
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2006 Novell Inc. 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.
*******************************************************************************/
//
// Samples.Extensions.EdirEventSample.cs
//
// Author:
// Palaniappan N (NPalaniappan@novell.com)
//
// (C) 2006 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Events;
using Novell.Directory.Ldap.Events.Edir;
using Novell.Directory.Ldap.Events.Edir.EventData;
public class EdirEventSample
{
public const double TIME_OUT_IN_MINUTES = 5;
public static DateTime timeOut;
/**
* Check the queue for a response. If a response has been received,
* print the response information.
*/
static private bool checkForAChange(LdapResponseQueue queue)
{
LdapMessage message;
bool result = true;
try
{
//check if a response has been received so we don't block
//when calling getResponse()
if (queue.isResponseReceived())
{
message = queue.getResponse();
if (message != null)
{
// is the response a search result reference?
if (message is MonitorEventResponse)
{
MonitorEventResponse eventerrorresponse = (MonitorEventResponse) message;
Console.WriteLine("\nError in Registration ResultCode = " + eventerrorresponse.ResultCode);
EdirEventSpecifier[] specifiers = eventerrorresponse.SpecifierList;
for (int i = 0; i < specifiers.Length; i++)
{
Console.WriteLine("Specifier:" + "EventType = " + specifiers[i].EventType);
}
Environment.Exit(-1);
}
// is the response a event response ?
else if ( message is EdirEventIntermediateResponse)
{
Console.WriteLine("Edir Event Occured");
EdirEventIntermediateResponse eventresponse = (EdirEventIntermediateResponse) message;
//process the eventresponse Data, depending on the
// type of response
processEventData(eventresponse.EventResponseDataObject, eventresponse.EventType);
}
// the message is a Unknown response
else
{
Console.WriteLine("UnKnown Message =" + message);
}
}
}
}
catch (LdapException e)
{
Console.WriteLine("Error: " + e.ToString());
result = false;
}
return result;
}
public static void Main(String[] args)
{
if (args.Length != 3)
{
Console.WriteLine(
"Usage: mono EdirEventSample <host name> <login dn>"
+ " <password> ");
Console.WriteLine(
"Example: mono EdirEventSample Acme.com \"cn=admin,o=Acme\""
+ " secret ");
Environment.Exit(0);
}
int ldapPort = LdapConnection.DEFAULT_PORT;
int ldapVersion = LdapConnection.Ldap_V3;
String ldapHost = args[0];
String loginDN = args[1];
String password = args[2];
LdapResponseQueue queue = null;
LdapConnection lc = new LdapConnection();
try
{
// connect to the server
lc.Connect(ldapHost, ldapPort);
// authenticate to the server
lc.Bind(ldapVersion, loginDN, password);
//Create an Array of EdirEventSpecifier
EdirEventSpecifier[] specifier = new EdirEventSpecifier[1];
//Register for all Add Value events.
specifier[0] =
new EdirEventSpecifier(EdirEventType.EVT_CREATE_ENTRY,
//Generate an Value Event of Type Add Value
EdirEventResultType.EVT_STATUS_ALL
//Generate Event for all status
);
//Create an MonitorEventRequest using the specifiers.
MonitorEventRequest requestoperation =
new MonitorEventRequest(specifier);
//Send the request to server and get the response queue.
queue = lc.ExtendedOperation(requestoperation, null, null);
}
catch (LdapException e)
{
Console.WriteLine("Error: " + e.ToString());
try
{
lc.Disconnect();
}
catch (LdapException e2)
{
Console.WriteLine("Error: " + e2.ToString());
}
Environment.Exit(1);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES );
Console.WriteLine();
//Set the timeout value
timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES);
try
{
//Monitor till the timeout happens
while (DateTime.Now.CompareTo(timeOut) < 0)
{
if (!checkForAChange(queue))
break;
System.Threading.Thread.Sleep(10);
}
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
catch (System.Threading.ThreadInterruptedException e)
{
Console.WriteLine(e.Message);
}
//disconnect from the server before exiting
try
{
lc.Abandon(queue); //abandon the search
lc.Disconnect();
}
catch (LdapException e)
{
Console.WriteLine();
Console.WriteLine("Error: " + e.ToString());
}
Environment.Exit(0);
} // end main
/**
* Processes the Event Data depending on the Type.
* @param data EventResponseData.
* @param type Type of Data.
*/
static private void processEventData( BaseEdirEventData data, EdirEventType type)
{
switch (type)
{
case EdirEventType.EVT_CREATE_ENTRY :
// Value event.
//Output the relevant Data.
EntryEventData valueevent = (EntryEventData) data;
Console.WriteLine("Entry = " + valueevent.Entry);
Console.WriteLine("PrepetratorDN = " + valueevent.PerpetratorDN);
Console.WriteLine("TimeStamp = " + valueevent.TimeStamp);
Console.WriteLine();
break;
default :
//Unknow Event.
break;
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ConstantTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolConstantTest(bool useInterpreter)
{
foreach (bool value in new bool[] { true, false })
{
VerifyBoolConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteConstantTest(bool useInterpreter)
{
foreach (byte value in new byte[] { 0, 1, byte.MaxValue })
{
VerifyByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustomConstantTest(bool useInterpreter)
{
foreach (C value in new C[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharConstantTest(bool useInterpreter)
{
foreach (char value in new char[] { '\0', '\b', 'A', '\uffff' })
{
VerifyCharConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ConstantTest(bool useInterpreter)
{
foreach (D value in new D[] { null, new D(), new D(0), new D(5) })
{
VerifyCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalConstantTest(bool useInterpreter)
{
foreach (decimal value in new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue })
{
VerifyDecimalConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDelegateConstantTest(bool useInterpreter)
{
foreach (Delegate value in new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } })
{
VerifyDelegateConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleConstantTest(bool useInterpreter)
{
foreach (double value in new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN })
{
VerifyDoubleConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumConstantTest(bool useInterpreter)
{
foreach (E value in new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue })
{
VerifyEnumConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongConstantTest(bool useInterpreter)
{
foreach (El value in new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue })
{
VerifyEnumLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatConstantTest(bool useInterpreter)
{
foreach (float value in new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN })
{
VerifyFloatConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFuncOfObjectConstantTest(bool useInterpreter)
{
foreach (Func<object> value in new Func<object>[] { null, (Func<object>)delegate () { return null; } })
{
VerifyFuncOfObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceConstantTest(bool useInterpreter)
{
foreach (I value in new I[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyInterfaceConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustomConstantTest(bool useInterpreter)
{
foreach (IEquatable<C> value in new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustom2ConstantTest(bool useInterpreter)
{
foreach (IEquatable<D> value in new IEquatable<D>[] { null, new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntConstantTest(bool useInterpreter)
{
foreach (int value in new int[] { 0, 1, -1, int.MinValue, int.MaxValue })
{
VerifyIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongConstantTest(bool useInterpreter)
{
foreach (long value in new long[] { 0, 1, -1, long.MinValue, long.MaxValue })
{
VerifyLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckObjectConstantTest(bool useInterpreter)
{
foreach (object value in new object[] { null, new object(), new C(), new D(3) })
{
VerifyObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructConstantTest(bool useInterpreter)
{
foreach (S value in new S[] { default(S), new S() })
{
VerifyStructConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteConstantTest(bool useInterpreter)
{
foreach (sbyte value in new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue })
{
VerifySByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringConstantTest(bool useInterpreter)
{
foreach (Sc value in new Sc[] { default(Sc), new Sc(), new Sc(null) })
{
VerifyStructWithStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndFieldConstantTest(bool useInterpreter)
{
foreach (Scs value in new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) })
{
VerifyStructWithStringAndFieldConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortConstantTest(bool useInterpreter)
{
foreach (short value in new short[] { 0, 1, -1, short.MinValue, short.MaxValue })
{
VerifyShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoValuesConstantTest(bool useInterpreter)
{
foreach (Sp value in new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) })
{
VerifyStructWithTwoValuesConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueConstantTest(bool useInterpreter)
{
foreach (Ss value in new Ss[] { default(Ss), new Ss(), new Ss(new S()) })
{
VerifyStructWithValueConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStringConstantTest(bool useInterpreter)
{
foreach (string value in new string[] { null, "", "a", "foo" })
{
VerifyStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntConstantTest(bool useInterpreter)
{
foreach (uint value in new uint[] { 0, 1, uint.MaxValue })
{
VerifyUIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongConstantTest(bool useInterpreter)
{
foreach (ulong value in new ulong[] { 0, 1, ulong.MaxValue })
{
VerifyULongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortConstantTest(bool useInterpreter)
{
foreach (ushort value in new ushort[] { 0, 1, ushort.MaxValue })
{
VerifyUShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithEnumConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithCustomTest(bool useInterpreter)
{
CheckGenericHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithEnumTest(bool useInterpreter)
{
CheckGenericHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithObjectTest(bool useInterpreter)
{
CheckGenericHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructTest(bool useInterpreter)
{
CheckGenericHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructWithStringAndValueTest(bool useInterpreter)
{
CheckGenericHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassAndNewRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter);
}
#endregion
#region Generic helpers
public static void CheckGenericWithStructRestrictionConstantHelper<Ts>(bool useInterpreter) where Ts : struct
{
foreach (Ts value in new Ts[] { default(Ts), new Ts() })
{
VerifyGenericWithStructRestriction<Ts>(value, useInterpreter);
}
}
public static void CheckGenericHelper<T>(bool useInterpreter)
{
foreach (T value in new T[] { default(T) })
{
VerifyGeneric<T>(value, useInterpreter);
}
}
public static void CheckGenericWithClassRestrictionHelper<Tc>(bool useInterpreter) where Tc : class
{
foreach (Tc value in new Tc[] { null, default(Tc) })
{
VerifyGenericWithClassRestriction<Tc>(value, useInterpreter);
}
}
public static void CheckGenericWithClassAndNewRestrictionHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
foreach (Tcn value in new Tcn[] { null, default(Tcn), new Tcn() })
{
VerifyGenericWithClassAndNewRestriction<Tcn>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C
{
foreach (TC value in new TC[] { null, default(TC), (TC)new C() })
{
VerifyGenericWithSubClassRestriction<TC>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
foreach (TCn value in new TCn[] { null, default(TCn), new TCn(), (TCn)new C() })
{
VerifyGenericWithSubClassAndNewRestriction<TCn>(value, useInterpreter);
}
}
#endregion
#region Test verifiers
private static void VerifyBoolConstant(bool value, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Constant(value, typeof(bool)),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyByteConstant(byte value, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Constant(value, typeof(byte)),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustomConstant(C value, bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.Constant(value, typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCharConstant(char value, bool useInterpreter)
{
Expression<Func<char>> e =
Expression.Lambda<Func<char>>(
Expression.Constant(value, typeof(char)),
Enumerable.Empty<ParameterExpression>());
Func<char> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustom2Constant(D value, bool useInterpreter)
{
Expression<Func<D>> e =
Expression.Lambda<Func<D>>(
Expression.Constant(value, typeof(D)),
Enumerable.Empty<ParameterExpression>());
Func<D> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDecimalConstant(decimal value, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Constant(value, typeof(decimal)),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDelegateConstant(Delegate value, bool useInterpreter)
{
Expression<Func<Delegate>> e =
Expression.Lambda<Func<Delegate>>(
Expression.Constant(value, typeof(Delegate)),
Enumerable.Empty<ParameterExpression>());
Func<Delegate> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDoubleConstant(double value, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Constant(value, typeof(double)),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumConstant(E value, bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.Constant(value, typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumLongConstant(El value, bool useInterpreter)
{
Expression<Func<El>> e =
Expression.Lambda<Func<El>>(
Expression.Constant(value, typeof(El)),
Enumerable.Empty<ParameterExpression>());
Func<El> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFloatConstant(float value, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Constant(value, typeof(float)),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFuncOfObjectConstant(Func<object> value, bool useInterpreter)
{
Expression<Func<Func<object>>> e =
Expression.Lambda<Func<Func<object>>>(
Expression.Constant(value, typeof(Func<object>)),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyInterfaceConstant(I value, bool useInterpreter)
{
Expression<Func<I>> e =
Expression.Lambda<Func<I>>(
Expression.Constant(value, typeof(I)),
Enumerable.Empty<ParameterExpression>());
Func<I> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustomConstant(IEquatable<C> value, bool useInterpreter)
{
Expression<Func<IEquatable<C>>> e =
Expression.Lambda<Func<IEquatable<C>>>(
Expression.Constant(value, typeof(IEquatable<C>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustom2Constant(IEquatable<D> value, bool useInterpreter)
{
Expression<Func<IEquatable<D>>> e =
Expression.Lambda<Func<IEquatable<D>>>(
Expression.Constant(value, typeof(IEquatable<D>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIntConstant(int value, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Constant(value, typeof(int)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyLongConstant(long value, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Constant(value, typeof(long)),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyObjectConstant(object value, bool useInterpreter)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Constant(value, typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructConstant(S value, bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.Constant(value, typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifySByteConstant(sbyte value, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Constant(value, typeof(sbyte)),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringConstant(Sc value, bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.Constant(value, typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringAndFieldConstant(Scs value, bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.Constant(value, typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyShortConstant(short value, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Constant(value, typeof(short)),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithTwoValuesConstant(Sp value, bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.Constant(value, typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithValueConstant(Ss value, bool useInterpreter)
{
Expression<Func<Ss>> e =
Expression.Lambda<Func<Ss>>(
Expression.Constant(value, typeof(Ss)),
Enumerable.Empty<ParameterExpression>());
Func<Ss> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStringConstant(string value, bool useInterpreter)
{
Expression<Func<string>> e =
Expression.Lambda<Func<string>>(
Expression.Constant(value, typeof(string)),
Enumerable.Empty<ParameterExpression>());
Func<string> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUIntConstant(uint value, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Constant(value, typeof(uint)),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyULongConstant(ulong value, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Constant(value, typeof(ulong)),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUShortConstant(ushort value, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Constant(value, typeof(ushort)),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithStructRestriction<Ts>(Ts value, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.Constant(value, typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGeneric<T>(T value, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
Expression.Constant(value, typeof(T)),
Enumerable.Empty<ParameterExpression>());
Func<T> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassRestriction<Tc>(Tc value, bool useInterpreter) where Tc : class
{
Expression<Func<Tc>> e =
Expression.Lambda<Func<Tc>>(
Expression.Constant(value, typeof(Tc)),
Enumerable.Empty<ParameterExpression>());
Func<Tc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassAndNewRestriction<Tcn>(Tcn value, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<Tcn>> e =
Expression.Lambda<Func<Tcn>>(
Expression.Constant(value, typeof(Tcn)),
Enumerable.Empty<ParameterExpression>());
Func<Tcn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassRestriction<TC>(TC value, bool useInterpreter) where TC : C
{
Expression<Func<TC>> e =
Expression.Lambda<Func<TC>>(
Expression.Constant(value, typeof(TC)),
Enumerable.Empty<ParameterExpression>());
Func<TC> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(TCn value, bool useInterpreter) where TCn : C, new()
{
Expression<Func<TCn>> e =
Expression.Lambda<Func<TCn>>(
Expression.Constant(value, typeof(TCn)),
Enumerable.Empty<ParameterExpression>());
Func<TCn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
#endregion
[Fact]
public static void InvalidTypeValueType()
{
// implicit cast, but not reference assignable.
Assert.Throws<ArgumentException>(null, () => Expression.Constant(0, typeof(long)));
}
[Fact]
public static void InvalidTypeReferenceType()
{
Assert.Throws<ArgumentException>(null, () => Expression.Constant("hello", typeof(Expression)));
}
[Fact]
public static void NullType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Constant("foo", null));
}
[Fact]
public static void ByRefType()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(string).MakeByRefType()));
}
[Fact]
public static void PointerType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Constant(null, typeof(string).MakePointerType()));
}
[Fact]
public static void GenericType()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>)));
}
[Fact]
public static void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>).MakeGenericType(typeof(List<>))));
}
}
}
| |
using Innovator.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace InnovatorAdmin
{
public class ItemReference : IComparable<ItemReference>, IComparable, IEquatable<ItemReference>, ICloneable
{
private string _unique;
private string _baseUnique;
private string _type;
public string KeyedName { get; set; }
// Used when understanding dependencies
public ItemReference Origin { get; set; }
public string Type
{
get { return _type; }
set { _type = value; }
}
public string Unique
{
get { return _unique; }
set
{
_unique = value;
if (_unique.IndexOf("[config_id] = '") > 0)
_baseUnique = _unique.Substring(_unique.Length - 33, 32);
}
}
// Used with exporting
public int Levels { get; set; }
public SystemPropertyGroup SystemProps { get; set; }
public ItemReference()
{
this.Levels = -1;
this.SystemProps = SystemPropertyGroup.None;
}
public ItemReference(string type, string unique) : this()
{
this.Type = type;
this.Unique = unique;
}
public static ItemReference FromElement(XmlElement elem)
{
return elem.LocalName == "Item" ?
ItemReference.FromFullItem(elem, false) :
ItemReference.FromItemProp(elem);
}
public static ItemReference FromItemProp(XmlElement elem)
{
if (elem.Elements("Item").Any())
return FromFullItem(elem.Element("Item"), false);
return new ItemReference(elem.Attributes["type"].Value, elem.InnerText)
{
KeyedName = (elem.HasAttribute("keyed_name") ? elem.Attributes["keyed_name"].Value : "")
};
}
public static ItemReference FromFullItem(IReadOnlyItem elem, bool getKeyedName)
{
var result = new ItemReference();
FillItemRef(result, elem, getKeyedName);
return result;
}
internal static void FillItemRef(ItemReference result, IReadOnlyItem elem, bool getKeyedName)
{
result.Type = elem.Type().Value;
if (elem.Attribute("id").Exists)
{
result.Unique = elem.Attribute("id").Value;
}
else if (elem.Attribute("where").Exists)
{
result.Unique = elem.Attribute("where").Value;
}
if (getKeyedName)
{
if (result.Type == "FileType" && elem.Property("mimetype").HasValue())
{
result.KeyedName = elem.Property("extension").AsString("") + ", "
+ elem.Property("mimetype").AsString("");
}
else
{
IReadOnlyProperty_Base node = elem.Property("id");
if (node.Exists && node.KeyedName().Exists)
{
result.KeyedName = node.KeyedName().Value;
}
else
{
result.KeyedName = node.Attribute("_keyed_name").Value
?? elem.KeyedName().AsString(null)
?? elem.Property("name").AsString(null);
}
node = elem.SourceId();
if (node.Exists && node.KeyedName().Exists)
{
if (result.KeyedName.IsGuid())
{
var related = elem.RelatedId();
if (related.Exists && related.KeyedName().Exists)
{
result.KeyedName = node.Attribute("keyed_name").Value + " > " + related.Attribute("keyed_name").Value;
}
else
{
result.KeyedName = node.Attribute("keyed_name").Value + ": " + result.KeyedName;
}
}
else if (!string.IsNullOrEmpty(node.Attribute("keyed_name").Value))
{
result.KeyedName += " {" + node.Attribute("keyed_name").Value + "}";
}
}
}
}
}
public static ItemReference FromFullItem(XmlElement elem, bool getKeyedName)
{
var result = new ItemReference();
result.Type = elem.Attributes["type"].Value;
if (elem.HasAttribute("id"))
{
result.Unique = elem.Attributes["id"].Value;
}
else if (elem.HasAttribute("where"))
{
result.Unique = elem.Attributes["where"].Value;
}
if (getKeyedName)
{
if (result.Type == "FileType" && !string.IsNullOrEmpty(elem.Element("mimetype", null)))
{
result.KeyedName = elem.Element("extension", "") + ", " + elem.Element("mimetype", "");
}
else if (result.Type == "Identity" && !string.IsNullOrEmpty(elem.Element("name", null)))
{
result.KeyedName = elem.Element("name", "");
}
else
{
var node = elem.Elements(e => e.LocalName == "id" && e.HasAttribute("keyed_name")).SingleOrDefault();
if (node != null)
{
result.KeyedName = node.Attribute("keyed_name");
}
else
{
result.KeyedName = elem.Attribute("_keyed_name", null)
?? elem.Element("keyed_name", null)
?? elem.Element("name", null);
}
node = elem.Elements(e => e.LocalName == "source_id" && e.HasAttribute("keyed_name")).SingleOrDefault();
if (node != null)
{
if (result.KeyedName.IsGuid())
{
var related = elem.Elements(e => e.LocalName == "related_id" && e.HasAttribute("keyed_name")).SingleOrDefault();
if (related == null)
{
result.KeyedName = node.Attribute("keyed_name") + ": " + result.KeyedName;
}
else
{
result.KeyedName = node.Attribute("keyed_name") + " > " + related.Attribute("keyed_name");
}
}
else if (!string.IsNullOrEmpty(node.Attribute("keyed_name")))
{
result.KeyedName += " {" + node.Attribute("keyed_name") + "}";
}
}
}
}
return result;
}
public static IEnumerable<ItemReference> FromFullItems(XmlElement elem, bool getKeyedName)
{
var node = elem;
while (node != null && node.LocalName != "Item") node = node.ChildNodes.OfType<XmlElement>().FirstOrDefault();
if (node == null) return Enumerable.Empty<ItemReference>();
return (from e in node.ParentNode.ChildNodes.OfType<XmlElement>()
where e.LocalName == "Item"
select FromFullItem(e, getKeyedName));
}
public override bool Equals(object obj)
{
var itemRef = obj as ItemReference;
if (itemRef == null) return false;
return ((IEquatable<ItemReference>)this).Equals(itemRef);
}
bool IEquatable<ItemReference>.Equals(ItemReference itemRef)
{
return string.Equals(_baseUnique ?? _unique, itemRef._baseUnique ?? itemRef._unique, StringComparison.OrdinalIgnoreCase)
&& string.Equals(this.Type, itemRef.Type, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return (_baseUnique ?? _unique ?? "").ToUpperInvariant().GetHashCode()
^ (this.Type ?? "").ToUpperInvariant().GetHashCode();
}
public override string ToString()
{
return (this.Type ?? "") + ": " +
(string.IsNullOrEmpty(this.KeyedName) ?
(this.Unique ?? "") :
this.KeyedName
);
}
public int CompareTo(ItemReference other)
{
var compare = this.Type.ToUpperInvariant().CompareTo(other.Type.ToUpperInvariant());
if (compare == 0) compare = (this.KeyedName.ToUpperInvariant() ?? "").CompareTo(other.KeyedName.ToUpperInvariant() ?? "");
if (compare == 0) compare = this.Unique.CompareTo(other.Unique);
return compare;
}
public ItemReference Clone()
{
var result = new ItemReference();
result.KeyedName = this.KeyedName;
result.Origin = this.Origin;
result._type = this._type;
result._unique = this._unique;
result._baseUnique = this._baseUnique;
return result;
}
object ICloneable.Clone()
{
return this.Clone();
}
public int CompareTo(object obj)
{
var itemRef = obj as ItemReference;
if (itemRef == null) throw new ArgumentException();
return CompareTo(itemRef);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Xml;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.CoreModules.Avatar.Attachments
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
{
#region INonSharedRegionModule
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public int DebugLevel { get; set; }
/// <summary>
/// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes
/// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously.
/// </summary>
/// <remarks>
/// A value of 0 will apply no pause. The pause is specified in milliseconds.
/// </remarks>
public int ThrottlePer100PrimsRezzed { get; set; }
private Scene m_scene;
private IInventoryAccessModule m_invAccessModule;
/// <summary>
/// Are attachments enabled?
/// </summary>
public bool Enabled { get; private set; }
public string Name { get { return "Attachments Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Attachments"];
if (config != null)
{
Enabled = config.GetBoolean("Enabled", true);
ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0);
}
else
{
Enabled = true;
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
if (Enabled)
{
// Only register module with scene if it is enabled. All callers check for a null attachments module.
// Ideally, there should be a null attachments module for when this core attachments module has been
// disabled. Registering only when enabled allows for other attachments module implementations.
m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true);
m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments log",
"debug attachments log [0|1]",
"Turn on attachments debug logging",
" <= 0 - turns off debug logging\n"
+ " >= 1 - turns on attachment message debug logging",
HandleDebugAttachmentsLog);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments throttle",
"debug attachments throttle <ms>",
"Turn on attachments throttling.",
"This requires a millisecond value. " +
" == 0 - disable throttling.\n"
+ " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.",
HandleDebugAttachmentsThrottle);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments status",
"debug attachments status",
"Show current attachments debug status",
HandleDebugAttachmentsStatus);
}
// TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
}
private void HandleDebugAttachmentsLog(string module, string[] args)
{
int debugLevel;
if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel)))
{
MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]");
}
else
{
DebugLevel = debugLevel;
MainConsole.Instance.OutputFormat(
"Set attachments debug level to {0} in {1}", DebugLevel, m_scene.Name);
}
}
private void HandleDebugAttachmentsThrottle(string module, string[] args)
{
int ms;
if (args.Length == 4 && int.TryParse(args[3], out ms))
{
ThrottlePer100PrimsRezzed = ms;
MainConsole.Instance.OutputFormat(
"Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name);
return;
}
MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>");
}
private void HandleDebugAttachmentsStatus(string module, string[] args)
{
MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name);
MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel);
MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed);
}
/// <summary>
/// Listen for client triggered running state changes so that we can persist the script's object if necessary.
/// </summary>
/// <param name='localID'></param>
/// <param name='itemID'></param>
private void HandleScriptStateChange(uint localID, bool started)
{
SceneObjectGroup sog = m_scene.GetGroupByPrim(localID);
if (sog != null && sog.IsAttachment)
{
if (!started)
{
// FIXME: This is a convoluted way for working out whether the script state has changed to stop
// because it has been manually stopped or because the stop was called in UpdateDetachedObject() below
// This needs to be handled in a less tangled way.
ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar);
if (sp.ControllingClient.IsActive)
sog.HasGroupChanged = true;
}
else
{
sog.HasGroupChanged = true;
}
}
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
if (Enabled)
m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
}
public void RegionLoaded(Scene scene)
{
m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
}
public void Close()
{
RemoveRegion(m_scene);
}
#endregion
#region IAttachmentsModule
public void CopyAttachments(IScenePresence sp, AgentData ad)
{
lock (sp.AttachmentsSyncLock)
{
// Attachment objects
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (attachments.Count > 0)
{
ad.AttachmentObjects = new List<ISceneObject>();
ad.AttachmentObjectStates = new List<string>();
// IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
sp.InTransitScriptStates.Clear();
foreach (SceneObjectGroup sog in attachments)
{
// We need to make a copy and pass that copy
// because of transfers withn the same sim
ISceneObject clone = sog.CloneForNewScene();
// Attachment module assumes that GroupPosition holds the offsets...!
((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
((SceneObjectGroup)clone).IsAttachment = false;
ad.AttachmentObjects.Add(clone);
string state = sog.GetStateSnapshot();
ad.AttachmentObjectStates.Add(state);
sp.InTransitScriptStates.Add(state);
// Scripts of the originals will be removed when the Agent is successfully removed.
// sog.RemoveScriptInstances(true);
}
}
}
}
public void CopyAttachments(AgentData ad, IScenePresence sp)
{
// m_log.DebugFormat("[ATTACHMENTS MODULE]: Copying attachment data into {0} in {1}", sp.Name, m_scene.Name);
if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
{
lock (sp.AttachmentsSyncLock)
sp.ClearAttachments();
int i = 0;
foreach (ISceneObject so in ad.AttachmentObjects)
{
((SceneObjectGroup)so).LocalId = 0;
((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: Copying script state with {0} bytes for object {1} for {2} in {3}",
// ad.AttachmentObjectStates[i].Length, so.Name, sp.Name, m_scene.Name);
so.SetState(ad.AttachmentObjectStates[i++], m_scene);
m_scene.IncomingCreateObject(Vector3.Zero, so);
}
}
}
public void RezAttachments(IScenePresence sp)
{
if (!Enabled)
return;
if (null == sp.Appearance)
{
m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
return;
}
if (sp.GetAttachments().Count > 0)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments",
m_scene.Name, sp.Name);
return;
}
if (DebugLevel > 0)
m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name);
List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
// Let's get all items at once, so they get cached
UUID[] items = new UUID[attachments.Count];
int i = 0;
foreach (AvatarAttachment attach in attachments)
items[i++] = attach.ItemID;
m_scene.InventoryService.GetMultipleItems(sp.UUID, items);
foreach (AvatarAttachment attach in attachments)
{
uint attachmentPt = (uint)attach.AttachPoint;
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
// attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
// For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
// But they're not used anyway, the item is being looked up for now, so let's proceed.
//if (UUID.Zero == assetID)
//{
// m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
// continue;
//}
try
{
// If we're an NPC then skip all the item checks and manipulations since we don't have an
// inventory right now.
RezSingleAttachmentFromInventoryInternal(
sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true);
}
catch (Exception e)
{
UUID agentId = (sp.ControllingClient == null) ? default(UUID) : sp.ControllingClient.AgentId;
m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace);
}
}
}
public void DeRezAttachments(IScenePresence sp)
{
if (!Enabled)
return;
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Saving for {0} attachments for {1} in {2}",
attachments.Count, sp.Name, m_scene.Name);
if (attachments.Count <= 0)
return;
Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>();
foreach (SceneObjectGroup so in attachments)
{
// Scripts MUST be snapshotted before the object is
// removed from the scene because doing otherwise will
// clobber the run flag
// This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
// scripts performing attachment operations at the same time. Getting object states stops the scripts.
scriptStates[so] = PrepareScriptInstanceForSave(so, false);
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: For object {0} for {1} in {2} got saved state {3}",
// so.Name, sp.Name, m_scene.Name, scriptStates[so]);
}
lock (sp.AttachmentsSyncLock)
{
foreach (SceneObjectGroup so in attachments)
UpdateDetachedObject(sp, so, scriptStates[so]);
sp.ClearAttachments();
}
}
public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
m_scene.RegionInfo.RegionName, sp.Name, silent);
foreach (SceneObjectGroup sop in sp.GetAttachments())
{
sop.Scene.DeleteSceneObject(sop, silent);
}
sp.ClearAttachments();
}
public bool AttachObject(
IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append)
{
if (!Enabled)
return false;
group.DetachFromBackup();
bool success = AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append);
if (!success)
group.AttachToBackup();
return success;
}
/// <summary>
/// Internal method which actually does all the work for attaching an object.
/// </summary>
/// <returns>The object attached.</returns>
/// <param name='sp'></param>
/// <param name='group'>The object to attach.</param>
/// <param name='attachmentPt'></param>
/// <param name='silent'></param>
/// <param name='addToInventory'>If true then add object to user inventory.</param>
/// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param>
/// <param name='append'>Append to attachment point rather than replace.</param>
private bool AttachObjectInternal(
IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append)
{
if (group.GetSittingAvatarsCount() != 0)
{
if (DebugLevel > 0)
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
return false;
}
Vector3 attachPos = group.AbsolutePosition;
// If the attachment point isn't the same as the one previously used
// set it's offset position = 0 so that it appears on the attachment point
// and not in a weird location somewhere unknown.
if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint)
{
attachPos = Vector3.Zero;
}
// if the attachment point is the same as previous, make sure we get the saved
// position info.
if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint)
{
attachPos = group.RootPart.AttachedPos;
}
// AttachmentPt 0 means the client chose to 'wear' the attachment.
if (attachmentPt == (uint)AttachmentPoint.Default)
{
// Check object for stored attachment point
attachmentPt = group.AttachmentPoint;
}
// if we didn't find an attach point, look for where it was last attached
if (attachmentPt == 0)
{
attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint;
attachPos = group.RootPart.AttachedPos;
group.HasGroupChanged = true;
}
// if we still didn't find a suitable attachment point.......
if (attachmentPt == 0)
{
// Stick it on left hand with Zero Offset from the attachment point.
attachmentPt = (uint)AttachmentPoint.LeftHand;
attachPos = Vector3.Zero;
}
group.AttachmentPoint = attachmentPt;
group.AbsolutePosition = attachPos;
List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
if (attachments.Contains(group))
{
if (DebugLevel > 0)
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
group.Name, group.LocalId, sp.Name, attachmentPt);
return false;
}
// If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
while (attachments.Count >= 5)
{
if (attachments[0].FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, attachments[0]);
attachments.RemoveAt(0);
}
// If we're not appending, remove the rest as well
if (attachments.Count != 0 && !append)
{
foreach (SceneObjectGroup g in attachments)
{
if (g.FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, g);
}
}
lock (sp.AttachmentsSyncLock)
{
if (addToInventory && sp.PresenceType != PresenceType.Npc)
UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
AttachToAgent(sp, group, attachmentPt, attachPos, silent);
if (resumeScripts)
{
// Fire after attach, so we don't get messy perms dialogs
// 4 == AttachedRez
group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
group.ResumeScripts();
}
// Do this last so that event listeners have access to all the effects of the attachment
m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
}
return true;
}
private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append)
{
// Add the new attachment to inventory if we don't already have it.
UUID newAttachmentItemID = group.FromItemID;
if (newAttachmentItemID == UUID.Zero)
newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append);
}
public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
{
if (!Enabled)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}",
(AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name);
// We check the attachments in the avatar appearance here rather than the objects attached to the
// ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are
// already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done
// because pre-outfit folder viewers (most version 1 viewers) require it.
bool alreadyOn = false;
List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments();
foreach (AvatarAttachment existingAttachment in existingAttachments)
{
if (existingAttachment.ItemID == itemID)
{
alreadyOn = true;
break;
}
}
if (alreadyOn)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
sp.Name, itemID, AttachmentPt);
return null;
}
bool append = (AttachmentPt & 0x80) != 0;
AttachmentPt &= 0x7f;
return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append);
}
public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}",
rezlist.Count, sp.Name, m_scene.Name);
foreach (KeyValuePair<UUID, uint> rez in rezlist)
{
RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
}
}
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
{
DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
}
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
sp.UUID, soLocalId);
SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
if (so == null)
return;
if (so.AttachedAvatar != sp.UUID)
return;
UUID inventoryID = so.FromItemID;
// As per Linden spec, drop is disabled for temp attachs
if (inventoryID == UUID.Zero)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
so.Name, so.LocalId, inventoryID);
lock (sp.AttachmentsSyncLock)
{
if (!m_scene.Permissions.CanRezObject(
so.PrimCount, sp.UUID, sp.AbsolutePosition))
return;
bool changed = false;
if (inventoryID != UUID.Zero)
changed = sp.Appearance.DetachAttachment(inventoryID);
if (changed && m_scene.AvatarFactory != null)
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
sp.RemoveAttachment(so);
so.FromItemID = UUID.Zero;
SceneObjectPart rootPart = so.RootPart;
so.AbsolutePosition = absolutePos;
if (absoluteRot != Quaternion.Identity)
{
so.UpdateGroupRotationR(absoluteRot);
}
so.AttachedAvatar = UUID.Zero;
rootPart.SetParentLocalId(0);
so.ClearPartAttachmentData();
rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
so.HasGroupChanged = true;
so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint;
rootPart.Rezzed = DateTime.Now;
rootPart.RemFlag(PrimFlags.TemporaryOnRez);
so.AttachToBackup();
m_scene.EventManager.TriggerParcelPrimCountTainted();
rootPart.ScheduleFullUpdate();
rootPart.ClearUndoState();
List<UUID> uuids = new List<UUID>();
uuids.Add(inventoryID);
m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
}
m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
}
public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
{
if (so.AttachedAvatar != sp.UUID)
{
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
return;
}
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}",
so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name);
// Scripts MUST be snapshotted before the object is
// removed from the scene because doing otherwise will
// clobber the run flag
// This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
// scripts performing attachment operations at the same time. Getting object states stops the scripts.
string scriptedState = PrepareScriptInstanceForSave(so, true);
lock (sp.AttachmentsSyncLock)
{
// Save avatar attachment information
// m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
if (changed && m_scene.AvatarFactory != null)
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
sp.RemoveAttachment(so);
UpdateDetachedObject(sp, so, scriptedState);
}
}
public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
{
if (!Enabled)
return;
sog.UpdateGroupPosition(pos);
sog.HasGroupChanged = true;
}
#endregion
#region AttachmentModule private methods
// This is public but is not part of the IAttachmentsModule interface.
// RegionCombiner module needs to poke at it to deliver client events.
// This breaks the encapsulation of the module and should get fixed somehow.
public void SubscribeToClientEvents(IClientAPI client)
{
client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
client.OnObjectAttach += Client_OnObjectAttach;
client.OnObjectDetach += Client_OnObjectDetach;
client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
client.OnObjectDrop += Client_OnObjectDrop;
}
// This is public but is not part of the IAttachmentsModule interface.
// RegionCombiner module needs to poke at it to deliver client events.
// This breaks the encapsulation of the module and should get fixed somehow.
public void UnsubscribeFromClientEvents(IClientAPI client)
{
client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
client.OnObjectAttach -= Client_OnObjectAttach;
client.OnObjectDetach -= Client_OnObjectDetach;
client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
client.OnObjectDrop -= Client_OnObjectDrop;
}
/// <summary>
/// Update the attachment asset for the new sog details if they have changed.
/// </summary>
/// <remarks>
/// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
/// these details are not stored on the region.
/// </remarks>
/// <param name="sp"></param>
/// <param name="grp"></param>
/// <param name="saveAllScripted"></param>
private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
{
if (grp.FromItemID == UUID.Zero)
{
// We can't save temp attachments
grp.HasGroupChanged = false;
return;
}
// Saving attachments for NPCs messes them up for the real owner!
INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
if (module != null)
{
if (module.IsNPC(sp.UUID, m_scene))
return;
}
if (grp.HasGroupChanged)
{
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
grp.UUID, grp.AttachmentPoint);
string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
item = m_scene.InventoryService.GetItem(item);
if (item != null)
{
AssetBase asset = m_scene.CreateAsset(
grp.GetPartName(grp.LocalId),
grp.GetPartDescription(grp.LocalId),
(sbyte)AssetType.Object,
Utils.StringToBytes(sceneObjectXml),
sp.UUID);
if (m_invAccessModule != null)
m_invAccessModule.UpdateInventoryItemAsset(sp.UUID, item, asset);
// If the name of the object has been changed whilst attached then we want to update the inventory
// item in the viewer.
if (sp.ControllingClient != null)
sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
}
grp.HasGroupChanged = false; // Prevent it being saved over and over
}
else if (DebugLevel > 0)
{
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
grp.UUID, grp.AttachmentPoint);
}
}
/// <summary>
/// Attach this scene object to the given avatar.
/// </summary>
/// <remarks>
/// This isn't publicly available since attachments should always perform the corresponding inventory
/// operation (to show the attach in user inventory and update the asset with positional information).
/// </remarks>
/// <param name="sp"></param>
/// <param name="so"></param>
/// <param name="attachmentpoint"></param>
/// <param name="attachOffset"></param>
/// <param name="silent"></param>
private void AttachToAgent(
IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} at pt {2} pos {3} {4} in {5}",
so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos, m_scene.Name);
// Remove from database and parcel prim count
m_scene.DeleteFromStorage(so.UUID);
m_scene.EventManager.TriggerParcelPrimCountTainted();
so.AttachedAvatar = sp.UUID;
if (so.RootPart.PhysActor != null)
so.RootPart.RemoveFromPhysics();
so.AbsolutePosition = attachOffset;
so.RootPart.AttachedPos = attachOffset;
so.IsAttachment = true;
so.RootPart.SetParentLocalId(sp.LocalId);
so.AttachmentPoint = attachmentpoint;
sp.AddAttachment(so);
if (!silent)
{
if (so.HasPrivateAttachmentPoint)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
so.Name, sp.Name, so.AttachmentPoint);
// As this scene object can now only be seen by the attaching avatar, tell everybody else in the
// scene that it's no longer in their awareness.
m_scene.ForEachClient(
client =>
{ if (client.AgentId != so.AttachedAvatar)
client.SendKillObject(new List<uint>() { so.LocalId });
});
}
// Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
// will succeed, as that will not update if an attachment is selected.
so.IsSelected = false; // fudge....
so.ScheduleGroupForFullUpdate();
}
// In case it is later dropped again, don't let
// it get cleaned up
so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
}
/// <summary>
/// Add a scene object as a new attachment in the user inventory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="grp"></param>
/// <returns>The user inventory item created that holds the attachment.</returns>
private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
{
if (m_invAccessModule == null)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
grp.Name, grp.LocalId, sp.Name);
InventoryItemBase newItem
= m_invAccessModule.CopyToInventory(
DeRezAction.TakeCopy,
m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
new List<SceneObjectGroup> { grp },
sp.ControllingClient, true)[0];
// sets itemID so client can show item as 'attached' in inventory
grp.FromItemID = newItem.ID;
return newItem;
}
/// <summary>
/// Prepares the script instance for save.
/// </summary>
/// <remarks>
/// This involves triggering the detach event and getting the script state (which also stops the script)
/// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a
/// running script is performing attachment operations.
/// </remarks>
/// <returns>
/// The script state ready for persistence.
/// </returns>
/// <param name='grp'>
/// </param>
/// <param name='fireDetachEvent'>
/// If true, then fire the script event before we save its state.
/// </param>
private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent)
{
if (fireDetachEvent)
{
m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero);
// Allow detach event time to do some work before stopping the script
Thread.Sleep(2);
}
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
grp.SaveScriptedState(writer);
}
return sw.ToString();
}
}
private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState)
{
// Don't save attachments for HG visitors, it
// messes up their inventory. When a HG visitor logs
// out on a foreign grid, their attachments will be
// reloaded in the state they were in when they left
// the home grid. This is best anyway as the visited
// grid may use an incompatible script engine.
bool saveChanged
= sp.PresenceType != PresenceType.Npc
&& (m_scene.UserManagementModule == null
|| m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
// Remove the object from the scene so no more updates
// are sent. Doing this before the below changes will ensure
// updates can't cause "HUD artefacts"
m_scene.DeleteSceneObject(so, false, false);
// Prepare sog for storage
so.AttachedAvatar = UUID.Zero;
so.RootPart.SetParentLocalId(0);
so.IsAttachment = false;
if (saveChanged)
{
// We cannot use AbsolutePosition here because that would
// attempt to cross the prim as it is detached
so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
UpdateKnownItem(sp, so, scriptedState);
}
// Now, remove the scripts
so.RemoveScriptInstances(true);
}
protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append)
{
if (m_invAccessModule == null)
return null;
SceneObjectGroup objatt;
if (itemID != UUID.Zero)
objatt = m_invAccessModule.RezObject(sp.ControllingClient,
itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
false, false, sp.UUID, true);
else
objatt = m_invAccessModule.RezObject(sp.ControllingClient,
null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
false, false, sp.UUID, true);
if (objatt == null)
{
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
itemID, sp.Name, attachmentPt);
return null;
}
else if (itemID == UUID.Zero)
{
// We need to have a FromItemID for multiple attachments on a single attach point to appear. This is
// true on Singularity 1.8.5 and quite possibly other viewers as well. As NPCs don't have an inventory
// we will satisfy this requirement by inserting a random UUID.
objatt.FromItemID = UUID.Random();
}
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}",
objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
// HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
objatt.HasGroupChanged = false;
bool tainted = false;
if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
tainted = true;
// FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
// course of events. If not, then it's probably not worth trying to recover the situation
// since this is more likely to trigger further exceptions and confuse later debugging. If
// exceptions can be thrown in expected error conditions (not NREs) then make this consistent
// since other normal error conditions will simply return false instead.
// This will throw if the attachment fails
try
{
AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
// Make sure the object doesn't stick around and bail
sp.RemoveAttachment(objatt);
m_scene.DeleteSceneObject(objatt, false);
return null;
}
if (tainted)
objatt.HasGroupChanged = true;
if (ThrottlePer100PrimsRezzed > 0)
{
int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed);
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}",
throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
Thread.Sleep(throttleMs);
}
return objatt;
}
/// <summary>
/// Update the user inventory to reflect an attachment
/// </summary>
/// <param name="sp"></param>
/// <param name="AttachmentPt"></param>
/// <param name="itemID"></param>
/// <param name="att"></param>
private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append)
{
// m_log.DebugFormat(
// "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
// att.Name, sp.Name, AttachmentPt, itemID);
if (UUID.Zero == itemID)
{
m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
return;
}
if (0 == AttachmentPt)
{
m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
return;
}
InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
item = m_scene.InventoryService.GetItem(item);
if (item == null)
return;
int attFlag = append ? 0x80 : 0;
bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID);
if (changed && m_scene.AvatarFactory != null)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
sp.Name, att.Name, AttachmentPt);
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
}
}
#endregion
#region Client Event Handlers
private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
{
if (!Enabled)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
(AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp == null)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
remoteClient.Name, remoteClient.AgentId);
return null;
}
return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
}
private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
RezMultipleAttachmentsFromInventory(sp, rezlist);
else
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
remoteClient.Name, remoteClient.AgentId);
}
private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
objectLocalID, remoteClient.Name, AttachmentPt, silent);
if (!Enabled)
return;
try
{
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp == null)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
return;
}
// If we can't take it, we can't attach it!
SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
if (part == null)
return;
if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage(
"You don't have sufficient permissions to attach this object", false);
return;
}
bool append = (AttachmentPt & 0x80) != 0;
AttachmentPt &= 0x7f;
// Calls attach with a Zero position
if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append))
{
if (DebugLevel > 0)
m_log.Debug(
"[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
+ ", AttachmentPoint: " + AttachmentPt);
// Save avatar attachment information
m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
}
}
private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
if (sp != null && group != null && group.FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, group);
}
private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
{
List<SceneObjectGroup> attachments = sp.GetAttachments();
foreach (SceneObjectGroup group in attachments)
{
if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
{
DetachSingleAttachmentToInv(sp, group);
return;
}
}
}
}
private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
DetachSingleAttachmentToGround(sp, soLocalId);
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.Serialization;
namespace System.ServiceModel.Channels
{
[DataContract]
internal sealed class BaseUriWithWildcard
{
[DataMember]
private Uri _baseAddress;
private const char segmentDelimiter = '/';
[DataMember]
private HostNameComparisonMode _hostNameComparisonMode;
private const string plus = "+";
private const string star = "*";
private const int HttpUriDefaultPort = 80;
private const int HttpsUriDefaultPort = 443;
// Derived from [DataMember] fields
private Comparand _comparand;
private int _hashCode;
public BaseUriWithWildcard(Uri baseAddress, HostNameComparisonMode hostNameComparisonMode)
{
_baseAddress = baseAddress;
_hostNameComparisonMode = hostNameComparisonMode;
this.SetComparisonAddressAndHashCode();
// Note the Uri may contain query string for WSDL purpose.
// So do not check IsValid().
}
private BaseUriWithWildcard(string protocol, int defaultPort, string binding, int segmentCount, string path, string sampleBinding)
{
string[] urlParameters = SplitBinding(binding);
if (urlParameters.Length != segmentCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new FormatException(SR.Format(SR.Hosting_MisformattedBinding, binding, protocol, sampleBinding)));
}
int currentIndex = segmentCount - 1;
string host = ParseHostAndHostNameComparisonMode(urlParameters[currentIndex]);
int port = -1;
if (--currentIndex >= 0)
{
string portString = urlParameters[currentIndex].Trim();
if (!string.IsNullOrEmpty(portString) &&
!int.TryParse(portString, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out port))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.Hosting_MisformattedPort, protocol, binding, portString)));
}
if (port == defaultPort)
{
// Set to -1 so that Uri does not show it in the string.
port = -1;
}
}
try
{
Fx.Assert(path != null, "path should never be null here");
_baseAddress = new UriBuilder(protocol, host, port, path).Uri;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.Hosting_MisformattedBindingData, binding,
protocol)));
}
SetComparisonAddressAndHashCode();
}
internal Uri BaseAddress
{
get { return _baseAddress; }
}
internal HostNameComparisonMode HostNameComparisonMode
{
get { return _hostNameComparisonMode; }
}
private static string[] SplitBinding(string binding)
{
bool parsingIPv6Address = false;
string[] tokens = null;
const char splitChar = ':', startIPv6Address = '[', endIPv6Address = ']';
List<int> splitLocations = null;
for (int i = 0; i < binding.Length; i++)
{
if (parsingIPv6Address && binding[i] == endIPv6Address)
{
parsingIPv6Address = false;
}
else if (binding[i] == startIPv6Address)
{
parsingIPv6Address = true;
}
else if (!parsingIPv6Address && binding[i] == splitChar)
{
if (splitLocations == null)
{
splitLocations = new List<int>();
}
splitLocations.Add(i);
}
}
if (splitLocations == null)
{
tokens = new string[] { binding };
}
else
{
tokens = new string[splitLocations.Count + 1];
int startIndex = 0;
for (int i = 0; i < tokens.Length; i++)
{
if (i < splitLocations.Count)
{
int nextSplitIndex = splitLocations[i];
tokens[i] = binding.Substring(startIndex, nextSplitIndex - startIndex);
startIndex = nextSplitIndex + 1;
}
else //splitting the last segment
{
if (startIndex < binding.Length)
{
tokens[i] = binding.Substring(startIndex, binding.Length - startIndex);
}
else
{
//splitChar was the last character in the string
tokens[i] = string.Empty;
}
}
}
}
return tokens;
}
internal static BaseUriWithWildcard CreateHostedUri(string protocol, string binding, string path)
{
Fx.Assert(protocol != null, "caller must verify");
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
}
if (path == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("path");
}
throw ExceptionHelper.PlatformNotSupported();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.Hosting_NotSupportedProtocol, binding)));
}
internal static BaseUriWithWildcard CreateHostedPipeUri(string binding, string path)
{
// For net.pipe, binding format is: "<hostName>"
return new BaseUriWithWildcard(UriEx.UriSchemeNetPipe, -1, binding, 1, path, "*");
}
public override bool Equals(object o)
{
BaseUriWithWildcard other = o as BaseUriWithWildcard;
if (other == null || other._hashCode != _hashCode || other._hostNameComparisonMode != _hostNameComparisonMode ||
other._comparand.Port != _comparand.Port)
{
return false;
}
if (!object.ReferenceEquals(other._comparand.Scheme, _comparand.Scheme))
{
return false;
}
return _comparand.Address.Equals(other._comparand.Address);
}
public override int GetHashCode()
{
return _hashCode;
}
internal bool IsBaseOf(Uri fullAddress)
{
if ((object)_baseAddress.Scheme != (object)fullAddress.Scheme)
{
return false;
}
if (_baseAddress.Port != fullAddress.Port)
{
return false;
}
if (this.HostNameComparisonMode == HostNameComparisonMode.Exact)
{
if (string.Compare(_baseAddress.Host, fullAddress.Host, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
}
string s1 = _baseAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped);
string s2 = fullAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped);
if (s1.Length > s2.Length)
{
return false;
}
if (s1.Length < s2.Length &&
s1[s1.Length - 1] != segmentDelimiter &&
s2[s1.Length] != segmentDelimiter)
{
// Matching over segments
return false;
}
return string.Compare(s2, 0, s1, 0, s1.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
UriSchemeKeyedCollection.ValidateBaseAddress(_baseAddress, "context");
if (!HostNameComparisonModeHelper.IsDefined(this.HostNameComparisonMode))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("context", SR.Hosting_BaseUriDeserializedNotValid);
}
this.SetComparisonAddressAndHashCode();
}
private string ParseHostAndHostNameComparisonMode(string host)
{
if (string.IsNullOrEmpty(host) || host.Equals(star))
{
_hostNameComparisonMode = HostNameComparisonMode.WeakWildcard;
host = DnsCache.MachineName;
}
else if (host.Equals(plus))
{
_hostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
host = DnsCache.MachineName;
}
else
{
_hostNameComparisonMode = HostNameComparisonMode.Exact;
}
return host;
}
private void SetComparisonAddressAndHashCode()
{
if (this.HostNameComparisonMode == HostNameComparisonMode.Exact)
{
// Use canonical string representation of the full base address for comparison
_comparand.Address = _baseAddress.ToString();
}
else
{
// Use canonical string representation of the absolute path for comparison
_comparand.Address = _baseAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
}
_comparand.Port = _baseAddress.Port;
_comparand.Scheme = _baseAddress.Scheme;
if ((_comparand.Port == -1) && ((object)_comparand.Scheme == (object)UriEx.UriSchemeNetTcp))
{
// Compensate for the fact that the Uri type doesn't know about our default TCP port number
_comparand.Port = 808;
//desktop: this.comparand.Port = TcpUri.DefaultPort;
}
_hashCode = _comparand.Address.GetHashCode() ^ _comparand.Port ^ (int)this.HostNameComparisonMode;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.HostNameComparisonMode, this.BaseAddress);
}
private struct Comparand
{
public string Address;
public int Port;
public string Scheme;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// What kind of "player" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
// Leave $Game::defaultPlayerClass and $Game::defaultPlayerDataBlock as empty strings ("")
// to spawn a the $Game::defaultCameraClass as the control object.
$Game::DefaultPlayerClass = "";
$Game::DefaultPlayerDataBlock = "";
$Game::DefaultPlayerSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
//-----------------------------------------------------------------------------
// What kind of "camera" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
$Game::DefaultCameraClass = "Camera";
$Game::DefaultCameraDataBlock = "Observer";
$Game::DefaultCameraSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
// Global movement speed that affects all Cameras
$Camera::MovementSpeed = 30;
//-----------------------------------------------------------------------------
// GameConnection manages the communication between the server's world and the
// client's simulation. These functions are responsible for maintaining the
// client's camera and player objects.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// This is the main entry point for spawning a control object for the client.
// The control object is the actual game object that the client is responsible
// for controlling in the client and server simulations. We also spawn a
// convenient camera object for use as an alternate control object. We do not
// have to spawn this camera object in order to function in the simulation.
//
// Called for each client after it's finished downloading the mission and is
// ready to start playing.
//-----------------------------------------------------------------------------
function GameConnection::onClientEnterGame(%this)
{
// This function currently relies on some helper functions defined in
// core/scripts/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
// Find a spawn point for the camera
%cameraSpawnPoint = pickCameraSpawnPoint($Game::DefaultCameraSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%this.spawnCamera(%cameraSpawnPoint);
// Find a spawn point for the player
%playerSpawnPoint = pickPlayerSpawnPoint($Game::DefaultPlayerSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%this.spawnPlayer(%playerSpawnPoint);
}
//-----------------------------------------------------------------------------
// Clean up the client's control objects
//-----------------------------------------------------------------------------
function GameConnection::onClientLeaveGame(%this)
{
// Cleanup the camera
if (isObject(%this.camera))
%this.camera.delete();
// Cleanup the player
if (isObject(%this.player))
%this.player.delete();
}
//-----------------------------------------------------------------------------
// Handle a player's death
//-----------------------------------------------------------------------------
function GameConnection::onDeath(%this, %sourceObject, %sourceClient, %damageType, %damLoc)
{
// Clear out the name on the corpse
if (isObject(%this.player))
{
if (%this.player.isMethod("setShapeName"))
%this.player.setShapeName("");
}
// Switch the client over to the death cam
if (isObject(%this.camera) && isObject(%this.player))
{
%this.camera.setMode("Corpse", %this.player);
%this.setControlObject(%this.camera);
}
// Unhook the player object
%this.player = 0;
}
//-----------------------------------------------------------------------------
// Server, mission, and game management
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// The server has started up so do some game start up
//-----------------------------------------------------------------------------
function onServerCreated()
{
// Server::GameType is sent to the master server.
// This variable should uniquely identify your game and/or mod.
$Server::GameType = "Torque 3D";
// Server::MissionType sent to the master server. Clients can
// filter servers based on mission type.
$Server::MissionType = "pureLIGHT";
// GameStartTime is the sim time the game started. Used to calculated
// game elapsed time.
$Game::StartTime = 0;
// Create the server physics world.
physicsInitWorld( "server" );
// Load up any objects or datablocks saved to the editor managed scripts
%datablockFiles = new ArrayObject();
%datablockFiles.add( "art/ribbons/ribbonExec.cs" );
%datablockFiles.add( "art/particles/managedParticleData.cs" );
%datablockFiles.add( "art/particles/managedParticleEmitterData.cs" );
%datablockFiles.add( "art/decals/managedDecalData.cs" );
%datablockFiles.add( "art/datablocks/managedDatablocks.cs" );
%datablockFiles.add( "art/forest/managedItemData.cs" );
%datablockFiles.add( "art/datablocks/datablockExec.cs" );
loadDatablockFiles( %datablockFiles, true );
// Run the other gameplay scripts in this folder
exec("./scriptExec.cs");
// Keep track of when the game started
$Game::StartTime = $Sim::Time;
}
//-----------------------------------------------------------------------------
// This function is called as part of a server shutdown
//-----------------------------------------------------------------------------
function onServerDestroyed()
{
// Destroy the server physcis world
physicsDestroyWorld( "server" );
}
//-----------------------------------------------------------------------------
// Called by loadMission() once the mission is finished loading
//-----------------------------------------------------------------------------
function onMissionLoaded()
{
// Start the server side physics simulation
physicsStartSimulation( "server" );
// Nothing special for now, just start up the game play
startGame();
}
//-----------------------------------------------------------------------------
// Called by endMission(), right before the mission is destroyed
//-----------------------------------------------------------------------------
function onMissionEnded()
{
// Stop the server physics simulation
physicsStopSimulation( "server" );
// Normally the game should be ended first before the next
// mission is loaded, this is here in case loadMission has been
// called directly. The mission will be ended if the server
// is destroyed, so we only need to cleanup here.
$Game::Running = false;
}
//-----------------------------------------------------------------------------
// Called once the game has started
//-----------------------------------------------------------------------------
function startGame()
{
if ($Game::Running)
{
error("startGame(): End the game first!");
return;
}
$Game::Running = true;
}
//-----------------------------------------------------------------------------
// Called once the game has ended
//-----------------------------------------------------------------------------
function endGame()
{
if (!$Game::Running)
{
error("endGame(): No game running!");
return;
}
// Inform the client the game is over
for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ )
{
%cl = ClientGroup.getObject( %clientIndex );
commandToClient(%cl, 'GameEnd');
}
// Delete all the temporary mission objects
resetMission();
$Game::Running = false;
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Primitives;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
public class AcceptHeaderParserTest
{
[Fact]
public void ParseAcceptHeader_ParsesSimpleHeader()
{
// Arrange
var header = "application/json";
var expected = new List<MediaTypeSegmentWithQuality>
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"),1.0)
};
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string> { header });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_ParsesSimpleHeaderWithMultipleValues()
{
// Arrange
var header = "application/json, application/xml;q=0.8";
var expected = new List<MediaTypeSegmentWithQuality>
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"),1.0),
new MediaTypeSegmentWithQuality(new StringSegment("application/xml;q=0.8"),0.8)
};
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string> { header });
// Assert
Assert.Equal(expected, parsed);
foreach (var mediaType in parsed)
{
Assert.Same(header, mediaType.MediaType.Buffer);
}
}
[Fact]
public void ParseAcceptHeader_ParsesSimpleHeaderWithMultipleValues_InvalidFormat()
{
// Arrange
var header = "application/json, application/xml,;q=0.8";
var expectedMediaTypes = new List<MediaTypeSegmentWithQuality>
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"),1.0),
new MediaTypeSegmentWithQuality(new StringSegment("application/xml"),1.0),
};
// Act
var mediaTypes = AcceptHeaderParser.ParseAcceptHeader(new List<string> { header });
// Assert
Assert.Equal(expectedMediaTypes, mediaTypes);
}
public static TheoryData<string[], string[]> ParseAcceptHeaderWithInvalidMediaTypesData =>
new TheoryData<string[], string[]>
{
{ new [] { ";q=0.9" }, new string[] { } },
{ new [] { "/" }, new string[] { } },
{ new [] { "*/" }, new string[] { } },
{ new [] { "/*" }, new string[] { } },
{ new [] { "/;q=0.9" }, new string[] { } },
{ new [] { "*/;q=0.9" }, new string[] { } },
{ new [] { "/*;q=0.9" }, new string[] { } },
{ new [] { "/;q=0.9,text/html" }, new string[] { "text/html" } },
{ new [] { "*/;q=0.9,text/html" }, new string[] { "text/html" } },
{ new [] { "/*;q=0.9,text/html" }, new string[] { "text/html" } },
{ new [] { "img/png,/;q=0.9,text/html" }, new string[] { "img/png", "text/html" } },
{ new [] { "img/png,*/;q=0.9,text/html" }, new string[] { "img/png", "text/html" } },
{ new [] { "img/png,/*;q=0.9,text/html" }, new string[] { "img/png", "text/html" } },
{ new [] { "img/png, /;q=0.9" }, new string[] { "img/png", } },
{ new [] { "img/png, */;q=0.9" }, new string[] { "img/png", } },
{ new [] { "img/png;q=1.0, /*;q=0.9" }, new string[] { "img/png;q=1.0", } },
};
[Theory]
[MemberData(nameof(ParseAcceptHeaderWithInvalidMediaTypesData))]
public void ParseAcceptHeader_GracefullyRecoversFromInvalidMediaTypeValues_AndReturnsValidMediaTypes(
string[] acceptHeader,
string[] expected)
{
// Arrange
var expectedMediaTypes = expected.Select(e => new MediaTypeSegmentWithQuality(new StringSegment(e), 1.0)).ToList();
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(acceptHeader);
// Assert
Assert.Equal(expectedMediaTypes, parsed);
}
[Fact]
public void ParseAcceptHeader_ParsesMultipleHeaderValues()
{
// Arrange
var expected = new List<MediaTypeSegmentWithQuality>
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"), 1.0),
new MediaTypeSegmentWithQuality(new StringSegment("application/xml;q=0.8"), 0.8)
};
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(
new List<string> { "application/json", "", "application/xml;q=0.8" });
// Assert
Assert.Equal(expected, parsed);
}
// The text "*/*Content-Type" parses as a valid media type value. However it's followed
// by ':' instead of whitespace or a delimiter, which means that it's actually invalid.
[Fact]
public void ParseAcceptHeader_ValidMediaType_FollowedByNondelimiter()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[0];
var input = "*/*Content-Type:application/json";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_ValidMediaType_FollowedBySemicolon()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[0];
var input = "*/*Content-Type;application/json";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_ValidMediaType_FollowedByComma()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[]
{
new MediaTypeSegmentWithQuality(new StringSegment("*/*Content-Type"), 1.0),
new MediaTypeSegmentWithQuality(new StringSegment("application/json"), 1.0),
};
var input = "*/*Content-Type,application/json";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_ValidMediaType_FollowedByWhitespace()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[]
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"), 1.0),
};
var input = "*/*Content-Type application/json";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_InvalidTokenAtStart()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[0];
var input = ":;:";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_DelimiterAtStart()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[0];
var input = ",;:";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
[Fact]
public void ParseAcceptHeader_InvalidTokenAtEnd()
{
// Arrange
var expected = new MediaTypeSegmentWithQuality[0];
var input = "*/*:";
// Act
var parsed = AcceptHeaderParser.ParseAcceptHeader(new List<string>() { input });
// Assert
Assert.Equal(expected, parsed);
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. 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.
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class UnknownFieldSetTest {
private MessageDescriptor descriptor;
private TestAllTypes allFields;
private ByteString allFieldsData;
/// <summary>
/// An empty message that has been parsed from allFieldsData. So, it has
/// unknown fields of every type.
/// </summary>
private TestEmptyMessage emptyMessage;
private UnknownFieldSet unknownFields;
[SetUp]
public void SetUp() {
descriptor = TestAllTypes.Descriptor;
allFields = TestUtil.GetAllSet();
allFieldsData = allFields.ToByteString();
emptyMessage = TestEmptyMessage.ParseFrom(allFieldsData);
unknownFields = emptyMessage.UnknownFields;
}
private UnknownField GetField(String name) {
FieldDescriptor field = descriptor.FindDescriptor<FieldDescriptor>(name);
Assert.IsNotNull(field);
return unknownFields.FieldDictionary[field.FieldNumber];
}
/// <summary>
/// Constructs a protocol buffer which contains fields with all the same
/// numbers as allFieldsData except that each field is some other wire
/// type.
/// </summary>
private ByteString GetBizarroData() {
UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.CreateBuilder();
UnknownField varintField = UnknownField.CreateBuilder().AddVarint(1).Build();
UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary) {
if (entry.Value.VarintList.Count == 0) {
// Original field is not a varint, so use a varint.
bizarroFields.AddField(entry.Key, varintField);
} else {
// Original field *is* a varint, so use something else.
bizarroFields.AddField(entry.Key, fixed32Field);
}
}
return bizarroFields.Build().ToByteString();
}
// =================================================================
[Test]
public void Varint() {
UnknownField field = GetField("optional_int32");
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(allFields.OptionalInt32, (long) field.VarintList[0]);
}
[Test]
public void Fixed32() {
UnknownField field = GetField("optional_fixed32");
Assert.AreEqual(1, field.Fixed32List.Count);
Assert.AreEqual(allFields.OptionalFixed32, (int) field.Fixed32List[0]);
}
[Test]
public void Fixed64() {
UnknownField field = GetField("optional_fixed64");
Assert.AreEqual(1, field.Fixed64List.Count);
Assert.AreEqual(allFields.OptionalFixed64, (long) field.Fixed64List[0]);
}
[Test]
public void LengthDelimited() {
UnknownField field = GetField("optional_bytes");
Assert.AreEqual(1, field.LengthDelimitedList.Count);
Assert.AreEqual(allFields.OptionalBytes, field.LengthDelimitedList[0]);
}
[Test]
public void Group() {
FieldDescriptor nestedFieldDescriptor =
TestAllTypes.Types.OptionalGroup.Descriptor.FindDescriptor<FieldDescriptor>("a");
Assert.IsNotNull(nestedFieldDescriptor);
UnknownField field = GetField("optionalgroup");
Assert.AreEqual(1, field.GroupList.Count);
UnknownFieldSet group = field.GroupList[0];
Assert.AreEqual(1, group.FieldDictionary.Count);
Assert.IsTrue(group.HasField(nestedFieldDescriptor.FieldNumber));
UnknownField nestedField = group[nestedFieldDescriptor.FieldNumber];
Assert.AreEqual(1, nestedField.VarintList.Count);
Assert.AreEqual(allFields.OptionalGroup.A, (long) nestedField.VarintList[0]);
}
[Test]
public void Serialize() {
// Check that serializing the UnknownFieldSet produces the original data again.
ByteString data = emptyMessage.ToByteString();
Assert.AreEqual(allFieldsData, data);
}
[Test]
public void CopyFrom() {
TestEmptyMessage message =
TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Build();
Assert.AreEqual(emptyMessage.ToString(), message.ToString());
}
[Test]
public void MergeFrom() {
TestEmptyMessage source =
TestEmptyMessage.CreateBuilder()
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(2,
UnknownField.CreateBuilder()
.AddVarint(2).Build())
.AddField(3,
UnknownField.CreateBuilder()
.AddVarint(4).Build())
.Build())
.Build();
TestEmptyMessage destination =
TestEmptyMessage.CreateBuilder()
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(1,
UnknownField.CreateBuilder()
.AddVarint(1).Build())
.AddField(3,
UnknownField.CreateBuilder()
.AddVarint(3).Build())
.Build())
.MergeFrom(source)
.Build();
Assert.AreEqual(
"1: 1\n" +
"2: 2\n" +
"3: 3\n" +
"3: 4\n",
destination.ToString());
}
[Test]
public void Clear() {
UnknownFieldSet fields =
UnknownFieldSet.CreateBuilder().MergeFrom(unknownFields).Clear().Build();
Assert.AreEqual(0, fields.FieldDictionary.Count);
}
[Test]
public void ClearMessage() {
TestEmptyMessage message =
TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Clear().Build();
Assert.AreEqual(0, message.SerializedSize);
}
[Test]
public void ParseKnownAndUnknown() {
// Test mixing known and unknown fields when parsing.
UnknownFieldSet fields =
UnknownFieldSet.CreateBuilder(unknownFields)
.AddField(123456,
UnknownField.CreateBuilder().AddVarint(654321).Build())
.Build();
ByteString data = fields.ToByteString();
TestAllTypes destination = TestAllTypes.ParseFrom(data);
TestUtil.AssertAllFieldsSet(destination);
Assert.AreEqual(1, destination.UnknownFields.FieldDictionary.Count);
UnknownField field = destination.UnknownFields[123456];
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(654321, (long) field.VarintList[0]);
}
[Test]
public void WrongTypeTreatedAsUnknown() {
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing.
ByteString bizarroData = GetBizarroData();
TestAllTypes allTypesMessage = TestAllTypes.ParseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
Assert.AreEqual(emptyMessage.ToString(), allTypesMessage.ToString());
}
[Test]
public void UnknownExtensions() {
// Make sure fields are properly parsed to the UnknownFieldSet even when
// they are declared as extension numbers.
TestEmptyMessageWithExtensions message =
TestEmptyMessageWithExtensions.ParseFrom(allFieldsData);
Assert.AreEqual(unknownFields.FieldDictionary.Count,
message.UnknownFields.FieldDictionary.Count);
Assert.AreEqual(allFieldsData, message.ToByteString());
}
[Test]
public void WrongExtensionTypeTreatedAsUnknown() {
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing extensions.
ByteString bizarroData = GetBizarroData();
TestAllExtensions allExtensionsMessage = TestAllExtensions.ParseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
Assert.AreEqual(emptyMessage.ToString(),
allExtensionsMessage.ToString());
}
[Test]
public void ParseUnknownEnumValue() {
FieldDescriptor singularField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_nested_enum");
FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_nested_enum");
Assert.IsNotNull(singularField);
Assert.IsNotNull(repeatedField);
ByteString data =
UnknownFieldSet.CreateBuilder()
.AddField(singularField.FieldNumber,
UnknownField.CreateBuilder()
.AddVarint((int) TestAllTypes.Types.NestedEnum.BAR)
.AddVarint(5) // not valid
.Build())
.AddField(repeatedField.FieldNumber,
UnknownField.CreateBuilder()
.AddVarint((int) TestAllTypes.Types.NestedEnum.FOO)
.AddVarint(4) // not valid
.AddVarint((int) TestAllTypes.Types.NestedEnum.BAZ)
.AddVarint(6) // not valid
.Build())
.Build()
.ToByteString();
{
TestAllTypes message = TestAllTypes.ParseFrom(data);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
message.OptionalNestedEnum);
TestUtil.AssertEqual(new [] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ},
message.RepeatedNestedEnumList);
TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList);
TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList);
}
{
TestAllExtensions message =
TestAllExtensions.ParseFrom(data, TestUtil.CreateExtensionRegistry());
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
TestUtil.AssertEqual(new[] { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ },
message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension));
TestUtil.AssertEqual(new[] { 5UL }, message.UnknownFields[singularField.FieldNumber].VarintList);
TestUtil.AssertEqual(new[] { 4UL, 6UL }, message.UnknownFields[repeatedField.FieldNumber].VarintList);
}
}
[Test]
public void LargeVarint() {
ByteString data =
UnknownFieldSet.CreateBuilder()
.AddField(1,
UnknownField.CreateBuilder()
.AddVarint(0x7FFFFFFFFFFFFFFFL)
.Build())
.Build()
.ToByteString();
UnknownFieldSet parsed = UnknownFieldSet.ParseFrom(data);
UnknownField field = parsed[1];
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, field.VarintList[0]);
}
[Test]
public void EqualsAndHashCode() {
UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
UnknownField fixed64Field = UnknownField.CreateBuilder().AddFixed64(1).Build();
UnknownField varIntField = UnknownField.CreateBuilder().AddVarint(1).Build();
UnknownField lengthDelimitedField = UnknownField.CreateBuilder().AddLengthDelimited(ByteString.Empty).Build();
UnknownField groupField = UnknownField.CreateBuilder().AddGroup(unknownFields).Build();
UnknownFieldSet a = UnknownFieldSet.CreateBuilder().AddField(1, fixed32Field).Build();
UnknownFieldSet b = UnknownFieldSet.CreateBuilder().AddField(1, fixed64Field).Build();
UnknownFieldSet c = UnknownFieldSet.CreateBuilder().AddField(1, varIntField).Build();
UnknownFieldSet d = UnknownFieldSet.CreateBuilder().AddField(1, lengthDelimitedField).Build();
UnknownFieldSet e = UnknownFieldSet.CreateBuilder().AddField(1, groupField).Build();
CheckEqualsIsConsistent(a);
CheckEqualsIsConsistent(b);
CheckEqualsIsConsistent(c);
CheckEqualsIsConsistent(d);
CheckEqualsIsConsistent(e);
CheckNotEqual(a, b);
CheckNotEqual(a, c);
CheckNotEqual(a, d);
CheckNotEqual(a, e);
CheckNotEqual(b, c);
CheckNotEqual(b, d);
CheckNotEqual(b, e);
CheckNotEqual(c, d);
CheckNotEqual(c, e);
CheckNotEqual(d, e);
}
/// <summary>
/// Asserts that the given field sets are not equal and have different
/// hash codes.
/// </summary>
/// <remarks>
/// It's valid for non-equal objects to have the same hash code, so
/// this test is stricter than it needs to be. However, this should happen
/// relatively rarely.
/// </remarks>
/// <param name="s1"></param>
/// <param name="s2"></param>
private static void CheckNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) {
String equalsError = string.Format("{0} should not be equal to {1}", s1, s2);
Assert.IsFalse(s1.Equals(s2), equalsError);
Assert.IsFalse(s2.Equals(s1), equalsError);
Assert.IsFalse(s1.GetHashCode() == s2.GetHashCode(),
string.Format("{0} should have a different hash code from {1}", s1, s2));
}
/**
* Asserts that the given field sets are equal and have identical hash codes.
*/
private static void CheckEqualsIsConsistent(UnknownFieldSet set) {
// Object should be equal to itself.
Assert.AreEqual(set, set);
// Object should be equal to a copy of itself.
UnknownFieldSet copy = UnknownFieldSet.CreateBuilder(set).Build();
Assert.AreEqual(set, copy);
Assert.AreEqual(copy, set);
Assert.AreEqual(set.GetHashCode(), copy.GetHashCode());
}
}
}
| |
#region Namespaces
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Electrical;
#endregion
namespace TraverseAllSystems
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
/// <summary>
/// Return true to include this system in the
/// exported system graphs.
/// </summary>
static bool IsDesirableSystemPredicate(MEPSystem s)
{
return 1 < s.Elements.Size
&& !s.Name.Equals("unassigned")
&& ((s is MechanicalSystem
&& ((MechanicalSystem)s).IsWellConnected)
|| (s is PipingSystem
&& ((PipingSystem)s).IsWellConnected)
|| (s is ElectricalSystem
&& ((ElectricalSystem)s).IsMultipleNetwork));
}
/// <summary>
/// Create a and return the path of a random temporary directory.
/// </summary>
static string GetTemporaryDirectory()
{
string tempDirectory = Path.Combine(
Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
FilteredElementCollector allSystems
= new FilteredElementCollector(doc)
.OfClass(typeof(MEPSystem));
int nAllSystems = allSystems.Count<Element>();
IEnumerable<MEPSystem> desirableSystems
= allSystems.Cast<MEPSystem>().Where<MEPSystem>(
s => IsDesirableSystemPredicate(s));
int nDesirableSystems = desirableSystems
.Count<Element>();
// Check for shared parameter
// to store graph information.
Definition def = SharedParameterMgr.GetDefinition(
desirableSystems.First<MEPSystem>());
if (null == def)
{
//message = "Please initialise the MEP graph "
// + "storage shared parameter before "
// + "launching this command.";
//return Result.Failed;
SharedParameterMgr.Create(doc);
def = SharedParameterMgr.GetDefinition(
desirableSystems.First<MEPSystem>());
if (null == def)
{
message = "Error creating the "
+ "storage shared parameter.";
return Result.Failed;
}
}
string outputFolder = GetTemporaryDirectory();
string json;
int nXmlFiles = 0;
int nJsonGraphs = 0;
int nJsonBytes = 0;
// Collect one JSON string per system.
List<string> json_collector = new List<string>();
using (Transaction t = new Transaction(doc))
{
t.Start("Determine MEP Graph Structure and Store in JSON Shared Parameter");
System.Text.StringBuilder[] sbs = new System.Text.StringBuilder[3];
for (int i = 0; i < 3; ++i)
{
sbs[i] = new System.Text.StringBuilder();
sbs[i].Append("[");
}
foreach (MEPSystem system in desirableSystems)
{
Debug.Print(system.Name);
// Debug test -- limit to HWS systems.
//if( !system.Name.StartsWith( "HWS" ) ) { continue; }
FamilyInstance root = system.BaseEquipment;
// Traverse the system and dump the
// traversal graph into an XML file
TraversalTree tree = new TraversalTree(system);
if (tree.Traverse())
{
string filename = system.Id.IntegerValue.ToString();
filename = Path.ChangeExtension(
Path.Combine(outputFolder, filename), "xml");
tree.DumpIntoXML(filename);
// Uncomment to preview the
// resulting XML structure
//Process.Start( fileName );
json = Options.StoreJsonGraphBottomUp
? tree.DumpToJsonBottomUp()
: tree.DumpToJsonTopDown();
Debug.Assert(2 < json.Length,
"expected valid non-empty JSON graph data");
Debug.Print(json);
json_collector.Add(json);
Parameter p = system.get_Parameter(def);
p.Set(json);
nJsonBytes += json.Length;
++nJsonGraphs;
++nXmlFiles;
}
tree.CollectUniqueIds(sbs);
}
for (int i = 0; i < 3; ++i)
{
if(sbs[i][sbs[i].Length - 1] == ',')
{
sbs[i].Remove(sbs[i].Length - 1, 1);
}
sbs[i].Append("]");
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("{\"id\": 1 , \"name\" : \"MEP Systems\" , \"children\" : [{\"id\": 2 , \"name\": \"Mechanical System\",\"children\":");
sb.Append(sbs[0].ToString());
sb.Append("},{\"id\":3,\"name\":\"Electrical System\", \"children\":");
sb.Append(sbs[1].ToString());
sb.Append("},{\"id\":4,\"name\":\"Piping System\", \"children\":");
sb.Append(sbs[2].ToString());
sb.Append("}]}");
System.IO.StreamWriter file = new System.IO.StreamWriter(Path.ChangeExtension(Path.Combine(outputFolder, @"jsonData"), "json"));
file.WriteLine(sb.ToString());
file.Flush();
file.Close();
t.Commit();
}
string main = string.Format(
"{0} XML files and {1} JSON graphs ({2} bytes) "
+ "generated in {3} ({4} total systems, {5} desirable):",
nXmlFiles, nJsonGraphs, nJsonBytes,
outputFolder, nAllSystems, nDesirableSystems);
List<string> system_list = desirableSystems
.Select<Element, string>(e =>
string.Format("{0}({1})", e.Id, e.Name))
.ToList<string>();
system_list.Sort();
string detail = string.Join(", ",
system_list.ToArray<string>());
TaskDialog dlg = new TaskDialog(
nXmlFiles.ToString() + " Systems");
dlg.MainInstruction = main;
dlg.MainContent = detail;
dlg.Show();
string json_systems = string.Join(",", json_collector);
const string _json_format_to_store_systrms_in_root
= "{{"
+ "\"id\" : {0}, "
+ "\"text\" : \"{1}\", "
+ "\"children\" : [{2}]}}";
json = string.Format(
_json_format_to_store_systrms_in_root,
-1, doc.Title, json_systems);
Debug.Print(json);
return Result.Succeeded;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace ChromeControlPHAWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
using System.Threading;
namespace RefactoringEssentials
{
#if NR6
public
#endif
static class SyntaxTokenExtensions
{
public static SyntaxNode GetAncestor(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.GetAncestor<SyntaxNode>(predicate);
}
public static T GetAncestor<T>(this SyntaxToken token, Func<T, bool> predicate = null)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.FirstAncestorOrSelf(predicate)
: default(T);
}
public static IEnumerable<T> GetAncestors<T>(this SyntaxToken token)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().OfType<T>()
: Enumerable.Empty<T>();
}
public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().Where(predicate)
: Enumerable.Empty<SyntaxNode>();
}
public static SyntaxNode GetCommonRoot(this SyntaxToken token1, SyntaxToken token2)
{
// Contract.ThrowIfTrue(token1.RawKind == 0 || token2.RawKind == 0);
// find common starting node from two tokens.
// as long as two tokens belong to same tree, there must be at least on common root (Ex, compilation unit)
if (token1.Parent == null || token2.Parent == null)
{
return null;
}
return token1.Parent.GetCommonRoot(token2.Parent);
}
public static bool CheckParent<T>(this SyntaxToken token, Func<T, bool> valueChecker) where T : SyntaxNode
{
var parentNode = token.Parent as T;
if (parentNode == null)
{
return false;
}
return valueChecker(parentNode);
}
public static int Width(this SyntaxToken token)
{
return token.Span.Length;
}
public static int FullWidth(this SyntaxToken token)
{
return token.FullSpan.Length;
}
public static SyntaxToken FindTokenFromEnd(this SyntaxNode root, int position, bool includeZeroWidth = true, bool findInsideTrivia = false)
{
var token = root.FindToken(position, findInsideTrivia);
var previousToken = token.GetPreviousToken(
includeZeroWidth, findInsideTrivia, findInsideTrivia, findInsideTrivia);
if (token.SpanStart == position &&
previousToken.RawKind != 0 &&
previousToken.Span.End == position)
{
return previousToken;
}
return token;
}
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (foo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// lock (expr)
// |
// for ( ; ; Foo(), |
if (token.Kind() == SyntaxKind.OpenBraceToken &&
token.Parent.IsKind(SyntaxKind.Block))
{
return true;
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var statement = token.GetAncestor<StatementSyntax>();
if (statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
if (token.Kind() == SyntaxKind.CloseBraceToken &&
token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Kind() == SyntaxKind.CloseBraceToken &&
token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (token.Kind() == SyntaxKind.ColonToken)
{
if (token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.LabeledStatement))
{
return true;
}
}
if (token.Kind() == SyntaxKind.DoKeyword &&
token.Parent.IsKind(SyntaxKind.DoStatement))
{
return true;
}
if (token.Kind() == SyntaxKind.CloseParenToken)
{
var parent = token.Parent;
if (parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
}
if (token.Kind() == SyntaxKind.ElseKeyword)
{
return true;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Foo;
// using System;
// |
// [assembly: Foo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
var parenExpr = token.Parent as ParenthesizedExpressionSyntax;
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfNode<T>(this SyntaxToken token)
where T : SyntaxNode
{
var node = token.GetAncestor<T>();
return node != null && token == node.GetLastToken(includeZeroWidth: true);
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if foo || |
// #if foo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax)
{
var prefix = targetToken.Parent as PrefixUnaryExpressionSyntax;
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax)
{
var binary = targetToken.Parent as BinaryExpressionSyntax;
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Foo( |
// Foo(expr, |
// Foo(bar: |
// new Foo( |
// new Foo(expr, |
// new Foo(bar: |
// Foo : base( |
// Foo : base(bar: |
// Foo : this( |
// Foo : ths(bar: |
// Foo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.IsParentKind(SyntaxKind.Argument) &&
targetToken.Parent.GetParent().IsParentKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.GetParent().GetParent().GetParent();
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
if (targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword))
{
return true;
}
return false;
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(SyntaxToken targetToken)
{
// cases:
// int Foo { |
// int Foo { private |
// int Foo { set { } |
// int Foo { set; |
// int Foo { [Bar]|
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Foo { |
// int Foo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Foo { set { } |
// int Foo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
{
return true;
}
// int Foo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Foo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
var decl = node.Parent as TypeDeclarationSyntax;
return decl.TypeParameterList == node;
}
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration))
{
var decl = node.Parent as DelegateDeclarationSyntax;
return decl.TypeParameterList == node;
}
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IFoo<|
// interface IFoo<A,|
// interface IFoo<[Bar]|
// deletate X D<|
// deletate X D<A,|
// deletate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.IsParentKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.GetParent().GetParent()))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as ArgumentSyntax;
if (node != null && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsKindOrHasMatchingText(this SyntaxToken token, SyntaxKind kind)
{
return token.Kind() == kind || token.HasMatchingText(kind);
}
public static bool HasMatchingText(this SyntaxToken token, SyntaxKind kind)
{
return token.ToString() == SyntaxFacts.GetText(kind);
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind1, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind2)
{
return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind2;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind1, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind2)
{
return Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind2;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind1, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind2, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind3)
{
return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind2
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind3;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind1, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind2, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind3)
{
return Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind2
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind3;
}
public static bool IsKind(this SyntaxToken token, params Microsoft.CodeAnalysis.CSharp.SyntaxKind[] kinds)
{
return kinds.Contains(Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token));
}
public static bool IsKind(this SyntaxToken token, params Microsoft.CodeAnalysis.VisualBasic.SyntaxKind[] kinds)
{
return kinds.Contains(Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token));
}
public static bool IsLiteral(this SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.FalseKeyword:
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.TrueKeyword:
return true;
default:
return false;
}
}
public static bool IntersectsWith(this SyntaxToken token, int position)
{
return token.Span.IntersectsWith(position);
}
public static SyntaxToken GetPreviousTokenIfTouchingWord(this SyntaxToken token, int position)
{
return token.IntersectsWith(position) && IsWord(token)
? token.GetPreviousToken(includeSkipped: true)
: token;
}
public static bool IsWord(this SyntaxToken token)
{
return token.IsKind(SyntaxKind.IdentifierToken)
|| SyntaxFacts.IsKeywordKind(token.Kind())
|| SyntaxFacts.IsContextualKeyword(token.Kind())
|| SyntaxFacts.IsPreprocessorKeyword(token.Kind());
}
public static SyntaxToken GetNextNonZeroWidthTokenOrEndOfFile(this SyntaxToken token)
{
return token.GetNextTokenOrEndOfFile();
}
public static SyntaxToken GetNextTokenOrEndOfFile(
this SyntaxToken token,
bool includeZeroWidth = false,
bool includeSkipped = false,
bool includeDirectives = false,
bool includeDocumentationComments = false)
{
var nextToken = token.GetNextToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
return nextToken.Kind() == SyntaxKind.None
? token.GetAncestor<CompilationUnitSyntax>().EndOfFileToken
: nextToken;
}
public static SyntaxToken With(this SyntaxToken token, SyntaxTriviaList leading, SyntaxTriviaList trailing)
{
return token.WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
}
/// <summary>
/// Determines whether the given SyntaxToken is the first token on a line in the specified SourceText.
/// </summary>
public static bool IsFirstTokenOnLine(this SyntaxToken token, SourceText text)
{
var previousToken = token.GetPreviousToken(includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
if (previousToken.Kind() == SyntaxKind.None)
{
return true;
}
var tokenLine = text.Lines.IndexOf(token.SpanStart);
var previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart);
return tokenLine > previousTokenLine;
}
public static bool SpansPreprocessorDirective(this IEnumerable<SyntaxToken> tokens)
{
// we want to check all leading trivia of all tokens (except the
// first one), and all trailing trivia of all tokens (except the
// last one).
var first = true;
var previousToken = default(SyntaxToken);
foreach (var token in tokens)
{
if (first)
{
first = false;
}
else
{
// check the leading trivia of this token, and the trailing trivia
// of the previous token.
if (SpansPreprocessorDirective(token.LeadingTrivia) ||
SpansPreprocessorDirective(previousToken.TrailingTrivia))
{
return true;
}
}
previousToken = token;
}
return false;
}
private static bool SpansPreprocessorDirective(SyntaxTriviaList list)
{
return list.Any(t => t.GetStructure() is DirectiveTriviaSyntax);
}
public static SyntaxToken WithoutTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (!token.LeadingTrivia.Any() && !token.TrailingTrivia.Any())
{
return token;
}
return token.With(new SyntaxTriviaList(), new SyntaxTriviaList());
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (trivia.Length == 0)
{
return token;
}
return token.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
SyntaxTriviaList trivia)
{
if (trivia.Count == 0)
{
return token;
}
return token.WithLeadingTrivia(trivia.Concat(token.LeadingTrivia));
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithPrependedLeadingTrivia(trivia.ToSyntaxTriviaList());
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithTrailingTrivia(token.TrailingTrivia.Concat(trivia));
}
/// <summary>
/// Retrieves all trivia after this token, including it's trailing trivia and
/// the leading trivia of the next token.
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllTrailingTrivia(this SyntaxToken token)
{
foreach (var trivia in token.TrailingTrivia)
{
yield return trivia;
}
var nextToken = token.GetNextTokenOrEndOfFile(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
foreach (var trivia in nextToken.LeadingTrivia)
{
yield return trivia;
}
}
public static bool TryParseGenericName(this SyntaxToken genericIdentifier, CancellationToken cancellationToken, out GenericNameSyntax genericName)
{
if (genericIdentifier.GetNextToken(includeSkipped: true).Kind() == SyntaxKind.LessThanToken)
{
var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName();
var syntaxTree = genericIdentifier.SyntaxTree;
var name = SyntaxFactory.ParseName(syntaxTree.GetText(cancellationToken).ToString(TextSpan.FromBounds(genericIdentifier.SpanStart, lastToken.Span.End)));
genericName = name as GenericNameSyntax;
return genericName != null;
}
genericName = null;
return false;
}
/// <summary>
/// Lexically, find the last token that looks like it's part of this generic name.
/// </summary>
/// <param name="genericIdentifier">The "name" of the generic identifier, last token before
/// the "&"</param>
/// <returns>The last token in the name</returns>
/// <remarks>This is related to the code in <see cref="SyntaxTreeExtensions.IsInPartiallyWrittenGeneric(SyntaxTree, int, CancellationToken)"/></remarks>
public static SyntaxToken FindLastTokenOfPartialGenericName(this SyntaxToken genericIdentifier)
{
//Contract.ThrowIfFalse(genericIdentifier.Kind() == SyntaxKind.IdentifierToken);
// advance to the "<" token
var token = genericIdentifier.GetNextToken(includeSkipped: true);
//Contract.ThrowIfFalse(token.Kind() == SyntaxKind.LessThanToken);
int stack = 0;
do
{
// look forward one token
{
var next = token.GetNextToken(includeSkipped: true);
if (next.Kind() == SyntaxKind.None)
{
return token;
}
token = next;
}
if (token.Kind() == SyntaxKind.GreaterThanToken)
{
if (stack == 0)
{
return token;
}
else
{
stack--;
continue;
}
}
switch (token.Kind())
{
case SyntaxKind.LessThanLessThanToken:
stack++;
goto case SyntaxKind.LessThanToken;
// fall through
case SyntaxKind.LessThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
case SyntaxKind.CommaToken:
break;
// If we see a member declaration keyword, we know we've gone too far
case SyntaxKind.ClassKeyword:
case SyntaxKind.StructKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.DelegateKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.VoidKeyword:
return token.GetPreviousToken(includeSkipped: true);
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk. Go back to the token before.
return token.GetPreviousToken(includeSkipped: true);
}
}
while (true);
}
public static bool IsRegularStringLiteral(this SyntaxToken token)
{
return token.Kind() == SyntaxKind.StringLiteralToken && !token.IsVerbatimStringLiteral();
}
public static bool IsValidAttributeTarget(this SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.FieldKeyword:
case SyntaxKind.EventKeyword:
case SyntaxKind.MethodKeyword:
case SyntaxKind.ParamKeyword:
case SyntaxKind.PropertyKeyword:
case SyntaxKind.ReturnKeyword:
case SyntaxKind.TypeKeyword:
return true;
default:
return false;
}
}
}
}
| |
/*
* Copyright (C) 2012, 2013 OUYA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class OuyaMenuAdmin : MonoBehaviour
{
private static Vector3 m_pos = Vector3.zero;
private static Vector3 m_euler = Vector3.zero;
[MenuItem("OUYA/Export Core Package", priority = 100)]
public static void MenuPackageCore()
{
string[] paths =
{
"Assets/Ouya/SDK",
"Assets/Plugins/Bitmap.cs",
"Assets/Plugins/BitmapDrawable.cs",
"Assets/Plugins/BitmapFactory.cs",
"Assets/Plugins/ByteArrayOutputStream.cs",
"Assets/Plugins/DebugInput.cs",
"Assets/Plugins/Drawable.cs",
"Assets/Plugins/InputStream.cs",
"Assets/Plugins/JniHandleOwnership.cs",
"Assets/Plugins/JSONArray.cs",
"Assets/Plugins/JSONObject.cs",
"Assets/Plugins/OutputStream.cs",
"Assets/Plugins/OuyaContent.cs",
"Assets/Plugins/OuyaController.cs",
"Assets/Plugins/OuyaMod.cs",
"Assets/Plugins/OuyaModScreenshot.cs",
"Assets/Plugins/OuyaSDK.cs",
"Assets/Plugins/OuyaUnityActivity.cs",
"Assets/Plugins/OuyaUnityPlugin.cs",
"Assets/Plugins/UnityPlayer.cs",
"Assets/Plugins/Android/AndroidManifest.xml",
"Assets/Plugins/Android/assets/key.der",
"Assets/Plugins/Android/jni/Android.mk",
"Assets/Plugins/Android/jni/Application.mk",
"Assets/Plugins/Android/jni/jni.cpp",
"Assets/Plugins/Android/libs/armeabi-v7a/lib-ouya-ndk.so",
"Assets/Plugins/Android/libs/armeabi-v7a/lib-ouya-ndk.so.meta",
"Assets/Plugins/Android/libs/ouya-sdk.jar",
"Assets/Plugins/Android/OuyaUnityPlugin.jar",
"Assets/Plugins/Android/res/drawable/app_icon.png",
"Assets/Plugins/Android/res/drawable-xhdpi/ouya_icon.png",
"Assets/Plugins/Android/res/values/strings.xml",
"Assets/Plugins/Android/src/DebugInput.java",
"Assets/Plugins/Android/src/IOuyaActivity.java",
"Assets/Plugins/Android/src/MainActivity.java",
"Assets/Plugins/Android/src/OuyaUnityActivity.java",
"Assets/Plugins/Android/src/OuyaInputView.java",
"Assets/Plugins/Android/src/OuyaUnityPlugin.java",
"Assets/Plugins/Android/src/UnityOuyaFacade.java",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-Core.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-Core.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Export Examples Package", priority = 110)]
public static void MenuPackageExamples()
{
string[] paths =
{
"Assets/Ouya/Examples",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-Examples.unitypackage", ExportPackageOptions.Recurse | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-Examples.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Export StarterKit Package", priority = 120)]
public static void MenuPackageStarterKit()
{
string[] paths =
{
"Assets/Ouya/StarterKit",
};
AssetDatabase.ExportPackage(paths, "OuyaSDK-StarterKit.unitypackage", ExportPackageOptions.Recurse | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive);
Debug.Log(string.Format("Export OuyaSDK-StarterKit.unitypackage success in: {0}", Directory.GetCurrentDirectory()));
}
[MenuItem("OUYA/Copy Object Transform", priority=1000)]
public static void MenuCopyObjectTransform()
{
if (Selection.activeGameObject)
{
m_pos = Selection.activeGameObject.transform.position;
m_euler = Selection.activeGameObject.transform.rotation.eulerAngles;
}
}
[MenuItem("OUYA/Copy Scene Transform", priority = 1000)]
public static void MenuCopySceneTransform()
{
if (SceneView.currentDrawingSceneView &&
SceneView.currentDrawingSceneView.camera &&
SceneView.currentDrawingSceneView.camera.transform)
{
m_pos = SceneView.currentDrawingSceneView.camera.transform.position;
m_euler = SceneView.currentDrawingSceneView.camera.transform.rotation.eulerAngles;
}
}
[MenuItem("OUYA/Paste Stored Transform", priority = 1000)]
public static void MenuSetTransform()
{
if (Selection.activeGameObject)
{
Selection.activeGameObject.transform.position = m_pos;
Selection.activeGameObject.transform.rotation = Quaternion.Euler(m_euler);
}
}
public static void MenuGeneratePluginJar()
{
UpdatePaths();
if (CompileApplicationClasses())
{
BuildApplicationJar();
AssetDatabase.Refresh();
}
}
private static string m_pathUnityProject = string.Empty;
private static string m_pathUnityEditor = string.Empty;
private static string m_pathUnityJar = string.Empty;
private static string m_pathJDK = string.Empty;
private static string m_pathToolsJar = string.Empty;
private static string m_pathJar = string.Empty;
private static string m_pathJavaC = string.Empty;
private static string m_pathJavaP = string.Empty;
private static string m_pathSDK = string.Empty;
private static string m_pathOuyaSDKJar = string.Empty;
private static void UpdatePaths()
{
m_pathUnityProject = new DirectoryInfo(Directory.GetCurrentDirectory()).FullName;
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
m_pathUnityEditor = EditorApplication.applicationPath;
OuyaPanel.FindFile(new DirectoryInfo(string.Format("{0}", EditorApplication.applicationPath)), OuyaPanel.FILE_UNITY_JAR, ref m_pathUnityJar);
m_pathUnityJar = m_pathUnityJar.Replace(@"\", "/");
break;
case RuntimePlatform.WindowsEditor:
m_pathUnityEditor = new FileInfo(EditorApplication.applicationPath).Directory.FullName;
OuyaPanel.FindFile(new DirectoryInfo(string.Format("{0}/{1}", m_pathUnityEditor, OuyaPanel.PATH_UNITY_JAR_WIN)), OuyaPanel.FILE_UNITY_JAR, ref m_pathUnityJar);
break;
}
m_pathSDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_ANDROID_SDK);
m_pathJDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_JAVA_JDK);
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
m_pathToolsJar = string.Format("{0}/Contents/Classes/classes.jar", m_pathJDK);
m_pathJar = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAR_MAC);
m_pathJavaC = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAC_MAC);
m_pathJavaP = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAP_MAC);
break;
case RuntimePlatform.WindowsEditor:
m_pathToolsJar = string.Format("{0}/lib/tools.jar", m_pathJDK);
m_pathJar = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAR_WIN);
m_pathJavaC = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAC_WIN);
m_pathJavaP = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAP_WIN);
break;
}
m_pathOuyaSDKJar = string.Format("{0}/Assets/Plugins/Android/libs/ouya-sdk.jar", m_pathUnityProject);
}
private static string GetPathAndroidJar()
{
return string.Format("{0}/platforms/android-{1}/android.jar", m_pathSDK, (int)PlayerSettings.Android.minSdkVersion);
}
public static void GetAssets(string extension, Dictionary<string, string> files, DirectoryInfo directory)
{
if (null == directory)
{
return;
}
foreach (FileInfo file in directory.GetFiles(extension))
{
if (string.IsNullOrEmpty(file.FullName) ||
files.ContainsKey(file.FullName.ToLower()))
{
continue;
}
files.Add(file.FullName.ToLower(), file.FullName);
}
foreach (DirectoryInfo subDir in directory.GetDirectories())
{
if (null == subDir)
{
continue;
}
if (subDir.Name.ToUpper().Equals(".SVN"))
{
continue;
}
//Debug.Log(string.Format("Directory: {0}", subDir));
GetAssets(extension, files, subDir);
}
}
static bool CompileApplicationClasses()
{
string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject);
if (!Directory.Exists(pathClasses))
{
Directory.CreateDirectory(pathClasses);
}
Dictionary<string, string> javaFiles = new Dictionary<string, string>();
GetAssets("*.java", javaFiles, new DirectoryInfo("Assets/Plugins/Android/src"));
string includeFiles = string.Empty;
int index = 0;
foreach (KeyValuePair<string, string> kvp in javaFiles)
{
//Debug.Log(string.Format("Found: {0}", kvp.Value));
if (index == 0)
{
includeFiles = string.Format("\"{0}\"", kvp.Value);
}
else
{
includeFiles += string.Format(" \"{0}\"", kvp.Value);
}
++index;
}
Debug.Log(string.Format("includeFiles: {0}", includeFiles));
string jars = string.Empty;
if (File.Exists(m_pathToolsJar))
{
Debug.Log(string.Format("Found Java tools jar: {0}", m_pathToolsJar));
}
else
{
Debug.LogError(string.Format("Failed to find Java tools jar: {0}", m_pathToolsJar));
return false;
}
if (File.Exists(GetPathAndroidJar()))
{
Debug.Log(string.Format("Found Android jar: {0}", GetPathAndroidJar()));
}
else
{
Debug.LogError(string.Format("Failed to find Android jar: {0}", GetPathAndroidJar()));
return false;
}
if (File.Exists(m_pathUnityJar))
{
Debug.Log(string.Format("Found Unity jar: {0}", m_pathUnityJar));
}
else
{
Debug.LogError(string.Format("Failed to find Unity jar: {0}", m_pathUnityJar));
return false;
}
string output = string.Empty;
string error = string.Empty;
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
jars = string.Format("\"{0}:{1}:{2}:{3}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathUnityJar, m_pathOuyaSDKJar);
OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"",
includeFiles,
jars,
pathClasses),
ref output,
ref error);
break;
case RuntimePlatform.WindowsEditor:
jars = string.Format("\"{0}\";\"{1}\";\"{2}\";\"{3}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathUnityJar, m_pathOuyaSDKJar);
OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-Xlint:deprecation -g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"",
includeFiles,
jars,
pathClasses),
ref output,
ref error);
break;
default:
return false;
}
if (!string.IsNullOrEmpty(error))
{
Debug.LogError(error);
if (OuyaPanel.StopOnErrors)
{
return false;
}
}
return true;
}
static void BuildApplicationJar()
{
string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject);
OuyaPanel.RunProcess(m_pathJar, pathClasses, string.Format("cvfM OuyaUnityPlugin.jar tv/"));
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.OuyaUnityPlugin", "OuyaUnityPlugin");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.UnityOuyaFacade", "UnityOuyaFacade");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.IOuyaActivity", "IOuyaActivity");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.OuyaUnityActivity", "OuyaUnityActivity");
OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.MainActivity", "MainActivity");
string pathAppJar = string.Format("{0}/OuyaUnityPlugin.jar", pathClasses);
string pathDest = string.Format("{0}/Assets/Plugins/Android/OuyaUnityPlugin.jar", m_pathUnityProject);
if (File.Exists(pathDest))
{
File.Delete(pathDest);
}
if (File.Exists(pathAppJar))
{
File.Move(pathAppJar, pathDest);
}
if (Directory.Exists(pathClasses))
{
Directory.Delete(pathClasses, true);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hydra.Data.Model
{
public partial class Item
: AbstractIdNameDescriptionWithPosition
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Item"/> class.
/// </summary>
public Item()
: base()
{
this.DeviceHistory = new HashSet<DeviceHistory>();
this.ItemOwner = new HashSet<Item>();
this.ItemDetail = new HashSet<Item>();
this.ItemDevice = new HashSet<ItemDevice>();
this.ItemStatus = new HashSet<ItemStatus>();
this.MyItems = new HashSet<MyItems>();
this.ItemGroup = new HashSet<ItemGroup>();
}
#endregion
#region Foreign Keys
/// <summary>
/// Gets or sets the location ID.
/// </summary>
/// <value>The location ID.</value>
[ForeignKey("Location")]
public Nullable<int> LocationID { get; set; }
/// <summary>
/// Gets or sets the image ID.
/// </summary>
/// <value>The image ID.</value>
[ForeignKey("Image")]
public Nullable<int> ImageID { get; set; }
/// <summary>
/// Gets or sets the detail ID.
/// </summary>
/// <value>The detail ID.</value>
[ForeignKey("Detail")]
public Nullable<int> DetailID { get; set; }
/// <summary>
/// Gets or sets the organisation ID.
/// </summary>
/// <value>The organisation ID.</value>
[ForeignKey("Organisation")]
public Nullable<int> OrganisationID { get; set; }
/// <summary>
/// Gets or sets the owner ID.
/// </summary>
/// <value>The owner ID.</value>
[ForeignKey("Owner")]
public Nullable<int> OwnerID { get; set; }
#endregion
#region Attributes
/// <summary>
/// Gets or sets the item ID.
/// </summary>
/// <value>The item ID.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[Required, MaxLength(128)]
public string ItemID { get; set; }
/// <summary>
/// Gets or sets the colour.
/// </summary>
/// <value>The colour.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[MaxLength(10)]
public string Colour { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public Nullable<int> Type { get; set; }
/// <summary>
/// Gets or sets the type of the contact.
/// </summary>
/// <value>The type of the contact.</value>
public Nullable<int> ContactType { get; set; }
/// <summary>
/// Gets or sets the contact telephone number.
/// </summary>
/// <value>The contact telephone number.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[MaxLength(20)]
public string ContactTelephoneNumber { get; set; }
/// <summary>
/// Gets or sets the contact email address.
/// </summary>
/// <value>The contact email address.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[MaxLength(256)]
public string ContactEmailAddress { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance has license.
/// </summary>
/// <value>
/// <c>true</c> if this instance has license; otherwise, <c>false</c>.
/// </value>
public bool HasLicense { get; set; }
/// <summary>
/// Gets or sets the create date.
/// </summary>
/// <value>The create date.</value>
public Nullable<System.DateTime> CreateDate { get; set; }
/// <summary>
/// Gets or sets the removed date.
/// </summary>
/// <value>The removed date.</value>
public Nullable<System.DateTime> RemovedDate { get; set; }
/// <summary>
/// Gets or sets the contact mobile number.
/// </summary>
/// <value>The contact mobile number.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[MaxLength(20)]
public string ContactMobileNumber { get; set; }
/// <summary>
/// Gets or sets the is enabled.
/// </summary>
/// <value>The is enabled.</value>
public Nullable<bool> IsEnabled { get; set; }
/// <summary>
/// Gets or sets the is deleted.
/// </summary>
/// <value>The is deleted.</value>
public Nullable<bool> IsDeleted { get; set; }
/// <summary>
/// Gets or sets the unique ID.
/// </summary>
/// <value>The unique ID.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[Required, MaxLength(128)]
public string UniqueID { get; set; }
/// <summary>
/// Gets or sets the cost centre.
/// </summary>
/// <value>The cost centre.</value>
[Column(TypeName = DataTypeConstants.VARCHAR)]
[MaxLength(60)]
public string CostCentre { get; set; }
/// <summary>
/// Gets or sets the gender.
/// </summary>
/// <value>The gender.</value>
public Nullable<int> Gender { get; set; }
/// <summary>
/// Gets or sets the date of birth.
/// </summary>
/// <value>The date of birth.</value>
public Nullable<System.DateTime> DateOfBirth { get; set; }
/// <summary>
/// Gets or sets the context location.
/// </summary>
/// <value>The context location.</value>
[Column(TypeName = DataTypeConstants.TEXT)]
public string ContextLocation { get; set; }
/// <summary>
/// Gets or sets the last movement date.
/// </summary>
/// <value>The last movement date.</value>
public Nullable<System.DateTime> LastMovementDate { get; set; }
/// <summary>
/// Gets or sets the latest temperature.
/// </summary>
/// <value>The latest temperature.</value>
public Nullable<float> LatestTemperature { get; set; }
/// <summary>
/// Gets or sets the latest temperature date.
/// </summary>
/// <value>The latest temperature date.</value>
public Nullable<System.DateTime> LatestTemperatureDate { get; set; }
/// <summary>
/// Gets or sets the type of the temperature.
/// </summary>
/// <value>The type of the temperature.</value>
public Nullable<int> TemperatureType { get; set; }
/// <summary>
/// Gets or sets the hierarchy.
/// </summary>
/// <value>The hierarchy.</value>
[Column(TypeName = DataTypeConstants.TEXT)]
public string Hierarchy { get; set; }
#endregion
#region Navigation
/// <summary>
/// Gets or sets the image.
/// </summary>
/// <value>The image.</value>
public virtual Image Image { get; set; }
/// <summary>
/// Gets or sets the owner.
/// </summary>
/// <value>The owner.</value>
public virtual Item Owner { get; set; }
/// <summary>
/// Gets or sets the detail.
/// </summary>
/// <value>The detail.</value>
public virtual Item Detail { get; set; }
/// <summary>
/// Gets or sets the location.
/// </summary>
/// <value>The location.</value>
public virtual Location Location { get; set; }
/// <summary>
/// Gets or sets the organisation.
/// </summary>
/// <value>The organisation.</value>
public virtual Organisation Organisation { get; set; }
/// <summary>
/// Gets or sets the device history.
/// </summary>
/// <value>The device history.</value>
public virtual ICollection<DeviceHistory> DeviceHistory { get; set; }
/// <summary>
/// Gets or sets the item owner.
/// </summary>
/// <value>The item owner.</value>
public virtual ICollection<Item> ItemOwner { get; set; }
/// <summary>
/// Gets or sets the item detail.
/// </summary>
/// <value>The item detail.</value>
public virtual ICollection<Item> ItemDetail { get; set; }
/// <summary>
/// Gets or sets the item device.
/// </summary>
/// <value>The item device.</value>
public virtual ICollection<ItemDevice> ItemDevice { get; set; }
/// <summary>
/// Gets or sets the item status.
/// </summary>
/// <value>The item status.</value>
public virtual ICollection<ItemStatus> ItemStatus { get; set; }
/// <summary>
/// Gets or sets my items.
/// </summary>
/// <value>My items.</value>
public virtual ICollection<MyItems> MyItems { get; set; }
/// <summary>
/// Gets or sets the item group.
/// </summary>
/// <value>The item group.</value>
public virtual ICollection<ItemGroup> ItemGroup { get; set; }
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VirtualMachinesOperations.
/// </summary>
public static partial class VirtualMachinesOperationsExtensions
{
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult Capture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return operations.CaptureAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> CaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine CreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> CreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Delete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.DeleteAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> DeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves information about the model view or the instance view of a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
public static VirtualMachine Get(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?))
{
return operations.GetAsync(resourceGroupName, vmName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves information about the model view or the instance view of a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> GetAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse ConvertToManagedDisks(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.ConvertToManagedDisksAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> ConvertToManagedDisksAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ConvertToManagedDisksWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Deallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.DeallocateAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> DeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Sets the state of the virtual machine to generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Generalize(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.GeneralizeAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Sets the state of the virtual machine to generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> GeneralizeAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GeneralizeWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<VirtualMachine> List(this IVirtualMachinesOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAsync(this IVirtualMachinesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<VirtualMachine> ListAll(this IVirtualMachinesOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllAsync(this IVirtualMachinesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all available virtual machine sizes to which the specified virtual
/// machine can be resized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static IEnumerable<VirtualMachineSize> ListAvailableSizes(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.ListAvailableSizesAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all available virtual machine sizes to which the specified virtual
/// machine can be resized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<VirtualMachineSize>> ListAvailableSizesAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAvailableSizesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse PowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.PowerOffAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> PowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Restart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.RestartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> RestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Start(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.StartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> StartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse Redeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.RedeployAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> RedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult BeginCapture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return operations.BeginCaptureAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> BeginCaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine BeginCreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> BeginCreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginDelete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginDeleteAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginDeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginConvertToManagedDisks(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginConvertToManagedDisksAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginConvertToManagedDisksAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginConvertToManagedDisksWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginDeallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginDeallocateAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginDeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginPowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginPowerOffAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginPowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginRestart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginRestartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginRestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginStart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginStartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginStartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static OperationStatusResponse BeginRedeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginRedeployAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginRedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListAllNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.OpenXml4Net.OPC;
using NPOI.OpenXml4Net.OPC.Internal;
using System.IO;
using System.Collections.Generic;
using System;
using TestCases.OpenXml4Net;
using NPOI.Util;
using System.Reflection;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace TestCases.OPC
{
[TestFixture]
public class TestPackage
{
private static POILogger logger = POILogFactory.GetLogger(typeof(TestPackage));
/**
* Test that just opening and closing the file doesn't alter the document.
*/
[Test]
public void TestOpenSave()
{
String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx");
FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE);
p.Save(targetFile.FullName);
// Compare the original and newly saved document
Assert.IsTrue(File.Exists(targetFile.FullName));
ZipFileAssert.AssertEqual(new FileInfo(originalFile), targetFile);
File.Delete(targetFile.FullName);
}
/**
* Test that when we create a new Package, we give it
* the correct default content types
*/
[Test]
public void TestCreateGetsContentTypes()
{
FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestCreatePackageTMP.docx");
// Zap the target file, in case of an earlier run
if (File.Exists(targetFile.FullName))
File.Delete(targetFile.FullName);
OPCPackage pkg = OPCPackage.Create(targetFile.FullName);
// Check it has content types for rels and xml
ContentTypeManager ctm = GetContentTypeManager(pkg);
Assert.AreEqual(
"application/xml",
ctm.GetContentType(
PackagingUriHelper.CreatePartName("/foo.xml")
)
);
Assert.AreEqual(
ContentTypes.RELATIONSHIPS_PART,
ctm.GetContentType(
PackagingUriHelper.CreatePartName("/foo.rels")
)
);
Assert.IsNull(
ctm.GetContentType(
PackagingUriHelper.CreatePartName("/foo.txt")
)
);
}
///**
// * Test namespace creation.
// */
//public void TestCreatePackageAddPart() {
// FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestCreatePackageTMP.docx");
// FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestCreatePackageOUTPUT.docx");
// // Zap the target file, in case of an earlier run
// if(targetFile.exists()) targetFile.delete();
// // Create a namespace
// OPCPackage pkg = OPCPackage.Create(targetFile);
// PackagePartName corePartName = PackagingURIHelper
// .CreatePartName("/word/document.xml");
// pkg.AddRelationship(corePartName, TargetMode.INTERNAL,
// PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
// PackagePart corePart = pkg
// .CreatePart(
// corePartName,
// "application/vnd.openxmlformats-officedocument.wordProcessingml.document.main+xml");
// Document doc = DocumentHelper.CreateDocument();
// Namespace nsWordProcessinML = new Namespace("w",
// "http://schemas.openxmlformats.org/wordProcessingml/2006/main");
// Element elDocument = doc.AddElement(new QName("document",
// nsWordProcessinML));
// Element elBody = elDocument.AddElement(new QName("body",
// nsWordProcessinML));
// Element elParagraph = elBody.AddElement(new QName("p",
// nsWordProcessinML));
// Element elRun = elParagraph
// .AddElement(new QName("r", nsWordProcessinML));
// Element elText = elRun.AddElement(new QName("t", nsWordProcessinML));
// elText.SetText("Hello Open XML !");
// StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream());
// pkg.Close();
// ZipFileAssert.AssertEqual(expectedFile, targetFile);
// File.Delete(targetFile.FullName);
//}
///**
// * Tests that we can create a new namespace, add a core
// * document and another part, save and re-load and
// * have everything Setup as expected
// */
//public void TestCreatePackageWithCoreDocument() {
// MemoryStream baos = new MemoryStream();
// OPCPackage pkg = OPCPackage.Create(baos);
// // Add a core document
// PackagePartName corePartName = PackagingURIHelper.CreatePartName("/xl/workbook.xml");
// // Create main part relationship
// pkg.AddRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
// // Create main document part
// PackagePart corePart = pkg.CreatePart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
// // Put in some dummy content
// Stream coreOut = corePart.GetOutputStream();
// coreOut.Write(Encoding.UTF8.GetBytes("<dummy-xml />"));
// coreOut.Close();
// // And another bit
// PackagePartName sheetPartName = PackagingURIHelper.CreatePartName("/xl/worksheets/sheet1.xml");
// PackageRelationship rel =
// corePart.AddRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
// PackagePart part = pkg.CreatePart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
// // Dummy content again
// coreOut = corePart.GetOutputStream();
// coreOut.Write("<dummy-xml2 />".GetBytes());
// coreOut.Close();
// //add a relationship with internal target: "#Sheet1!A1"
// corePart.AddRelationship(new Uri("#Sheet1!A1",UriKind.Relative), TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2");
// // Check things are as expected
// PackageRelationshipCollection coreRels =
// pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
// Assert.AreEqual(1, coreRels.Size);
// PackageRelationship coreRel = coreRels.GetRelationship(0);
// Assert.AreEqual("/", coreRel.SourceUri.ToString());
// Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString());
// assertNotNull(pkg.GetPart(coreRel));
// // Save and re-load
// pkg.Close();
// File tmp = TempFile.CreateTempFile("testCreatePackageWithCoreDocument", ".zip");
// FileOutputStream fout = new FileOutputStream(tmp);
// fout.Write(baos.ToArray());
// fout.Close();
// pkg = OPCPackage.Open(tmp.GetPath());
// //tmp.delete();
// // Check still right
// coreRels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
// Assert.AreEqual(1, coreRels.Size);
// coreRel = coreRels.GetRelationship(0);
// Assert.AreEqual("/", coreRel.SourceUri.ToString());
// Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString());
// corePart = pkg.GetPart(coreRel);
// Assert.IsNotNull(corePart);
// PackageRelationshipCollection rels = corePart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
// Assert.AreEqual(1, rels.Size);
// rel = rels.GetRelationship(0);
// Assert.AreEqual("Sheet1!A1", rel.TargetUri.OriginalString);
// assertMSCompatibility(pkg);
//}
//private void assertMSCompatibility(OPCPackage pkg) {
// PackagePartName relName = PackagingURIHelper.CreatePartName(PackageRelationship.GetContainerPartRelationship());
// PackagePart relPart = pkg.GetPart(relName);
// SAXReader Reader = new SAXReader();
// Document xmlRelationshipsDoc = Reader
// .Read(relPart.GetInputStream());
// Element root = xmlRelationshipsDoc.GetRootElement();
// for (Iterator i = root
// .elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME); i
// .HasNext();) {
// Element element = (Element) i.next();
// String value = element.attribute(
// PackageRelationship.TARGET_ATTRIBUTE_NAME)
// .GetValue();
// Assert.IsTrue("Root target must not start with a leadng slash ('/'): " + value, value[0] != '/');
// }
//}
///**
// * Test namespace opening.
// */
//public void TestOpenPackage() {
// FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestOpenPackageTMP.docx");
// FileInfo inputFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageINPUT.docx");
// FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageOUTPUT.docx");
// // Copy the input file in the output directory
// FileHelper.CopyFile(inputFile.FullName, targetFile.FullName);
// // Create a namespace
// OPCPackage pkg = OPCPackage.Open(targetFile.FullName);
// // Modify core part
// PackagePartName corePartName = PackagingURIHelper
// .CreatePartName("/word/document.xml");
// PackagePart corePart = pkg.GetPart(corePartName);
// // Delete some part to have a valid document
// foreach (PackageRelationship rel in corePart.Relationships) {
// corePart.RemoveRelationship(rel.Id);
// pkg.RemovePart(PackagingURIHelper.CreatePartName(PackagingURIHelper
// .ResolvePartUri(corePart.PartName.URI, rel
// .TargetUri)));
// }
// // Create a content
// Document doc = DocumentHelper.CreateDocument();
// Namespace nsWordProcessinML = new Namespace("w",
// "http://schemas.openxmlformats.org/wordProcessingml/2006/main");
// Element elDocument = doc.AddElement(new QName("document",
// nsWordProcessinML));
// Element elBody = elDocument.AddElement(new QName("body",
// nsWordProcessinML));
// Element elParagraph = elBody.AddElement(new QName("p",
// nsWordProcessinML));
// Element elRun = elParagraph
// .AddElement(new QName("r", nsWordProcessinML));
// Element elText = elRun.AddElement(new QName("t", nsWordProcessinML));
// elText.SetText("Hello Open XML !");
// StreamHelper.saveXmlInStream(doc, corePart.GetOutputStream());
// // Save and close
// try {
// pkg.Close();
// } catch (IOException e) {
// Assert.Fail();
// }
// ZipFileAssert.AssertEqual(expectedFile, targetFile);
// File.Delete(targetFile.FullName);
//}
/**
* Checks that we can write a namespace to a simple
* OutputStream, in Addition to the normal writing
* to a file
*/
[Test]
public void TestSaveToOutputStream()
{
String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx");
FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE);
FileStream fs = targetFile.OpenWrite();
p.Save(fs);
fs.Close();
// Compare the original and newly saved document
Assert.IsTrue(File.Exists(targetFile.FullName));
ZipFileAssert.AssertEqual(new FileInfo(originalFile), targetFile);
File.Delete(targetFile.FullName);
}
/**
* Checks that we can open+read a namespace from a
* simple InputStream, in Addition to the normal
* Reading from a file
*/
[Test]
public void TestOpenFromInputStream()
{
String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx");
FileStream finp = new FileStream(originalFile, FileMode.Open,FileAccess.Read);
OPCPackage p = OPCPackage.Open(finp);
Assert.IsNotNull(p);
Assert.IsNotNull(p.Relationships);
Assert.AreEqual(12, p.GetParts().Count);
// Check it has the usual bits
Assert.IsTrue(p.HasRelationships);
Assert.IsTrue(p.ContainPart(PackagingUriHelper.CreatePartName("/_rels/.rels")));
}
/**
* TODO: fix and enable
*/
//[Test]
public void disabled_testRemovePartRecursive()
{
String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx");
FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
FileInfo tempFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageRemovePartRecursiveTMP.docx");
OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE);
p.RemovePartRecursive(PackagingUriHelper.CreatePartName(new Uri(
"/word/document.xml", UriKind.Relative)));
p.Save(tempFile.FullName);
// Compare the original and newly saved document
Assert.IsTrue(File.Exists(targetFile.FullName));
ZipFileAssert.AssertEqual(targetFile, tempFile);
File.Delete(targetFile.FullName);
}
[Test]
public void TestDeletePart()
{
Dictionary<PackagePartName, String> expectedValues;
Dictionary<PackagePartName, String> values;
values = new Dictionary<PackagePartName, String>();
// Expected values
expectedValues = new Dictionary<PackagePartName, String>();
expectedValues.Add(PackagingUriHelper.CreatePartName("/_rels/.rels"),
"application/vnd.openxmlformats-package.relationships+xml");
expectedValues
.Add(PackagingUriHelper.CreatePartName("/docProps/app.xml"),
"application/vnd.openxmlformats-officedocument.extended-properties+xml");
expectedValues.Add(PackagingUriHelper
.CreatePartName("/docProps/core.xml"),
"application/vnd.openxmlformats-package.core-properties+xml");
expectedValues
.Add(PackagingUriHelper.CreatePartName("/word/fontTable.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml");
expectedValues.Add(PackagingUriHelper
.CreatePartName("/word/media/image1.gif"), "image/gif");
expectedValues
.Add(PackagingUriHelper.CreatePartName("/word/settings.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml");
expectedValues
.Add(PackagingUriHelper.CreatePartName("/word/styles.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
expectedValues.Add(PackagingUriHelper
.CreatePartName("/word/theme/theme1.xml"),
"application/vnd.openxmlformats-officedocument.theme+xml");
expectedValues
.Add(
PackagingUriHelper
.CreatePartName("/word/webSettings.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx");
OPCPackage p = OPCPackage.Open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.DeletePart(PackagingUriHelper.CreatePartName("/word/document.xml"));
foreach (PackagePart part in p.GetParts())
{
values.Add(part.PartName, part.ContentType);
logger.Log(POILogger.DEBUG, part.PartName);
}
// Compare expected values with values return by the namespace
foreach (PackagePartName partName in expectedValues.Keys)
{
Assert.IsNotNull(values[partName]);
Assert.AreEqual(expectedValues[partName], values[partName]);
}
// Don't save modifications
p.Revert();
}
[Test]
public void TestDeletePartRecursive()
{
Dictionary<PackagePartName, String> expectedValues;
Dictionary<PackagePartName, String> values;
values = new Dictionary<PackagePartName, String>();
// Expected values
expectedValues = new Dictionary<PackagePartName, String>();
expectedValues.Add(PackagingUriHelper.CreatePartName("/_rels/.rels"),
"application/vnd.openxmlformats-package.relationships+xml");
expectedValues
.Add(PackagingUriHelper.CreatePartName("/docProps/app.xml"),
"application/vnd.openxmlformats-officedocument.extended-properties+xml");
expectedValues.Add(PackagingUriHelper
.CreatePartName("/docProps/core.xml"),
"application/vnd.openxmlformats-package.core-properties+xml");
String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx");
OPCPackage p = OPCPackage.Open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.DeletePartRecursive(PackagingUriHelper.CreatePartName("/word/document.xml"));
foreach (PackagePart part in p.GetParts())
{
values.Add(part.PartName, part.ContentType);
logger.Log(POILogger.DEBUG, part.PartName);
}
// Compare expected values with values return by the namespace
foreach (PackagePartName partName in expectedValues.Keys)
{
Assert.IsNotNull(values[partName]);
Assert.AreEqual(expectedValues[partName], values[partName]);
}
// Don't save modifications
p.Revert();
}
/**
* Test that we can open a file by path, and then
* write Changes to it.
*/
[Test]
public void TestOpenFileThenOverWrite()
{
string tempFile = TempFile.GetTempFilePath("poiTesting", "tmp");
FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx");
FileHelper.CopyFile(origFile.FullName, tempFile);
// Open the temp file
OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);
// Close it
p.Close();
// Delete it
File.Delete(tempFile);
// Reset
FileHelper.CopyFile(origFile.FullName, tempFile);
p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);
// Save it to the same file - not allowed
try
{
p.Save(tempFile);
Assert.Fail("You shouldn't be able to call save(File) to overwrite the current file");
}
catch (IOException) { }
p.Close();
// Delete it
File.Delete(tempFile);
// Open it read only, then close and delete - allowed
FileHelper.CopyFile(origFile.FullName, tempFile);
p = OPCPackage.Open(tempFile, PackageAccess.READ);
p.Close();
File.Delete(tempFile);
}
/**
* Test that we can open a file by path, save it
* to another file, then delete both
*/
[Test]
public void TestOpenFileThenSaveDelete()
{
string tempFile = TempFile.GetTempFilePath("poiTesting", "tmp");
string tempFile2 = TempFile.GetTempFilePath("poiTesting", "tmp");
FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx");
FileHelper.CopyFile(origFile.FullName, tempFile);
// Open the temp file
OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);
// Save it to a different file
p.Save(tempFile2);
p.Close();
// Delete both the files
File.Delete(tempFile);
File.Delete(tempFile2);
}
private static ContentTypeManager GetContentTypeManager(OPCPackage pkg)
{
FieldInfo f = typeof(OPCPackage).GetField("contentTypeManager",BindingFlags.NonPublic|BindingFlags.Instance);
//f.SetAccessible(true);
return (ContentTypeManager)f.GetValue(pkg);
}
[Test]
public void TestGetPartsByName()
{
String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx");
OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE);
List<PackagePart> rs = pkg.GetPartsByName(new Regex("^/word/.*?\\.xml$"));
Dictionary<String, PackagePart> selected = new Dictionary<String, PackagePart>();
foreach (PackagePart p in rs)
selected.Add(p.PartName.Name, p);
Assert.AreEqual(6, selected.Count);
Assert.IsTrue(selected.ContainsKey("/word/document.xml"));
Assert.IsTrue(selected.ContainsKey("/word/fontTable.xml"));
Assert.IsTrue(selected.ContainsKey("/word/settings.xml"));
Assert.IsTrue(selected.ContainsKey("/word/styles.xml"));
Assert.IsTrue(selected.ContainsKey("/word/theme/theme1.xml"));
Assert.IsTrue(selected.ContainsKey("/word/webSettings.xml"));
}
[Test]
public void TestReplaceContentType()
{
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.xlsx");
OPCPackage p = OPCPackage.Open(is1);
ContentTypeManager mgr = GetContentTypeManager(p);
Assert.True(mgr.IsContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
Assert.False(mgr.IsContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
Assert.True(
p.ReplaceContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
"application/vnd.ms-excel.sheet.macroEnabled.main+xml")
);
Assert.False(mgr.IsContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
Assert.True(mgr.IsContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
//using Cairo;
namespace OpenSim.Region.CoreModules.Scripting.VectorRender
{
public class VectorRenderModule : IRegionModule, IDynamicTextureRender
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "VectorRenderModule";
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
public VectorRenderModule()
{
}
#region IDynamicTextureRender Members
public string GetContentType()
{
return ("vector");
}
public string GetName()
{
return m_name;
}
public bool SupportsAsynchronous()
{
return true;
}
public byte[] ConvertUrl(string url, string extraParams)
{
return null;
}
public byte[] ConvertStream(Stream data, string extraParams)
{
return null;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
return false;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
Draw(bodyData, id, extraParams);
return true;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
Bitmap bitmap = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
Graphics graph = Graphics.FromImage(bitmap);
Font myFont = new Font(fontName, fontSize);
SizeF stringSize = new SizeF();
stringSize = graph.MeasureString(text, myFont);
xSize = stringSize.Width;
ySize = stringSize.Height;
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
if (m_scene == null)
{
m_scene = scene;
}
}
public void PostInitialise()
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
private void Draw(string data, UUID id, string extraParams)
{
// We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha
// we will now support multiple comma seperated params in the form width:256,height:512,alpha:255
int width = 256;
int height = 256;
int alpha = 255; // 0 is transparent
Color bgColour = Color.White; // Default background color
char altDataDelim = ';';
char[] paramDelimiter = { ',' };
char[] nvpDelimiter = { ':' };
extraParams = extraParams.Trim();
extraParams = extraParams.ToLower();
string[] nvps = extraParams.Split(paramDelimiter);
int temp = -1;
foreach (string pair in nvps)
{
string[] nvp = pair.Split(nvpDelimiter);
string name = "";
string value = "";
if (nvp[0] != null)
{
name = nvp[0].Trim();
}
if (nvp.Length == 2)
{
value = nvp[1].Trim();
}
switch (name)
{
case "width":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
width = 1;
}
else if (temp > 2048)
{
width = 2048;
}
else
{
width = temp;
}
}
break;
case "height":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
height = 1;
}
else if (temp > 2048)
{
height = 2048;
}
else
{
height = temp;
}
}
break;
case "alpha":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 0)
{
alpha = 0;
}
else if (temp > 255)
{
alpha = 255;
}
else
{
alpha = temp;
}
}
// Allow a bitmap w/o the alpha component to be created
else if (value.ToLower() == "false") {
alpha = 256;
}
break;
case "bgcolour":
int hex = 0;
if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
bgColour = Color.FromArgb(hex);
}
else
{
bgColour = Color.FromName(value);
}
break;
case "altdatadelim":
altDataDelim = value.ToCharArray()[0];
break;
case "":
// blank string has been passed do nothing just use defaults
break;
default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future
// could be either set alpha or just an int
if (name == "setalpha")
{
alpha = 0; // set the texture to have transparent background (maintains backwards compat)
}
else
{
// this function used to accept an int on its own that represented both
// width and height, this is to maintain backwards compat, could be removed
// but would break existing scripts
temp = parseIntParam(name);
if (temp != -1)
{
if (temp > 1024)
temp = 1024;
if (temp < 128)
temp = 128;
width = temp;
height = temp;
}
}
break;
}
}
Bitmap bitmap;
if (alpha == 256)
{
bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
}
else
{
bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
}
Graphics graph = Graphics.FromImage(bitmap);
// this is really just to save people filling the
// background color in their scripts, only do when fully opaque
if (alpha >= 255)
{
graph.FillRectangle(new SolidBrush(bgColour), 0, 0, width, height);
}
for (int w = 0; w < bitmap.Width; w++)
{
if (alpha <= 255)
{
for (int h = 0; h < bitmap.Height; h++)
{
bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h)));
}
}
}
GDIDraw(data, graph, altDataDelim);
byte[] imageJ2000 = new byte[0];
try
{
imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true);
}
catch (Exception)
{
m_log.Error(
"[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Empty byte data returned!");
}
m_textureManager.ReturnData(id, imageJ2000);
}
private int parseIntParam(string strInt)
{
int parsed;
try
{
parsed = Convert.ToInt32(strInt);
}
catch (Exception)
{
//Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used
// m_log.Debug("Problem with Draw. Please verify parameters." + e.ToString());
parsed = -1;
}
return parsed;
}
/*
private void CairoDraw(string data, System.Drawing.Graphics graph)
{
using (Win32Surface draw = new Win32Surface(graph.GetHdc()))
{
Context contex = new Context(draw);
contex.Antialias = Antialias.None; //fastest method but low quality
contex.LineWidth = 7;
char[] lineDelimiter = { ';' };
char[] partsDelimiter = { ',' };
string[] lines = data.Split(lineDelimiter);
foreach (string line in lines)
{
string nextLine = line.Trim();
if (nextLine.StartsWith("MoveTO"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.MoveTo(x, y);
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.LineTo(x, y);
contex.Stroke();
}
}
}
graph.ReleaseHdc();
}
*/
private void GDIDraw(string data, Graphics graph, char dataDelim)
{
Point startPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
Pen drawPen = new Pen(Color.Black, 7);
string fontName = "Arial";
float fontSize = 14;
Font myFont = new Font(fontName, fontSize);
SolidBrush myBrush = new SolidBrush(Color.Black);
char[] lineDelimiter = {dataDelim};
char[] partsDelimiter = {','};
string[] lines = data.Split(lineDelimiter);
foreach (string line in lines)
{
string nextLine = line.Trim();
//replace with switch, or even better, do some proper parsing
if (nextLine.StartsWith("MoveTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
startPoint.X = (int) x;
startPoint.Y = (int) y;
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.DrawLine(drawPen, startPoint, endPoint);
startPoint.X = endPoint.X;
startPoint.Y = endPoint.Y;
}
else if (nextLine.StartsWith("Text"))
{
nextLine = nextLine.Remove(0, 4);
nextLine = nextLine.Trim();
graph.DrawString(nextLine, myFont, myBrush, startPoint);
}
else if (nextLine.StartsWith("Image"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
Image image = ImageHttpRequest(nextLine);
graph.DrawImage(image, (float) startPoint.X, (float) startPoint.Y, x, y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("Rectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FillRectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("Ellipse"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FontSize"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
fontSize = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("FontProp"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
string [] fprops = nextLine.Split(partsDelimiter);
foreach (string prop in fprops) {
switch (prop)
{
case "B":
if (!(myFont.Bold))
myFont = new Font(myFont, myFont.Style | FontStyle.Bold);
break;
case "I":
if (!(myFont.Italic))
myFont = new Font(myFont, myFont.Style | FontStyle.Italic);
break;
case "U":
if (!(myFont.Underline))
myFont = new Font(myFont, myFont.Style | FontStyle.Underline);
break;
case "S":
if (!(myFont.Strikeout))
myFont = new Font(myFont, myFont.Style | FontStyle.Strikeout);
break;
case "R":
myFont = new Font(myFont, FontStyle.Regular);
break;
}
}
}
else if (nextLine.StartsWith("FontName"))
{
nextLine = nextLine.Remove(0, 8);
fontName = nextLine.Trim();
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("PenSize"))
{
nextLine = nextLine.Remove(0, 7);
nextLine = nextLine.Trim();
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
drawPen.Width = size;
}
else if (nextLine.StartsWith("PenColour"))
{
nextLine = nextLine.Remove(0, 9);
nextLine = nextLine.Trim();
int hex = 0;
Color newColour;
if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
newColour = Color.FromArgb(hex);
}
else
{
// this doesn't fail, it just returns black if nothing is found
newColour = Color.FromName(nextLine);
}
myBrush.Color = newColour;
drawPen.Color = newColour;
}
}
}
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length == 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
}
else if (parts.Length > 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
line = "";
for (int i = 2; i < parts.Length; i++)
{
line = line + parts[i].Trim();
line = line + " ";
}
}
}
private Bitmap ImageHttpRequest(string url)
{
WebRequest request = HttpWebRequest.Create(url);
//Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used.
//Ckrinke Stream str = null;
HttpWebResponse response = (HttpWebResponse) (request).GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Bitmap image = new Bitmap(response.GetResponseStream());
return image;
}
return null;
}
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
namespace Google.GData.Extensions {
/// <summary>
/// GData schema extension describing a nested entry link.
/// </summary>
public class EntryLink : IExtensionElementFactory
{
/// <summary>holds the href property of the EntryLink element</summary>
private string href;
/// <summary>holds the readOnlySet property of the EntryLink element</summary>
private bool readOnly;
/// <summary>holds the AtomEntry property of the EntryLink element</summary>
private AtomEntry entry;
/// <summary>holds the rel attribute of the EntyrLink element</summary>
private string rel;
private bool readOnlySet;
/// <summary>
/// Entry URI
/// </summary>
public string Href
{
get { return href; }
set { href = value; }
}
/// <summary>
/// Read only flag.
/// </summary>
public bool ReadOnly
{
get { return this.readOnly; }
set { this.readOnly = value; this.readOnlySet = true; }
}
/// <summary>
/// Nested entry (optional).
/// </summary>
public AtomEntry Entry
{
get { return entry; }
set { entry = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Rel</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Rel
{
get {return this.rel;}
set {this.rel = value;}
}
/////////////////////////////////////////////////////////////////////////////
#region EntryLink Parser
//////////////////////////////////////////////////////////////////////
/// <summary>parses an xml node to create an EntryLink object</summary>
/// <param name="node">entrylink node</param>
/// <param name="parser">AtomFeedParser to use</param>
/// <returns> the created EntryLink object</returns>
//////////////////////////////////////////////////////////////////////
public static EntryLink ParseEntryLink(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
EntryLink link = null;
Tracing.Assert(node != null, "node should not be null");
if (node == null)
{
throw new ArgumentNullException("node");
}
object localname = node.LocalName;
if (localname.Equals(GDataParserNameTable.XmlEntryLinkElement))
{
link = new EntryLink();
if (node.Attributes != null)
{
if (node.Attributes[GDataParserNameTable.XmlAttributeHref] != null)
{
link.Href = node.Attributes[GDataParserNameTable.XmlAttributeHref].Value;
}
if (node.Attributes[GDataParserNameTable.XmlAttributeReadOnly] != null)
{
link.ReadOnly = node.Attributes[GDataParserNameTable.XmlAttributeReadOnly].Value.Equals(Utilities.XSDTrue);
}
if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null)
{
link.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value;
}
}
if (node.HasChildNodes)
{
XmlNode entryChild = node.FirstChild;
while (entryChild != null && entryChild is XmlElement)
{
if (entryChild.LocalName == AtomParserNameTable.XmlAtomEntryElement &&
entryChild.NamespaceURI == BaseNameTable.NSAtom)
{
if (link.Entry == null)
{
XmlReader reader = new XmlNodeReader(entryChild);
// move the reader to the first node
reader.Read();
AtomFeedParser p = new AtomFeedParser();
p.NewAtomEntry += new FeedParserEventHandler(link.OnParsedNewEntry);
p.ParseEntry(reader);
}
else
{
throw new ArgumentException("Only one entry is allowed inside the g:entryLink");
}
}
entryChild = entryChild.NextSibling;
}
}
}
return link;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Event chaining. We catch this from the AtomFeedParser
/// we want to set this to our property, and do not add the entry to the collection
/// </summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feed entry</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
internal void OnParsedNewEntry(object sender, FeedParserEventArgs e)
{
// by default, if our event chain is not hooked, add it to the collection
Tracing.TraceCall("received new item notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
if (e.CreatingEntry == false)
{
if (e.Entry != null)
{
// add it to the collection
Tracing.TraceMsg("\t new EventEntry found");
this.Entry = e.Entry;
e.DiscardEntry = true;
}
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region overloaded for persistence
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public static string XmlName
{
get { return GDataParserNameTable.XmlEntryLinkElement; }
}
/// <summary>
/// Used to save the EntryLink instance into the passed in xmlwriter
/// </summary>
/// <param name="writer">the XmlWriter to write into</param>
public void Save(XmlWriter writer)
{
if (Utilities.IsPersistable(this.Href) ||
this.readOnlySet ||
this.entry != null)
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (Utilities.IsPersistable(this.Href))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHref, this.Href);
}
if (Utilities.IsPersistable(this.Rel))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, this.Rel);
}
if (this.readOnlySet)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeReadOnly,
Utilities.ConvertBooleanToXSDString(this.ReadOnly));
}
if (entry != null)
{
entry.SaveToXml(writer);
}
writer.WriteEndElement();
}
}
#endregion
#region IExtensionElementFactory Members
/// <summary>
/// returns the xml local name for this element
/// </summary>
string IExtensionElementFactory.XmlName
{
get
{
return XmlName;
}
}
/// <summary>
/// returns the xml namespace for this element
/// </summary>
public string XmlNameSpace
{
get
{
return BaseNameTable.gNamespace;
}
}
/// <summary>
/// returns the xml prefix to be used for this element
/// </summary>
public string XmlPrefix
{
get
{
return BaseNameTable.gDataPrefix;
}
}
/// <summary>
/// factory method to create an instance of a batchinterrupt during parsing
/// </summary>
/// <param name="node">the xmlnode that is going to be parsed</param>
/// <param name="parser">the feedparser that is used right now</param>
/// <returns></returns>
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return EntryLink.ParseEntryLink(node, parser);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace NVelocity.App
{
using System;
using System.IO;
using Commons.Collections;
using Context;
using Exception;
using Runtime;
using Runtime.Log;
/// <summary> <p>
/// This class provides a separate new-able instance of the
/// Velocity template engine. The alternative model for use
/// is using the Velocity class which employs the singleton
/// model.
/// </p>
/// <p>Velocity will call
/// the parameter-less Init() at the first use of this class
/// if the Init() wasn't explicitly called. While this will
/// ensure that Velocity functions, it probably won't
/// function in the way you intend, so it is strongly recommended that
/// you call an Init() method yourself if you use the default constructor.
/// </p>
///
/// </summary>
/// <version> $Id: VelocityEngine.java 687177 2008-08-19 22:00:32Z nbubna $
/// </version>
public class VelocityEngine
{
/// <summary> Set an entire configuration at once. This is
/// useful in cases where the parent application uses
/// the ExtendedProperties class and the velocity configuration
/// is a subset of the parent application's configuration.
///
/// </summary>
/// <param name="configuration">*
/// </param>
public virtual ExtendedProperties ExtendedProperties
{
set
{
ri.Configuration = value;
}
}
/// <summary> Returns a convenient LogMessage instance that wraps the current LogChute.
/// Use this to Log Error messages. It has the usual methods you'd expect.
/// </summary>
/// <returns> A Log object.
/// </returns>
/// <since> 1.5
/// </since>
virtual public Log Log
{
get
{
return ri.Log;
}
}
private RuntimeInstance ri = new RuntimeInstance();
/// <summary> Init-less CTOR</summary>
public VelocityEngine()
{
// do nothing
}
/// <summary> CTOR that invokes an Init(String), initializing
/// the engine using the properties file specified
///
/// </summary>
/// <param name="propsFilename">name of properties file to Init with
/// </param>
/// <param name="initDefault">Loads default properties if true; does not load otherwise.</param>
/// <throws> Exception </throws>
/// <since> 1.5
/// </since>
public VelocityEngine(string propsFilename, bool initDefault = true)
{
ri.Init(propsFilename, initDefault);
}
/// <summary> CTOR that invokes an Init(String), initializing
/// the engine using the Properties specified
///
/// </summary>
/// <param name="p">name of properties to Init with
/// </param>
/// <param name="initDefault">Loads default properties if true; does not load otherwise.</param>
/// <throws> Exception </throws>
/// <since> 1.5
/// </since>
public VelocityEngine(ExtendedProperties p, bool initDefault = true)
{
ri.Init(p, initDefault);
}
/// <summary> Initialize the Velocity runtime engine, using the default
/// properties of the Velocity distribution
/// </summary>
/// <param name="initDefault">Loads default properties if true; does not load otherwise.</param>
/// <throws> Exception </throws>
public virtual void Init(bool initDefault = true)
{
ri.Init(initDefault);
}
/// <summary> Initialize the Velocity runtime engine, using default properties
/// plus the properties in the properties file passed in as the arg
///
/// </summary>
/// <param name="propsFilename">file containing properties to use to Initialize
/// the Velocity runtime
/// </param>
/// <param name="initDefault">Loads default properties if true; does not load otherwise.</param>
/// <throws> Exception </throws>
public virtual void Init(string propsFilename, bool initDefault = true)
{
ri.Init(propsFilename, initDefault);
}
/// <summary> Initialize the Velocity runtime engine, using default properties
/// plus the properties in the passed in java.util.Properties object
///
/// </summary>
/// <param name="p"> Proprties object containing initialization properties
/// </param>
/// <param name="initDefault">Loads default properties if true; does not load otherwise.</param>
/// <throws> Exception </throws>
/// <summary>
/// </summary>
public virtual void Init(ExtendedProperties p, bool initDefault = true)
{
ri.Init(p, initDefault);
}
/// <summary> Set a Velocity Runtime property.
///
/// </summary>
/// <param name="key">
/// </param>
/// <param name="value">
/// </param>
public virtual void SetProperty(string key, object value)
{
ri.SetProperty(key, value);
}
/// <summary> Add a Velocity Runtime property.
///
/// </summary>
/// <param name="key">
/// </param>
/// <param name="value">
/// </param>
public virtual void AddProperty(string key, object value)
{
ri.AddProperty(key, value);
}
/// <summary> Clear a Velocity Runtime property.
///
/// </summary>
/// <param name="key">of property to clear
/// </param>
public virtual void ClearProperty(string key)
{
ri.ClearProperty(key);
}
/// <summary> Get a Velocity Runtime property.
///
/// </summary>
/// <param name="key">property to retrieve
/// </param>
/// <returns> property value or null if the property
/// not currently set
/// </returns>
public virtual object GetProperty(string key)
{
return ri.GetProperty(key);
}
/// <summary> renders the input string using the context into the output writer.
/// To be used when a template is dynamically constructed, or want to use
/// Velocity as a token replacer.
///
/// </summary>
/// <param name="context">context to use in rendering input string
/// </param>
/// <param name="out"> Writer in which to render the output
/// </param>
/// <param name="logTag"> string to be used as the template name for Log
/// messages in case of Error
/// </param>
/// <param name="instring">input string containing the VTL to be rendered
///
/// </param>
/// <returns> true if successful, false otherwise. If false, see
/// Velocity runtime Log
/// </returns>
/// <throws> ParseErrorException The template could not be parsed. </throws>
/// <throws> MethodInvocationException A method on a context object could not be invoked. </throws>
/// <throws> ResourceNotFoundException A referenced resource could not be loaded. </throws>
/// <throws> IOException While rendering to the writer, an I/O problem occured. </throws>
public virtual bool Evaluate(IContext context, TextWriter writer, string logTag, string instring)
{
return ri.Evaluate(context, writer, logTag, instring);
}
/// <summary> Renders the input reader using the context into the output writer.
/// To be used when a template is dynamically constructed, or want to
/// use Velocity as a token replacer.
///
/// </summary>
/// <param name="context">context to use in rendering input string
/// </param>
/// <param name="writer"> Writer in which to render the output
/// </param>
/// <param name="logTag"> string to be used as the template name for Log messages
/// in case of Error
/// </param>
/// <param name="reader">Reader containing the VTL to be rendered
///
/// </param>
/// <returns> true if successful, false otherwise. If false, see
/// Velocity runtime Log
/// </returns>
/// <throws> ParseErrorException The template could not be parsed. </throws>
/// <throws> MethodInvocationException A method on a context object could not be invoked. </throws>
/// <throws> ResourceNotFoundException A referenced resource could not be loaded. </throws>
/// <throws> IOException While reading from the reader or rendering to the writer, </throws>
/// <summary> an I/O problem occured.
/// </summary>
/// <since> Velocity v1.1
/// </since>
public virtual bool Evaluate(IContext context, TextWriter writer, string logTag, TextReader reader)
{
return ri.Evaluate(context, writer, logTag, reader);
}
/// <summary> Invokes a currently registered Velocimacro with the params provided
/// and places the rendered stream into the writer.
/// <br>
/// Note : currently only accepts args to the VM if they are in the context.
///
/// </summary>
/// <param name="vmName">name of Velocimacro to call
/// </param>
/// <param name="logTag">string to be used for template name in case of Error. if null,
/// the vmName will be used
/// </param>
/// <param name="params">keys for args used to invoke Velocimacro, in java format
/// rather than VTL (eg "foo" or "bar" rather than "$foo" or "$bar")
/// </param>
/// <param name="context">Context object containing data/objects used for rendering.
/// </param>
/// <param name="writer"> Writer for output stream
/// </param>
/// <returns> true if Velocimacro exists and successfully invoked, false otherwise.
/// </returns>
/// <throws> IOException While rendering to the writer, an I/O problem occured. </throws>
public virtual bool InvokeVelocimacro(string vmName, string logTag, string[] parameters, IContext context, TextWriter writer)
{
return ri.InvokeVelocimacro(vmName, logTag, parameters, context, writer);
}
/// <summary> merges a template and puts the rendered stream into the writer
///
/// </summary>
/// <param name="templateName">name of template to be used in merge
/// </param>
/// <param name="encoding">encoding used in template
/// </param>
/// <param name="context"> filled context to be used in merge
/// </param>
/// <param name="writer"> writer to write template into
///
/// </param>
/// <returns> true if successful, false otherwise. Errors
/// logged to velocity Log
/// </returns>
/// <throws> ResourceNotFoundException </throws>
/// <throws> ParseErrorException </throws>
/// <throws> MethodInvocationException </throws>
/// <throws> Exception </throws>
/// <summary>
/// </summary>
/// <since> Velocity v1.1
/// </since>
public virtual bool MergeTemplate(string templateName, string encoding, IContext context, TextWriter writer)
{
Template template = ri.GetTemplate(templateName, encoding);
if (template == null)
{
string msg = "VelocityEngine.mergeTemplate() was unable to load template '" + templateName + "'";
Log.Error(msg);
throw new ResourceNotFoundException(msg);
}
else
{
template.Merge(context, writer);
return true;
}
}
/// <summary> Returns a <code>Template</code> from the Velocity
/// resource management system.
///
/// </summary>
/// <param name="name">The file name of the desired template.
/// </param>
/// <returns> The template.
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException if template cannot be parsed due </throws>
/// <summary> to syntax (or other) Error.
/// </summary>
/// <throws> Exception if an Error occurs in template initialization </throws>
public virtual Template GetTemplate(string name)
{
return ri.GetTemplate(name);
}
/// <summary> Returns a <code>Template</code> from the Velocity
/// resource management system.
///
/// </summary>
/// <param name="name">The file name of the desired template.
/// </param>
/// <param name="encoding">The character encoding to use for the template.
/// </param>
/// <returns> The template.
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException if template cannot be parsed due </throws>
/// <summary> to syntax (or other) Error.
/// </summary>
/// <throws> Exception if an Error occurs in template initialization </throws>
/// <summary>
/// </summary>
/// <since> Velocity v1.1
/// </since>
public virtual Template GetTemplate(string name, string encoding)
{
return ri.GetTemplate(name, encoding);
}
/// <summary> Determines if a resource is accessable via the currently
/// configured resource loaders.
/// <br><br>
/// Note that the current implementation will <b>not</b>
/// change the state of the system in any real way - so this
/// cannot be used to pre-load the resource cache, as the
/// previous implementation did as a side-effect.
/// <br><br>
/// The previous implementation exhibited extreme lazyness and
/// sloth, and the author has been flogged.
///
/// </summary>
/// <param name="resourceName"> name of the resource to search for
/// </param>
/// <returns> true if found, false otherwise
/// </returns>
/// <since> 1.5
/// </since>
public virtual bool ResourceExists(string resourceName)
{
return (ri.GetLoaderNameForResource(resourceName) != null);
}
/// <summary> <p>
/// Sets an application attribute (which can be any Object) that will be
/// accessible from any component of the system that gets a
/// RuntimeServices. This allows communication between the application
/// environment and custom pluggable components of the Velocity engine,
/// such as ResourceLoaders and LogChutes.
/// </p>
///
/// <p>
/// Note that there is no enforcement or rules for the key
/// used - it is up to the application developer. However, to
/// help make the intermixing of components possible, using
/// the target Class name (e.g. com.foo.bar ) as the key
/// might help avoid collision.
/// </p>
///
/// </summary>
/// <param name="key">object 'name' under which the object is stored
/// </param>
/// <param name="value">object to store under this key
/// </param>
public virtual void SetApplicationAttribute(object key, object value)
{
ri.SetApplicationAttribute(key, value);
}
/// <summary> <p>
/// Return an application attribute (which can be any Object)
/// that was set by the application in order to be accessible from
/// any component of the system that gets a RuntimeServices.
/// This allows communication between the application
/// environment and custom pluggable components of the
/// Velocity engine, such as ResourceLoaders and LogChutes.
/// </p>
///
/// </summary>
/// <param name="key">object 'name' under which the object is stored
/// </param>
/// <returns> value object to store under this key
/// </returns>
/// <since> 1.5
/// </since>
public virtual object GetApplicationAttribute(object key)
{
return ri.GetApplicationAttribute(key);
}
}
}
| |
using Serilog.Context;
using Serilog.Core.Enrichers;
using Serilog.Events;
using Serilog.Tests.Support;
#if REMOTING
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Services;
#endif
using System;
using System.Threading;
using System.Threading.Tasks;
using Serilog.Core;
using Xunit;
namespace Serilog.Tests.Context
{
public class LogContextTests
{
static LogContextTests()
{
#if REMOTING
LifetimeServices.LeaseTime = TimeSpan.FromMilliseconds(100);
LifetimeServices.LeaseManagerPollTime = TimeSpan.FromMilliseconds(10);
#endif
}
public LogContextTests()
{
#if REMOTING
// ReSharper disable AssignNullToNotNullAttribute
CallContext.LogicalSetData(typeof(LogContext).FullName, null);
// ReSharper restore AssignNullToNotNullAttribute
#endif
}
[Fact]
public void PushedPropertiesAreAvailableToLoggers()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.PushProperty("A", 1))
using (LogContext.Push(new PropertyEnricher("B", 2)))
using (LogContext.Push(new PropertyEnricher("C", 3), new PropertyEnricher("D", 4))) // Different overload
{
log.Write(Some.InformationEvent());
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A"].LiteralValue());
Assert.Equal(2, lastEvent.Properties["B"].LiteralValue());
Assert.Equal(3, lastEvent.Properties["C"].LiteralValue());
Assert.Equal(4, lastEvent.Properties["D"].LiteralValue());
}
}
[Fact]
public void LogContextCanBeCloned()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
ILogEventEnricher clonedContext;
using (LogContext.PushProperty("A", 1))
{
clonedContext = LogContext.Clone();
}
using (LogContext.Push(clonedContext))
{
log.Write(Some.InformationEvent());
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A"].LiteralValue());
}
}
[Fact]
public void ClonedLogContextCanSharedAcrossThreads()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
ILogEventEnricher clonedContext;
using (LogContext.PushProperty("A", 1))
{
clonedContext = LogContext.Clone();
}
var t = new Thread(() =>
{
using (LogContext.Push(clonedContext))
{
log.Write(Some.InformationEvent());
}
});
t.Start();
t.Join();
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A"].LiteralValue());
}
[Fact]
public void MoreNestedPropertiesOverrideLessNestedOnes()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.PushProperty("A", 1))
{
log.Write(Some.InformationEvent());
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A"].LiteralValue());
using (LogContext.PushProperty("A", 2))
{
log.Write(Some.InformationEvent());
Assert.Equal(2, lastEvent.Properties["A"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.Equal(1, lastEvent.Properties["A"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.False(lastEvent.Properties.ContainsKey("A"));
}
[Fact]
public void MultipleNestedPropertiesOverrideLessNestedOnes()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.Push(new PropertyEnricher("A1", 1), new PropertyEnricher("A2", 2)))
{
log.Write(Some.InformationEvent());
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A1"].LiteralValue());
Assert.Equal(2, lastEvent.Properties["A2"].LiteralValue());
using (LogContext.Push(new PropertyEnricher("A1", 10), new PropertyEnricher("A2", 20)))
{
log.Write(Some.InformationEvent());
Assert.Equal(10, lastEvent.Properties["A1"].LiteralValue());
Assert.Equal(20, lastEvent.Properties["A2"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.Equal(1, lastEvent.Properties["A1"].LiteralValue());
Assert.Equal(2, lastEvent.Properties["A2"].LiteralValue());
}
log.Write(Some.InformationEvent());
Assert.False(lastEvent.Properties.ContainsKey("A1"));
Assert.False(lastEvent.Properties.ContainsKey("A2"));
}
[Fact]
public async Task ContextPropertiesCrossAsyncCalls()
{
await TestWithSyncContext(async () =>
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.PushProperty("A", 1))
{
var pre = Thread.CurrentThread.ManagedThreadId;
await Task.Yield();
var post = Thread.CurrentThread.ManagedThreadId;
log.Write(Some.InformationEvent());
Assert.NotNull(lastEvent);
Assert.Equal(1, lastEvent!.Properties["A"].LiteralValue());
Assert.False(Thread.CurrentThread.IsThreadPoolThread);
Assert.True(Thread.CurrentThread.IsBackground);
Assert.NotEqual(pre, post);
}
},
new ForceNewThreadSyncContext());
}
[Fact]
public async Task ContextEnrichersInAsyncScopeCanBeCleared()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.Push(new PropertyEnricher("A", 1)))
{
await Task.Run(() =>
{
LogContext.Reset();
log.Write(Some.InformationEvent());
});
Assert.NotNull(lastEvent);
Assert.Empty(lastEvent!.Properties);
// Reset should only work for current async scope, outside of it previous Context
// instance should be available again.
log.Write(Some.InformationEvent());
Assert.Equal(1, lastEvent.Properties["A"].LiteralValue());
}
}
[Fact]
public async Task ContextEnrichersCanBeTemporarilyCleared()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.CreateLogger();
using (LogContext.Push(new PropertyEnricher("A", 1)))
{
using (LogContext.Suspend())
{
await Task.Run(() =>
{
log.Write(Some.InformationEvent());
});
Assert.NotNull(lastEvent);
Assert.Empty(lastEvent!.Properties);
}
// Suspend should only work for scope of using. After calling Dispose all enrichers
// should be restored.
log.Write(Some.InformationEvent());
Assert.Equal(1, lastEvent.Properties["A"].LiteralValue());
}
}
#if APPDOMAIN
// Must not actually try to pass context across domains,
// since user property types may not be serializable.
[Fact]
public void DoesNotPreventCrossDomainCalls()
{
AppDomain? domain = null;
try
{
domain = AppDomain.CreateDomain("LogContextTests", null, AppDomain.CurrentDomain.SetupInformation);
// ReSharper disable AssignNullToNotNullAttribute
var callable = (RemotelyCallable)domain.CreateInstanceAndUnwrap(typeof(RemotelyCallable).Assembly.FullName, typeof(RemotelyCallable).FullName);
// ReSharper restore AssignNullToNotNullAttribute
using (LogContext.PushProperty("Anything", 1001))
Assert.True(callable.IsCallable());
}
finally
{
if (domain != null)
AppDomain.Unload(domain);
}
}
#endif
#if APPDOMAIN && REMOTING
[Fact]
public void DoesNotThrowOnCrossDomainCallsWhenLeaseExpired()
{
RemotingException? remotingException = null;
AppDomain.CurrentDomain.FirstChanceException +=
(_, e) => remotingException = e.Exception is RemotingException re ? re : remotingException;
var logger = new LoggerConfiguration().Enrich.FromLogContext().CreateLogger();
var remote = AppDomain.CreateDomain("Remote", null, AppDomain.CurrentDomain.SetupInformation);
try
{
using (LogContext.PushProperty("Prop", 42))
{
remote.DoCallBack(CallFromRemote);
#pragma warning disable Serilog003
logger.Information("Prop = {Prop}");
#pragma warning restore Serilog003
}
}
finally
{
AppDomain.Unload(remote);
}
Assert.Null(remotingException);
static void CallFromRemote() => Thread.Sleep(200);
}
[Fact]
public async Task DisconnectRemoteObjectsAfterCrossDomainCallsOnDispose()
{
var tracker = new InMemoryRemoteObjectTracker();
TrackingServices.RegisterTrackingHandler(tracker);
var remote = AppDomain.CreateDomain("Remote", null, AppDomain.CurrentDomain.SetupInformation);
try
{
using (LogContext.PushProperty("Prop1", 42))
{
remote.DoCallBack(CallFromRemote);
using (LogContext.PushProperty("Prop2", 24))
{
remote.DoCallBack(CallFromRemote);
}
}
}
finally
{
AppDomain.Unload(remote);
}
await Task.Delay(200);
// This is intermittently 2 or 3 (now, 4), depending on the moods of the test runner;
// I think "at least two" is what we're concerned about, here.
Assert.InRange(tracker.DisconnectCount, 2, 4);
static void CallFromRemote() { }
}
#endif
static async Task TestWithSyncContext(Func<Task> testAction, SynchronizationContext syncContext)
{
var prevCtx = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(syncContext);
Task t;
try
{
t = testAction();
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevCtx);
}
await t;
}
}
#if REMOTING
class InMemoryRemoteObjectTracker : ITrackingHandler
{
public int DisconnectCount { get; set; }
public void DisconnectedObject(object obj) => DisconnectCount++;
public void MarshaledObject(object obj, ObjRef or) { }
public void UnmarshaledObject(object obj, ObjRef or) { }
}
#endif
#if APPDOMAIN
public class RemotelyCallable : MarshalByRefObject
{
public bool IsCallable()
{
LogEvent? lastEvent = null;
var log = new LoggerConfiguration()
.WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
.Enrich.FromLogContext()
.CreateLogger();
using (LogContext.PushProperty("Number", 42))
log.Information("Hello");
Assert.NotNull(lastEvent);
return 42.Equals(lastEvent!.Properties["Number"].LiteralValue());
}
}
#endif
class ForceNewThreadSyncContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object? state) => new Thread(x => d(x)) { IsBackground = true }.Start(state);
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using static NodaTime.NodaConstants;
using System.Text;
using NodaTime.Annotations;
using NodaTime.Properties;
using NodaTime.Utility;
using JetBrains.Annotations;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="Period"/> values.
/// </summary>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class PeriodPattern : IPattern<Period>
{
/// <summary>
/// Pattern which uses the normal ISO format for all the supported ISO
/// fields, but extends the time part with "s" for milliseconds, "t" for ticks and "n" for nanoseconds.
/// No normalization is carried out, and a period may contain weeks as well as years, months and days.
/// Each element may also be negative, independently of other elements. This pattern round-trips its
/// values: a parse/format cycle will produce an identical period, including units.
/// </summary>
public static PeriodPattern RoundtripPattern { get; } = new PeriodPattern(new RoundtripPatternImpl());
/// <summary>
/// A "normalizing" pattern which abides by the ISO-8601 duration format as far as possible.
/// Weeks are added to the number of days (after multiplying by 7). Time units are normalized
/// (extending into days where necessary), and fractions of seconds are represented within the
/// seconds part. Unlike ISO-8601, which pattern allows for negative values within a period.
/// </summary>
/// <remarks>
/// Note that normalizing the period when formatting will cause an <see cref="System.OverflowException"/>
/// if the period contains more than <see cref="System.Int64.MaxValue"/> ticks when the
/// combined weeks/days/time portions are considered. Such a period could never
/// be useful anyway, however.
/// </remarks>
public static PeriodPattern NormalizingIsoPattern { get; } = new PeriodPattern(new NormalizingIsoPatternImpl());
private readonly IPattern<Period> pattern;
private PeriodPattern([NotNull] IPattern<Period> pattern)
{
this.pattern = Preconditions.CheckNotNull(pattern, nameof(pattern));
}
/// <summary>
/// Parses the given text value according to the rules of this pattern.
/// </summary>
/// <remarks>
/// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as
/// the argument being null are wrapped in a parse result.
/// </remarks>
/// <param name="text">The text value to parse.</param>
/// <returns>The result of parsing, which may be successful or unsuccessful.</returns>
public ParseResult<Period> Parse(string text) => pattern.Parse(text);
/// <summary>
/// Formats the given period as text according to the rules of this pattern.
/// </summary>
/// <param name="value">The period to format.</param>
/// <returns>The period formatted according to this pattern.</returns>
public string Format(Period value) => pattern.Format(value);
/// <summary>
/// Formats the given value as text according to the rules of this pattern,
/// appending to the given <see cref="StringBuilder"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="builder">The <c>StringBuilder</c> to append to.</param>
/// <returns>The builder passed in as <paramref name="builder"/>.</returns>
public StringBuilder AppendFormat(Period value, [NotNull] StringBuilder builder) => pattern.AppendFormat(value, builder);
private static void AppendValue(StringBuilder builder, long value, string suffix)
{
// Avoid having a load of conditions in the calling code by checking here
if (value == 0)
{
return;
}
FormatHelper.FormatInvariant(value, builder);
builder.Append(suffix);
}
private static ParseResult<Period> InvalidUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, Messages.Parse_InvalidUnitSpecifier, unitCharacter);
private static ParseResult<Period> RepeatedUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, Messages.Parse_RepeatedUnitSpecifier, unitCharacter);
private static ParseResult<Period> MisplacedUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, Messages.Parse_MisplacedUnitSpecifier, unitCharacter);
private sealed class RoundtripPatternImpl : IPattern<Period>
{
public ParseResult<Period> Parse(string text)
{
if (text == null)
{
return ParseResult<Period>.ArgumentNull("text");
}
if (text.Length == 0)
{
return ParseResult<Period>.ValueStringEmpty;
}
ValueCursor valueCursor = new ValueCursor(text);
valueCursor.MoveNext();
if (valueCursor.Current != 'P')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'P');
}
bool inDate = true;
PeriodBuilder builder = new PeriodBuilder();
PeriodUnits unitsSoFar = 0;
while (valueCursor.MoveNext())
{
long unitValue;
if (inDate && valueCursor.Current == 'T')
{
inDate = false;
continue;
}
var failure = valueCursor.ParseInt64<Period>(out unitValue);
if (failure != null)
{
return failure;
}
if (valueCursor.Length == valueCursor.Index)
{
return ParseResult<Period>.EndOfString(valueCursor);
}
// Various failure cases:
// - Repeated unit (e.g. P1M2M)
// - Time unit is in date part (e.g. P5M)
// - Date unit is in time part (e.g. PT1D)
// - Unit is in incorrect order (e.g. P5D1Y)
// - Unit is invalid (e.g. P5J)
// - Unit is missing (e.g. P5)
PeriodUnits unit;
switch (valueCursor.Current)
{
case 'Y': unit = PeriodUnits.Years; break;
case 'M': unit = inDate ? PeriodUnits.Months : PeriodUnits.Minutes; break;
case 'W': unit = PeriodUnits.Weeks; break;
case 'D': unit = PeriodUnits.Days; break;
case 'H': unit = PeriodUnits.Hours; break;
case 'S': unit = PeriodUnits.Seconds; break;
case 's': unit = PeriodUnits.Milliseconds; break;
case 't': unit = PeriodUnits.Ticks; break;
case 'n': unit = PeriodUnits.Nanoseconds; break;
default: return InvalidUnit(valueCursor, valueCursor.Current);
}
if ((unit & unitsSoFar) != 0)
{
return RepeatedUnit(valueCursor, valueCursor.Current);
}
// This handles putting months before years, for example. Less significant units
// have higher integer representations.
if (unit < unitsSoFar)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// The result of checking "there aren't any time units in this unit" should be
// equal to "we're still in the date part".
if ((unit & PeriodUnits.AllTimeUnits) == 0 != inDate)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
builder[unit] = unitValue;
unitsSoFar |= unit;
}
return ParseResult<Period>.ForValue(builder.Build());
}
public string Format([NotNull] Period value) => AppendFormat(value, new StringBuilder()).ToString();
public StringBuilder AppendFormat([NotNull] Period value, [NotNull] StringBuilder builder)
{
Preconditions.CheckNotNull(value, nameof(value));
Preconditions.CheckNotNull(builder, nameof(builder));
builder.Append("P");
AppendValue(builder, value.Years, "Y");
AppendValue(builder, value.Months, "M");
AppendValue(builder, value.Weeks, "W");
AppendValue(builder, value.Days, "D");
if (value.HasTimeComponent)
{
builder.Append("T");
AppendValue(builder, value.Hours, "H");
AppendValue(builder, value.Minutes, "M");
AppendValue(builder, value.Seconds, "S");
AppendValue(builder, value.Milliseconds, "s");
AppendValue(builder, value.Ticks, "t");
AppendValue(builder, value.Nanoseconds, "n");
}
return builder;
}
}
private sealed class NormalizingIsoPatternImpl : IPattern<Period>
{
// TODO: Tidy this up a *lot*.
public ParseResult<Period> Parse(string text)
{
if (text == null)
{
return ParseResult<Period>.ArgumentNull("text");
}
if (text.Length == 0)
{
return ParseResult<Period>.ValueStringEmpty;
}
ValueCursor valueCursor = new ValueCursor(text);
valueCursor.MoveNext();
if (valueCursor.Current != 'P')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'P');
}
bool inDate = true;
PeriodBuilder builder = new PeriodBuilder();
PeriodUnits unitsSoFar = 0;
while (valueCursor.MoveNext())
{
long unitValue;
if (inDate && valueCursor.Current == 'T')
{
inDate = false;
continue;
}
bool negative = valueCursor.Current == '-';
var failure = valueCursor.ParseInt64<Period>(out unitValue);
if (failure != null)
{
return failure;
}
if (valueCursor.Length == valueCursor.Index)
{
return ParseResult<Period>.EndOfString(valueCursor);
}
// Various failure cases:
// - Repeated unit (e.g. P1M2M)
// - Time unit is in date part (e.g. P5M)
// - Date unit is in time part (e.g. PT1D)
// - Unit is in incorrect order (e.g. P5D1Y)
// - Unit is invalid (e.g. P5J)
// - Unit is missing (e.g. P5)
PeriodUnits unit;
switch (valueCursor.Current)
{
case 'Y': unit = PeriodUnits.Years; break;
case 'M': unit = inDate ? PeriodUnits.Months : PeriodUnits.Minutes; break;
case 'W': unit = PeriodUnits.Weeks; break;
case 'D': unit = PeriodUnits.Days; break;
case 'H': unit = PeriodUnits.Hours; break;
case 'S': unit = PeriodUnits.Seconds; break;
case ',':
case '.': unit = PeriodUnits.Nanoseconds; break; // Special handling below
default: return InvalidUnit(valueCursor, valueCursor.Current);
}
if ((unit & unitsSoFar) != 0)
{
return RepeatedUnit(valueCursor, valueCursor.Current);
}
// This handles putting months before years, for example. Less significant units
// have higher integer representations.
if (unit < unitsSoFar)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// The result of checking "there aren't any time units in this unit" should be
// equal to "we're still in the date part".
if ((unit & PeriodUnits.AllTimeUnits) == 0 != inDate)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// Seen a . or , which need special handling.
if (unit == PeriodUnits.Nanoseconds)
{
// Check for already having seen seconds, e.g. PT5S0.5
if ((unitsSoFar & PeriodUnits.Seconds) != 0)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
builder.Seconds = unitValue;
if (!valueCursor.MoveNext())
{
return ParseResult<Period>.MissingNumber(valueCursor);
}
int totalNanoseconds;
// Can cope with at most 999999999 nanoseconds
if (!valueCursor.ParseFraction(9, 9, out totalNanoseconds, 1))
{
return ParseResult<Period>.MissingNumber(valueCursor);
}
// Use whether or not the seconds value was negative (even if 0)
// as the indication of whether this value is negative.
if (negative)
{
totalNanoseconds = -totalNanoseconds;
}
builder.Milliseconds = (totalNanoseconds / NanosecondsPerMillisecond) % MillisecondsPerSecond;
builder.Ticks = (totalNanoseconds / NanosecondsPerTick) % TicksPerMillisecond;
builder.Nanoseconds = totalNanoseconds % NanosecondsPerTick;
if (valueCursor.Current != 'S')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'S');
}
if (valueCursor.MoveNext())
{
return ParseResult<Period>.ExpectedEndOfString(valueCursor);
}
return ParseResult<Period>.ForValue(builder.Build());
}
builder[unit] = unitValue;
unitsSoFar |= unit;
}
if (unitsSoFar == 0)
{
return ParseResult<Period>.ForInvalidValue(valueCursor, Messages.Parse_EmptyPeriod);
}
return ParseResult<Period>.ForValue(builder.Build());
}
public string Format([NotNull] Period value) => AppendFormat(value, new StringBuilder()).ToString();
public StringBuilder AppendFormat([NotNull] Period value, [NotNull] StringBuilder builder)
{
Preconditions.CheckNotNull(value, nameof(value));
Preconditions.CheckNotNull(builder, nameof(builder));
value = value.Normalize();
// Always ensure we've got *some* unit; arbitrarily pick days.
if (value.Equals(Period.Zero))
{
builder.Append("P0D");
return builder;
}
builder.Append("P");
AppendValue(builder, value.Years, "Y");
AppendValue(builder, value.Months, "M");
AppendValue(builder, value.Weeks, "W");
AppendValue(builder, value.Days, "D");
if (value.HasTimeComponent)
{
builder.Append("T");
AppendValue(builder, value.Hours, "H");
AppendValue(builder, value.Minutes, "M");
long nanoseconds = value.Milliseconds * NanosecondsPerMillisecond + value.Ticks * NanosecondsPerTick + value.Nanoseconds;
long seconds = value.Seconds;
if (nanoseconds != 0 || seconds != 0)
{
if (nanoseconds < 0 || seconds < 0)
{
builder.Append("-");
nanoseconds = -nanoseconds;
seconds = -seconds;
}
FormatHelper.FormatInvariant(seconds, builder);
if (nanoseconds != 0)
{
builder.Append(".");
FormatHelper.AppendFractionTruncate((int)nanoseconds, 9, 9, builder);
}
builder.Append("S");
}
}
return builder;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Rynchodon.Utility;
using VRage.Collections;
using VRageMath;
namespace Rynchodon.Autopilot.Pathfinding
{
struct PathNode
{
/// <summary>The key of the parent to this node.</summary>
public long ParentKey;
/// <summary>Distance from start to this node.</summary>
public float DistToCur;
/// <summary>The position of this node, relative to obstruction.</summary>
public Vector3D Position;
/// <summary>The direction from parent to this node.</summary>
public Vector3 DirectionFromParent;
/// <summary>The position hash for this node, used for indexing.</summary>
public long Key { get { return Position.GetHash(); } }
public PathNode(ref PathNode parent, ref Vector3D position)
{
Profiler.StartProfileBlock();
this.ParentKey = parent.Position.GetHash();
this.Position = position;
Vector3D disp; Vector3D.Subtract(ref position, ref parent.Position, out disp);
this.DirectionFromParent = disp;
this.DistToCur = parent.DistToCur + this.DirectionFromParent.Normalize();
Profiler.EndProfileBlock();
}
}
abstract class PathNodeSet : IComparable<PathNodeSet>
{
/// <summary>Nodes will be a discrete distance from this position. Relative to obstruction.</summary>
public Vector3D m_referencePosition;
/// <summary>Where this set starts from. Relative to obstruction.</summary>
public Vector3D m_startPosition;
/// <summary>PathNodeSet that this PathNodeSet is trying to reach.</summary>
public IEnumerable<PathNodeSet> m_targets;
public abstract IEnumerable<Vector3D> BlueSkyNodes { get; }
public abstract int CompareTo(PathNodeSet other);
public abstract bool HasReached(long key);
public abstract bool TryGetReached(long key, out PathNode reached);
public abstract void Setup(ref Vector3D referencePosition, ref Vector3D startPosition, bool m_canChangeCourse, int maxNodeDistance);
}
//class RootNode : PathNodeSet
//{
// public override IEnumerable<Vector3D> BlueSkyNodes { get { yield break; } }
// public override int CompareTo(PathNodeSet other) { throw new NotImplementedException(); }
// public override bool HasReached(long key) { return m_startPosition.GetHash() == key; }
// public override void Setup(ref Vector3D referencePosition, ref Vector3D startPosition, bool m_canChangeCourse)
// {
// m_referencePosition = referencePosition;
// m_startPosition = startPosition;
// }
// public override bool TryGetReached(long key, out PathNode reached)
// {
// if (m_startPosition.GetHash() == key)
// {
// reached = new PathNode() { Position = m_startPosition };
// return true;
// }
// reached = default(PathNode);
// return false;
// }
//}
class FindingSet : PathNodeSet
{
public const int MaxOpenNodes = 1024;
public const int DefaultNodeDistance = 128;
public const int MinNodeDistance = 2; // needs to be greater than the minimum distance for poping a waypoint
public const float TurnPenalty = 100f;
public static double MinPathDistance(ref Vector3D to, ref Vector3D from)
{
Vector3D displacement; Vector3D.Subtract(ref to, ref from, out displacement);
return MinPathDistance(ref displacement);
}
public static double MinPathDistance(ref Vector3D displacement)
{
double X = Math.Abs(displacement.X), Y = Math.Abs(displacement.Y), Z = Math.Abs(displacement.Z), temp;
// sort so that X is min and Z is max
if (Y < X)
{
temp = X;
X = Y;
Y = temp;
}
if (Z < Y)
{
temp = Y;
Y = Z;
Z = temp;
if (Y < X)
{
temp = X;
X = Y;
Y = temp;
}
}
return X * MathHelper.Sqrt3 + (Y - X) * MathHelper.Sqrt2 + Z - Y;
}
/// <summary>Nodes that have not been testing for reachable, sorted by estimated distance to target set. Use AddOpenNode to add nodes.</summary>
public MyBinaryStructHeap<float, PathNode> m_openNodes;
/// <summary>Nodes that have been reached, indexed by position hash or "Key".</summary>
public Dictionary<long, PathNode> m_reachedNodes;
/// <summary>Nodes that have been reached that are not near anything.</summary>
public List<Vector3D> m_blueSkyNodes;
public bool Failed { get { return NodeDistance == MinNodeDistance && m_openNodes.Count == 0; } }
private Logable Log {
get {
return new Logable(
ResourcePool<FindingSet>.InstancesCreated.ToString(),
m_referencePosition.ToString() + ":" + m_startPosition.ToString(),
string.Concat(m_blueSkyNodes.Count, ':', m_reachedNodes.Count, ':', m_openNodes.Count));
}
}
#if PROFILE
public int m_unreachableNodes;
#endif
/// <summary>Affects the distance between path nodes and their children when creating new path nodes. Before the start node is processed, it will be DefaultNodeDistance * 2.</summary>
public int NodeDistance { get; private set; }
public override IEnumerable<Vector3D> BlueSkyNodes { get { return m_blueSkyNodes; } }
public FindingSet()
{
m_openNodes = new MyBinaryStructHeap<float, PathNode>(MaxOpenNodes);
m_reachedNodes = new Dictionary<long, PathNode>();
m_blueSkyNodes = new List<Vector3D>();
NodeDistance = DefaultNodeDistance << 1;
#if PROFILE
m_unreachableNodes = 0;
#endif
}
public void Clear()
{
m_openNodes.Clear();
m_reachedNodes.Clear();
m_blueSkyNodes.Clear();
NodeDistance = DefaultNodeDistance << 1;
m_targets = null;
#if PROFILE
m_unreachableNodes = 0;
#endif
}
/// <summary>
/// Compares this PathNodeSet to another for the purposes of scheduling.
/// </summary>
/// <param name="other">The object to compare this to.</param>
/// <returns>A negative integer, zero, or a positive integer, indicating scheduling priority.</returns>
public override int CompareTo(PathNodeSet other)
{
FindingSet otherFS = (FindingSet)other;
if (this.Failed)
return 1;
else if (otherFS.Failed)
return -1;
int value = m_blueSkyNodes.Count - otherFS.m_blueSkyNodes.Count;
if (value != 0)
return value;
value = m_reachedNodes.Count - otherFS.m_reachedNodes.Count;
if (value != 0)
return value;
return 0;
}
public override void Setup(ref Vector3D reference, ref Vector3D start, bool canChangeCourse, int maxNodeDistance)
{
Clear();
m_referencePosition = reference;
m_startPosition = start;
PathNode firstNode = new PathNode() { Position = start };
if (!canChangeCourse)
{
Vector3D direction; Vector3D.Subtract(ref reference, ref start, out direction);
direction.Normalize();
firstNode.DirectionFromParent = direction;
}
AddOpenNode(ref firstNode, 0f);
m_reachedNodes.Add(firstNode.Key, firstNode);
if (maxNodeDistance < MinNodeDistance)
maxNodeDistance = MinNodeDistance;
while (NodeDistance > maxNodeDistance)
NodeDistance = NodeDistance >> 1;
Log.DebugLog("Finished setup. reference: " + reference + ", start: " + start + ", NodeDistance: " + NodeDistance, Logger.severity.DEBUG);
}
/// <summary>
/// Add a node to m_openNodes.
/// </summary>
/// <param name="node">The newly created node.</param>
/// <param name="estimatedDistance">Distance from start to node + estimated distance to target.</param>
public void AddOpenNode(ref PathNode node, float estimatedDistance)
{
if (m_openNodes.Count == MaxOpenNodes)
m_openNodes.RemoveMax();
m_openNodes.Insert(node, estimatedDistance);
}
/// <summary>
/// Change the distance between reached nodes and their children. When doubling, m_openNodes will be rebuilt.
/// New children will be created and added to the open list for every reached node.
/// </summary>
/// <param name="halve">When true, NodeDistance will be halved. When false, NodeDistance will be doubled.</param>
public void ChangeNodeDistance(bool halve, bool canChangeCourse)
{
if (!halve)
m_openNodes.Clear();
if (halve)
{
NodeDistance = NodeDistance >> 1;
Log.DebugLog("Halved node distance, now: " + NodeDistance);
}
else
{
NodeDistance = NodeDistance << 1;
Log.DebugLog("Doubled node distance, now: " + NodeDistance);
}
foreach (PathNode reachedNode in m_reachedNodes.Values)
{
PathNode reachedNode2 = reachedNode;
if (canChangeCourse)
CreatePathNode(ref reachedNode2);
else
CreatePathNodeLine(ref reachedNode2);
}
}
public void CreatePathNode(PathNode currentNode, bool canChangeCourse)
{
if (canChangeCourse)
CreatePathNode(ref currentNode);
else
CreatePathNodeLine(ref currentNode);
}
public void CreatePathNode(ref PathNode currentNode, bool canChangeCourse)
{
if (canChangeCourse)
CreatePathNode(ref currentNode);
else
CreatePathNodeLine(ref currentNode);
}
/// <summary>
/// Create path nodes around the specified node and add them to open list. Do not use if pathfinder cannot change course.
/// </summary>
/// <param name="currentNode">The node that will be the parent to the new nodes.</param>
private void CreatePathNode(ref PathNode currentNode)
{
long currentKey = currentNode.Position.GetHash();
foreach (Vector3I neighbour in Globals.NeighboursOne)
CreatePathNode(currentKey, ref currentNode, neighbour, 1f);
foreach (Vector3I neighbour in Globals.NeighboursTwo)
CreatePathNode(currentKey, ref currentNode, neighbour, MathHelper.Sqrt2);
foreach (Vector3I neighbour in Globals.NeighboursThree)
CreatePathNode(currentKey, ref currentNode, neighbour, MathHelper.Sqrt3);
}
/// <summary>
/// Create a path node from a parent.
/// </summary>
/// <param name="parentKey">The key of the parent's postion.</param>
/// <param name="parent">The parent of the new node.</param>
/// <param name="neighbour">The cell direction of the new node.</param>
/// <param name="distMulti">Multiplied by NodeDistance to get the distance the new node will be from its parent.</param>
private void CreatePathNode(long parentKey, ref PathNode parent, Vector3I neighbour, float distMulti)
{
Profiler.StartProfileBlock();
Vector3D position = parent.Position + neighbour * NodeDistance * distMulti;
// round position so that is a discrete number of steps from m_referencePosition
Vector3D finishToPosition; Vector3D.Subtract(ref position, ref m_referencePosition, out finishToPosition);
VectorExtensions.RoundTo(ref finishToPosition, NodeDistance);
Vector3D.Add(ref m_referencePosition, ref finishToPosition, out position);
Log.DebugLog("m_reachedNodes == null", Logger.severity.FATAL, condition: m_reachedNodes == null);
if (m_reachedNodes.ContainsKey(position.GetHash()))
{
Profiler.EndProfileBlock();
return;
}
PathNode result = new PathNode(ref parent, ref position);
float turn; Vector3.Dot(ref parent.DirectionFromParent, ref result.DirectionFromParent, out turn);
if (turn < 0f)
{
Profiler.EndProfileBlock();
return;
}
double distToDest = double.MaxValue;
foreach (PathNodeSet target in m_targets)
{
double dist = MinPathDistance(ref target.m_startPosition, ref position);
if (dist < distToDest)
distToDest = dist;
}
float resultKey = result.DistToCur + (float)distToDest;
if (turn > 0.99f && parent.ParentKey != 0f)
{
parentKey = parent.ParentKey;
}
else
{
if (turn < 0f)
{
Profiler.EndProfileBlock();
return;
}
resultKey += TurnPenalty * (1f - turn);
}
//Log.DebugLog("DirectionFromParent is incorrect. DirectionFromParent: " + result.DirectionFromParent + ", parent: " + parent.Position + ", current: " + result.Position + ", direction: " +
// Vector3.Normalize(result.Position - parent.Position), Logger.severity.ERROR, condition: !Vector3.Normalize(result.Position - parent.Position).Equals(result.DirectionFromParent, 0.01f));
//Log.DebugLog("Length is incorrect. Length: " + (result.DistToCur - parent.DistToCur) + ", distance: " + Vector3D.Distance(result.Position, parent.Position), Logger.severity.ERROR,
// condition: Math.Abs((result.DistToCur - parent.DistToCur) - (Vector3D.Distance(result.Position, parent.Position))) > 0.01f);
//Log.DebugLog("resultKey <= 0", Logger.severity.ERROR, condition: resultKey <= 0f);
AddOpenNode(ref result, resultKey);
Profiler.EndProfileBlock();
}
/// <summary>
/// Create a PathNode between parent and destination. Only for forward search.
/// </summary>
/// <param name="parent">The node that will be the parent to the new node.</param>
private void CreatePathNodeLine(ref PathNode parent)
{
Vector3D direction = parent.DirectionFromParent;
Vector3D disp; Vector3D.Multiply(ref direction, NodeDistance, out disp);
Vector3D position; Vector3D.Add(ref parent.Position, ref disp, out position);
PathNode result = new PathNode()
{
DirectionFromParent = parent.DirectionFromParent,
DistToCur = parent.DistToCur + NodeDistance,
ParentKey = parent.Key,
Position = position
};
// do not bother with key as there will only be one open node
AddOpenNode(ref result, 0f);
}
public override bool HasReached(long key)
{
return m_reachedNodes.ContainsKey(key);
}
public override bool TryGetReached(long key, out PathNode reached)
{
return m_reachedNodes.TryGetValue(key, out reached);
}
} // class
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Multiplayer;
using osu.Game.Users;
namespace osu.Game.Screens.Multiplayer
{
public class RoomInspector : Container
{
private readonly MarginPadding contentPadding = new MarginPadding { Horizontal = 20, Vertical = 10 };
private const float transition_duration = 100;
private readonly Box statusStrip;
private readonly Container coverContainer;
private readonly FillFlowContainer topFlow, participantsFlow;
private readonly ModeTypeInfo modeTypeInfo;
private readonly OsuSpriteText participants, participantsSlash, maxParticipants, name, status, beatmapTitle, beatmapDash, beatmapArtist, beatmapAuthor;
private readonly ParticipantInfo participantInfo;
private readonly ScrollContainer participantsScroll;
private readonly Bindable<string> nameBind = new Bindable<string>();
private readonly Bindable<User> hostBind = new Bindable<User>();
private readonly Bindable<RoomStatus> statusBind = new Bindable<RoomStatus>();
private readonly Bindable<GameType> typeBind = new Bindable<GameType>();
private readonly Bindable<BeatmapInfo> beatmapBind = new Bindable<BeatmapInfo>();
private readonly Bindable<int?> maxParticipantsBind = new Bindable<int?>();
private readonly Bindable<User[]> participantsBind = new Bindable<User[]>();
private OsuColour colours;
private LocalisationEngine localisation;
private Room room;
public Room Room
{
get { return room; }
set
{
if (value == room) return;
room = value;
nameBind.BindTo(Room.Name);
hostBind.BindTo(Room.Host);
statusBind.BindTo(Room.Status);
typeBind.BindTo(Room.Type);
beatmapBind.BindTo(Room.Beatmap);
maxParticipantsBind.BindTo(Room.MaxParticipants);
participantsBind.BindTo(Room.Participants);
}
}
public RoomInspector()
{
Width = 520;
RelativeSizeAxes = Axes.Y;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"343138"),
},
topFlow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = 200,
Masking = true,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
coverContainer = new Container
{
RelativeSizeAxes = Axes.Both,
},
},
},
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(Color4.Black.Opacity(0.5f), Color4.Black.Opacity(0)),
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(20),
Children = new Drawable[]
{
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
LayoutDuration = transition_duration,
Children = new[]
{
participants = new OsuSpriteText
{
TextSize = 30,
Font = @"Exo2.0-Bold"
},
participantsSlash = new OsuSpriteText
{
Text = @"/",
TextSize = 30,
Font = @"Exo2.0-Light"
},
maxParticipants = new OsuSpriteText
{
TextSize = 30,
Font = @"Exo2.0-Light"
},
},
},
name = new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
TextSize = 30,
},
},
},
},
},
statusStrip = new Box
{
RelativeSizeAxes = Axes.X,
Height = 5,
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"28242d"),
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Padding = contentPadding,
Spacing = new Vector2(0f, 5f),
Children = new Drawable[]
{
status = new OsuSpriteText
{
TextSize = 14,
Font = @"Exo2.0-Bold",
},
new FillFlowContainer
{
AutoSizeAxes = Axes.X,
Height = 30,
Direction = FillDirection.Horizontal,
LayoutDuration = transition_duration,
Spacing = new Vector2(5f, 0f),
Children = new Drawable[]
{
modeTypeInfo = new ModeTypeInfo(),
new Container
{
AutoSizeAxes = Axes.X,
RelativeSizeAxes = Axes.Y,
Margin = new MarginPadding { Left = 5 },
Children = new[]
{
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Children = new[]
{
beatmapTitle = new OsuSpriteText
{
Font = @"Exo2.0-BoldItalic",
},
beatmapDash = new OsuSpriteText
{
Font = @"Exo2.0-BoldItalic",
},
beatmapArtist = new OsuSpriteText
{
Font = @"Exo2.0-RegularItalic",
},
},
},
beatmapAuthor = new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
TextSize = 14,
},
},
},
},
},
},
},
},
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = contentPadding,
Children = new Drawable[]
{
participantInfo = new ParticipantInfo(@"Rank Range "),
},
},
},
},
participantsScroll = new OsuScrollContainer
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
RelativeSizeAxes = Axes.X,
Padding = new MarginPadding { Top = contentPadding.Top, Left = 38, Right = 37 },
Children = new[]
{
participantsFlow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
LayoutDuration = transition_duration,
Spacing = new Vector2(5f),
},
},
},
};
nameBind.ValueChanged += displayName;
hostBind.ValueChanged += displayUser;
typeBind.ValueChanged += displayGameType;
maxParticipantsBind.ValueChanged += displayMaxParticipants;
participantsBind.ValueChanged += displayParticipants;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, LocalisationEngine localisation)
{
this.localisation = localisation;
this.colours = colours;
beatmapAuthor.Colour = colours.Gray9;
//binded here instead of ctor because dependencies are needed
statusBind.ValueChanged += displayStatus;
beatmapBind.ValueChanged += displayBeatmap;
statusBind.TriggerChange();
beatmapBind.TriggerChange();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
participantsScroll.Height = DrawHeight - topFlow.DrawHeight;
}
private void displayName(string value)
{
name.Text = value;
}
private void displayUser(User value)
{
participantInfo.Host = value;
}
private void displayStatus(RoomStatus value)
{
status.Text = value.Message;
foreach (Drawable d in new Drawable[] { statusStrip, status })
d.FadeColour(value.GetAppropriateColour(colours), transition_duration);
}
private void displayGameType(GameType value)
{
modeTypeInfo.Type = value;
}
private void displayBeatmap(BeatmapInfo value)
{
modeTypeInfo.Beatmap = value;
if (value != null)
{
coverContainer.FadeIn(transition_duration);
coverContainer.Children = new[]
{
new AsyncLoadWrapper(new BeatmapSetCover(value.BeatmapSet)
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
FillMode = FillMode.Fill,
OnLoadComplete = d => d.FadeInFromZero(400, Easing.Out),
}) { RelativeSizeAxes = Axes.Both },
};
beatmapTitle.Current = localisation.GetUnicodePreference(value.Metadata.TitleUnicode, value.Metadata.Title);
beatmapDash.Text = @" - ";
beatmapArtist.Current = localisation.GetUnicodePreference(value.Metadata.ArtistUnicode, value.Metadata.Artist);
beatmapAuthor.Text = $"mapped by {value.Metadata.Author}";
}
else
{
coverContainer.FadeOut(transition_duration);
beatmapTitle.Current = null;
beatmapArtist.Current = null;
beatmapTitle.Text = "Changing map";
beatmapDash.Text = beatmapArtist.Text = beatmapAuthor.Text = string.Empty;
}
}
private void displayMaxParticipants(int? value)
{
if (value == null)
{
participantsSlash.FadeOut(transition_duration);
maxParticipants.FadeOut(transition_duration);
}
else
{
participantsSlash.FadeIn(transition_duration);
maxParticipants.FadeIn(transition_duration);
maxParticipants.Text = value.ToString();
}
}
private void displayParticipants(User[] value)
{
participants.Text = value.Length.ToString();
participantInfo.Participants = value;
participantsFlow.ChildrenEnumerable = value.Select(u => new UserTile(u));
}
private class UserTile : Container, IHasTooltip
{
private readonly User user;
public string TooltipText => user.Username;
public UserTile(User user)
{
this.user = user;
Size = new Vector2(70f);
CornerRadius = 5f;
Masking = true;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"27252d"),
},
new UpdateableAvatar
{
RelativeSizeAxes = Axes.Both,
User = user,
},
};
}
}
}
}
| |
// <copyright file="GpBiCg.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Double.Solvers
{
/// <summary>
/// A Generalized Product Bi-Conjugate Gradient iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The Generalized Product Bi-Conjugate Gradient (GPBiCG) solver is an
/// alternative version of the Bi-Conjugate Gradient stabilized (CG) solver.
/// Unlike the CG solver the GPBiCG solver can be used on
/// non-symmetric matrices. <br/>
/// Note that much of the success of the solver depends on the selection of the
/// proper preconditioner.
/// </para>
/// <para>
/// The GPBiCG algorithm was taken from: <br/>
/// GPBiCG(m,l): A hybrid of BiCGSTAB and GPBiCG methods with
/// efficiency and robustness
/// <br/>
/// S. Fujino
/// <br/>
/// Applied Numerical Mathematics, Volume 41, 2002, pp 107 - 117
/// <br/>
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class GpBiCg : IIterativeSolver<double>
{
/// <summary>
/// Indicates the number of <c>BiCGStab</c> steps should be taken
/// before switching.
/// </summary>
int _numberOfBiCgStabSteps = 1;
/// <summary>
/// Indicates the number of <c>GPBiCG</c> steps should be taken
/// before switching.
/// </summary>
int _numberOfGpbiCgSteps = 4;
/// <summary>
/// Gets or sets the number of steps taken with the <c>BiCgStab</c> algorithm
/// before switching over to the <c>GPBiCG</c> algorithm.
/// </summary>
public int NumberOfBiCgStabSteps
{
get
{
return _numberOfBiCgStabSteps;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_numberOfBiCgStabSteps = value;
}
}
/// <summary>
/// Gets or sets the number of steps taken with the <c>GPBiCG</c> algorithm
/// before switching over to the <c>BiCgStab</c> algorithm.
/// </summary>
public int NumberOfGpBiCgSteps
{
get
{
return _numberOfGpbiCgSteps;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_numberOfGpbiCgSteps = value;
}
}
/// <summary>
/// Calculates the true residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
/// <param name="residual">Residual values in <see cref="Vector"/>.</param>
/// <param name="x">Instance of the <see cref="Vector"/> x.</param>
/// <param name="b">Instance of the <see cref="Vector"/> b.</param>
static void CalculateTrueResidual(Matrix<double> matrix, Vector<double> residual, Vector<double> x, Vector<double> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Decide if to do steps with BiCgStab
/// </summary>
/// <param name="iterationNumber">Number of iteration</param>
/// <returns><c>true</c> if yes, otherwise <c>false</c></returns>
bool ShouldRunBiCgStabSteps(int iterationNumber)
{
// Run the first steps as BiCGStab
// The number of steps past a whole iteration set
var difference = iterationNumber % (_numberOfBiCgStabSteps + _numberOfGpbiCgSteps);
// Do steps with BiCGStab if:
// - The difference is zero or more (i.e. we have done zero or more complete cycles)
// - The difference is less than the number of BiCGStab steps that should be taken
return (difference >= 0) && (difference < _numberOfBiCgStabSteps);
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<double> matrix, Vector<double> input, Vector<double> result, Iterator<double> iterator, IPreconditioner<double> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (result.Count != input.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (input.Count != matrix.RowCount)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix);
}
if (iterator == null)
{
iterator = new Iterator<double>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<double>();
}
preconditioner.Initialize(matrix);
// x_0 is initial guess
// Take x_0 = 0
var xtemp = new DenseVector(input.Count);
// r_0 = b - Ax_0
// This is basically a SAXPY so it could be made a lot faster
var residuals = new DenseVector(matrix.RowCount);
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Define the temporary scalars
double beta = 0;
// Define the temporary vectors
// rDash_0 = r_0
var rdash = DenseVector.OfVector(residuals);
// t_-1 = 0
var t = new DenseVector(residuals.Count);
var t0 = new DenseVector(residuals.Count);
// w_-1 = 0
var w = new DenseVector(residuals.Count);
// Define the remaining temporary vectors
var c = new DenseVector(residuals.Count);
var p = new DenseVector(residuals.Count);
var s = new DenseVector(residuals.Count);
var u = new DenseVector(residuals.Count);
var y = new DenseVector(residuals.Count);
var z = new DenseVector(residuals.Count);
var temp = new DenseVector(residuals.Count);
var temp2 = new DenseVector(residuals.Count);
var temp3 = new DenseVector(residuals.Count);
// for (k = 0, 1, .... )
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue)
{
// p_k = r_k + beta_(k-1) * (p_(k-1) - u_(k-1))
p.Subtract(u, temp);
temp.Multiply(beta, temp2);
residuals.Add(temp2, p);
// Solve M b_k = p_k
preconditioner.Approximate(p, temp);
// s_k = A b_k
matrix.Multiply(temp, s);
// alpha_k = (r*_0 * r_k) / (r*_0 * s_k)
var alpha = rdash.DotProduct(residuals)/rdash.DotProduct(s);
// y_k = t_(k-1) - r_k - alpha_k * w_(k-1) + alpha_k s_k
s.Subtract(w, temp);
t.Subtract(residuals, y);
temp.Multiply(alpha, temp2);
y.Add(temp2, temp3);
temp3.CopyTo(y);
// Store the old value of t in t0
t.CopyTo(t0);
// t_k = r_k - alpha_k s_k
s.Multiply(-alpha, temp2);
residuals.Add(temp2, t);
// Solve M d_k = t_k
preconditioner.Approximate(t, temp);
// c_k = A d_k
matrix.Multiply(temp, c);
var cdot = c.DotProduct(c);
// cDot can only be zero if c is a zero vector
// We'll set cDot to 1 if it is zero to prevent NaN's
// Note that the calculation should continue fine because
// c.DotProduct(t) will be zero and so will c.DotProduct(y)
if (cdot.AlmostEqualNumbersBetween(0, 1))
{
cdot = 1.0;
}
// Even if we don't want to do any BiCGStab steps we'll still have
// to do at least one at the start to initialize the
// system, but we'll only have to take special measures
// if we don't do any so ...
var ctdot = c.DotProduct(t);
double eta;
double sigma;
if (((_numberOfBiCgStabSteps == 0) && (iterationNumber == 0)) || ShouldRunBiCgStabSteps(iterationNumber))
{
// sigma_k = (c_k * t_k) / (c_k * c_k)
sigma = ctdot/cdot;
// eta_k = 0
eta = 0;
}
else
{
var ydot = y.DotProduct(y);
// yDot can only be zero if y is a zero vector
// We'll set yDot to 1 if it is zero to prevent NaN's
// Note that the calculation should continue fine because
// y.DotProduct(t) will be zero and so will c.DotProduct(y)
if (ydot.AlmostEqualNumbersBetween(0, 1))
{
ydot = 1.0;
}
var ytdot = y.DotProduct(t);
var cydot = c.DotProduct(y);
var denom = (cdot*ydot) - (cydot*cydot);
// sigma_k = ((y_k * y_k)(c_k * t_k) - (y_k * t_k)(c_k * y_k)) / ((c_k * c_k)(y_k * y_k) - (y_k * c_k)(c_k * y_k))
sigma = ((ydot*ctdot) - (ytdot*cydot))/denom;
// eta_k = ((c_k * c_k)(y_k * t_k) - (y_k * c_k)(c_k * t_k)) / ((c_k * c_k)(y_k * y_k) - (y_k * c_k)(c_k * y_k))
eta = ((cdot*ytdot) - (cydot*ctdot))/denom;
}
// u_k = sigma_k s_k + eta_k (t_(k-1) - r_k + beta_(k-1) u_(k-1))
u.Multiply(beta, temp2);
t0.Add(temp2, temp);
temp.Subtract(residuals, temp3);
temp3.CopyTo(temp);
temp.Multiply(eta, temp);
s.Multiply(sigma, temp2);
temp.Add(temp2, u);
// z_k = sigma_k r_k +_ eta_k z_(k-1) - alpha_k u_k
z.Multiply(eta, z);
u.Multiply(-alpha, temp2);
z.Add(temp2, temp3);
temp3.CopyTo(z);
residuals.Multiply(sigma, temp2);
z.Add(temp2, temp3);
temp3.CopyTo(z);
// x_(k+1) = x_k + alpha_k p_k + z_k
p.Multiply(alpha, temp2);
xtemp.Add(temp2, temp3);
temp3.CopyTo(xtemp);
xtemp.Add(z, temp3);
temp3.CopyTo(xtemp);
// r_(k+1) = t_k - eta_k y_k - sigma_k c_k
// Copy the old residuals to a temp vector because we'll
// need those in the next step
residuals.CopyTo(t0);
y.Multiply(-eta, temp2);
t.Add(temp2, residuals);
c.Multiply(-sigma, temp2);
residuals.Add(temp2, temp3);
temp3.CopyTo(residuals);
// beta_k = alpha_k / sigma_k * (r*_0 * r_(k+1)) / (r*_0 * r_k)
// But first we check if there is a possible NaN. If so just reset beta to zero.
beta = (!sigma.AlmostEqualNumbersBetween(0, 1)) ? alpha/sigma*rdash.DotProduct(residuals)/rdash.DotProduct(t0) : 0;
// w_k = c_k + beta_k s_k
s.Multiply(beta, temp2);
c.Add(temp2, w);
// Get the real value
preconditioner.Approximate(xtemp, result);
// Now check for convergence
if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue)
{
// Recalculate the residuals and go round again. This is done to ensure that
// we have the proper residuals.
CalculateTrueResidual(matrix, residuals, result, input);
}
// Next iteration.
iterationNumber++;
}
}
}
}
| |
/*********************************************************************************
= Author: Michael Parsons
=
= Date: Mar 22/2012
= Assembly: ILPathways.Business
= Description: Store properties related to a success story
= Notes:
=
=
= Copyright 2012, Illinois workNet All rights reserved.
********************************************************************************/
using System;
using System.Collections.Generic;
namespace ILPathways.Business
{
///<summary>
///Represents an object that describes a AppItemStoryProperties
///</summary>
[Serializable]
public class AppItemStoryProperties : BaseBusinessDataEntity
{
///<summary>
///Initializes a new instance of the ILPathways.Business.AppItemStoryProperties class.
///</summary>
public AppItemStoryProperties() {}
/// <summary>
/// Story type constants
/// </summary>
public static int StoryTypePersonal = 0;
public static int StoryTypeWia = 1;
public static int StoryTypeIwtsWorker = 2;
public static int StoryTypeBusiness = 3;
public static int StoryTypeProjects = 4;
#region Properties created from dictionary for AppItemStoryProperties
private Guid _appItemRowId;
/// <summary>
/// Gets/Sets AppItemRowId
/// </summary>
public Guid AppItemRowId
{
get
{
return this._appItemRowId;
}
set
{
if (this._appItemRowId == value) {
//Ignore set
} else {
this._appItemRowId = value;
HasChanged = true;
}
}
}
private int _storyType;
/// <summary>
/// Gets/Sets StoryType
/// 0-personal
/// 1-wia
/// 2-iwts
/// 3-business
/// 4-projects
/// </summary>
public int StoryType
{
get
{
return this._storyType;
}
set
{
if (this._storyType == value) {
//Ignore set
} else {
this._storyType = value;
HasChanged = true;
}
}
}
private string _iwdsServiceType = "";
/// <summary>
/// Gets/Sets IwdsServiceType Code
/// Relates to Group.MemberType:
/// 1-Adult
/// 2-Dislocated worker
/// 3-Youth
/// 4-TAA
/// </summary>
public string IwdsServiceType
{
get
{
return this._iwdsServiceType;
}
set
{
if (this._iwdsServiceType == value) {
//Ignore set
} else {
this._iwdsServiceType = value.Trim();
HasChanged = true;
}
}
}
/// <summary>
/// Gets IwdsServiceType Title
/// </summary>
public string IwdsServiceTypeTitle
{
get
{
string title = "";
switch ( IwdsServiceType )
{
case "1":
title = "Adult";
break;
case "2":
title = "Dislocated worker";
break;
case "3":
title = "Youth";
break;
case "4":
title = "TAA";
break;
default:
break;
}
return title;
}
}
private int _targetUserId;
/// <summary>
/// Gets/Sets TargetUserId
/// </summary>
public int TargetUserId
{
get
{
return this._targetUserId;
}
set
{
if (this._targetUserId == value) {
//Ignore set
} else {
this._targetUserId = value;
HasChanged = true;
}
}
}
private string _firstName = "";
/// <summary>
/// Gets/Sets FirstName
/// </summary>
public string FirstName
{
get
{
return this._firstName;
}
set
{
if (this._firstName == value) {
//Ignore set
} else {
this._firstName = value.Trim();
HasChanged = true;
}
}
}
private string _lastName = "";
/// <summary>
/// Gets/Sets LastName
/// </summary>
public string LastName
{
get
{
return this._lastName;
}
set
{
if (this._lastName == value) {
//Ignore set
} else {
this._lastName = value.Trim();
HasChanged = true;
}
}
}
private string _targetTitle = "";
/// <summary>
/// Gets/Sets TargetTitle
/// </summary>
public string TargetTitle
{
get
{
return this._targetTitle;
}
set
{
if (this._targetTitle == value) {
//Ignore set
} else {
this._targetTitle = value.Trim();
HasChanged = true;
}
}
}
private string _address1 = "";
/// <summary>
/// Gets/Sets Address1
/// </summary>
public string Address1
{
get
{
return this._address1;
}
set
{
if (this._address1 == value) {
//Ignore set
} else {
this._address1 = value.Trim();
HasChanged = true;
}
}
}
private string _address2 = "";
/// <summary>
/// Gets/Sets Address2
/// </summary>
public string Address2
{
get
{
return this._address2;
}
set
{
if (this._address2 == value) {
//Ignore set
} else {
this._address2 = value.Trim();
HasChanged = true;
}
}
}
private string _city = "";
/// <summary>
/// Gets/Sets City
/// </summary>
public string City
{
get
{
return this._city;
}
set
{
if (this._city == value) {
//Ignore set
} else {
this._city = value.Trim();
HasChanged = true;
}
}
}
private string _zipcode = "";
/// <summary>
/// Gets/Sets Zipcode
/// </summary>
public string Zipcode
{
get
{
return this._zipcode;
}
set
{
if (this._zipcode == value) {
//Ignore set
} else {
this._zipcode = value.Trim();
HasChanged = true;
}
}
}
public string ZipCode
{
get
{
return this._zipcode;
}
set
{
if ( this._zipcode == value )
{
//Ignore set
} else
{
this._zipcode = value.Trim();
HasChanged = true;
}
}
}
private string _stateCode = "IL";
/// <summary>
/// Gets/Sets StateCode
/// </summary>
public string StateCode
{
get
{
return this._stateCode;
}
set
{
if ( this._stateCode == value )
{
//Ignore set
} else
{
this._stateCode = value.Trim();
HasChanged = true;
}
}
}//
private int _lwia;
/// <summary>
/// Gets/Sets Lwia
/// </summary>
public int Lwia
{
get
{
return this._lwia;
}
set
{
if ( this._lwia == value )
{
//Ignore set
} else
{
this._lwia = value;
HasChanged = true;
}
}
}
private string _congDistrict = "";
/// <summary>
/// Gets/Sets CongDistrict
/// </summary>
public string CongDistrict
{
get
{
return this._congDistrict;
}
set
{
if (this._congDistrict == value) {
//Ignore set
} else {
this._congDistrict = value.Trim();
HasChanged = true;
}
}
}
private string _serviceLocation = "";
/// <summary>
/// Gets/Sets ServiceLocation
/// </summary>
public string ServiceLocation
{
get
{
return this._serviceLocation;
}
set
{
if (this._serviceLocation == value) {
//Ignore set
} else {
this._serviceLocation = value.Trim();
HasChanged = true;
}
}
}
private string _cipCode = "";
/// <summary>
/// Gets/Sets CipCode
/// </summary>
public string CipCode
{
get
{
return this._cipCode;
}
set
{
if (this._cipCode == value) {
//Ignore set
} else {
this._cipCode = value.Trim();
HasChanged = true;
}
}
}
private int _serviceId;
/// <summary>
/// Gets/Sets ServiceId
/// </summary>
public int ServiceId
{
get
{
return this._serviceId;
}
set
{
if ( this._serviceId == value )
{
//Ignore set
} else
{
this._serviceId = value;
HasChanged = true;
}
}
}
private string _serviceDesc = "";
/// <summary>
/// Gets/Sets ServiceDesc
/// </summary>
public string ServiceDesc
{
get
{
return this._serviceDesc;
}
set
{
if (this._serviceDesc == value) {
//Ignore set
} else {
this._serviceDesc = value.Trim();
HasChanged = true;
}
}
}
private int _industryId;
/// <summary>
/// Gets/Sets IndustryId
/// </summary>
public int IndustryId
{
get
{
return this._industryId;
}
set
{
if (this._industryId == value) {
//Ignore set
} else {
this._industryId = value;
HasChanged = true;
}
}
}
private bool _youthYearRound;
/// <summary>
/// Gets/Sets YouthYearRound
/// </summary>
public bool YouthYearRound
{
get
{
return this._youthYearRound;
}
set
{
if (this._youthYearRound == value) {
//Ignore set
} else {
this._youthYearRound = value;
HasChanged = true;
}
}
}
private bool _youthEducation;
/// <summary>
/// Gets/Sets YouthEducation
/// </summary>
public bool YouthEducation
{
get
{
return this._youthEducation;
}
set
{
if (this._youthEducation == value) {
//Ignore set
} else {
this._youthEducation = value;
HasChanged = true;
}
}
}
private bool _youthSummer;
/// <summary>
/// Gets/Sets YouthSummer
/// </summary>
public bool YouthSummer
{
get
{
return this._youthSummer;
}
set
{
if (this._youthSummer == value) {
//Ignore set
} else {
this._youthSummer = value;
HasChanged = true;
}
}
}
#endregion
#region external properties
AppUser _contact = null;
/// <summary>
/// Get/Set Related Contact
/// </summary>
public AppUser RelatedContact
{
get
{
return this._contact;
}
set
{
this._contact = value;
}
}
private string _careerCluster = "";
/// <summary>
/// Gets/Sets CareerCluster
/// </summary>
public string CareerCluster
{
get
{
return this._careerCluster;
}
set
{
this._careerCluster = value.Trim();
}
}
#endregion
} // end class
} // end Namespace
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.UserModel
{
/**
* All known types of automatic shapes in DrawingML
*
* @author Yegor Kozlov
*/
public enum ShapeTypes:int
{
/// <summary>
/// Allow accessing the Initial value.
/// </summary>
None = 0,
Line = 1,
LineInv = 2,
Triangle = 3,
RightTriangle = 4,
Rectangle = 5,
Diamond = 6,
Parallelogram = 7,
Trapezoid = 8,
NonIsoscelesTrapezoid = 9,
Pentagon = 10,
Hexagon = 11,
Heptagon = 12,
Octagon = 13,
Decagon = 14,
Dodecagon = 15,
Star4 = 16,
Star5 = 17,
Star6 = 18,
Star7 = 19,
Star8 = 20,
Star10 = 21,
Star12 = 22,
Star16 = 23,
Star24 = 24,
Star32 = 25,
RoundedRectangle = 26,
Rounded1Rectangle = 27,
Rounded2SameRectangle = 28,
Rounded2DiagonalRectangle = 29,
SnipRoundedRectangle = 30,
Snip1Rectangle = 31,
Snip2SameRectangle = 32,
Snip2DiagonalRectangle = 33,
Plaque = 34,
Ellipse = 35,
Teardrop = 36,
HomePlate = 37,
Chevron = 38,
PieWedge = 39,
Pie = 40,
BlockArc = 41,
Donut = 42,
NoSmoking = 43,
RightArrow = 44,
LeftArrow = 45,
UpArrow = 46,
DownArrow = 47,
StripedRightArrow = 48,
NotchedRightArrow = 49,
BentUpArrow = 50,
LeftRightArrow = 51,
UpDownArrow = 52,
LeftUpArrow = 53,
LeftRightUpArrow = 54,
QuadArrow = 55,
LeftArrowCallout = 56,
RightArrowCallout = 57,
UpArrowCallout = 58,
DownArrowCallout = 59,
LeftRightArrowCallout = 60,
UpDownArrowCallout = 61,
QuadArrowCallout = 62,
BentArrow = 63,
UTurnArrow = 64,
CircularArrow = 65,
LeftCircularArrow = 66,
LeftRightCircularArrow = 67,
CurvedRightArrow = 68,
CurvedLeftArrow = 69,
CurvedUpArrow = 70,
CurvedDownArrow = 71,
SwooshArrow = 72,
Cube = 73,
Can = 74,
LightningBolt = 75,
Heart = 76,
Sun = 77,
Moon = 78,
SmileyFace = 79,
IrregularSeal1 = 80,
IrregularSeal2 = 81,
FoldedCorner = 82,
Bevel = 83,
Frame = 84,
HalfFrame = 85,
Corner = 86,
DiagonalStripe = 87,
Chord = 88,
Arc = 89,
LeftBracket = 90,
RightBracket = 91,
LeftBrace = 92,
RightBrace = 93,
BracketPair = 94,
BracePair = 95,
StraightConnector1 = 96,
BentConnector2 = 97,
BentConnector3 = 98,
BentConnector4 = 99,
BentConnector5 = 100,
CurvedConnector2 = 101,
CurvedConnector3 = 102,
CurvedConnector4 = 103,
CurvedConnector5 = 104,
Callout1 = 105,
Callout2 = 106,
Callout3 = 107,
AccentCallout1 = 108,
AccentCallout2 = 109,
AccentCallout3 = 110,
BorderCallout1 = 111,
BorderCallout2 = 112,
BorderCallout3 = 113,
AccentBorderCallout1 = 114,
AccentBorderCallout2 = 115,
AccentBorderCallout3 = 116,
WedgeRectangleCallout = 117,
WedgeRoundRectangleCallout = 118,
WedgeEllipseCallout = 119,
CloudCallout = 120,
Cloud = 121,
Ribbon = 122,
Ribbon2 = 123,
EllipseRibbon = 124,
EllipseRibbon2 = 125,
LeftRightRibbon = 126,
VerticalScroll = 127,
HorizontalScroll = 128,
Wave = 129,
DoubleWave = 130,
Plus = 131,
FlowChartProcess = 132,
FlowChartDecision = 133,
FlowChartInputOutput = 134,
FlowChartPredefinedProcess = 135,
FlowChartInternalStorage = 136,
FlowChartDocument = 137,
FlowChartMultiDocument = 138,
FlowChartTerminator = 139,
FlowChartPreparation = 140,
FlowChartManualInput = 141,
FlowChartManualOperation = 142,
FlowChartConnector = 143,
FlowChartPunchedCard = 144,
FlowChartPunchedTape = 145,
FlowChartSummingJunction = 146,
FlowChartOr = 147,
FlowChartCollate = 148,
FlowChartSort = 149,
FlowChartExtract = 150,
FlowChartMerge = 151,
FlowChartOfflineStorage = 152,
FlowChartOnlineStorage = 153,
FlowChartMagneticTape = 154,
FlowChartMagneticDisk = 155,
FlowChartMagneticDrum = 156,
FlowChartDisplay = 157,
FlowChartDelay = 158,
FlowChartAlternateProcess = 159,
FlowChartOffpageConnector = 160,
ActionButtonBlank = 161,
ActionButtonHome = 162,
ActionButtonHelp = 163,
ActionButtonInformation = 164,
ActionButtonForwardNext = 165,
ActionButtonBackPrevious = 166,
ActionButtonEnd = 167,
ActionButtonBeginning = 168,
ActionButtonReturn = 169,
ActionButtonDocument = 170,
ActionButtonSound = 171,
ActionButtonMovie = 172,
Gear6 = 173,
Gear9 = 174,
Funnel = 175,
MathPlus = 176,
MathMinus = 177,
MathMultiply = 178,
MathDivide = 179,
MathEqual = 180,
MathNotEqual = 181,
CornerTabs = 182,
SquareTabs = 183,
PlaqueTabs = 184,
ChartX = 185,
ChartStar = 186,
ChartPlus = 187,
}
}
| |
// 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.
// NOTE: this file was generated from 'xd.xml'
using System.Diagnostics.Contracts;
namespace System.ServiceModel
{
internal class ServiceModelStringsVersion1 : ServiceModelStrings
{
public const string String0 = "mustUnderstand";
public const string String1 = "Envelope";
public const string String2 = "http://www.w3.org/2003/05/soap-envelope";
public const string String3 = "http://www.w3.org/2005/08/addressing";
public const string String4 = "Header";
public const string String5 = "Action";
public const string String6 = "To";
public const string String7 = "Body";
public const string String8 = "Algorithm";
public const string String9 = "RelatesTo";
public const string String10 = "http://www.w3.org/2005/08/addressing/anonymous";
public const string String11 = "URI";
public const string String12 = "Reference";
public const string String13 = "MessageID";
public const string String14 = "Id";
public const string String15 = "Identifier";
public const string String16 = "http://schemas.xmlsoap.org/ws/2005/02/rm";
public const string String17 = "Transforms";
public const string String18 = "Transform";
public const string String19 = "DigestMethod";
public const string String20 = "DigestValue";
public const string String21 = "Address";
public const string String22 = "ReplyTo";
public const string String23 = "SequenceAcknowledgement";
public const string String24 = "AcknowledgementRange";
public const string String25 = "Upper";
public const string String26 = "Lower";
public const string String27 = "BufferRemaining";
public const string String28 = "http://schemas.microsoft.com/ws/2006/05/rm";
public const string String29 = "http://schemas.xmlsoap.org/ws/2005/02/rm/SequenceAcknowledgement";
public const string String30 = "SecurityTokenReference";
public const string String31 = "Sequence";
public const string String32 = "MessageNumber";
public const string String33 = "http://www.w3.org/2000/09/xmldsig#";
public const string String34 = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
public const string String35 = "KeyInfo";
public const string String36 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
public const string String37 = "http://www.w3.org/2001/04/xmlenc#";
public const string String38 = "http://schemas.xmlsoap.org/ws/2005/02/sc";
public const string String39 = "DerivedKeyToken";
public const string String40 = "Nonce";
public const string String41 = "Signature";
public const string String42 = "SignedInfo";
public const string String43 = "CanonicalizationMethod";
public const string String44 = "SignatureMethod";
public const string String45 = "SignatureValue";
public const string String46 = "DataReference";
public const string String47 = "EncryptedData";
public const string String48 = "EncryptionMethod";
public const string String49 = "CipherData";
public const string String50 = "CipherValue";
public const string String51 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
public const string String52 = "Security";
public const string String53 = "Timestamp";
public const string String54 = "Created";
public const string String55 = "Expires";
public const string String56 = "Length";
public const string String57 = "ReferenceList";
public const string String58 = "ValueType";
public const string String59 = "Type";
public const string String60 = "EncryptedHeader";
public const string String61 = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd";
public const string String62 = "RequestSecurityTokenResponseCollection";
public const string String63 = "http://schemas.xmlsoap.org/ws/2005/02/trust";
public const string String64 = "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret";
public const string String65 = "http://schemas.microsoft.com/ws/2006/02/transactions";
public const string String66 = "s";
public const string String67 = "Fault";
public const string String68 = "MustUnderstand";
public const string String69 = "role";
public const string String70 = "relay";
public const string String71 = "Code";
public const string String72 = "Reason";
public const string String73 = "Text";
public const string String74 = "Node";
public const string String75 = "Role";
public const string String76 = "Detail";
public const string String77 = "Value";
public const string String78 = "Subcode";
public const string String79 = "NotUnderstood";
public const string String80 = "qname";
public const string String81 = "";
public const string String82 = "From";
public const string String83 = "FaultTo";
public const string String84 = "EndpointReference";
public const string String85 = "PortType";
public const string String86 = "ServiceName";
public const string String87 = "PortName";
public const string String88 = "ReferenceProperties";
public const string String89 = "RelationshipType";
public const string String90 = "Reply";
public const string String91 = "a";
public const string String92 = "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity";
public const string String93 = "Identity";
public const string String94 = "Spn";
public const string String95 = "Upn";
public const string String96 = "Rsa";
public const string String97 = "Dns";
public const string String98 = "X509v3Certificate";
public const string String99 = "http://www.w3.org/2005/08/addressing/fault";
public const string String100 = "ReferenceParameters";
public const string String101 = "IsReferenceParameter";
public const string String102 = "http://www.w3.org/2005/08/addressing/reply";
public const string String103 = "http://www.w3.org/2005/08/addressing/none";
public const string String104 = "Metadata";
public const string String105 = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
public const string String106 = "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous";
public const string String107 = "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault";
public const string String108 = "http://schemas.xmlsoap.org/ws/2004/06/addressingex";
public const string String109 = "RedirectTo";
public const string String110 = "Via";
public const string String111 = "http://www.w3.org/2001/10/xml-exc-c14n#";
public const string String112 = "PrefixList";
public const string String113 = "InclusiveNamespaces";
public const string String114 = "ec";
public const string String115 = "SecurityContextToken";
public const string String116 = "Generation";
public const string String117 = "Label";
public const string String118 = "Offset";
public const string String119 = "Properties";
public const string String120 = "Cookie";
public const string String121 = "wsc";
public const string String122 = "http://schemas.xmlsoap.org/ws/2004/04/sc";
public const string String123 = "http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk";
public const string String124 = "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct";
public const string String125 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/SCT";
public const string String126 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/SCT";
public const string String127 = "RenewNeeded";
public const string String128 = "BadContextToken";
public const string String129 = "c";
public const string String130 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk";
public const string String131 = "http://schemas.xmlsoap.org/ws/2005/02/sc/sct";
public const string String132 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT";
public const string String133 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT";
public const string String134 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew";
public const string String135 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew";
public const string String136 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel";
public const string String137 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel";
public const string String138 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
public const string String139 = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
public const string String140 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
public const string String141 = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
public const string String142 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
public const string String143 = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
public const string String144 = "http://www.w3.org/2001/04/xmlenc#des-cbc";
public const string String145 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
public const string String146 = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
public const string String147 = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
public const string String148 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
public const string String149 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1";
public const string String150 = "http://www.w3.org/2001/04/xmlenc#ripemd160";
public const string String151 = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
public const string String152 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
public const string String153 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
public const string String154 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
public const string String155 = "http://www.w3.org/2000/09/xmldsig#sha1";
public const string String156 = "http://www.w3.org/2001/04/xmlenc#sha256";
public const string String157 = "http://www.w3.org/2001/04/xmlenc#sha512";
public const string String158 = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public const string String159 = "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
public const string String160 = "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap";
public const string String161 = "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap";
public const string String162 = "http://schemas.microsoft.com/ws/2006/05/security";
public const string String163 = "dnse";
public const string String164 = "o";
public const string String165 = "Password";
public const string String166 = "PasswordText";
public const string String167 = "Username";
public const string String168 = "UsernameToken";
public const string String169 = "BinarySecurityToken";
public const string String170 = "EncodingType";
public const string String171 = "KeyIdentifier";
public const string String172 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary";
public const string String173 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#HexBinary";
public const string String174 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text";
public const string String175 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier";
public const string String176 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ";
public const string String177 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ1510";
public const string String178 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID";
public const string String179 = "Assertion";
public const string String180 = "urn:oasis:names:tc:SAML:1.0:assertion";
public const string String181 = "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license";
public const string String182 = "FailedAuthentication";
public const string String183 = "InvalidSecurityToken";
public const string String184 = "InvalidSecurity";
public const string String185 = "k";
public const string String186 = "SignatureConfirmation";
public const string String187 = "TokenType";
public const string String188 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1";
public const string String189 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey";
public const string String190 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1";
public const string String191 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
public const string String192 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
public const string String193 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID";
public const string String194 = "AUTH-HASH";
public const string String195 = "RequestSecurityTokenResponse";
public const string String196 = "KeySize";
public const string String197 = "RequestedTokenReference";
public const string String198 = "AppliesTo";
public const string String199 = "Authenticator";
public const string String200 = "CombinedHash";
public const string String201 = "BinaryExchange";
public const string String202 = "Lifetime";
public const string String203 = "RequestedSecurityToken";
public const string String204 = "Entropy";
public const string String205 = "RequestedProofToken";
public const string String206 = "ComputedKey";
public const string String207 = "RequestSecurityToken";
public const string String208 = "RequestType";
public const string String209 = "Context";
public const string String210 = "BinarySecret";
public const string String211 = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego";
public const string String212 = " http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego";
public const string String213 = "wst";
public const string String214 = "http://schemas.xmlsoap.org/ws/2004/04/trust";
public const string String215 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/Issue";
public const string String216 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/Issue";
public const string String217 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue";
public const string String218 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/CK/PSHA1";
public const string String219 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/SymmetricKey";
public const string String220 = "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Nonce";
public const string String221 = "KeyType";
public const string String222 = "http://schemas.xmlsoap.org/ws/2004/04/trust/SymmetricKey";
public const string String223 = "http://schemas.xmlsoap.org/ws/2004/04/trust/PublicKey";
public const string String224 = "Claims";
public const string String225 = "InvalidRequest";
public const string String226 = "RequestFailed";
public const string String227 = "SignWith";
public const string String228 = "EncryptWith";
public const string String229 = "EncryptionAlgorithm";
public const string String230 = "CanonicalizationAlgorithm";
public const string String231 = "ComputedKeyAlgorithm";
public const string String232 = "UseKey";
public const string String233 = "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego";
public const string String234 = "http://schemas.microsoft.com/net/2004/07/secext/TLSNego";
public const string String235 = "t";
public const string String236 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
public const string String237 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue";
public const string String238 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
public const string String239 = "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey";
public const string String240 = "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1";
public const string String241 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce";
public const string String242 = "RenewTarget";
public const string String243 = "CancelTarget";
public const string String244 = "RequestedTokenCancelled";
public const string String245 = "RequestedAttachedReference";
public const string String246 = "RequestedUnattachedReference";
public const string String247 = "IssuedTokens";
public const string String248 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew";
public const string String249 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel";
public const string String250 = "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey";
public const string String251 = "Access";
public const string String252 = "AccessDecision";
public const string String253 = "Advice";
public const string String254 = "AssertionID";
public const string String255 = "AssertionIDReference";
public const string String256 = "Attribute";
public const string String257 = "AttributeName";
public const string String258 = "AttributeNamespace";
public const string String259 = "AttributeStatement";
public const string String260 = "AttributeValue";
public const string String261 = "Audience";
public const string String262 = "AudienceRestrictionCondition";
public const string String263 = "AuthenticationInstant";
public const string String264 = "AuthenticationMethod";
public const string String265 = "AuthenticationStatement";
public const string String266 = "AuthorityBinding";
public const string String267 = "AuthorityKind";
public const string String268 = "AuthorizationDecisionStatement";
public const string String269 = "Binding";
public const string String270 = "Condition";
public const string String271 = "Conditions";
public const string String272 = "Decision";
public const string String273 = "DoNotCacheCondition";
public const string String274 = "Evidence";
public const string String275 = "IssueInstant";
public const string String276 = "Issuer";
public const string String277 = "Location";
public const string String278 = "MajorVersion";
public const string String279 = "MinorVersion";
public const string String280 = "NameIdentifier";
public const string String281 = "Format";
public const string String282 = "NameQualifier";
public const string String283 = "Namespace";
public const string String284 = "NotBefore";
public const string String285 = "NotOnOrAfter";
public const string String286 = "saml";
public const string String287 = "Statement";
public const string String288 = "Subject";
public const string String289 = "SubjectConfirmation";
public const string String290 = "SubjectConfirmationData";
public const string String291 = "ConfirmationMethod";
public const string String292 = "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key";
public const string String293 = "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches";
public const string String294 = "SubjectLocality";
public const string String295 = "DNSAddress";
public const string String296 = "IPAddress";
public const string String297 = "SubjectStatement";
public const string String298 = "urn:oasis:names:tc:SAML:1.0:am:unspecified";
public const string String299 = "xmlns";
public const string String300 = "Resource";
public const string String301 = "UserName";
public const string String302 = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName";
public const string String303 = "EmailName";
public const string String304 = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
public const string String305 = "u";
public const string String306 = "ChannelInstance";
public const string String307 = "http://schemas.microsoft.com/ws/2005/02/duplex";
public const string String308 = "Encoding";
public const string String309 = "MimeType";
public const string String310 = "CarriedKeyName";
public const string String311 = "Recipient";
public const string String312 = "EncryptedKey";
public const string String313 = "KeyReference";
public const string String314 = "e";
public const string String315 = "http://www.w3.org/2001/04/xmlenc#Element";
public const string String316 = "http://www.w3.org/2001/04/xmlenc#Content";
public const string String317 = "KeyName";
public const string String318 = "MgmtData";
public const string String319 = "KeyValue";
public const string String320 = "RSAKeyValue";
public const string String321 = "Modulus";
public const string String322 = "Exponent";
public const string String323 = "X509Data";
public const string String324 = "X509IssuerSerial";
public const string String325 = "X509IssuerName";
public const string String326 = "X509SerialNumber";
public const string String327 = "X509Certificate";
public const string String328 = "AckRequested";
public const string String329 = "http://schemas.xmlsoap.org/ws/2005/02/rm/AckRequested";
public const string String330 = "AcksTo";
public const string String331 = "Accept";
public const string String332 = "CreateSequence";
public const string String333 = "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence";
public const string String334 = "CreateSequenceRefused";
public const string String335 = "CreateSequenceResponse";
public const string String336 = "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequenceResponse";
public const string String337 = "FaultCode";
public const string String338 = "InvalidAcknowledgement";
public const string String339 = "LastMessage";
public const string String340 = "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage";
public const string String341 = "LastMessageNumberExceeded";
public const string String342 = "MessageNumberRollover";
public const string String343 = "Nack";
public const string String344 = "netrm";
public const string String345 = "Offer";
public const string String346 = "r";
public const string String347 = "SequenceFault";
public const string String348 = "SequenceTerminated";
public const string String349 = "TerminateSequence";
public const string String350 = "http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence";
public const string String351 = "UnknownSequence";
public const string String352 = "http://schemas.microsoft.com/ws/2006/02/tx/oletx";
public const string String353 = "oletx";
public const string String354 = "OleTxTransaction";
public const string String355 = "PropagationToken";
public const string String356 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor";
public const string String357 = "wscoor";
public const string String358 = "CreateCoordinationContext";
public const string String359 = "CreateCoordinationContextResponse";
public const string String360 = "CoordinationContext";
public const string String361 = "CurrentContext";
public const string String362 = "CoordinationType";
public const string String363 = "RegistrationService";
public const string String364 = "Register";
public const string String365 = "RegisterResponse";
public const string String366 = "ProtocolIdentifier";
public const string String367 = "CoordinatorProtocolService";
public const string String368 = "ParticipantProtocolService";
public const string String369 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContext";
public const string String370 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContextResponse";
public const string String371 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor/Register";
public const string String372 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor/RegisterResponse";
public const string String373 = "http://schemas.xmlsoap.org/ws/2004/10/wscoor/fault";
public const string String374 = "ActivationCoordinatorPortType";
public const string String375 = "RegistrationCoordinatorPortType";
public const string String376 = "InvalidState";
public const string String377 = "InvalidProtocol";
public const string String378 = "InvalidParameters";
public const string String379 = "NoActivity";
public const string String380 = "ContextRefused";
public const string String381 = "AlreadyRegistered";
public const string String382 = "http://schemas.xmlsoap.org/ws/2004/10/wsat";
public const string String383 = "wsat";
public const string String384 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Completion";
public const string String385 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Durable2PC";
public const string String386 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Volatile2PC";
public const string String387 = "Prepare";
public const string String388 = "Prepared";
public const string String389 = "ReadOnly";
public const string String390 = "Commit";
public const string String391 = "Rollback";
public const string String392 = "Committed";
public const string String393 = "Aborted";
public const string String394 = "Replay";
public const string String395 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Commit";
public const string String396 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Rollback";
public const string String397 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Committed";
public const string String398 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Aborted";
public const string String399 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepare";
public const string String400 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepared";
public const string String401 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/ReadOnly";
public const string String402 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/Replay";
public const string String403 = "http://schemas.xmlsoap.org/ws/2004/10/wsat/fault";
public const string String404 = "CompletionCoordinatorPortType";
public const string String405 = "CompletionParticipantPortType";
public const string String406 = "CoordinatorPortType";
public const string String407 = "ParticipantPortType";
public const string String408 = "InconsistentInternalState";
public const string String409 = "mstx";
public const string String410 = "Enlistment";
public const string String411 = "protocol";
public const string String412 = "LocalTransactionId";
public const string String413 = "IsolationLevel";
public const string String414 = "IsolationFlags";
public const string String415 = "Description";
public const string String416 = "Loopback";
public const string String417 = "RegisterInfo";
public const string String418 = "ContextId";
public const string String419 = "TokenId";
public const string String420 = "AccessDenied";
public const string String421 = "InvalidPolicy";
public const string String422 = "CoordinatorRegistrationFailed";
public const string String423 = "TooManyEnlistments";
public const string String424 = "Disabled";
public const string String425 = "ActivityId";
public const string String426 = "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics";
public const string String427 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1";
public const string String428 = "http://schemas.xmlsoap.org/ws/2002/12/policy";
public const string String429 = "FloodMessage";
public const string String430 = "LinkUtility";
public const string String431 = "Hops";
public const string String432 = "http://schemas.microsoft.com/net/2006/05/peer/HopCount";
public const string String433 = "PeerVia";
public const string String434 = "http://schemas.microsoft.com/net/2006/05/peer";
public const string String435 = "PeerFlooder";
public const string String436 = "PeerTo";
public const string String437 = "http://schemas.microsoft.com/ws/2005/05/routing";
public const string String438 = "PacketRoutable";
public const string String439 = "http://schemas.microsoft.com/ws/2005/05/addressing/none";
public const string String440 = "http://schemas.microsoft.com/ws/2005/05/envelope/none";
public const string String441 = "http://www.w3.org/2001/XMLSchema-instance";
public const string String442 = "http://www.w3.org/2001/XMLSchema";
public const string String443 = "nil";
public const string String444 = "type";
public const string String445 = "char";
public const string String446 = "boolean";
public const string String447 = "byte";
public const string String448 = "unsignedByte";
public const string String449 = "short";
public const string String450 = "unsignedShort";
public const string String451 = "int";
public const string String452 = "unsignedInt";
public const string String453 = "long";
public const string String454 = "unsignedLong";
public const string String455 = "float";
public const string String456 = "double";
public const string String457 = "decimal";
public const string String458 = "dateTime";
public const string String459 = "string";
public const string String460 = "base64Binary";
public const string String461 = "anyType";
public const string String462 = "duration";
public const string String463 = "guid";
public const string String464 = "anyURI";
public const string String465 = "QName";
public const string String466 = "time";
public const string String467 = "date";
public const string String468 = "hexBinary";
public const string String469 = "gYearMonth";
public const string String470 = "gYear";
public const string String471 = "gMonthDay";
public const string String472 = "gDay";
public const string String473 = "gMonth";
public const string String474 = "integer";
public const string String475 = "positiveInteger";
public const string String476 = "negativeInteger";
public const string String477 = "nonPositiveInteger";
public const string String478 = "nonNegativeInteger";
public const string String479 = "normalizedString";
public const string String480 = "ConnectionLimitReached";
public const string String481 = "http://schemas.xmlsoap.org/soap/envelope/";
public const string String482 = "actor";
public const string String483 = "faultcode";
public const string String484 = "faultstring";
public const string String485 = "faultactor";
public const string String486 = "detail";
public override int Count { get { return 487; } }
public override string this[int index]
{
get
{
Contract.Assert(index >= 0 && index < this.Count, "check index");
switch (index)
{
case 0: return String0;
case 1: return String1;
case 2: return String2;
case 3: return String3;
case 4: return String4;
case 5: return String5;
case 6: return String6;
case 7: return String7;
case 8: return String8;
case 9: return String9;
case 10: return String10;
case 11: return String11;
case 12: return String12;
case 13: return String13;
case 14: return String14;
case 15: return String15;
case 16: return String16;
case 17: return String17;
case 18: return String18;
case 19: return String19;
case 20: return String20;
case 21: return String21;
case 22: return String22;
case 23: return String23;
case 24: return String24;
case 25: return String25;
case 26: return String26;
case 27: return String27;
case 28: return String28;
case 29: return String29;
case 30: return String30;
case 31: return String31;
case 32: return String32;
case 33: return String33;
case 34: return String34;
case 35: return String35;
case 36: return String36;
case 37: return String37;
case 38: return String38;
case 39: return String39;
case 40: return String40;
case 41: return String41;
case 42: return String42;
case 43: return String43;
case 44: return String44;
case 45: return String45;
case 46: return String46;
case 47: return String47;
case 48: return String48;
case 49: return String49;
case 50: return String50;
case 51: return String51;
case 52: return String52;
case 53: return String53;
case 54: return String54;
case 55: return String55;
case 56: return String56;
case 57: return String57;
case 58: return String58;
case 59: return String59;
case 60: return String60;
case 61: return String61;
case 62: return String62;
case 63: return String63;
case 64: return String64;
case 65: return String65;
case 66: return String66;
case 67: return String67;
case 68: return String68;
case 69: return String69;
case 70: return String70;
case 71: return String71;
case 72: return String72;
case 73: return String73;
case 74: return String74;
case 75: return String75;
case 76: return String76;
case 77: return String77;
case 78: return String78;
case 79: return String79;
case 80: return String80;
case 81: return String81;
case 82: return String82;
case 83: return String83;
case 84: return String84;
case 85: return String85;
case 86: return String86;
case 87: return String87;
case 88: return String88;
case 89: return String89;
case 90: return String90;
case 91: return String91;
case 92: return String92;
case 93: return String93;
case 94: return String94;
case 95: return String95;
case 96: return String96;
case 97: return String97;
case 98: return String98;
case 99: return String99;
case 100: return String100;
case 101: return String101;
case 102: return String102;
case 103: return String103;
case 104: return String104;
case 105: return String105;
case 106: return String106;
case 107: return String107;
case 108: return String108;
case 109: return String109;
case 110: return String110;
case 111: return String111;
case 112: return String112;
case 113: return String113;
case 114: return String114;
case 115: return String115;
case 116: return String116;
case 117: return String117;
case 118: return String118;
case 119: return String119;
case 120: return String120;
case 121: return String121;
case 122: return String122;
case 123: return String123;
case 124: return String124;
case 125: return String125;
case 126: return String126;
case 127: return String127;
case 128: return String128;
case 129: return String129;
case 130: return String130;
case 131: return String131;
case 132: return String132;
case 133: return String133;
case 134: return String134;
case 135: return String135;
case 136: return String136;
case 137: return String137;
case 138: return String138;
case 139: return String139;
case 140: return String140;
case 141: return String141;
case 142: return String142;
case 143: return String143;
case 144: return String144;
case 145: return String145;
case 146: return String146;
case 147: return String147;
case 148: return String148;
case 149: return String149;
case 150: return String150;
case 151: return String151;
case 152: return String152;
case 153: return String153;
case 154: return String154;
case 155: return String155;
case 156: return String156;
case 157: return String157;
case 158: return String158;
case 159: return String159;
case 160: return String160;
case 161: return String161;
case 162: return String162;
case 163: return String163;
case 164: return String164;
case 165: return String165;
case 166: return String166;
case 167: return String167;
case 168: return String168;
case 169: return String169;
case 170: return String170;
case 171: return String171;
case 172: return String172;
case 173: return String173;
case 174: return String174;
case 175: return String175;
case 176: return String176;
case 177: return String177;
case 178: return String178;
case 179: return String179;
case 180: return String180;
case 181: return String181;
case 182: return String182;
case 183: return String183;
case 184: return String184;
case 185: return String185;
case 186: return String186;
case 187: return String187;
case 188: return String188;
case 189: return String189;
case 190: return String190;
case 191: return String191;
case 192: return String192;
case 193: return String193;
case 194: return String194;
case 195: return String195;
case 196: return String196;
case 197: return String197;
case 198: return String198;
case 199: return String199;
case 200: return String200;
case 201: return String201;
case 202: return String202;
case 203: return String203;
case 204: return String204;
case 205: return String205;
case 206: return String206;
case 207: return String207;
case 208: return String208;
case 209: return String209;
case 210: return String210;
case 211: return String211;
case 212: return String212;
case 213: return String213;
case 214: return String214;
case 215: return String215;
case 216: return String216;
case 217: return String217;
case 218: return String218;
case 219: return String219;
case 220: return String220;
case 221: return String221;
case 222: return String222;
case 223: return String223;
case 224: return String224;
case 225: return String225;
case 226: return String226;
case 227: return String227;
case 228: return String228;
case 229: return String229;
case 230: return String230;
case 231: return String231;
case 232: return String232;
case 233: return String233;
case 234: return String234;
case 235: return String235;
case 236: return String236;
case 237: return String237;
case 238: return String238;
case 239: return String239;
case 240: return String240;
case 241: return String241;
case 242: return String242;
case 243: return String243;
case 244: return String244;
case 245: return String245;
case 246: return String246;
case 247: return String247;
case 248: return String248;
case 249: return String249;
case 250: return String250;
case 251: return String251;
case 252: return String252;
case 253: return String253;
case 254: return String254;
case 255: return String255;
case 256: return String256;
case 257: return String257;
case 258: return String258;
case 259: return String259;
case 260: return String260;
case 261: return String261;
case 262: return String262;
case 263: return String263;
case 264: return String264;
case 265: return String265;
case 266: return String266;
case 267: return String267;
case 268: return String268;
case 269: return String269;
case 270: return String270;
case 271: return String271;
case 272: return String272;
case 273: return String273;
case 274: return String274;
case 275: return String275;
case 276: return String276;
case 277: return String277;
case 278: return String278;
case 279: return String279;
case 280: return String280;
case 281: return String281;
case 282: return String282;
case 283: return String283;
case 284: return String284;
case 285: return String285;
case 286: return String286;
case 287: return String287;
case 288: return String288;
case 289: return String289;
case 290: return String290;
case 291: return String291;
case 292: return String292;
case 293: return String293;
case 294: return String294;
case 295: return String295;
case 296: return String296;
case 297: return String297;
case 298: return String298;
case 299: return String299;
case 300: return String300;
case 301: return String301;
case 302: return String302;
case 303: return String303;
case 304: return String304;
case 305: return String305;
case 306: return String306;
case 307: return String307;
case 308: return String308;
case 309: return String309;
case 310: return String310;
case 311: return String311;
case 312: return String312;
case 313: return String313;
case 314: return String314;
case 315: return String315;
case 316: return String316;
case 317: return String317;
case 318: return String318;
case 319: return String319;
case 320: return String320;
case 321: return String321;
case 322: return String322;
case 323: return String323;
case 324: return String324;
case 325: return String325;
case 326: return String326;
case 327: return String327;
case 328: return String328;
case 329: return String329;
case 330: return String330;
case 331: return String331;
case 332: return String332;
case 333: return String333;
case 334: return String334;
case 335: return String335;
case 336: return String336;
case 337: return String337;
case 338: return String338;
case 339: return String339;
case 340: return String340;
case 341: return String341;
case 342: return String342;
case 343: return String343;
case 344: return String344;
case 345: return String345;
case 346: return String346;
case 347: return String347;
case 348: return String348;
case 349: return String349;
case 350: return String350;
case 351: return String351;
case 352: return String352;
case 353: return String353;
case 354: return String354;
case 355: return String355;
case 356: return String356;
case 357: return String357;
case 358: return String358;
case 359: return String359;
case 360: return String360;
case 361: return String361;
case 362: return String362;
case 363: return String363;
case 364: return String364;
case 365: return String365;
case 366: return String366;
case 367: return String367;
case 368: return String368;
case 369: return String369;
case 370: return String370;
case 371: return String371;
case 372: return String372;
case 373: return String373;
case 374: return String374;
case 375: return String375;
case 376: return String376;
case 377: return String377;
case 378: return String378;
case 379: return String379;
case 380: return String380;
case 381: return String381;
case 382: return String382;
case 383: return String383;
case 384: return String384;
case 385: return String385;
case 386: return String386;
case 387: return String387;
case 388: return String388;
case 389: return String389;
case 390: return String390;
case 391: return String391;
case 392: return String392;
case 393: return String393;
case 394: return String394;
case 395: return String395;
case 396: return String396;
case 397: return String397;
case 398: return String398;
case 399: return String399;
case 400: return String400;
case 401: return String401;
case 402: return String402;
case 403: return String403;
case 404: return String404;
case 405: return String405;
case 406: return String406;
case 407: return String407;
case 408: return String408;
case 409: return String409;
case 410: return String410;
case 411: return String411;
case 412: return String412;
case 413: return String413;
case 414: return String414;
case 415: return String415;
case 416: return String416;
case 417: return String417;
case 418: return String418;
case 419: return String419;
case 420: return String420;
case 421: return String421;
case 422: return String422;
case 423: return String423;
case 424: return String424;
case 425: return String425;
case 426: return String426;
case 427: return String427;
case 428: return String428;
case 429: return String429;
case 430: return String430;
case 431: return String431;
case 432: return String432;
case 433: return String433;
case 434: return String434;
case 435: return String435;
case 436: return String436;
case 437: return String437;
case 438: return String438;
case 439: return String439;
case 440: return String440;
case 441: return String441;
case 442: return String442;
case 443: return String443;
case 444: return String444;
case 445: return String445;
case 446: return String446;
case 447: return String447;
case 448: return String448;
case 449: return String449;
case 450: return String450;
case 451: return String451;
case 452: return String452;
case 453: return String453;
case 454: return String454;
case 455: return String455;
case 456: return String456;
case 457: return String457;
case 458: return String458;
case 459: return String459;
case 460: return String460;
case 461: return String461;
case 462: return String462;
case 463: return String463;
case 464: return String464;
case 465: return String465;
case 466: return String466;
case 467: return String467;
case 468: return String468;
case 469: return String469;
case 470: return String470;
case 471: return String471;
case 472: return String472;
case 473: return String473;
case 474: return String474;
case 475: return String475;
case 476: return String476;
case 477: return String477;
case 478: return String478;
case 479: return String479;
case 480: return String480;
case 481: return String481;
case 482: return String482;
case 483: return String483;
case 484: return String484;
case 485: return String485;
case 486: return String486;
default: return null;
}
}
}
}
}
| |
// BankRichPersonAccount.cs (c) Kari Laitinen
// http://www.naturalprogramming.com
// 2004-11-17 File created.
// 2004-11-17 Last modification.
// A solution to Exercise 12-8.
using System ;
class BankAccount
{
protected string account_owner ;
protected long account_number ;
protected double account_balance ;
public BankAccount( string given_account_owner,
long given_account_number,
double initial_balance )
{
account_owner = given_account_owner ;
account_number = given_account_number ;
account_balance = initial_balance ;
}
public void show_account_data()
{
Console.Write( "\n\nB A N K A C C O U N T D A T A : "
+ "\n Account owner : " + account_owner
+ "\n Account number: " + account_number
+ "\n Current balance: " + account_balance ) ;
}
public virtual void deposit_money( double amount_to_deposit )
{
Console.Write( "\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
Console.Write( "\n Amount deposited: " + amount_to_deposit
+ "\n Old account balance: " + account_balance ) ;
account_balance = account_balance + amount_to_deposit ;
Console.Write( " New balance: " + account_balance ) ;
}
public virtual void withdraw_money( double amount_to_withdraw )
{
Console.Write( "\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
if ( account_balance < amount_to_withdraw )
{
Console.Write("\n -- Transaction not completed: "
+ "Not enough money to withdraw " + amount_to_withdraw ) ;
}
else
{
Console.Write("\n Amount withdrawn: " + amount_to_withdraw
+ "\n Old account balance: " + account_balance ) ;
account_balance = account_balance - amount_to_withdraw ;
Console.Write(" New balance: " + account_balance ) ;
}
}
public void transfer_money_to( BankAccount receiving_account,
double amount_to_transfer )
{
Console.Write( "\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
if ( account_balance >= amount_to_transfer )
{
receiving_account.account_balance =
receiving_account.account_balance + amount_to_transfer ;
Console.Write("\n " + amount_to_transfer + " was transferred to "
+ receiving_account.account_owner + " (Account no. "
+ receiving_account.account_number + ")."
+ "\n Balance before transfer: " + account_balance ) ;
account_balance = account_balance - amount_to_transfer ;
Console.Write(" New balance: " + account_balance ) ;
}
else
{
Console.Write( "\n -- Not enough money for transfer." ) ;
}
}
}
class AccountWithCredit : BankAccount
{
protected double credit_limit ;
public AccountWithCredit( string given_account_owner,
long given_account_number,
double initial_balance,
double given_credit_limit )
: base( given_account_owner,
given_account_number,
initial_balance )
{
credit_limit = given_credit_limit ;
}
public override void withdraw_money( double amount_to_withdraw )
{
Console.Write( "\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
if ( account_balance + credit_limit < amount_to_withdraw )
{
Console.Write(
"\n -- Transaction not completed: "
+ "Not enough credit to withdraw "+ amount_to_withdraw ) ;
}
else
{
Console.Write(
"\n Amount withdrawn: " + amount_to_withdraw
+ "\n Old account balance: " + account_balance ) ;
account_balance = account_balance - amount_to_withdraw ;
Console.Write( " New balance: " + account_balance ) ;
}
}
}
class RestrictedAccount : BankAccount
{
protected double maximum_amount_to_withdraw ;
public RestrictedAccount( string given_account_owner,
long given_account_number,
double initial_balance,
double given_withdrawal_limit )
: base( given_account_owner,
given_account_number,
initial_balance )
{
maximum_amount_to_withdraw = given_withdrawal_limit ;
}
public override void withdraw_money( double amount_to_withdraw )
{
if ( amount_to_withdraw > maximum_amount_to_withdraw )
{
Console.Write(
"\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
Console.Write(
"\n -- Transaction not completed: Cannot withdraw "
+ amount_to_withdraw + "\n -- Withdrawal limit is "
+ maximum_amount_to_withdraw + "." ) ;
}
else
{
base.withdraw_money( amount_to_withdraw ) ;
}
}
}
class RichPersonAccount : BankAccount
{
protected double minimum_amount_to_deposit ;
public RichPersonAccount( string given_account_owner,
long given_account_number,
double initial_balance,
double given_deposit_limit )
: base( given_account_owner,
given_account_number,
initial_balance )
{
minimum_amount_to_deposit = given_deposit_limit ;
}
public override void deposit_money( double amount_to_deposit )
{
if ( amount_to_deposit < minimum_amount_to_deposit )
{
Console.Write(
"\n\nTRANSACTION FOR ACCOUNT OF " + account_owner
+ " (Account number " + account_number + ")" ) ;
Console.Write(
"\n -- Transaction not completed: Cannot deposit "
+ amount_to_deposit + "\n -- Minimum deposit amount is "
+ minimum_amount_to_deposit + "." ) ;
}
else
{
base.deposit_money( amount_to_deposit ) ;
}
}
}
class BankRichPersonAccount
{
static void Main()
{
RichPersonAccount rockefeller_account = new
RichPersonAccount( "John D.", 55555, 900000.00, 9000.00 ) ;
rockefeller_account.deposit_money( 8000.00 ) ;
RichPersonAccount getty_account = new
RichPersonAccount( "Paul Getty", 66666, 900000.00, 7000.00 ) ;
getty_account.deposit_money( 8000.00 ) ;
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// 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
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System.Web;
using CultureInfo = System.Globalization.CultureInfo;
using Encoding = System.Text.Encoding;
using System.Collections.Generic;
#endregion
/// <summary>
/// HTTP handler factory that dispenses handlers for rendering views and
/// resources needed to display the error log.
/// </summary>
public class ErrorLogPageFactory : IHttpHandlerFactory
{
private static readonly object _authorizationHandlersKey = new object();
private static readonly IRequestAuthorizationHandler[] _zeroAuthorizationHandlers = new IRequestAuthorizationHandler[0];
/// <summary>
/// Returns an object that implements the <see cref="IHttpHandler"/>
/// interface and which is responsible for serving the request.
/// </summary>
/// <returns>
/// A new <see cref="IHttpHandler"/> object that processes the request.
/// </returns>
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
//
// The request resource is determined by the looking up the
// value of the PATH_INFO server variable.
//
string resource = context.Request.PathInfo.Length == 0 ? string.Empty :
context.Request.PathInfo.Substring(1).ToLower(CultureInfo.InvariantCulture);
IHttpHandler handler = FindHandler(resource);
if (handler == null)
throw new HttpException(404, "Resource not found.");
//
// Check if authorized then grant or deny request.
//
int authorized = IsAuthorized(context);
if (authorized == 0
|| (authorized < 0 // Compatibility case...
&& !context.Request.IsLocal
&& !SecurityConfiguration.Default.AllowRemoteAccess))
{
(new ManifestResourceHandler("RemoteAccessError.htm", "text/html")).ProcessRequest(context);
HttpResponse response = context.Response;
response.Status = "403 Forbidden";
response.End();
//
// HttpResponse.End docs say that it throws
// ThreadAbortException and so should never end up here but
// that's not been the observation in the debugger. So as a
// precautionary measure, bail out anyway.
//
return null;
}
return handler;
}
private static IHttpHandler FindHandler(string name)
{
Debug.Assert(name != null);
switch (name)
{
case "detail":
return new ErrorDetailPage();
case "html":
return new ErrorHtmlPage();
case "xml":
return new ErrorXmlHandler();
case "json":
return new ErrorJsonHandler();
case "rss":
return new ErrorRssHandler();
case "digestrss":
return new ErrorDigestRssHandler();
case "download":
return new ErrorLogDownloadHandler();
case "stylesheet":
return new ManifestResourceHandler("ErrorLog.css",
"text/css", Encoding.GetEncoding("Windows-1252"));
case "test":
throw new TestException();
case "about":
return new AboutPage();
default:
return name.Length == 0 ? new ErrorLogPage() : null;
}
}
/// <summary>
/// Enables the factory to reuse an existing handler instance.
/// </summary>
public virtual void ReleaseHandler(IHttpHandler handler)
{
}
/// <summary>
/// Determines if the request is authorized by objects implementing
/// <see cref="IRequestAuthorizationHandler" />.
/// </summary>
/// <returns>
/// Returns zero if unauthorized, a value greater than zero if
/// authorized otherwise a value less than zero if no handlers
/// were available to answer.
/// </returns>
private static int IsAuthorized(HttpContext context)
{
Debug.Assert(context != null);
int authorized = /* uninitialized */ -1;
var authorizationHandlers = GetAuthorizationHandlers(context).GetEnumerator();
while (authorized != 0 && authorizationHandlers.MoveNext())
{
IRequestAuthorizationHandler authorizationHandler = authorizationHandlers.Current;
authorized = authorizationHandler.Authorize(context) ? 1 : 0;
}
return authorized;
}
private static IList<IRequestAuthorizationHandler> GetAuthorizationHandlers(HttpContext context)
{
Debug.Assert(context != null);
object key = _authorizationHandlersKey;
IList<IRequestAuthorizationHandler> handlers = (IList<IRequestAuthorizationHandler>)context.Items[key];
if (handlers == null)
{
const int capacity = 4;
List<IRequestAuthorizationHandler> list = new List<IRequestAuthorizationHandler>(capacity);
HttpApplication application = context.ApplicationInstance;
IRequestAuthorizationHandler appReqHandler = application as IRequestAuthorizationHandler;
if (appReqHandler != null)
{
list.Add(appReqHandler);
}
foreach (IHttpModule module in HttpModuleRegistry.GetModules(application))
{
IRequestAuthorizationHandler modReqHander = module as IRequestAuthorizationHandler;
if (modReqHander != null)
{
list.Add(modReqHander);
}
}
if (list != null)
context.Items[key] = handlers = list.AsReadOnly();
}
return handlers;
}
}
public interface IRequestAuthorizationHandler
{
bool Authorize(HttpContext context);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Hashtable = System.Collections.IDictionary;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlDeserializationEvents = System.Object;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
private TempAssembly _tempAssembly;
private bool _typedSerializer;
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if NET_NATIVE
public string DefaultNamespace = null;
private XmlSerializer innerSerializer;
private readonly Type rootType;
#endif
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static InternalHashtable s_xmlSerializerTable = new InternalHashtable();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !NET_NATIVE
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null)
#else
public XmlSerializer(Type type, Type[] extraTypes) : this(type)
#endif // NET_NATIVE
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException("type");
#if NET_NATIVE
this.DefaultNamespace = defaultNamespace;
rootType = type;
#endif
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !NET_NATIVE
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
{
#if NET_NATIVE
throw new PlatformNotSupportedException();
#else
if (type == null)
throw new ArgumentNullException("type");
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
_mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
if (xmlMapping == null)
throw new ArgumentNullException("xmlMapping");
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
SerializePrimitive(xmlWriter, o, namespaces);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(stream, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(textReader, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
try
{
if (_primitiveType != null)
{
return DeserializePrimitive(xmlReader, events);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
#if !NET_NATIVE
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
#else
if (this.innerSerializer == null)
{
return false;
}
return this.innerSerializer.CanDeserialize(xmlReader);
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>();
XmlSerializerImplementation contract = null;
TempAssembly tempAssembly = null;
{
if (XmlMapping.IsShallow(mappings))
{
return Array.Empty<XmlSerializer>();
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
}
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
InternalHashtable typedMappingTable = null;
lock (s_xmlSerializerTable)
{
typedMappingTable = s_xmlSerializerTable[type] as InternalHashtable;
if (typedMappingTable == null)
{
typedMappingTable = new InternalHashtable();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
InternalHashtable pendingKeys = new InternalHashtable();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
serializers[i] = typedMappingTable[mappingKey] as XmlSerializer;
if (serializers[i] == null)
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = (int)pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return Array.Empty<XmlSerializer>();
#if NET_NATIVE
var serializers = new List<XmlSerializer>();
foreach (var t in types)
{
serializers.Add(new XmlSerializer(t));
}
return serializers.ToArray();
#else
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
#endif
}
#if NET_NATIVE
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type];
if (typeDesc == null)
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else if (_primitiveType == typeof(TimeSpan))
{
writer.Write_TimeSpan(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else if (_primitiveType == typeof(TimeSpan))
{
o = reader.Read_TimeSpan();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
// Copyright (C) 2005-2013, Andriy Kozachuk
// Copyright (C) 2014 Extesla, LLC.
//
// 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 OpenGamingLibrary.Numerics.Utils;
namespace OpenGamingLibrary.Numerics.OpHelpers
{
/// <summary>
/// Contains helping methods for work with FHT (Fast Hartley Transform).
/// FHT is a better alternative of FFT (Fast Fourier Transform) - at least for <see cref="BigInteger" />.
/// </summary>
static unsafe internal class FhtHelper
{
#region struct TrigValues
/// <summary>
/// Trigonometry values.
/// </summary>
struct TrigValues
{
/// <summary>
/// Sin value from <see cref="SineTable" />.
/// </summary>
public double TableSin;
/// <summary>
/// Cos value from <see cref="SineTable" />.
/// </summary>
public double TableCos;
/// <summary>
/// Sin value.
/// </summary>
public double Sin;
/// <summary>
/// Cos value.
/// </summary>
public double Cos;
}
#endregion struct SinCos
#region Private constants (or static readonly fields)
// double[] data base
const int DoubleDataBytes = 1;
const int DoubleDataLengthShift = 2 - (DoubleDataBytes >> 1);
const int DoubleDataDigitShift = DoubleDataBytes << 3;
const long DoubleDataBaseInt = 1L << DoubleDataDigitShift;
const double DoubleDataBase = DoubleDataBaseInt;
const double DoubleDataBaseDiv2 = DoubleDataBase / 2.0;
// SQRT(2) and SQRT(2) / 2
static readonly double Sqrt2 = System.Math.Sqrt(2.0);
static readonly double Sqrt2Div2 = Sqrt2 / 2.0;
// SIN() table
static readonly double[] SineTable = new double[31];
#endregion Private constants (or static readonly fields)
#region Constructors
// .cctor
static FhtHelper()
{
// Initialize SinTable
FillSineTable(SineTable);
}
#endregion Constructors
#region Data conversion methods
/// <summary>
/// Converts <see cref="BigInteger" /> digits into real representation (used in FHT).
/// </summary>
/// <param name="digits">Big integer digits.</param>
/// <param name="length"><paramref name="digits" /> length.</param>
/// <param name="newLength">Multiplication result length (must be pow of 2).</param>
/// <returns>Double array.</returns>
static public double[] ConvertDigitsToDouble(uint[] digits, uint length, uint newLength)
{
fixed (uint* digitsPtr = digits)
{
return ConvertDigitsToDouble(digitsPtr, length, newLength);
}
}
/// <summary>
/// Converts <see cref="BigInteger" /> digits into real representation (used in FHT).
/// </summary>
/// <param name="digitsPtr">Big integer digits.</param>
/// <param name="length"><paramref name="digitsPtr" /> length.</param>
/// <param name="newLength">Multiplication result length (must be pow of 2).</param>
/// <returns>Double array.</returns>
static public double[] ConvertDigitsToDouble(uint* digitsPtr, uint length, uint newLength)
{
// Maybe fix newLength (make it the nearest bigger pow of 2)
newLength = 1U << Bits.CeilLog2(newLength);
// For better FHT accuracy we will choose length smaller then dwords.
// So new length must be modified accordingly
newLength <<= DoubleDataLengthShift;
double[] data = ArrayPool<double>.Instance.GetArray(newLength);
// Run in unsafe context
fixed (double* slice = data)
{
// Amount of units pointed by digitsPtr
uint unitCount = length << DoubleDataLengthShift;
// Copy all words from digits into new double[]
byte* unitDigitsPtr = (byte*)digitsPtr;
for (uint i = 0; i < unitCount; ++i)
{
slice[i] = unitDigitsPtr[i];
}
// Clear remaining double values (this array is from pool and may be dirty)
DigitHelper.SetBlockDigits(slice + unitCount, newLength - unitCount, 0.0);
// FHT (as well as FFT) works more accurate with "balanced" data, so let's balance it
double carry = 0, dataDigit;
for (uint i = 0; i < unitCount || i < newLength && carry != 0; ++i)
{
dataDigit = slice[i] + carry;
if (dataDigit >= DoubleDataBaseDiv2)
{
dataDigit -= DoubleDataBase;
carry = 1.0;
}
else
{
carry = 0;
}
slice[i] = dataDigit;
}
if (carry > 0)
{
slice[0] -= carry;
}
}
return data;
}
/// <summary>
/// Converts real digits representation (result of FHT) into usual <see cref="BigInteger" /> digits.
/// </summary>
/// <param name="array">Real digits representation.</param>
/// <param name="length"><paramref name="array" /> length.</param>
/// <param name="digitsLength">New digits array length (we always do know the upper value for this array).</param>
/// <param name="digitsRes">Big integer digits.</param>
static unsafe public void ConvertDoubleToDigits(double[] array, uint length, uint digitsLength, uint[] digitsRes)
{
fixed (double* slice = array)
fixed (uint* digitsResPtr = digitsRes)
{
ConvertDoubleToDigits(slice, length, digitsLength, digitsResPtr);
}
}
/// <summary>
/// Converts real digits representation (result of FHT) into usual <see cref="BigInteger" /> digits.
/// </summary>
/// <param name="slice">Real digits representation.</param>
/// <param name="length"><paramref name="slice" /> length.</param>
/// <param name="digitsLength">New digits array length (we always do know the upper value for this array).</param>
/// <param name="digitsResPtr">Resulting digits storage.</param>
/// <returns>Big integer digits (dword values).</returns>
static unsafe public void ConvertDoubleToDigits(double* slice, uint length, uint digitsLength, uint* digitsResPtr)
{
// Calculate data multiplier (don't forget about additional div 2)
double normalizeMultiplier = 0.5 / length;
// Count of units in digits
uint unitCount = digitsLength << DoubleDataLengthShift;
// Carry and current digit
double carry = 0, dataDigit;
long carryInt = 0, dataDigitInt;
#if DEBUG
// Rounding error
double error, maxError = 0;
#endif
// Walk thru all double digits
byte* unitDigitsPtr = (byte*)digitsResPtr;
for (uint i = 0; i < length; ++i)
{
// Get data digit (don't forget it might be balanced)
dataDigit = slice[i] * normalizeMultiplier;
#if DEBUG
// Round to the nearest
dataDigitInt = (long)(dataDigit < 0 ? dataDigit - 0.5 : dataDigit + 0.5);
// Calculate and (maybe) store max error
error = System.Math.Abs(dataDigit - dataDigitInt);
if (error > maxError)
{
maxError = error;
}
// Add carry
dataDigitInt += carryInt;
#else
// Round to the nearest
dataDigitInt = (long)(dataDigit < 0 ? dataDigit - 0.5 : dataDigit + 0.5) + carryInt;
#endif
// Get next carry floored; maybe modify data digit
carry = dataDigitInt / DoubleDataBase;
if (carry < 0)
{
carry += carry % 1.0;
}
carryInt = (long)carry;
dataDigitInt -= carryInt << DoubleDataDigitShift;
if (dataDigitInt < 0)
{
dataDigitInt += DoubleDataBaseInt;
--carryInt;
}
// Maybe add to the digits
if (i < unitCount)
{
unitDigitsPtr[i] = (byte)dataDigitInt;
}
}
// Last carry must be accounted
if (carryInt < 0)
{
digitsResPtr[0] -= (uint)-carryInt;
}
else if (carryInt > 0)
{
uint digitsCarry = (uint)carryInt, oldDigit;
for (uint i = 0; digitsCarry != 0 && i < digitsLength; ++i)
{
oldDigit = digitsResPtr[i];
digitsResPtr[i] += digitsCarry;
// Check for an overflow
digitsCarry = digitsResPtr[i] < oldDigit ? 1U : 0U;
}
}
#if DEBUG
// Finally store max error in public visible field
lock (BigInteger._maxFhtRoundErrorLock)
{
if (maxError > BigInteger.MaxFhtRoundError)
{
BigInteger.MaxFhtRoundError = maxError;
}
}
#endif
}
#endregion Data conversion methods
#region FHT
/// <summary>
/// Performs FHT "in place" for given double[] array.
/// </summary>
/// <param name="array">Double array.</param>
/// <param name="length">Array length.</param>
static public void Fht(double[] array, uint length)
{
fixed (double* slice = array)
{
Fht(slice, length, Bits.Msb(length));
}
}
/// <summary>
/// Performs FHT "in place" for given double[] array slice.
/// </summary>
/// <param name="slice">Double array slice.</param>
/// <param name="length">Slice length.</param>
/// <param name="lengthLog2">Log2(<paramref name="length" />).</param>
static public void Fht(double* slice, uint length, int lengthLog2)
{
// Special fast processing for length == 4
if (length == 4)
{
Fht4(slice);
return;
}
// Divide data into 2 recursively processed parts
length >>= 1;
--lengthLog2;
double* rightSlice = slice + length;
uint lengthDiv2 = length >> 1;
uint lengthDiv4 = length >> 2;
// Perform initial "butterfly" operations over left and right array parts
double leftDigit = slice[0];
double rightDigit = rightSlice[0];
slice[0] = leftDigit + rightDigit;
rightSlice[0] = leftDigit - rightDigit;
leftDigit = slice[lengthDiv2];
rightDigit = rightSlice[lengthDiv2];
slice[lengthDiv2] = leftDigit + rightDigit;
rightSlice[lengthDiv2] = leftDigit - rightDigit;
// Get initial trig values
//TrigValues trigValues = GetInitialTrigValues(lengthLog2);
TrigValues trigValues = new TrigValues();
GetInitialTrigValues(&trigValues, lengthLog2);
// Perform "butterfly"
for (uint i = 1; i < lengthDiv4; ++i)
{
FhtButterfly(slice, rightSlice, i, length - i, trigValues.Cos, trigValues.Sin);
FhtButterfly(slice, rightSlice, lengthDiv2 - i, lengthDiv2 + i, trigValues.Sin, trigValues.Cos);
// Get next trig values
NextTrigValues(&trigValues);
}
// Final "butterfly"
FhtButterfly(slice, rightSlice, lengthDiv4, length - lengthDiv4, Sqrt2Div2, Sqrt2Div2);
// Finally perform recursive run
Fht(slice, length, lengthLog2);
Fht(rightSlice, length, lengthLog2);
}
/// <summary>
/// Performs FHT "in place" for given double[] array slice.
/// Fast version for length == 4.
/// </summary>
/// <param name="slice">Double array slice.</param>
static private void Fht4(double* slice)
{
// Get 4 digits
double d0 = slice[0];
double d1 = slice[1];
double d2 = slice[2];
double d3 = slice[3];
// Perform fast "butterfly" addition/subtraction for them.
// In case when length == 4 we can do it without trigonometry
double d02 = d0 + d2;
double d13 = d1 + d3;
slice[0] = d02 + d13;
slice[1] = d02 - d13;
d02 = d0 - d2;
d13 = d1 - d3;
slice[2] = d02 + d13;
slice[3] = d02 - d13;
}
#endregion FHT
#region FHT results multiplication
/// <summary>
/// Multiplies two FHT results and stores multiplication in first one.
/// </summary>
/// <param name="data">First FHT result.</param>
/// <param name="data2">Second FHT result.</param>
/// <param name="length">FHT results length.</param>
static public void MultiplyFhtResults(double[] data, double[] data2, uint length)
{
fixed (double* slice = data, slice2 = data2)
{
MultiplyFhtResults(slice, slice2, length);
}
}
/// <summary>
/// Multiplies two FHT results and stores multiplication in first one.
/// </summary>
/// <param name="slice">First FHT result.</param>
/// <param name="slice2">Second FHT result.</param>
/// <param name="length">FHT results length.</param>
static public void MultiplyFhtResults(double* slice, double* slice2, uint length)
{
// Step0 and Step1
slice[0] *= 2.0 * slice2[0];
slice[1] *= 2.0 * slice2[1];
// Perform all other steps
double d11, d12, d21, d22, ad, sd;
for (uint stepStart = 2, stepEnd = 4, index1, index2; stepStart < length; stepStart *= 2, stepEnd *= 2)
{
for (index1 = stepStart, index2 = stepEnd - 1; index1 < stepEnd; index1 += 2, index2 -= 2)
{
d11 = slice[index1];
d12 = slice[index2];
d21 = slice2[index1];
d22 = slice2[index2];
ad = d11 + d12;
sd = d11 - d12;
slice[index1] = d21 * ad + d22 * sd;
slice[index2] = d22 * ad - d21 * sd;
}
}
}
#endregion FHT results multiplication
#region Reverse FHT
/// <summary>
/// Performs FHT reverse "in place" for given double[] array.
/// </summary>
/// <param name="array">Double array.</param>
/// <param name="length">Array length.</param>
static public void ReverseFht(double[] array, uint length)
{
fixed (double* slice = array)
{
ReverseFht(slice, length, Bits.Msb(length));
}
}
/// <summary>
/// Performs reverse FHT "in place" for given double[] array slice.
/// </summary>
/// <param name="slice">Double array slice.</param>
/// <param name="length">Slice length.</param>
/// <param name="lengthLog2">Log2(<paramref name="length" />).</param>
static public void ReverseFht(double* slice, uint length, int lengthLog2)
{
// Special fast processing for length == 8
if (length == 8)
{
ReverseFht8(slice);
return;
}
// Divide data into 2 recursively processed parts
length >>= 1;
--lengthLog2;
double* rightSlice = slice + length;
uint lengthDiv2 = length >> 1;
uint lengthDiv4 = length >> 2;
// Perform recursive run
ReverseFht(slice, length, lengthLog2);
ReverseFht(rightSlice, length, lengthLog2);
// Get initial trig values
TrigValues trigValues = new TrigValues();
GetInitialTrigValues(&trigValues, lengthLog2);
// Perform "butterfly"
for (uint i = 1; i < lengthDiv4; ++i)
{
ReverseFhtButterfly(slice, rightSlice, i, length - i, trigValues.Cos, trigValues.Sin);
ReverseFhtButterfly(slice, rightSlice, lengthDiv2 - i, lengthDiv2 + i, trigValues.Sin, trigValues.Cos);
// Get next trig values
NextTrigValues(&trigValues);
}
// Final "butterfly"
ReverseFhtButterfly(slice, rightSlice, lengthDiv4, length - lengthDiv4, Sqrt2Div2, Sqrt2Div2);
ReverseFhtButterfly2(slice, rightSlice, 0, 0, 1.0, 0);
ReverseFhtButterfly2(slice, rightSlice, lengthDiv2, lengthDiv2, 0, 1.0);
}
/// <summary>
/// Performs reverse FHT "in place" for given double[] array slice.
/// Fast version for length == 8.
/// </summary>
/// <param name="slice">Double array slice.</param>
static private void ReverseFht8(double* slice)
{
// Get 8 digits
double d0 = slice[0];
double d1 = slice[1];
double d2 = slice[2];
double d3 = slice[3];
double d4 = slice[4];
double d5 = slice[5];
double d6 = slice[6];
double d7 = slice[7];
// Calculate add and subtract pairs for first 4 digits
double da01 = d0 + d1;
double ds01 = d0 - d1;
double da23 = d2 + d3;
double ds23 = d2 - d3;
// Calculate add and subtract pairs for first pairs
double daa0123 = da01 + da23;
double dsa0123 = da01 - da23;
double das0123 = ds01 + ds23;
double dss0123 = ds01 - ds23;
// Calculate add and subtract pairs for next 4 digits
double da45 = d4 + d5;
double ds45 = (d4 - d5) * Sqrt2;
double da67 = d6 + d7;
double ds67 = (d6 - d7) * Sqrt2;
// Calculate add and subtract pairs for next pairs
double daa4567 = da45 + da67;
double dsa4567 = da45 - da67;
// Store digits values
slice[0] = daa0123 + daa4567;
slice[4] = daa0123 - daa4567;
slice[2] = dsa0123 + dsa4567;
slice[6] = dsa0123 - dsa4567;
slice[1] = das0123 + ds45;
slice[5] = das0123 - ds45;
slice[3] = dss0123 + ds67;
slice[7] = dss0123 - ds67;
}
#endregion Reverse FHT
#region "Butterfly" methods for FHT
/// <summary>
/// Performs "butterfly" operation for <see cref="Fht(double*, uint, int)" />.
/// </summary>
/// <param name="slice1">First data array slice.</param>
/// <param name="slice2">Second data array slice.</param>
/// <param name="index1">First slice index.</param>
/// <param name="index2">Second slice index.</param>
/// <param name="cos">Cos value.</param>
/// <param name="sin">Sin value.</param>
static private void FhtButterfly(double* slice1, double* slice2, uint index1, uint index2, double cos, double sin)
{
double d11 = slice1[index1];
double d12 = slice1[index2];
double temp = slice2[index1];
slice1[index1] = d11 + temp;
d11 -= temp;
temp = slice2[index2];
slice1[index2] = d12 + temp;
d12 -= temp;
slice2[index1] = d11 * cos + d12 * sin;
slice2[index2] = d11 * sin - d12 * cos;
}
/// <summary>
/// Performs "butterfly" operation for <see cref="ReverseFht(double*, uint, int)" />.
/// </summary>
/// <param name="slice1">First data array slice.</param>
/// <param name="slice2">Second data array slice.</param>
/// <param name="index1">First slice index.</param>
/// <param name="index2">Second slice index.</param>
/// <param name="cos">Cos value.</param>
/// <param name="sin">Sin value.</param>
static private void ReverseFhtButterfly(double* slice1, double* slice2, uint index1, uint index2, double cos, double sin)
{
double d21 = slice2[index1];
double d22 = slice2[index2];
double temp = slice1[index1];
double temp2 = d21 * cos + d22 * sin;
slice1[index1] = temp + temp2;
slice2[index1] = temp - temp2;
temp = slice1[index2];
temp2 = d21 * sin - d22 * cos;
slice1[index2] = temp + temp2;
slice2[index2] = temp - temp2;
}
/// <summary>
/// Performs "butterfly" operation for <see cref="ReverseFht(double*, uint, int)" />.
/// Another version.
/// </summary>
/// <param name="slice1">First data array slice.</param>
/// <param name="slice2">Second data array slice.</param>
/// <param name="index1">First slice index.</param>
/// <param name="index2">Second slice index.</param>
/// <param name="cos">Cos value.</param>
/// <param name="sin">Sin value.</param>
static private void ReverseFhtButterfly2(double* slice1, double* slice2, uint index1, uint index2, double cos, double sin)
{
double temp = slice1[index1];
double temp2 = slice2[index1] * cos + slice2[index2] * sin;
slice1[index1] = temp + temp2;
slice2[index2] = temp - temp2;
}
#endregion "Butterfly" methods for FHT
#region Trigonometry working methods
/// <summary>
/// Fills sine table for FHT.
/// </summary>
/// <param name="sineTable">Sine table to fill.</param>
static private void FillSineTable(double[] sineTable)
{
for (int i = 0, p = 1; i < sineTable.Length; ++i, p *= 2)
{
sineTable[i] = System.Math.Sin(System.Math.PI / p);
}
}
/// <summary>
/// Initializes trigonometry values for FHT.
/// </summary>
/// <param name="valuesPtr">Values to init.</param>
/// <param name="lengthLog2">Log2(processing slice length).</param>
static private void GetInitialTrigValues(TrigValues* valuesPtr, int lengthLog2)
{
valuesPtr->TableSin = SineTable[lengthLog2];
valuesPtr->TableCos = SineTable[lengthLog2 + 1];
valuesPtr->TableCos *= -2.0 * valuesPtr->TableCos;
valuesPtr->Sin = valuesPtr->TableSin;
valuesPtr->Cos = valuesPtr->TableCos + 1.0;
}
/// <summary>
/// Generates next trigonometry values for FHT basing on previous ones.
/// </summary>
/// <param name="valuesPtr">Current trig values.</param>
static private void NextTrigValues(TrigValues* valuesPtr)
{
double oldCos = valuesPtr->Cos;
valuesPtr->Cos = valuesPtr->Cos * valuesPtr->TableCos - valuesPtr->Sin * valuesPtr->TableSin + valuesPtr->Cos;
valuesPtr->Sin = valuesPtr->Sin * valuesPtr->TableCos + oldCos * valuesPtr->TableSin + valuesPtr->Sin;
}
#endregion Trigonometry working methods
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class ArqueoCaja
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel txtTitulo;
private global::Gtk.Table pneBotonera;
private global::Gtk.VBox vbox18;
private global::Gtk.Button btn500;
private global::Valle.GtkUtilidades.MiLabel lbl500;
private global::Gtk.VBox vbox19;
private global::Gtk.Button btn200;
private global::Valle.GtkUtilidades.MiLabel lbl200;
private global::Gtk.VBox vbox20;
private global::Gtk.Button btn100;
private global::Valle.GtkUtilidades.MiLabel lbl100;
private global::Gtk.VBox vbox21;
private global::Gtk.Button btn50;
private global::Valle.GtkUtilidades.MiLabel lbl50;
private global::Gtk.VBox vbox22;
private global::Gtk.Button btn20;
private global::Valle.GtkUtilidades.MiLabel lbl20;
private global::Gtk.VBox vbox23;
private global::Gtk.Button btn10;
private global::Valle.GtkUtilidades.MiLabel lbl10;
private global::Gtk.VBox vbox24;
private global::Gtk.Button btn5;
private global::Valle.GtkUtilidades.MiLabel lbl5;
private global::Gtk.VBox vbox25;
private global::Gtk.Button btn2;
private global::Valle.GtkUtilidades.MiLabel lbl2;
private global::Gtk.VBox vbox26;
private global::Gtk.Button btn1;
private global::Valle.GtkUtilidades.MiLabel lbl1;
private global::Gtk.VBox vbox27;
private global::Gtk.Button btn50c;
private global::Valle.GtkUtilidades.MiLabel lbl50c;
private global::Gtk.VBox vbox28;
private global::Gtk.Button btn20c;
private global::Valle.GtkUtilidades.MiLabel lbl20c;
private global::Gtk.VBox vbox29;
private global::Gtk.Button btnVarios;
private global::Valle.GtkUtilidades.MiLabel lblVarios;
private global::Gtk.VBox vbox30;
private global::Gtk.Button btnTargeta;
private global::Valle.GtkUtilidades.MiLabel lblTargeta;
private global::Gtk.VBox vbox31;
private global::Gtk.Button btnGastos;
private global::Valle.GtkUtilidades.MiLabel lblGastos;
private global::Gtk.HButtonBox hbuttonbox1;
private global::Gtk.Button btnCancelar;
private global::Gtk.VBox vbox3;
private global::Gtk.Image image14;
private global::Gtk.Label label2;
private global::Gtk.Button btnAbrirCajon;
private global::Gtk.Button btnAceptar;
private global::Gtk.VBox vbox2;
private global::Gtk.Image image29;
private global::Gtk.Label label1;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.ArqueoCaja
this.Name = "Valle.TpvFinal.ArqueoCaja";
this.Title = global::Mono.Unix.Catalog.GetString ("ArqueoCaja");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child Valle.TpvFinal.ArqueoCaja.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
this.vbox1.BorderWidth = ((uint)(12));
// Container child vbox1.Gtk.Box+BoxChild
this.txtTitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.txtTitulo.HeightRequest = 25;
this.txtTitulo.Events = ((global::Gdk.EventMask)(256));
this.txtTitulo.Name = "txtTitulo";
this.vbox1.Add (this.txtTitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.txtTitulo]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.pneBotonera = new global::Gtk.Table (((uint)(3)), ((uint)(5)), false);
this.pneBotonera.Name = "pneBotonera";
this.pneBotonera.RowSpacing = ((uint)(6));
this.pneBotonera.ColumnSpacing = ((uint)(6));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox18 = new global::Gtk.VBox ();
this.vbox18.Name = "vbox18";
this.vbox18.Spacing = 6;
// Container child vbox18.Gtk.Box+BoxChild
this.btn500 = new global::Gtk.Button ();
this.btn500.WidthRequest = 119;
this.btn500.HeightRequest = 80;
this.btn500.CanFocus = true;
this.btn500.Name = "btn500";
// Container child btn500.Gtk.Container+ContainerChild
global::Gtk.Alignment w2 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w3 = new global::Gtk.HBox ();
w3.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w4 = new global::Gtk.Image ();
w4.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.500E.jpeg");
w3.Add (w4);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w6 = new global::Gtk.Label ();
w3.Add (w6);
w2.Add (w3);
this.btn500.Add (w2);
this.vbox18.Add (this.btn500);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.vbox18 [this.btn500]));
w10.Position = 0;
w10.Expand = false;
w10.Fill = false;
// Container child vbox18.Gtk.Box+BoxChild
this.lbl500 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl500.HeightRequest = 30;
this.lbl500.Events = ((global::Gdk.EventMask)(256));
this.lbl500.Name = "lbl500";
this.vbox18.Add (this.lbl500);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vbox18 [this.lbl500]));
w11.Position = 1;
w11.Expand = false;
w11.Fill = false;
this.pneBotonera.Add (this.vbox18);
global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox18]));
w12.XOptions = ((global::Gtk.AttachOptions)(4));
w12.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox19 = new global::Gtk.VBox ();
this.vbox19.Name = "vbox19";
this.vbox19.Spacing = 6;
// Container child vbox19.Gtk.Box+BoxChild
this.btn200 = new global::Gtk.Button ();
this.btn200.WidthRequest = 114;
this.btn200.HeightRequest = 80;
this.btn200.CanFocus = true;
this.btn200.Name = "btn200";
// Container child btn200.Gtk.Container+ContainerChild
global::Gtk.Alignment w13 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w14 = new global::Gtk.HBox ();
w14.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w15 = new global::Gtk.Image ();
w15.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.200E.jpeg");
w14.Add (w15);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w17 = new global::Gtk.Label ();
w14.Add (w17);
w13.Add (w14);
this.btn200.Add (w13);
this.vbox19.Add (this.btn200);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox19 [this.btn200]));
w21.Position = 0;
w21.Expand = false;
w21.Fill = false;
// Container child vbox19.Gtk.Box+BoxChild
this.lbl200 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl200.HeightRequest = 30;
this.lbl200.Events = ((global::Gdk.EventMask)(256));
this.lbl200.Name = "lbl200";
this.vbox19.Add (this.lbl200);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox19 [this.lbl200]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
this.pneBotonera.Add (this.vbox19);
global::Gtk.Table.TableChild w23 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox19]));
w23.LeftAttach = ((uint)(1));
w23.RightAttach = ((uint)(2));
w23.XOptions = ((global::Gtk.AttachOptions)(4));
w23.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox20 = new global::Gtk.VBox ();
this.vbox20.Name = "vbox20";
this.vbox20.Spacing = 6;
// Container child vbox20.Gtk.Box+BoxChild
this.btn100 = new global::Gtk.Button ();
this.btn100.WidthRequest = 114;
this.btn100.HeightRequest = 80;
this.btn100.CanFocus = true;
this.btn100.Name = "btn100";
// Container child btn100.Gtk.Container+ContainerChild
global::Gtk.Alignment w24 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w25 = new global::Gtk.HBox ();
w25.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w26 = new global::Gtk.Image ();
w26.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.100E.jpeg");
w25.Add (w26);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w28 = new global::Gtk.Label ();
w25.Add (w28);
w24.Add (w25);
this.btn100.Add (w24);
this.vbox20.Add (this.btn100);
global::Gtk.Box.BoxChild w32 = ((global::Gtk.Box.BoxChild)(this.vbox20 [this.btn100]));
w32.Position = 0;
w32.Expand = false;
w32.Fill = false;
// Container child vbox20.Gtk.Box+BoxChild
this.lbl100 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl100.HeightRequest = 30;
this.lbl100.Events = ((global::Gdk.EventMask)(256));
this.lbl100.Name = "lbl100";
this.vbox20.Add (this.lbl100);
global::Gtk.Box.BoxChild w33 = ((global::Gtk.Box.BoxChild)(this.vbox20 [this.lbl100]));
w33.Position = 1;
w33.Expand = false;
w33.Fill = false;
this.pneBotonera.Add (this.vbox20);
global::Gtk.Table.TableChild w34 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox20]));
w34.LeftAttach = ((uint)(2));
w34.RightAttach = ((uint)(3));
w34.XOptions = ((global::Gtk.AttachOptions)(4));
w34.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox21 = new global::Gtk.VBox ();
this.vbox21.Name = "vbox21";
this.vbox21.Spacing = 6;
// Container child vbox21.Gtk.Box+BoxChild
this.btn50 = new global::Gtk.Button ();
this.btn50.WidthRequest = 114;
this.btn50.HeightRequest = 80;
this.btn50.CanFocus = true;
this.btn50.Name = "btn50";
// Container child btn50.Gtk.Container+ContainerChild
global::Gtk.Alignment w35 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w36 = new global::Gtk.HBox ();
w36.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w37 = new global::Gtk.Image ();
w37.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.50E.jpeg");
w36.Add (w37);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w39 = new global::Gtk.Label ();
w36.Add (w39);
w35.Add (w36);
this.btn50.Add (w35);
this.vbox21.Add (this.btn50);
global::Gtk.Box.BoxChild w43 = ((global::Gtk.Box.BoxChild)(this.vbox21 [this.btn50]));
w43.Position = 0;
w43.Expand = false;
w43.Fill = false;
// Container child vbox21.Gtk.Box+BoxChild
this.lbl50 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl50.HeightRequest = 30;
this.lbl50.Events = ((global::Gdk.EventMask)(256));
this.lbl50.Name = "lbl50";
this.vbox21.Add (this.lbl50);
global::Gtk.Box.BoxChild w44 = ((global::Gtk.Box.BoxChild)(this.vbox21 [this.lbl50]));
w44.Position = 1;
w44.Expand = false;
w44.Fill = false;
this.pneBotonera.Add (this.vbox21);
global::Gtk.Table.TableChild w45 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox21]));
w45.LeftAttach = ((uint)(3));
w45.RightAttach = ((uint)(4));
w45.XOptions = ((global::Gtk.AttachOptions)(4));
w45.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox22 = new global::Gtk.VBox ();
this.vbox22.Name = "vbox22";
this.vbox22.Spacing = 6;
// Container child vbox22.Gtk.Box+BoxChild
this.btn20 = new global::Gtk.Button ();
this.btn20.WidthRequest = 114;
this.btn20.HeightRequest = 80;
this.btn20.CanFocus = true;
this.btn20.Name = "btn20";
// Container child btn20.Gtk.Container+ContainerChild
global::Gtk.Alignment w46 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w47 = new global::Gtk.HBox ();
w47.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w48 = new global::Gtk.Image ();
w48.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.20E.jpeg");
w47.Add (w48);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w50 = new global::Gtk.Label ();
w47.Add (w50);
w46.Add (w47);
this.btn20.Add (w46);
this.vbox22.Add (this.btn20);
global::Gtk.Box.BoxChild w54 = ((global::Gtk.Box.BoxChild)(this.vbox22 [this.btn20]));
w54.Position = 0;
w54.Expand = false;
w54.Fill = false;
// Container child vbox22.Gtk.Box+BoxChild
this.lbl20 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl20.HeightRequest = 30;
this.lbl20.Events = ((global::Gdk.EventMask)(256));
this.lbl20.Name = "lbl20";
this.vbox22.Add (this.lbl20);
global::Gtk.Box.BoxChild w55 = ((global::Gtk.Box.BoxChild)(this.vbox22 [this.lbl20]));
w55.Position = 1;
w55.Expand = false;
w55.Fill = false;
this.pneBotonera.Add (this.vbox22);
global::Gtk.Table.TableChild w56 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox22]));
w56.LeftAttach = ((uint)(4));
w56.RightAttach = ((uint)(5));
w56.XOptions = ((global::Gtk.AttachOptions)(4));
w56.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox23 = new global::Gtk.VBox ();
this.vbox23.Name = "vbox23";
this.vbox23.Spacing = 6;
// Container child vbox23.Gtk.Box+BoxChild
this.btn10 = new global::Gtk.Button ();
this.btn10.WidthRequest = 90;
this.btn10.HeightRequest = 90;
this.btn10.CanFocus = true;
this.btn10.Name = "btn10";
// Container child btn10.Gtk.Container+ContainerChild
global::Gtk.Alignment w57 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w58 = new global::Gtk.HBox ();
w58.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w59 = new global::Gtk.Image ();
w59.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.10E.jpeg");
w58.Add (w59);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w61 = new global::Gtk.Label ();
w58.Add (w61);
w57.Add (w58);
this.btn10.Add (w57);
this.vbox23.Add (this.btn10);
global::Gtk.Box.BoxChild w65 = ((global::Gtk.Box.BoxChild)(this.vbox23 [this.btn10]));
w65.Position = 0;
w65.Expand = false;
w65.Fill = false;
// Container child vbox23.Gtk.Box+BoxChild
this.lbl10 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl10.HeightRequest = 25;
this.lbl10.Events = ((global::Gdk.EventMask)(256));
this.lbl10.Name = "lbl10";
this.vbox23.Add (this.lbl10);
global::Gtk.Box.BoxChild w66 = ((global::Gtk.Box.BoxChild)(this.vbox23 [this.lbl10]));
w66.Position = 1;
w66.Expand = false;
w66.Fill = false;
this.pneBotonera.Add (this.vbox23);
global::Gtk.Table.TableChild w67 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox23]));
w67.TopAttach = ((uint)(1));
w67.BottomAttach = ((uint)(2));
w67.XOptions = ((global::Gtk.AttachOptions)(4));
w67.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox24 = new global::Gtk.VBox ();
this.vbox24.Name = "vbox24";
this.vbox24.Spacing = 6;
// Container child vbox24.Gtk.Box+BoxChild
this.btn5 = new global::Gtk.Button ();
this.btn5.WidthRequest = 90;
this.btn5.HeightRequest = 90;
this.btn5.CanFocus = true;
this.btn5.Name = "btn5";
// Container child btn5.Gtk.Container+ContainerChild
global::Gtk.Alignment w68 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w69 = new global::Gtk.HBox ();
w69.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w70 = new global::Gtk.Image ();
w70.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.5E.jpeg");
w69.Add (w70);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w72 = new global::Gtk.Label ();
w69.Add (w72);
w68.Add (w69);
this.btn5.Add (w68);
this.vbox24.Add (this.btn5);
global::Gtk.Box.BoxChild w76 = ((global::Gtk.Box.BoxChild)(this.vbox24 [this.btn5]));
w76.Position = 0;
w76.Expand = false;
w76.Fill = false;
// Container child vbox24.Gtk.Box+BoxChild
this.lbl5 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl5.HeightRequest = 25;
this.lbl5.Events = ((global::Gdk.EventMask)(256));
this.lbl5.Name = "lbl5";
this.vbox24.Add (this.lbl5);
global::Gtk.Box.BoxChild w77 = ((global::Gtk.Box.BoxChild)(this.vbox24 [this.lbl5]));
w77.Position = 1;
w77.Expand = false;
w77.Fill = false;
this.pneBotonera.Add (this.vbox24);
global::Gtk.Table.TableChild w78 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox24]));
w78.TopAttach = ((uint)(1));
w78.BottomAttach = ((uint)(2));
w78.LeftAttach = ((uint)(1));
w78.RightAttach = ((uint)(2));
w78.XOptions = ((global::Gtk.AttachOptions)(4));
w78.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox25 = new global::Gtk.VBox ();
this.vbox25.Name = "vbox25";
this.vbox25.Spacing = 6;
// Container child vbox25.Gtk.Box+BoxChild
this.btn2 = new global::Gtk.Button ();
this.btn2.WidthRequest = 90;
this.btn2.HeightRequest = 90;
this.btn2.CanFocus = true;
this.btn2.Name = "btn2";
// Container child btn2.Gtk.Container+ContainerChild
global::Gtk.Alignment w79 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w80 = new global::Gtk.HBox ();
w80.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w81 = new global::Gtk.Image ();
w81.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.dosE.jpeg");
w80.Add (w81);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w83 = new global::Gtk.Label ();
w80.Add (w83);
w79.Add (w80);
this.btn2.Add (w79);
this.vbox25.Add (this.btn2);
global::Gtk.Box.BoxChild w87 = ((global::Gtk.Box.BoxChild)(this.vbox25 [this.btn2]));
w87.Position = 0;
w87.Expand = false;
w87.Fill = false;
// Container child vbox25.Gtk.Box+BoxChild
this.lbl2 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl2.HeightRequest = 25;
this.lbl2.Events = ((global::Gdk.EventMask)(256));
this.lbl2.Name = "lbl2";
this.vbox25.Add (this.lbl2);
global::Gtk.Box.BoxChild w88 = ((global::Gtk.Box.BoxChild)(this.vbox25 [this.lbl2]));
w88.Position = 1;
w88.Expand = false;
w88.Fill = false;
this.pneBotonera.Add (this.vbox25);
global::Gtk.Table.TableChild w89 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox25]));
w89.TopAttach = ((uint)(1));
w89.BottomAttach = ((uint)(2));
w89.LeftAttach = ((uint)(2));
w89.RightAttach = ((uint)(3));
w89.XOptions = ((global::Gtk.AttachOptions)(4));
w89.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox26 = new global::Gtk.VBox ();
this.vbox26.Name = "vbox26";
this.vbox26.Spacing = 6;
// Container child vbox26.Gtk.Box+BoxChild
this.btn1 = new global::Gtk.Button ();
this.btn1.WidthRequest = 90;
this.btn1.HeightRequest = 90;
this.btn1.CanFocus = true;
this.btn1.Name = "btn1";
// Container child btn1.Gtk.Container+ContainerChild
global::Gtk.Alignment w90 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w91 = new global::Gtk.HBox ();
w91.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w92 = new global::Gtk.Image ();
w92.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.UnE.jpeg");
w91.Add (w92);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w94 = new global::Gtk.Label ();
w91.Add (w94);
w90.Add (w91);
this.btn1.Add (w90);
this.vbox26.Add (this.btn1);
global::Gtk.Box.BoxChild w98 = ((global::Gtk.Box.BoxChild)(this.vbox26 [this.btn1]));
w98.Position = 0;
w98.Expand = false;
w98.Fill = false;
// Container child vbox26.Gtk.Box+BoxChild
this.lbl1 = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl1.HeightRequest = 25;
this.lbl1.Events = ((global::Gdk.EventMask)(256));
this.lbl1.Name = "lbl1";
this.vbox26.Add (this.lbl1);
global::Gtk.Box.BoxChild w99 = ((global::Gtk.Box.BoxChild)(this.vbox26 [this.lbl1]));
w99.Position = 1;
w99.Expand = false;
w99.Fill = false;
this.pneBotonera.Add (this.vbox26);
global::Gtk.Table.TableChild w100 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox26]));
w100.TopAttach = ((uint)(1));
w100.BottomAttach = ((uint)(2));
w100.LeftAttach = ((uint)(3));
w100.RightAttach = ((uint)(4));
w100.XOptions = ((global::Gtk.AttachOptions)(4));
w100.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox27 = new global::Gtk.VBox ();
this.vbox27.Name = "vbox27";
this.vbox27.Spacing = 6;
// Container child vbox27.Gtk.Box+BoxChild
this.btn50c = new global::Gtk.Button ();
this.btn50c.WidthRequest = 90;
this.btn50c.HeightRequest = 90;
this.btn50c.CanFocus = true;
this.btn50c.Name = "btn50c";
// Container child btn50c.Gtk.Container+ContainerChild
global::Gtk.Alignment w101 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w102 = new global::Gtk.HBox ();
w102.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w103 = new global::Gtk.Image ();
w103.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.50C.jpeg");
w102.Add (w103);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w105 = new global::Gtk.Label ();
w102.Add (w105);
w101.Add (w102);
this.btn50c.Add (w101);
this.vbox27.Add (this.btn50c);
global::Gtk.Box.BoxChild w109 = ((global::Gtk.Box.BoxChild)(this.vbox27 [this.btn50c]));
w109.Position = 0;
w109.Expand = false;
w109.Fill = false;
// Container child vbox27.Gtk.Box+BoxChild
this.lbl50c = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl50c.HeightRequest = 25;
this.lbl50c.Events = ((global::Gdk.EventMask)(256));
this.lbl50c.Name = "lbl50c";
this.vbox27.Add (this.lbl50c);
global::Gtk.Box.BoxChild w110 = ((global::Gtk.Box.BoxChild)(this.vbox27 [this.lbl50c]));
w110.Position = 1;
w110.Expand = false;
w110.Fill = false;
this.pneBotonera.Add (this.vbox27);
global::Gtk.Table.TableChild w111 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox27]));
w111.TopAttach = ((uint)(1));
w111.BottomAttach = ((uint)(2));
w111.LeftAttach = ((uint)(4));
w111.RightAttach = ((uint)(5));
w111.XOptions = ((global::Gtk.AttachOptions)(4));
w111.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox28 = new global::Gtk.VBox ();
this.vbox28.Name = "vbox28";
this.vbox28.Spacing = 6;
// Container child vbox28.Gtk.Box+BoxChild
this.btn20c = new global::Gtk.Button ();
this.btn20c.WidthRequest = 90;
this.btn20c.HeightRequest = 90;
this.btn20c.CanFocus = true;
this.btn20c.Name = "btn20c";
// Container child btn20c.Gtk.Container+ContainerChild
global::Gtk.Alignment w112 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w113 = new global::Gtk.HBox ();
w113.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w114 = new global::Gtk.Image ();
w114.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.20C.jpeg");
w113.Add (w114);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w116 = new global::Gtk.Label ();
w113.Add (w116);
w112.Add (w113);
this.btn20c.Add (w112);
this.vbox28.Add (this.btn20c);
global::Gtk.Box.BoxChild w120 = ((global::Gtk.Box.BoxChild)(this.vbox28 [this.btn20c]));
w120.Position = 0;
w120.Expand = false;
w120.Fill = false;
// Container child vbox28.Gtk.Box+BoxChild
this.lbl20c = new global::Valle.GtkUtilidades.MiLabel ();
this.lbl20c.HeightRequest = 25;
this.lbl20c.Events = ((global::Gdk.EventMask)(256));
this.lbl20c.Name = "lbl20c";
this.vbox28.Add (this.lbl20c);
global::Gtk.Box.BoxChild w121 = ((global::Gtk.Box.BoxChild)(this.vbox28 [this.lbl20c]));
w121.Position = 1;
w121.Expand = false;
w121.Fill = false;
this.pneBotonera.Add (this.vbox28);
global::Gtk.Table.TableChild w122 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox28]));
w122.TopAttach = ((uint)(2));
w122.BottomAttach = ((uint)(3));
w122.XOptions = ((global::Gtk.AttachOptions)(4));
w122.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox29 = new global::Gtk.VBox ();
this.vbox29.Name = "vbox29";
this.vbox29.Spacing = 6;
// Container child vbox29.Gtk.Box+BoxChild
this.btnVarios = new global::Gtk.Button ();
this.btnVarios.WidthRequest = 90;
this.btnVarios.HeightRequest = 90;
this.btnVarios.CanFocus = true;
this.btnVarios.Name = "btnVarios";
// Container child btnVarios.Gtk.Container+ContainerChild
global::Gtk.Alignment w123 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w124 = new global::Gtk.HBox ();
w124.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w125 = new global::Gtk.Image ();
w125.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.monedas.jpeg");
w124.Add (w125);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w127 = new global::Gtk.Label ();
w124.Add (w127);
w123.Add (w124);
this.btnVarios.Add (w123);
this.vbox29.Add (this.btnVarios);
global::Gtk.Box.BoxChild w131 = ((global::Gtk.Box.BoxChild)(this.vbox29 [this.btnVarios]));
w131.Position = 0;
w131.Expand = false;
w131.Fill = false;
// Container child vbox29.Gtk.Box+BoxChild
this.lblVarios = new global::Valle.GtkUtilidades.MiLabel ();
this.lblVarios.HeightRequest = 25;
this.lblVarios.Events = ((global::Gdk.EventMask)(256));
this.lblVarios.Name = "lblVarios";
this.vbox29.Add (this.lblVarios);
global::Gtk.Box.BoxChild w132 = ((global::Gtk.Box.BoxChild)(this.vbox29 [this.lblVarios]));
w132.Position = 1;
w132.Expand = false;
w132.Fill = false;
this.pneBotonera.Add (this.vbox29);
global::Gtk.Table.TableChild w133 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox29]));
w133.TopAttach = ((uint)(2));
w133.BottomAttach = ((uint)(3));
w133.LeftAttach = ((uint)(1));
w133.RightAttach = ((uint)(2));
w133.XOptions = ((global::Gtk.AttachOptions)(4));
w133.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox30 = new global::Gtk.VBox ();
this.vbox30.Name = "vbox30";
this.vbox30.Spacing = 6;
// Container child vbox30.Gtk.Box+BoxChild
this.btnTargeta = new global::Gtk.Button ();
this.btnTargeta.WidthRequest = 90;
this.btnTargeta.HeightRequest = 90;
this.btnTargeta.CanFocus = true;
this.btnTargeta.Name = "btnTargeta";
// Container child btnTargeta.Gtk.Container+ContainerChild
global::Gtk.Alignment w134 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w135 = new global::Gtk.HBox ();
w135.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w136 = new global::Gtk.Image ();
w136.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.visa.jpeg");
w135.Add (w136);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w138 = new global::Gtk.Label ();
w135.Add (w138);
w134.Add (w135);
this.btnTargeta.Add (w134);
this.vbox30.Add (this.btnTargeta);
global::Gtk.Box.BoxChild w142 = ((global::Gtk.Box.BoxChild)(this.vbox30 [this.btnTargeta]));
w142.Position = 0;
w142.Expand = false;
w142.Fill = false;
// Container child vbox30.Gtk.Box+BoxChild
this.lblTargeta = new global::Valle.GtkUtilidades.MiLabel ();
this.lblTargeta.HeightRequest = 25;
this.lblTargeta.Events = ((global::Gdk.EventMask)(256));
this.lblTargeta.Name = "lblTargeta";
this.vbox30.Add (this.lblTargeta);
global::Gtk.Box.BoxChild w143 = ((global::Gtk.Box.BoxChild)(this.vbox30 [this.lblTargeta]));
w143.Position = 1;
w143.Expand = false;
w143.Fill = false;
this.pneBotonera.Add (this.vbox30);
global::Gtk.Table.TableChild w144 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox30]));
w144.TopAttach = ((uint)(2));
w144.BottomAttach = ((uint)(3));
w144.LeftAttach = ((uint)(2));
w144.RightAttach = ((uint)(3));
w144.XOptions = ((global::Gtk.AttachOptions)(4));
w144.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child pneBotonera.Gtk.Table+TableChild
this.vbox31 = new global::Gtk.VBox ();
this.vbox31.Name = "vbox31";
this.vbox31.Spacing = 6;
// Container child vbox31.Gtk.Box+BoxChild
this.btnGastos = new global::Gtk.Button ();
this.btnGastos.WidthRequest = 90;
this.btnGastos.HeightRequest = 90;
this.btnGastos.CanFocus = true;
this.btnGastos.Name = "btnGastos";
// Container child btnGastos.Gtk.Container+ContainerChild
global::Gtk.Alignment w145 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w146 = new global::Gtk.HBox ();
w146.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w147 = new global::Gtk.Image ();
w147.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.gastos.jpeg");
w146.Add (w147);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w149 = new global::Gtk.Label ();
w146.Add (w149);
w145.Add (w146);
this.btnGastos.Add (w145);
this.vbox31.Add (this.btnGastos);
global::Gtk.Box.BoxChild w153 = ((global::Gtk.Box.BoxChild)(this.vbox31 [this.btnGastos]));
w153.Position = 0;
w153.Expand = false;
w153.Fill = false;
// Container child vbox31.Gtk.Box+BoxChild
this.lblGastos = new global::Valle.GtkUtilidades.MiLabel ();
this.lblGastos.HeightRequest = 25;
this.lblGastos.Events = ((global::Gdk.EventMask)(256));
this.lblGastos.Name = "lblGastos";
this.vbox31.Add (this.lblGastos);
global::Gtk.Box.BoxChild w154 = ((global::Gtk.Box.BoxChild)(this.vbox31 [this.lblGastos]));
w154.Position = 1;
w154.Expand = false;
w154.Fill = false;
this.pneBotonera.Add (this.vbox31);
global::Gtk.Table.TableChild w155 = ((global::Gtk.Table.TableChild)(this.pneBotonera [this.vbox31]));
w155.TopAttach = ((uint)(2));
w155.BottomAttach = ((uint)(3));
w155.LeftAttach = ((uint)(3));
w155.RightAttach = ((uint)(4));
w155.XOptions = ((global::Gtk.AttachOptions)(4));
w155.YOptions = ((global::Gtk.AttachOptions)(4));
this.vbox1.Add (this.pneBotonera);
global::Gtk.Box.BoxChild w156 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.pneBotonera]));
w156.Position = 1;
w156.Expand = false;
w156.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbuttonbox1 = new global::Gtk.HButtonBox ();
this.hbuttonbox1.Name = "hbuttonbox1";
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnCancelar = new global::Gtk.Button ();
this.btnCancelar.CanFocus = true;
this.btnCancelar.Name = "btnCancelar";
// Container child btnCancelar.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.image14 = new global::Gtk.Image ();
this.image14.Name = "image14";
this.image14.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog);
this.vbox3.Add (this.image14);
global::Gtk.Box.BoxChild w157 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.image14]));
w157.Position = 0;
w157.Expand = false;
w157.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Cancelar");
this.vbox3.Add (this.label2);
global::Gtk.Box.BoxChild w158 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.label2]));
w158.Position = 1;
w158.Expand = false;
w158.Fill = false;
this.btnCancelar.Add (this.vbox3);
this.btnCancelar.Label = null;
this.hbuttonbox1.Add (this.btnCancelar);
global::Gtk.ButtonBox.ButtonBoxChild w160 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.btnCancelar]));
w160.Expand = false;
w160.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnAbrirCajon = new global::Gtk.Button ();
this.btnAbrirCajon.CanFocus = true;
this.btnAbrirCajon.Name = "btnAbrirCajon";
this.btnAbrirCajon.UseUnderline = true;
// Container child btnAbrirCajon.Gtk.Container+ContainerChild
global::Gtk.Alignment w161 = new global::Gtk.Alignment (0.5F, 0.5F, 0F, 0F);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w162 = new global::Gtk.HBox ();
w162.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w163 = new global::Gtk.Image ();
w163.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.STARTUP.ICO");
w162.Add (w163);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w165 = new global::Gtk.Label ();
w162.Add (w165);
w161.Add (w162);
this.btnAbrirCajon.Add (w161);
this.hbuttonbox1.Add (this.btnAbrirCajon);
global::Gtk.ButtonBox.ButtonBoxChild w169 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.btnAbrirCajon]));
w169.Position = 1;
w169.Expand = false;
w169.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnAceptar = new global::Gtk.Button ();
this.btnAceptar.CanFocus = true;
this.btnAceptar.Name = "btnAceptar";
// Container child btnAceptar.Gtk.Container+ContainerChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.image29 = new global::Gtk.Image ();
this.image29.Name = "image29";
this.image29.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog);
this.vbox2.Add (this.image29);
global::Gtk.Box.BoxChild w170 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.image29]));
w170.Position = 0;
w170.Expand = false;
w170.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Aceptar");
this.vbox2.Add (this.label1);
global::Gtk.Box.BoxChild w171 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.label1]));
w171.Position = 1;
w171.Expand = false;
w171.Fill = false;
this.btnAceptar.Add (this.vbox2);
this.btnAceptar.Label = null;
this.hbuttonbox1.Add (this.btnAceptar);
global::Gtk.ButtonBox.ButtonBoxChild w173 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.btnAceptar]));
w173.Position = 2;
w173.Expand = false;
w173.Fill = false;
this.vbox1.Add (this.hbuttonbox1);
global::Gtk.Box.BoxChild w174 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbuttonbox1]));
w174.Position = 2;
w174.Expand = false;
w174.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 625;
this.DefaultHeight = 571;
this.Show ();
this.ExposeEvent += new global::Gtk.ExposeEventHandler (this.OnExposeEvent);
this.btnGastos.Clicked += new global::System.EventHandler (this.OnBtnGastosClicked);
this.btnTargeta.Clicked += new global::System.EventHandler (this.OnBtnTargetaClicked);
this.btnVarios.Clicked += new global::System.EventHandler (this.OnBtnVariosClicked);
this.btn20c.Clicked += new global::System.EventHandler (this.OnBtn20cClicked);
this.btn50c.Clicked += new global::System.EventHandler (this.OnBtn50cClicked);
this.btn1.Clicked += new global::System.EventHandler (this.OnBtn1Clicked);
this.btn2.Clicked += new global::System.EventHandler (this.OnBtn2Clicked);
this.btn5.Clicked += new global::System.EventHandler (this.OnBtn5Clicked);
this.btn10.Clicked += new global::System.EventHandler (this.OnBtn10Clicked);
this.btn20.Clicked += new global::System.EventHandler (this.OnBtn20Clicked);
this.btn50.Clicked += new global::System.EventHandler (this.OnBtn50Clicked);
this.btn100.Clicked += new global::System.EventHandler (this.OnBtn100Clicked);
this.btn200.Clicked += new global::System.EventHandler (this.OnBtn200Clicked);
this.btn500.Clicked += new global::System.EventHandler (this.OnBtn500Clicked);
this.btnCancelar.Clicked += new global::System.EventHandler (this.OnBtnCancelarClicked);
this.btnAbrirCajon.Clicked += new global::System.EventHandler (this.OnBtnAbrirCajonClicked);
this.btnAceptar.Clicked += new global::System.EventHandler (this.OnBtnAceptarClicked);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DocumentationServerProtocol.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Protocols {
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Web.Services.Discovery;
using System.Web.UI;
using System.Diagnostics;
using System.Web.Services.Configuration;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Text;
using System.Net;
using System.Web.Services.Description;
using System.Threading;
using System.Web.Services.Diagnostics;
using System.Security.Permissions;
using System.Collections.Generic;
internal class DocumentationServerType : ServerType {
ServiceDescriptionCollection serviceDescriptions, serviceDescriptionsWithPost;
XmlSchemas schemas, schemasWithPost;
LogicalMethodInfo methodInfo;
public List<Action<Uri>> UriFixups { get; private set; }
void AddUriFixup(Action<Uri> fixup)
{
if (this.UriFixups != null)
{
this.UriFixups.Add(fixup);
}
}
// See comment on the ServerProtocol.IsCacheUnderPressure method for explanation of the excludeSchemeHostPortFromCachingKey logic.
internal DocumentationServerType(Type type, string uri, bool excludeSchemeHostPortFromCachingKey)
: base(typeof(DocumentationServerProtocol))
{
if (excludeSchemeHostPortFromCachingKey)
{
this.UriFixups = new List<Action<Uri>>();
}
//
// parse the uri from a string into a URI object
//
Uri uriObject = new Uri(uri, true);
//
// and get rid of the query string if there's one
//
uri = uriObject.GetLeftPart(UriPartial.Path);
methodInfo = new LogicalMethodInfo(typeof(DocumentationServerProtocol).GetMethod("Documentation", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
ServiceDescriptionReflector reflector = new ServiceDescriptionReflector(this.UriFixups);
reflector.Reflect(type, uri);
schemas = reflector.Schemas;
serviceDescriptions = reflector.ServiceDescriptions;
schemasWithPost = reflector.SchemasWithPost;
serviceDescriptionsWithPost = reflector.ServiceDescriptionsWithPost;
}
internal LogicalMethodInfo MethodInfo {
get { return methodInfo; }
}
internal XmlSchemas Schemas {
get { return schemas; }
}
internal ServiceDescriptionCollection ServiceDescriptions {
get { return serviceDescriptions; }
}
internal ServiceDescriptionCollection ServiceDescriptionsWithPost {
get { return serviceDescriptionsWithPost; }
}
internal XmlSchemas SchemasWithPost {
get { return schemasWithPost; }
}
}
internal class DocumentationServerProtocolFactory : ServerProtocolFactory {
protected override ServerProtocol CreateIfRequestCompatible(HttpRequest request) {
if (request.PathInfo.Length > 0)
return null;
if (request.HttpMethod != "GET")
// MethodNotAllowed = 405,
return new UnsupportedRequestProtocol(405);
return new DocumentationServerProtocol();
}
}
internal sealed class DocumentationServerProtocol : ServerProtocol {
DocumentationServerType serverType;
IHttpHandler handler = null;
object syncRoot = new object();
private const int MAX_PATH_SIZE = 1024;
internal override bool Initialize() {
//
// see if we already cached a DocumentationServerType
//
if (null == (serverType = (DocumentationServerType)GetFromCache(typeof(DocumentationServerProtocol), Type))
&& null == (serverType = (DocumentationServerType)GetFromCache(typeof(DocumentationServerProtocol), Type, true))) {
lock (InternalSyncObject) {
if (null == (serverType = (DocumentationServerType)GetFromCache(typeof(DocumentationServerProtocol), Type))
&& null == (serverType = (DocumentationServerType)GetFromCache(typeof(DocumentationServerProtocol), Type, true)))
{
//
// if not create a new DocumentationServerType and cache it
//
//
bool excludeSchemeHostPortFromCachingKey = this.IsCacheUnderPressure(typeof(DocumentationServerProtocol), Type);
string escapedUri = Uri.EscapeUriString(Request.Url.ToString()).Replace("#", "%23");
serverType = new DocumentationServerType(Type, escapedUri, excludeSchemeHostPortFromCachingKey);
AddToCache(typeof(DocumentationServerProtocol), Type, serverType, excludeSchemeHostPortFromCachingKey);
}
}
}
WebServicesSection config = WebServicesSection.Current;
if (config.WsdlHelpGenerator.Href != null && config.WsdlHelpGenerator.Href.Length > 0)
{
TraceMethod caller = Tracing.On ? new TraceMethod(this, "Initialize") : null;
if (Tracing.On) Tracing.Enter("ASP.NET", caller, new TraceMethod(typeof(PageParser), "GetCompiledPageInstance", config.WsdlHelpGenerator.HelpGeneratorVirtualPath, config.WsdlHelpGenerator.HelpGeneratorPath, Context));
handler = GetCompiledPageInstance(config.WsdlHelpGenerator.HelpGeneratorVirtualPath,
config.WsdlHelpGenerator.HelpGeneratorPath,
Context);
if (Tracing.On) Tracing.Exit("ASP.NET", caller);
}
return true;
}
// Asserts SecurityPermission and FileIOPermission.
// Justification: Security Permission is demanded by PageParser.GetCompiledPageInstance() method.
// It is used to initialize the IHttpHandler field of the DocumentationServerProtocol object.
// FileIOPermission is required to access the inputFile passed in as a parameter.
// It is used only to map the virtual path to the physical file path. The FileIOPermission is not used to access any file other than the one passed in.
[SecurityPermission(SecurityAction.Assert, Unrestricted = true)]
[FileIOPermissionAttribute(SecurityAction.Assert, Unrestricted = true)]
private IHttpHandler GetCompiledPageInstance(string virtualPath, string inputFile, HttpContext context)
{
return PageParser.GetCompiledPageInstance(virtualPath, inputFile, context);
}
internal override ServerType ServerType {
get { return serverType; }
}
internal override bool IsOneWay {
get { return false; }
}
internal override LogicalMethodInfo MethodInfo {
get { return serverType.MethodInfo; }
}
internal override object[] ReadParameters() {
return new object[0];
}
internal override void WriteReturns(object[] returnValues, Stream outputStream) {
try {
if (handler != null) {
Context.Items.Add("wsdls", serverType.ServiceDescriptions);
Context.Items.Add("schemas", serverType.Schemas);
// conditionally add post-enabled wsdls and schemas to support localhost-only post
if (Context.Request.Url.IsLoopback || Context.Request.IsLocal) {
Context.Items.Add("wsdlsWithPost", serverType.ServiceDescriptionsWithPost);
Context.Items.Add("schemasWithPost", serverType.SchemasWithPost);
}
Context.Items.Add("conformanceWarnings", WebServicesSection.Current.EnabledConformanceWarnings);
Response.ContentType = "text/html";
if (this.serverType.UriFixups == null)
{
handler.ProcessRequest(Context);
}
else
{
lock (this.syncRoot)
{
this.RunUriFixups();
handler.ProcessRequest(Context);
}
}
}
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
throw new InvalidOperationException(Res.GetString(Res.HelpGeneratorInternalError), e);
}
}
internal override bool WriteException(Exception e, Stream outputStream) {
return false;
}
internal void Documentation() {
// This is the "server method" that is called for this protocol
}
void RunUriFixups()
{
foreach (Action<Uri> fixup in this.serverType.UriFixups)
{
fixup(this.Context.Request.Url);
}
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Deleting;
public sealed class DeleteResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public DeleteResourceTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemsController>();
testContext.UseController<WorkItemGroupsController>();
testContext.UseController<RgbColorsController>();
}
[Fact]
public async Task Can_delete_existing_resource()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem? workItemsInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemsInDatabase.Should().BeNull();
});
}
[Fact]
public async Task Cannot_delete_unknown_resource()
{
// Arrange
string workItemId = Unknown.StringId.For<WorkItem, int>();
string route = $"/workItems/{workItemId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested resource does not exist.");
error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist.");
error.Source.Should().BeNull();
error.Meta.Should().NotContainKey("requestBody");
}
[Fact]
public async Task Can_delete_resource_with_OneToOne_relationship_from_dependent_side()
{
// Arrange
RgbColor existingColor = _fakers.RgbColor.Generate();
existingColor.Group = _fakers.WorkItemGroup.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RgbColors.Add(existingColor);
await dbContext.SaveChangesAsync();
});
string route = $"/rgbColors/{existingColor.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor? colorsInDatabase = await dbContext.RgbColors.FirstWithIdOrDefaultAsync(existingColor.Id);
colorsInDatabase.Should().BeNull();
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(existingColor.Group.Id);
groupInDatabase.Color.Should().BeNull();
});
}
[Fact]
public async Task Can_delete_existing_resource_with_OneToOne_relationship_from_principal_side()
{
// Arrange
WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate();
existingGroup.Color = _fakers.RgbColor.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Groups.Add(existingGroup);
await dbContext.SaveChangesAsync();
});
string route = $"/workItemGroups/{existingGroup.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup? groupsInDatabase = await dbContext.Groups.FirstWithIdOrDefaultAsync(existingGroup.Id);
groupsInDatabase.Should().BeNull();
RgbColor? colorInDatabase = await dbContext.RgbColors.FirstWithIdOrDefaultAsync(existingGroup.Color.Id);
colorInDatabase.ShouldNotBeNull();
colorInDatabase.Group.Should().BeNull();
});
}
[Fact]
public async Task Can_delete_existing_resource_with_OneToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem? workItemInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemInDatabase.Should().BeNull();
List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync();
userAccountsInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(0).Id);
userAccountsInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(1).Id);
});
}
[Fact]
public async Task Can_delete_resource_with_ManyToMany_relationship()
{
// Arrange
WorkItem existingWorkItem = _fakers.WorkItem.Generate();
existingWorkItem.Tags = _fakers.WorkTag.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(existingWorkItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{existingWorkItem.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem? workItemInDatabase = await dbContext.WorkItems.FirstWithIdOrDefaultAsync(existingWorkItem.Id);
workItemInDatabase.Should().BeNull();
WorkTag? tagInDatabase = await dbContext.WorkTags.FirstWithIdOrDefaultAsync(existingWorkItem.Tags.ElementAt(0).Id);
tagInDatabase.ShouldNotBeNull();
});
}
}
| |
// 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: Class that manages stores of local data. This class is used in
** cooperation with the LocalDataStore class.
**
**
=============================================================================*/
namespace System {
using System;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
// This class is an encapsulation of a slot so that it is managed in a secure fashion.
// It is constructed by the LocalDataStoreManager, holds the slot and the manager
// and cleans up when it is finalized.
// This class will not be marked serializable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class LocalDataStoreSlot
{
private LocalDataStoreMgr m_mgr;
private int m_slot;
private long m_cookie;
// Construct the object to encapsulate the slot.
internal LocalDataStoreSlot(LocalDataStoreMgr mgr, int slot, long cookie)
{
m_mgr = mgr;
m_slot = slot;
m_cookie = cookie;
}
// Accessors for the two fields of this class.
internal LocalDataStoreMgr Manager
{
get
{
return m_mgr;
}
}
internal int Slot
{
get
{
return m_slot;
}
}
internal long Cookie
{
get
{
return m_cookie;
}
}
// Release the slot reserved by this object when this object goes away.
~LocalDataStoreSlot()
{
LocalDataStoreMgr mgr = m_mgr;
if (mgr == null)
return;
int slot = m_slot;
// Mark the slot as free.
m_slot = -1;
mgr.FreeDataSlot(slot, m_cookie);
}
}
// This class will not be marked serializable
sealed internal class LocalDataStoreMgr
{
private const int InitialSlotTableSize = 64;
private const int SlotTableDoubleThreshold = 512;
private const int LargeSlotTableSizeIncrease = 128;
/*=========================================================================
** Create a data store to be managed by this manager and add it to the
** list. The initial size of the new store matches the number of slots
** allocated in this manager.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreHolder CreateLocalDataStore()
{
// Create a new local data store.
LocalDataStore store = new LocalDataStore(this, m_SlotInfoTable.Length);
LocalDataStoreHolder holder = new LocalDataStoreHolder(store);
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Add the store to the array list and return it.
m_ManagedLocalDataStores.Add(store);
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
return holder;
}
/*=========================================================================
* Remove the specified store from the list of managed stores..
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public void DeleteLocalDataStore(LocalDataStore store)
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Remove the store to the array list and return it.
m_ManagedLocalDataStores.Remove(store);
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Allocates a data slot by finding an available index and wrapping it
** an object to prevent clients from manipulating it directly, allowing us
** to make assumptions its integrity.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot AllocateDataSlot()
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
LocalDataStoreSlot slot;
int slotTableSize = m_SlotInfoTable.Length;
// In case FreeDataSlot has moved the pointer back, the next slot may not be available.
// Find the first actually available slot.
int availableSlot = m_FirstAvailableSlot;
while (availableSlot < slotTableSize)
{
if (!m_SlotInfoTable[availableSlot])
break;
availableSlot++;
}
// Check if there are any slots left.
if (availableSlot >= slotTableSize)
{
// The table is full so we need to increase its size.
int newSlotTableSize;
if (slotTableSize < SlotTableDoubleThreshold)
{
// The table is still relatively small so double it.
newSlotTableSize = slotTableSize * 2;
}
else
{
// The table is relatively large so simply increase its size by a given amount.
newSlotTableSize = slotTableSize + LargeSlotTableSizeIncrease;
}
// Allocate the new slot info table.
bool[] newSlotInfoTable = new bool[newSlotTableSize];
// Copy the old array into the new one.
Array.Copy(m_SlotInfoTable, newSlotInfoTable, slotTableSize);
m_SlotInfoTable = newSlotInfoTable;
}
// availableSlot is the index of the empty slot.
m_SlotInfoTable[availableSlot] = true;
// We do not need to worry about overflowing m_CookieGenerator. It would take centuries
// of intensive slot allocations on current machines to get the 2^64 counter to overflow.
// We will perform the increment with overflow check just to play it on the safe side.
slot = new LocalDataStoreSlot(this, availableSlot, checked(m_CookieGenerator++));
// Save the new "first available slot".hint
m_FirstAvailableSlot = availableSlot + 1;
// Return the selected slot
return slot;
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Allocate a slot and associate a name with it.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot AllocateNamedDataSlot(String name)
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Allocate a normal data slot.
LocalDataStoreSlot slot = AllocateDataSlot();
// Insert the association between the name and the data slot number
// in the hash table.
m_KeyToSlotMap.Add(name, slot);
return slot;
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Retrieve the slot associated with a name, allocating it if no such
** association has been defined.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot GetNamedDataSlot(String name)
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Lookup in the hashtable to try find a slot for the name.
LocalDataStoreSlot slot = m_KeyToSlotMap.GetValueOrDefault(name);
// If the name is not yet in the hashtable then add it.
if (null == slot)
return AllocateNamedDataSlot(name);
// The name was in the hashtable so return the associated slot.
return slot;
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Eliminate the association of a name with a slot. The actual slot will
** be reclaimed when the finalizer for the slot object runs.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
public void FreeNamedDataSlot(String name)
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Remove the name slot association from the hashtable.
m_KeyToSlotMap.Remove(name);
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Free's a previously allocated data slot on ALL the managed data stores.
=========================================================================*/
[System.Security.SecuritySafeCritical] // auto-generated
internal void FreeDataSlot(int slot, long cookie)
{
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(this, ref tookLock);
// Go thru all the managed stores and set the data on the specified slot to 0.
for (int i = 0; i < m_ManagedLocalDataStores.Count; i++)
{
((LocalDataStore)m_ManagedLocalDataStores[i]).FreeData(slot, cookie);
}
// Mark the slot as being no longer occupied.
m_SlotInfoTable[slot] = false;
if (slot < m_FirstAvailableSlot)
m_FirstAvailableSlot = slot;
}
finally
{
if (tookLock)
Monitor.Exit(this);
}
}
/*=========================================================================
** Check that this is a valid slot for this store
=========================================================================*/
public void ValidateSlot(LocalDataStoreSlot slot)
{
// Make sure the slot was allocated for this store.
if (slot == null || slot.Manager != this)
throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidSlot"));
Contract.EndContractBlock();
}
/*=========================================================================
** Return the number of allocated slots in this manager.
=========================================================================*/
internal int GetSlotTableLength()
{
return m_SlotInfoTable.Length;
}
private bool[] m_SlotInfoTable = new bool[InitialSlotTableSize];
private int m_FirstAvailableSlot;
private List<LocalDataStore> m_ManagedLocalDataStores = new List<LocalDataStore>();
private Dictionary<String, LocalDataStoreSlot> m_KeyToSlotMap = new Dictionary<String, LocalDataStoreSlot>();
private long m_CookieGenerator;
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Diagnostics;
using System.Web;
using Adxstudio.Xrm.Performance.AggregateEvent;
using Adxstudio.Xrm.Web;
namespace Adxstudio.Xrm.Performance
{
public sealed class PerformanceProfiler : IPerformanceProfiler
{
private static readonly Lazy<PerformanceProfiler> _instance = new Lazy<PerformanceProfiler>(CreateProfiler);
public static PerformanceProfiler Instance
{
get { return _instance.Value; }
}
private static PerformanceProfiler CreateProfiler()
{
return new PerformanceProfiler(new PerformanceAggregateLogger(new EventSourcePerformanceLogger()), new GuidIdGenerator());
}
private readonly IPerformanceLogger _logger;
private readonly IPerformanceMarkerIdGenerator _idGenerator;
private PerformanceProfiler(IPerformanceLogger logger, IPerformanceMarkerIdGenerator idGenerator)
{
if (logger == null) throw new ArgumentNullException("logger");
if (idGenerator == null) throw new ArgumentNullException("idGenerator");
_logger = logger;
_idGenerator = idGenerator;
}
public void AddMarker(string name, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
{
_logger.Log(new PerformanceMarker(GetId(), name, GetTimestamp(), GetRequestId(), GetSessionId(), area, tag));
}
public IPerformanceMarker StartMarker(string name, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
{
return new StopwatchPerformanceMarker(this, GetId(), name, GetTimestamp(), GetRequestId(), GetSessionId(), area, tag);
}
public void StopMarker(IPerformanceMarker marker)
{
if (marker == null)
{
// Err on the side of not having performance code throw any errors.
return;
}
marker.Stop();
_logger.Log(marker);
}
public TimeSpan UsingMarker(string name, Action<IPerformanceMarker> action, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
{
var marker = StartMarker(name, area, tag);
using (marker)
{
action(marker);
}
return marker.Elapsed.GetValueOrDefault();
}
public TimeSpan UsingMarker(string name, Action action, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
{
var marker = StartMarker(name, area, tag);
using (marker)
{
action();
}
return marker.Elapsed.GetValueOrDefault();
}
private string GetId()
{
return _idGenerator.GetId();
}
private string GetRequestId()
{
try
{
var context = HttpContext.Current;
return context == null ? null : context.Request.AnonymousID;
}
catch (Exception e)
{
WebEventSource.Log.GenericWarningException(e);
}
return null;
}
private string GetSessionId()
{
var context = HttpContext.Current;
return context == null || context.Session == null ? null : context.Session.SessionID;
}
private DateTime GetTimestamp()
{
return DateTime.UtcNow;
}
private class PerformanceMarker : IPerformanceMarker
{
public PerformanceMarker(string id, string name, DateTime timestamp, string requestId, string sessionId, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
{
Id = id;
Name = name;
Timestamp = timestamp;
RequestId = requestId;
SessionId = sessionId;
Area = area;
Tag = tag;
}
public PerformanceMarkerArea Area { get; private set; }
public virtual TimeSpan? Elapsed
{
get { return null; }
protected set { }
}
public string Id { get; private set; }
public string Name { get; private set; }
public string RequestId { get; private set; }
public string SessionId { get; private set; }
public PerformanceMarkerSource Source
{
get { return PerformanceMarkerSource.Server; }
}
public DateTime Timestamp { get; private set; }
public virtual PerformanceMarkerType Type
{
get { return PerformanceMarkerType.Marker; }
}
public string Tag { get; private set; }
public virtual void Dispose() { }
public virtual void Stop() { }
}
private class StopwatchPerformanceMarker : PerformanceMarker
{
private readonly IPerformanceProfiler _profiler;
private bool _stopped;
private readonly Stopwatch _stopwatch;
public StopwatchPerformanceMarker(IPerformanceProfiler profiler, string id, string name, DateTime timestamp, string requestId, string sessionId, PerformanceMarkerArea area = PerformanceMarkerArea.Unknown, string tag = null)
: base(id, name, timestamp, requestId, sessionId, area, tag)
{
if (profiler == null) throw new ArgumentNullException("profiler");
_profiler = profiler;
_stopwatch = Stopwatch.StartNew();
}
public override TimeSpan? Elapsed { get; protected set; }
public override PerformanceMarkerType Type
{
get { return PerformanceMarkerType.Stopwatch; }
}
public override void Dispose()
{
_profiler.StopMarker(this);
}
public override void Stop()
{
if (_stopped)
{
return;
}
_stopwatch.Stop();
Elapsed = _stopwatch.Elapsed;
_stopped = true;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Solvers;
using System.Collections;
using TMPro;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Experimental.UI
{
/// <summary>
/// Component to manage the visuals for a Mixed Reality Keyboard Preview window.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/MixedRealityKeyboardPreview")]
public class MixedRealityKeyboardPreview : MonoBehaviour
{
[SerializeField, Tooltip("The Text Mesh Pro text field to display the preview text.")]
private TextMeshPro previewText = null;
/// <summary>
/// The Text Mesh Pro text field to display the preview text.
/// </summary>
public TextMeshPro PreviewText
{
get { return previewText; }
set
{
if (previewText != value)
{
previewText = value;
if (previewText != null)
{
previewText.text = Text;
UpdateCaret();
}
}
}
}
[SerializeField, Tooltip("The transform to move based on the preview caret.")]
private Transform previewCaret = null;
/// <summary>
/// The transform to move based on the preview caret.
/// </summary>
public Transform PreviewCaret
{
get { return previewCaret; }
set
{
if (previewCaret != value)
{
previewCaret = value;
UpdateCaret();
}
}
}
private string text = string.Empty;
/// <summary>
/// The text to display in the preview.
/// </summary>
public string Text
{
get { return text; }
set
{
if (value != text)
{
text = value;
if (PreviewText != null)
{
PreviewText.text = text;
PreviewText.ForceMeshUpdate();
}
UpdateCaret();
}
}
}
private int caretIndex = 0;
/// <summary>
/// Where the caret lies within the text.
/// </summary>
public int CaretIndex
{
get { return caretIndex; }
set
{
if (value != caretIndex)
{
caretIndex = value;
UpdateCaret();
}
}
}
/// <summary>
/// Utility method which can be used to toggle if solvers update.
/// </summary>
public void ToggleSolvers()
{
var solverHandler = GetComponent<SolverHandler>();
if (solverHandler != null)
{
solverHandler.UpdateSolvers = !solverHandler.UpdateSolvers;
if (solverHandler.UpdateSolvers)
{
ApplyShellSolverParameters();
}
}
}
#region MonoBehaviour Implementation
private void OnEnable()
{
StartCoroutine(BlinkCaret());
}
private void Start()
{
ApplyShellSolverParameters();
}
#endregion MonoBehaviour Implementation
private void UpdateCaret()
{
caretIndex = Mathf.Clamp(caretIndex, 0, string.IsNullOrEmpty(text) ? 0 : text.Length);
if (previewCaret != null)
{
if (caretIndex == 0)
{
previewCaret.transform.localPosition = Vector3.zero;
}
else
{
Vector3 localPosition;
if (caretIndex == text.Length)
{
localPosition = PreviewText.textInfo.characterInfo[caretIndex - 1].topRight;
}
else
{
localPosition = PreviewText.textInfo.characterInfo[caretIndex].topLeft;
}
localPosition.y = 0.0f;
localPosition.z = 0.0f;
var position = PreviewText.transform.TransformPoint(localPosition);
previewCaret.transform.position = position;
}
}
}
private IEnumerator BlinkCaret()
{
while (previewCaret != null)
{
previewCaret.gameObject.SetActive(!previewCaret.gameObject.activeSelf);
// The default Window's text caret blinks every 530 milliseconds.
const float blinkTime = 0.53f;
yield return new WaitForSeconds(blinkTime);
}
}
private void ApplyShellSolverParameters()
{
var solver = GetComponent<Follow>();
if (solver != null)
{
// Position the keyboard in a comfortable place with a fixed pitch relative to the forward direction.
var solverHandler = solver.GetComponent<SolverHandler>();
if (solverHandler != null)
{
var forward = solverHandler.TransformTarget != null ? solverHandler.TransformTarget.forward : Vector3.forward;
var right = solverHandler.TransformTarget != null ? solverHandler.TransformTarget.right : Vector3.right;
// Calculate the initial view pitch.
var pitchOffsetDegrees = Vector3.SignedAngle(new Vector3(forward.x, 0.0f, forward.z), forward, right);
const float shellPitchOffset = 5.0f;
pitchOffsetDegrees += shellPitchOffset;
const float shellPitchMin = -50.0f;
const float shellPitchMax = 50.0f;
pitchOffsetDegrees = Mathf.Clamp(pitchOffsetDegrees, shellPitchMin, shellPitchMax);
solver.PitchOffset = pitchOffsetDegrees;
solver.SolverUpdate();
}
}
}
}
}
| |
using LibGD;
public static class GlobalMembersGdModesAndPalettes
{
/* Exercise all scaling with all interpolation modes and ensure that
* at least, something comes back. */
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
#define X
#define Y
#define NX
#define NY
static int Main()
{
int method;
int i;
for (method = (int)gdInterpolationMethod.GD_BELL; method <= gdInterpolationMethod.GD_TRIANGLE; method++) // GD_WEIGHTED4 is unsupported.
{
gdImageStruct[] im = new gdImageStruct[2];
// printf("Method = %d\n", method);
im[0] = gd.gdImageCreateTrueColor(DefineConstants.X, DefineConstants.Y);
im[1] = gd.gdImageCreate(DefineConstants.X, DefineConstants.Y);
for (i = 0; i < 2; i++)
{
gdImageStruct result;
// printf(" %s\n", i == 0 ? "truecolor" : "palette");
gd.gdImageFilledRectangle(im[i], 0, 0, DefineConstants.X - 1, DefineConstants.Y - 1, gd.gdImageColorExactAlpha(im[i], 255, 255, 255, 0));
gd.gdImageSetInterpolationMethod(im[i], method);
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", ((int)im[i].interpolation_id == method));
result = gd.gdImageScale(im[i], DefineConstants.NX, DefineConstants.NY);
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (result != null));
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (result != im[i]));
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (result.sx == DefineConstants.NX && result.sy == DefineConstants.NY));
gd.gdImageDestroy(result);
gd.gdImageDestroy(im[i]);
} // for
} // for
return GlobalMembersGdtest.gd.gdNumFailures();
} // main
}
| |
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Collections;
using System.Text;
using System.Xml.Serialization;
using ProtoBuf;
namespace DAL
{
class Database
{
public const DataFormat SubObjectFormat = DataFormat.Group;
static Database()
{
}
}
[ProtoContract]
public class VariousFieldTypes
{
[ProtoMember(1)] public int Int32;
[ProtoMember(2)] public uint UInt32;
[ProtoMember(3)] public long Int64;
[ProtoMember(4), DefaultValue((ulong)0)] public ulong UInt64;
[ProtoMember(5)] public short Int16;
[ProtoMember(6)] public ushort UInt16;
[ProtoMember(7)] public byte Byte;
[ProtoMember(8)] public sbyte SByte;
[ProtoMember(9)] public float Single;
[ProtoMember(10)] public double Double;
[ProtoMember(11)] public decimal Decimal;
[ProtoMember(12)] public string String;
}
// these are just so I don't need to hack everything too much
class TagAttribute : Attribute
{
public TagAttribute(int i) { }
}
class TableAttribute : Attribute
{
public string Name;
}
class SerializableAttribute : Attribute
{
}
class ColumnAttribute : Attribute
{
public string DbType;
public string Storage;
public bool IsDbGenerated;
public bool IsPrimaryKey;
public AutoSync AutoSync;
}
class AssociationAttribute : Attribute
{
public string Storage;
public string Name;
public string OtherKey;
}
enum AutoSync { OnInsert }
public class OrderList : CollectionBase
{
public int Add(OrderCompat order)
{
return List.Add(order);
}
public OrderCompat this[int index]
{
get { return (OrderCompat) List[index];}
set { List[index] = value; }
}
}
public class OrderLineList : CollectionBase
{
public int Add(OrderLineCompat orderLine)
{
return List.Add(orderLine);
}
public OrderLineCompat this[int index]
{
get { return (OrderLineCompat) List[index];}
set { List[index] = value; }
}
}
[ProtoContract, Serializable]
public class DatabaseCompat
{
public const bool MASTER_GROUP = false;
[ProtoMember(1, DataFormat = Database.SubObjectFormat), Tag(1)]
[XmlArray]
public OrderList Orders;
public DatabaseCompat()
{
Orders = new OrderList();
}
}
[ProtoContract, Serializable]
public class DatabaseCompatRem
#if REMOTING
: ISerializable
#endif
#if PLAT_XMLSERIALIZER
, IXmlSerializable
#endif
{
public const bool MASTER_GROUP = false;
[ProtoMember(1, DataFormat = Database.SubObjectFormat), Tag(1)]
[XmlArray]
public OrderList Orders;
public DatabaseCompatRem()
{
Orders = new OrderList();
}
#region ISerializable Members
#if REMOTING
protected DatabaseCompatRem(SerializationInfo info, StreamingContext context)
: this()
{
Serializer.Merge<DatabaseCompatRem>(info, this);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
Serializer.Serialize <DatabaseCompatRem>(info, this);
}
#endif
#endregion
#region IXmlSerializable Members
#if PLAT_XMLSERIALIZER
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
Serializer.Merge(reader, this);
}
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
Serializer.Serialize(writer, this);
}
#endif
#endregion
}
[ProtoContract, Serializable]
public class OrderCompat
{
private int _OrderID;
private string _CustomerID;
private int _EmployeeID;
private System.DateTime _OrderDate;
private System.DateTime _RequiredDate;
private System.DateTime _ShippedDate;
private int _ShipVia;
private decimal _Freight;
private string _ShipName;
private string _ShipAddress;
private string _ShipCity;
private string _ShipRegion;
private string _ShipPostalCode;
private string _ShipCountry;
private OrderLineList _Lines = new OrderLineList();
public OrderCompat()
{
this.Initialize();
}
[Column(Storage = "_OrderID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
[ProtoMember(1), Tag(1)]
public int OrderID
{
get
{
return this._OrderID;
}
set
{
if ((this._OrderID != value))
{
//this.OnOrderIDChanging(value);
this.SendPropertyChanging();
this._OrderID = value;
this.SendPropertyChanged("OrderID");
//this.OnOrderIDChanged();
}
}
}
[Column(Storage = "_CustomerID", DbType = "NChar(5)")]
[ProtoMember(2), Tag(2)]
public string CustomerID
{
get
{
return this._CustomerID;
}
set
{
if ((this._CustomerID != value))
{
//this.OnCustomerIDChanging(value);
this.SendPropertyChanging();
this._CustomerID = value;
this.SendPropertyChanged("CustomerID");
//this.OnCustomerIDChanged();
}
}
}
[Column(Storage = "_EmployeeID", DbType = "Int")]
[ProtoMember(3), Tag(3)]
public int EmployeeID
{
get
{
return this._EmployeeID;
}
set
{
if ((this._EmployeeID != value))
{
//this.OnEmployeeIDChanging(value);
this.SendPropertyChanging();
this._EmployeeID = value;
this.SendPropertyChanged("EmployeeID");
//this.OnEmployeeIDChanged();
}
}
}
[Column(Storage = "_OrderDate", DbType = "DateTime")]
[ProtoMember(4), Tag(4)]
public System.DateTime OrderDate
{
get
{
return this._OrderDate;
}
set
{
if ((this._OrderDate != value))
{
//this.OnOrderDateChanging(value);
this.SendPropertyChanging();
this._OrderDate = value;
this.SendPropertyChanged("OrderDate");
//this.OnOrderDateChanged();
}
}
}
[Column(Storage = "_RequiredDate", DbType = "DateTime")]
[ProtoMember(5), Tag(5)]
public System.DateTime RequiredDate
{
get
{
return this._RequiredDate;
}
set
{
if ((this._RequiredDate != value))
{
// this.OnRequiredDateChanging(value);
this.SendPropertyChanging();
this._RequiredDate = value;
this.SendPropertyChanged("RequiredDate");
// this.OnRequiredDateChanged();
}
}
}
[Column(Storage = "_ShippedDate", DbType = "DateTime")]
[ProtoMember(6), Tag(6)]
public System.DateTime ShippedDate
{
get
{
return this._ShippedDate;
}
set
{
if ((this._ShippedDate != value))
{
// this.OnShippedDateChanging(value);
this.SendPropertyChanging();
this._ShippedDate = value;
this.SendPropertyChanged("ShippedDate");
// this.OnShippedDateChanged();
}
}
}
[Column(Storage = "_ShipVia", DbType = "Int")]
[ProtoMember(7), Tag(7)]
public int ShipVia
{
get
{
return this._ShipVia;
}
set
{
if ((this._ShipVia != value))
{
// this.OnShipViaChanging(value);
this.SendPropertyChanging();
this._ShipVia = value;
this.SendPropertyChanged("ShipVia");
// this.OnShipViaChanged();
}
}
}
[Column(Storage = "_Freight", DbType = "Money")]
[ProtoMember(8), Tag(8)]
public decimal Freight
{
get
{
return this._Freight;
}
set
{
if ((this._Freight != value))
{
// this.OnFreightChanging(value);
this.SendPropertyChanging();
this._Freight = value;
this.SendPropertyChanged("Freight");
// this.OnFreightChanged();
}
}
}
[Column(Storage = "_ShipName", DbType = "NVarChar(40)")]
[ProtoMember(9), Tag(9)]
public string ShipName
{
get
{
return this._ShipName;
}
set
{
if ((this._ShipName != value))
{
// this.OnShipNameChanging(value);
this.SendPropertyChanging();
this._ShipName = value;
this.SendPropertyChanged("ShipName");
// this.OnShipNameChanged();
}
}
}
[Column(Storage = "_ShipAddress", DbType = "NVarChar(60)")]
[ProtoMember(10), Tag(10)]
public string ShipAddress
{
get
{
return this._ShipAddress;
}
set
{
if ((this._ShipAddress != value))
{
// this.OnShipAddressChanging(value);
this.SendPropertyChanging();
this._ShipAddress = value;
this.SendPropertyChanged("ShipAddress");
// this.OnShipAddressChanged();
}
}
}
[Column(Storage = "_ShipCity", DbType = "NVarChar(15)")]
[ProtoMember(11), Tag(11)]
public string ShipCity
{
get
{
return this._ShipCity;
}
set
{
if ((this._ShipCity != value))
{
// this.OnShipCityChanging(value);
this.SendPropertyChanging();
this._ShipCity = value;
this.SendPropertyChanged("ShipCity");
// this.OnShipCityChanged();
}
}
}
[Column(Storage = "_ShipRegion", DbType = "NVarChar(15)")]
[ProtoMember(12), Tag(12)]
public string ShipRegion
{
get
{
return this._ShipRegion;
}
set
{
if ((this._ShipRegion != value))
{
// this.OnShipRegionChanging(value);
this.SendPropertyChanging();
this._ShipRegion = value;
this.SendPropertyChanged("ShipRegion");
// this.OnShipRegionChanged();
}
}
}
[Column(Storage = "_ShipPostalCode", DbType = "NVarChar(10)")]
[ProtoMember(13), Tag(13)]
public string ShipPostalCode
{
get
{
return this._ShipPostalCode;
}
set
{
if ((this._ShipPostalCode != value))
{
// this.OnShipPostalCodeChanging(value);
this.SendPropertyChanging();
this._ShipPostalCode = value;
this.SendPropertyChanged("ShipPostalCode");
// this.OnShipPostalCodeChanged();
}
}
}
[Column(Storage = "_ShipCountry", DbType = "NVarChar(15)")]
[ProtoMember(14), Tag(14)]
public string ShipCountry
{
get
{
return this._ShipCountry;
}
set
{
if ((this._ShipCountry != value))
{
// this.OnShipCountryChanging(value);
this.SendPropertyChanging();
this._ShipCountry = value;
this.SendPropertyChanged("ShipCountry");
// this.OnShipCountryChanged();
}
}
}
[Association(Name = "Order_Order_Detail", Storage = "_Lines", OtherKey = "OrderID")]
[ProtoMember(15), Tag(15)]
[XmlArray]
public OrderLineList Lines
{
get
{
return this._Lines;
}
set { this._Lines = value; }
}
protected virtual void SendPropertyChanging()
{
}
protected virtual void SendPropertyChanged(String propertyName)
{
}
private void attach_Lines(OrderLineCompat entity)
{
this.SendPropertyChanging();
}
private void detach_Lines(OrderLineCompat entity)
{
this.SendPropertyChanging();
}
private void Initialize()
{
// OnCreated();
}
[ProtoBeforeDeserialization]
[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnDeserializing(StreamingContext context)
{
this.Initialize();
}
[ProtoBeforeSerialization]
[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnSerializing(StreamingContext context)
{
}
[ProtoAfterSerialization]
[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnSerialized(StreamingContext context)
{
}
}
[Table(Name = "dbo.[Order Details]")]
[ProtoContract, Serializable]
public class OrderLineCompat
{
private int _OrderID;
private int _ProductID;
private decimal _UnitPrice;
private short _Quantity;
private float _Discount;
public OrderLineCompat()
{
this.Initialize();
}
[Column(Storage = "_OrderID", DbType = "Int NOT NULL", IsPrimaryKey = true)]
[ProtoMember(1), Tag(1)]
public int OrderID
{
get
{
return this._OrderID;
}
set
{
this._OrderID = value;
}
}
[Column(Storage = "_ProductID", DbType = "Int NOT NULL", IsPrimaryKey = true)]
[ProtoMember(2), Tag(2)]
public int ProductID
{
get
{
return this._ProductID;
}
set
{
if ((this._ProductID != value))
{
// this.OnProductIDChanging(value);
this.SendPropertyChanging();
this._ProductID = value;
this.SendPropertyChanged("ProductID");
// this.OnProductIDChanged();
}
}
}
[Column(Storage = "_UnitPrice", DbType = "Money NOT NULL")]
[ProtoMember(3), Tag(3)]
public decimal UnitPrice
{
get
{
return this._UnitPrice;
}
set
{
if ((this._UnitPrice != value))
{
// this.OnUnitPriceChanging(value);
this.SendPropertyChanging();
this._UnitPrice = value;
this.SendPropertyChanged("UnitPrice");
// this.OnUnitPriceChanged();
}
}
}
[Column(Storage = "_Quantity", DbType = "SmallInt NOT NULL")]
[ProtoMember(4), Tag(4)]
public short Quantity
{
get
{
return this._Quantity;
}
set
{
if ((this._Quantity != value))
{
// this.OnQuantityChanging(value);
this.SendPropertyChanging();
this._Quantity = value;
this.SendPropertyChanged("Quantity");
// this.OnQuantityChanged();
}
}
}
[Column(Storage = "_Discount", DbType = "Real NOT NULL")]
[ProtoMember(5), Tag(5)]
public float Discount
{
get
{
return this._Discount;
}
set
{
if ((this._Discount != value))
{
// this.OnDiscountChanging(value);
this.SendPropertyChanging();
this._Discount = value;
this.SendPropertyChanged("Discount");
// this.OnDiscountChanged();
}
}
}
protected virtual void SendPropertyChanging()
{
}
protected virtual void SendPropertyChanged(String propertyName)
{
}
private void Initialize()
{
// OnCreated();
}
[ProtoBeforeDeserialization]
[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnDeserializing(StreamingContext context)
{
this.Initialize();
}
}
}
| |
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Runtime.Serialization;
using System.Threading;
namespace System
{
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeTypeHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeTypeHandle(type);
}
// Returns type for interop with EE. The type is guaranteed to be non-null.
internal RuntimeType GetTypeChecked()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsInstanceOfType(RuntimeType type, object? o);
internal static Type GetTypeHelper(Type typeStart, Type[]? genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
if (genericArgs != null)
{
type = type.MakeGenericType(genericArgs);
}
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
for (int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_PTR)
type = type.MakePointerType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_BYREF)
type = type.MakeByRefType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_SZARRAY)
type = type.MakeArrayType();
else
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object? right) => left.Equals(right);
public static bool operator ==(object? left, RuntimeTypeHandle right) => right.Equals(left);
public static bool operator !=(RuntimeTypeHandle left, object? right) => !left.Equals(right);
public static bool operator !=(object? left, RuntimeTypeHandle right) => !right.Equals(left);
// This is the RuntimeType for the type
internal RuntimeType m_type;
public override int GetHashCode()
{
return m_type != null ? m_type.GetHashCode() : 0;
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeTypeHandle))
return false;
RuntimeTypeHandle handle = (RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
}
public IntPtr Value => m_type != null ? m_type.m_handle : IntPtr.Zero;
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
internal RuntimeTypeHandle(RuntimeType type)
{
m_type = type;
}
internal static bool IsTypeDefinition(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
if (!((corElemType >= CorElementType.ELEMENT_TYPE_VOID && corElemType < CorElementType.ELEMENT_TYPE_PTR) ||
corElemType == CorElementType.ELEMENT_TYPE_VALUETYPE ||
corElemType == CorElementType.ELEMENT_TYPE_CLASS ||
corElemType == CorElementType.ELEMENT_TYPE_TYPEDBYREF ||
corElemType == CorElementType.ELEMENT_TYPE_I ||
corElemType == CorElementType.ELEMENT_TYPE_U ||
corElemType == CorElementType.ELEMENT_TYPE_OBJECT))
return false;
if (HasInstantiation(type) && !IsGenericTypeDefinition(type))
return false;
return true;
}
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType >= CorElementType.ELEMENT_TYPE_BOOLEAN && corElemType <= CorElementType.ELEMENT_TYPE_R8) ||
corElemType == CorElementType.ELEMENT_TYPE_I ||
corElemType == CorElementType.ELEMENT_TYPE_U;
}
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_BYREF;
}
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_PTR;
}
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY;
}
internal static bool IsSZArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_SZARRAY;
}
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY // IsArray
|| (corElemType == CorElementType.ELEMENT_TYPE_PTR) // IsPointer
|| (corElemType == CorElementType.ELEMENT_TYPE_BYREF); // IsByRef
}
internal static IntPtr[]? CopyRuntimeTypeHandles(RuntimeTypeHandle[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].Value;
}
length = outHandles.Length;
return outHandles;
}
internal static IntPtr[]? CopyRuntimeTypeHandles(Type[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].GetTypeHandleInternal().Value;
}
length = outHandles.Length;
return outHandles;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool hasNoDefaultCtor);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object Allocate(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
internal RuntimeType GetRuntimeType()
{
return m_type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern CorElementType GetCorElementType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeModule GetModule(RuntimeType type);
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetBaseType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern TypeAttributes GetAttributes(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetElementType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetArrayRank(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
private bool _firstCall;
private RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
public bool MoveNext()
{
if (_firstCall)
{
_firstCall = false;
}
else if (_handle.Value != IntPtr.Zero)
{
RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle);
}
return !(_handle.Value == IntPtr.Zero);
}
public RuntimeMethodHandleInternal Current => _handle;
// Glue to make this work nicely with C# foreach statement
public IntroducedMethodEnumerator GetEnumerator()
{
return this;
}
}
internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type)
{
return new IntroducedMethodEnumerator(type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Type[]? GetInterfaces(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetConstraints(QCallTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
Type[]? types = null;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetConstraints(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref types));
return types!;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr GetGCHandle(QCallTypeHandle handle, GCHandleType type);
internal IntPtr GetGCHandle(GCHandleType type)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
return GetGCHandle(new QCallTypeHandle(ref nativeHandle), type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetNumVirtuals(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void VerifyInterfaceIsImplemented(QCallTypeHandle handle, QCallTypeHandle interfaceHandle);
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
RuntimeTypeHandle nativeInterfaceHandle = interfaceHandle.GetNativeHandle();
VerifyInterfaceIsImplemented(new QCallTypeHandle(ref nativeHandle), new QCallTypeHandle(ref nativeInterfaceHandle));
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern RuntimeMethodHandleInternal GetInterfaceMethodImplementation(QCallTypeHandle handle, QCallTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
internal RuntimeMethodHandleInternal GetInterfaceMethodImplementation(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
RuntimeTypeHandle nativeInterfaceHandle = interfaceHandle.GetNativeHandle();
return GetInterfaceMethodImplementation(new QCallTypeHandle(ref nativeHandle), new QCallTypeHandle(ref nativeInterfaceHandle), interfaceMethodHandle);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsInterface(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsByRefLike(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsVisible(QCallTypeHandle typeHandle);
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new QCallTypeHandle(ref type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsValueType(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ConstructName(QCallTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string? name = null;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
ConstructName(new QCallTypeHandle(ref nativeHandle), formatFlags, new StringHandleOnStack(ref name));
return name!;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeType type);
internal static MdUtf8String GetUtf8Name(RuntimeType type)
{
return new MdUtf8String(_GetUtf8Name(type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CanCastTo(RuntimeType type, RuntimeType target);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetDeclaringType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypeByName(string name, bool throwOnError, bool ignoreCase, StackCrawlMarkHandle stackMark,
ObjectHandleOnStack assemblyLoadContext,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!, loadTypeFromPartialName);
}
internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark,
AssemblyLoadContext assemblyLoadContext,
bool loadTypeFromPartialName)
{
if (string.IsNullOrEmpty(name))
{
if (throwOnError)
throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
RuntimeType? type = null;
object? keepAlive = null;
AssemblyLoadContext assemblyLoadContextStack = assemblyLoadContext;
GetTypeByName(name, throwOnError, ignoreCase,
new StackCrawlMarkHandle(ref stackMark),
ObjectHandleOnStack.Create(ref assemblyLoadContextStack),
loadTypeFromPartialName, ObjectHandleOnStack.Create(ref type), ObjectHandleOnStack.Create(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypeByNameUsingCARules(string name, QCallModule scope, ObjectHandleOnStack type);
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(null, nameof(name));
RuntimeType type = null!;
GetTypeByNameUsingCARules(name, new QCallModule(ref scope), ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void GetInstantiation(QCallTypeHandle type, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray);
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetInstantiation(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref types), Interop.BOOL.TRUE);
return types;
}
internal Type[] GetInstantiationPublic()
{
Type[] types = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetInstantiation(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref types), Interop.BOOL.FALSE);
return types;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void Instantiate(QCallTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
internal RuntimeType Instantiate(Type[]? inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
IntPtr[]? instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
Instantiate(new QCallTypeHandle(ref nativeHandle), pInst, instCount, ObjectHandleOnStack.Create(ref type));
GC.KeepAlive(inst);
return type;
}
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeArray(QCallTypeHandle handle, int rank, ObjectHandleOnStack type);
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeArray(new QCallTypeHandle(ref nativeHandle), rank, ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeSZArray(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeSZArray()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeSZArray(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeByRef(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeByRef()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeByRef(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakePointer(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakePointer()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakePointer(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL IsCollectible(QCallTypeHandle handle);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool HasInstantiation(RuntimeType type);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGenericTypeDefinition(QCallTypeHandle type, ObjectHandleOnStack retType);
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType))
{
RuntimeTypeHandle nativeHandle = retType.GetTypeHandleInternal();
GetGenericTypeDefinition(new QCallTypeHandle(ref nativeHandle), ObjectHandleOnStack.Create(ref retType));
}
return retType;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericTypeDefinition(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericVariable(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetGenericVariableIndex(RuntimeType type);
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
return GetGenericVariableIndex(type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool ContainsGenericVariables(RuntimeType handle);
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[]? typeContext, RuntimeType[]? methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
IntPtr[]? typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[]? methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
GC.KeepAlive(typeContext);
GC.KeepAlive(methodContext);
return result;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr _GetMetadataImport(RuntimeType type);
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
#if FEATURE_TYPEEQUIVALENCE
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsEquivalentTo(RuntimeType rtType1, RuntimeType rtType2);
#endif // FEATURE_TYPEEQUIVALENCE
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved
// across the lifetime of the RuntimeMethodHandleInternal instance
// 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure
// When in doubt, do not use.
internal struct RuntimeMethodHandleInternal
{
internal static RuntimeMethodHandleInternal EmptyHandle => new RuntimeMethodHandleInternal();
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value => m_handle;
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal class RuntimeMethodInfoStub : IRuntimeMethodInfo
{
public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = methodHandleValue;
}
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable CA1823, 414
private object m_a = null!;
private object m_b = null!;
private object m_c = null!;
private object m_d = null!;
private object m_e = null!;
private object m_f = null!;
private object m_g = null!;
#pragma warning restore CA1823, 414
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => m_value;
}
internal interface IRuntimeMethodInfo
{
RuntimeMethodHandleInternal Value
{
get;
}
}
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return method;
}
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
}
internal IRuntimeMethodInfo GetMethodInfo()
{
return m_value;
}
// Used by EE
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public IntPtr Value => m_value != null ? m_value.Value.Value : IntPtr.Zero;
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
RuntimeMethodHandle handle = (RuntimeMethodHandle)obj;
return handle.Value == Value;
}
public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right) => left.Equals(right);
public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right) => !left.Equals(right);
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
}
internal bool IsNullHandle()
{
return m_value == null;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value!).Value);
GC.KeepAlive(m_value);
return ptr;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL GetIsCollectible(RuntimeMethodHandleInternal handle);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL IsCAVisibleFromDecoratedType(
QCallTypeHandle attrTypeHandle,
RuntimeMethodHandleInternal attrCtor,
QCallTypeHandle sourceTypeHandle,
QCallModule sourceModule);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo? _GetCurrentMethod(ref StackCrawlMark stackMark);
internal static IRuntimeMethodInfo? GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
GC.KeepAlive(method);
return retVal;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ConstructInstantiation(RuntimeMethodHandleInternal method, TypeNameFormatFlags format, StringHandleOnStack retString);
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string? name = null;
IRuntimeMethodInfo methodInfo = EnsureNonNullMethodInfo(method);
ConstructInstantiation(methodInfo.Value, format, new StringHandleOnStack(ref name));
GC.KeepAlive(methodInfo);
return name!;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
GC.KeepAlive(method);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetSlot(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
Debug.Assert(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
return slot;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetMethodDef(IRuntimeMethodInfo method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern string GetName(RuntimeMethodHandleInternal method);
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
GC.KeepAlive(method);
return name;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeMethodHandleInternal method);
internal static MdUtf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new MdUtf8String(_GetUtf8Name(method));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object InvokeMethod(object? target, object[]? arguments, Signature sig, bool constructor, bool wrapExceptions);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, ObjectHandleOnStack.Create(ref types), Interop.BOOL.TRUE);
GC.KeepAlive(method);
return types;
}
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(method, ObjectHandleOnStack.Create(ref types), Interop.BOOL.TRUE);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, ObjectHandleOnStack.Create(ref types), Interop.BOOL.FALSE);
GC.KeepAlive(method);
return types;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[]? methodInstantiation);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypicalMethodDefinition(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
{
GetTypicalMethodDefinition(method.Value, ObjectHandleOnStack.Create(ref method));
GC.KeepAlive(method);
}
return method;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetGenericParameterCount(RuntimeMethodHandleInternal method);
internal static int GetGenericParameterCount(IRuntimeMethodInfo method) => GetGenericParameterCount(method.Value);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void StripMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
StripMethodInstantiation(method.Value, ObjectHandleOnStack.Create(ref strippedMethod));
GC.KeepAlive(method);
return strippedMethod;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsDynamicMethod(RuntimeMethodHandleInternal method);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void Destroy(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Resolver GetResolver(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodBody? GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsConstructor(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved
// across the lifetime of the RuntimeFieldHandleInternal instance
// 3. When another object is used to keep the RuntimeFieldHandleInternal alive.
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value => m_handle;
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal interface IRuntimeFieldInfo
{
RuntimeFieldHandleInternal Value
{
get;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 414
private object m_keepalive = null!;
private object m_c = null!;
private object m_d = null!;
private int m_b;
private object m_e = null!;
private RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 414
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value => m_fieldHandle;
}
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeFieldHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeFieldHandle(field);
}
private IRuntimeFieldInfo m_ptr;
internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo)
{
m_ptr = fieldInfo;
}
internal IRuntimeFieldInfo GetRuntimeFieldInfo()
{
return m_ptr;
}
public IntPtr Value => m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
RuntimeFieldHandle handle = (RuntimeFieldHandle)obj;
return handle.Value == Value;
}
public bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
}
public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right) => left.Equals(right);
public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right) => !left.Equals(right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern string GetName(RtFieldInfo field);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static MdUtf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new MdUtf8String(_GetUtf8Name(field)); }
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
GC.KeepAlive(field);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object? GetValue(RtFieldInfo field, object? instance, RuntimeType fieldType, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object? GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType? contextType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, object? obj, object? value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object? value, RuntimeType? contextType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
#region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
#endregion
private static ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
#region Private Data Members
private RuntimeModule m_ptr;
#endregion
#region Constructor
internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
#endregion
#region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
public override bool Equals(object? obj)
{
if (!(obj is ModuleHandle))
return false;
ModuleHandle handle = (ModuleHandle)obj;
return handle.m_ptr == m_ptr;
}
public bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
}
public static bool operator ==(ModuleHandle left, ModuleHandle right) => left.Equals(right);
public static bool operator !=(ModuleHandle left, ModuleHandle right) => !left.Equals(right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(System.Reflection.Emit.DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
private static void ValidateModulePointer(RuntimeModule module)
{
// Make sure we have a valid Module to resolve against.
if (module == null)
throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle);
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
RuntimeType type = null!;
ResolveType(new QCallModule(ref module), typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, ObjectHandleOnStack.Create(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return type;
}
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ResolveType(QCallModule module,
int typeToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack type);
// SQL-CLR LKG9 Compiler dependency
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return retVal;
}
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[]? typeInstantiationContext, int typeInstCount, IntPtr[]? methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
return ResolveMethod(new QCallModule(ref module), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount);
}
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern RuntimeMethodHandleInternal ResolveMethod(QCallModule module,
int methodToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
IRuntimeFieldInfo field = null!;
ResolveField(new QCallModule(ref module), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, ObjectHandleOnStack.Create(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return field;
}
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ResolveField(QCallModule module,
int fieldToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack retField);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern Interop.BOOL _ContainsPropertyMatchingHash(QCallModule module, int propertyToken, uint hash);
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(new QCallModule(ref module), propertyToken, hash) != Interop.BOOL.FALSE;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void GetModuleType(QCallModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null!;
GetModuleType(new QCallModule(ref module), ObjectHandleOnStack.Create(ref type));
return type;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetPEKind(QCallModule handle, int* peKind, int* machine);
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
GetPEKind(new QCallModule(ref module), &lKind, &lMachine);
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion => GetMDStreamVersion(GetRuntimeModule().GetNativeHandle());
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr _GetMetadataImport(RuntimeModule module);
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
#endregion
}
internal unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion
#region FCalls
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo? methodHandle, RuntimeType? declaringType);
#endregion
#region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
internal RuntimeType[] m_arguments = null!;
internal RuntimeType m_declaringType = null!; // seems not used
internal RuntimeType m_returnTypeORfieldType = null!;
internal object? m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
#endregion
#region Constructors
public Signature(
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
CallingConventions callingConvention)
{
m_pMethod = method.Value;
m_arguments = arguments;
m_returnTypeORfieldType = returnType;
m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention;
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
#endregion
#region Internal Members
internal CallingConventions CallingConvention => (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags;
internal RuntimeType[] Arguments => m_arguments;
internal RuntimeType ReturnType => m_returnTypeORfieldType;
internal RuntimeType FieldType => m_returnTypeORfieldType;
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
}
internal abstract class Resolver
{
internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
internal int ClassTokenOrFilterOffset;
}
// ILHeader info
internal abstract RuntimeType? GetJitContext(out int securityControlFlags);
internal abstract byte[] GetCodeInfo(out int stackSize, out int initLocals, out int EHCount);
internal abstract byte[] GetLocalsSignature();
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract byte[]? GetRawEHInfo();
// token resolution
internal abstract string? GetStringLiteral(int token);
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[]? ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
}
}
| |
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 Half with 3 columns and 2 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct hmat3x2 : IEnumerable<Half>, IEquatable<hmat3x2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public Half m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public Half m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public Half m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public Half m11;
/// <summary>
/// Column 2, Rows 0
/// </summary>
public Half m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
public Half m21;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public hmat3x2(Half m00, Half m01, Half m10, Half m11, Half m20, Half m21)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.m20 = m20;
this.m21 = m21;
}
/// <summary>
/// Constructs this matrix from a hmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = Half.Zero;
this.m21 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a hmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a hmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = Half.Zero;
this.m21 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a hmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a hmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = Half.Zero;
this.m21 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a hmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hvec2 c0, hvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = Half.Zero;
this.m21 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat3x2(hvec2 c0, hvec2 c1, hvec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = c2.x;
this.m21 = c2.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public Half[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public Half[] Values1D => new[] { m00, m01, m10, m11, m20, m21 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public hvec2 Column0
{
get
{
return new hvec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public hvec2 Column1
{
get
{
return new hvec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public hvec2 Column2
{
get
{
return new hvec2(m20, m21);
}
set
{
m20 = value.x;
m21 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public hvec3 Row0
{
get
{
return new hvec3(m00, m10, m20);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public hvec3 Row1
{
get
{
return new hvec3(m01, m11, m21);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static hmat3x2 Zero { get; } = new hmat3x2(Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static hmat3x2 Ones { get; } = new hmat3x2(Half.One, Half.One, Half.One, Half.One, Half.One, Half.One);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static hmat3x2 Identity { get; } = new hmat3x2(Half.One, Half.Zero, Half.Zero, Half.One, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static hmat3x2 AllMaxValue { get; } = new hmat3x2(Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static hmat3x2 DiagonalMaxValue { get; } = new hmat3x2(Half.MaxValue, Half.Zero, Half.Zero, Half.MaxValue, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static hmat3x2 AllMinValue { get; } = new hmat3x2(Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static hmat3x2 DiagonalMinValue { get; } = new hmat3x2(Half.MinValue, Half.Zero, Half.Zero, Half.MinValue, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static hmat3x2 AllEpsilon { get; } = new hmat3x2(Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static hmat3x2 DiagonalEpsilon { get; } = new hmat3x2(Half.Epsilon, Half.Zero, Half.Zero, Half.Epsilon, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static hmat3x2 AllNaN { get; } = new hmat3x2(Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static hmat3x2 DiagonalNaN { get; } = new hmat3x2(Half.NaN, Half.Zero, Half.Zero, Half.NaN, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static hmat3x2 AllNegativeInfinity { get; } = new hmat3x2(Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static hmat3x2 DiagonalNegativeInfinity { get; } = new hmat3x2(Half.NegativeInfinity, Half.Zero, Half.Zero, Half.NegativeInfinity, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static hmat3x2 AllPositiveInfinity { get; } = new hmat3x2(Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static hmat3x2 DiagonalPositiveInfinity { get; } = new hmat3x2(Half.PositiveInfinity, Half.Zero, Half.Zero, Half.PositiveInfinity, Half.Zero, Half.Zero);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<Half> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
yield return m20;
yield return m21;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (3 x 2 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public Half this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
case 4: return m20;
case 5: return m21;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
case 4: this.m20 = value; break;
case 5: this.m21 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public Half this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(hmat3x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m10.Equals(rhs.m10)) && ((m11.Equals(rhs.m11) && m20.Equals(rhs.m20)) && m21.Equals(rhs.m21)));
/// <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 hmat3x2 && Equals((hmat3x2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(hmat3x2 lhs, hmat3x2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(hmat3x2 lhs, hmat3x2 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) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public hmat2x3 Transposed => new hmat2x3(m00, m10, m20, m01, m11, m21);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public Half MinElement => Half.Min(Half.Min(Half.Min(Half.Min(Half.Min(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public Half MaxElement => Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public Half Sum => (((m00 + m01) + m10) + ((m11 + m20) + m21));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Half.Abs(m00) + Half.Abs(m01)) + Half.Abs(m10)) + ((Half.Abs(m11) + Half.Abs(m20)) + Half.Abs(m21)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public Half NormMax => Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Abs(m00), Half.Abs(m01)), Half.Abs(m10)), Half.Abs(m11)), Half.Abs(m20)), Half.Abs(m21));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Half.Abs(m00), p) + Math.Pow((double)Half.Abs(m01), p)) + Math.Pow((double)Half.Abs(m10), p)) + ((Math.Pow((double)Half.Abs(m11), p) + Math.Pow((double)Half.Abs(m20), p)) + Math.Pow((double)Half.Abs(m21), p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication hmat3x2 * hmat2x3 -> hmat2.
/// </summary>
public static hmat2 operator*(hmat3x2 lhs, hmat2x3 rhs) => new hmat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12));
/// <summary>
/// Executes a matrix-matrix-multiplication hmat3x2 * hmat3 -> hmat3x2.
/// </summary>
public static hmat3x2 operator*(hmat3x2 lhs, hmat3 rhs) => new hmat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22));
/// <summary>
/// Executes a matrix-matrix-multiplication hmat3x2 * hmat4x3 -> hmat4x2.
/// </summary>
public static hmat4x2 operator*(hmat3x2 lhs, hmat4x3 rhs) => new hmat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static hvec2 operator*(hmat3x2 m, hvec3 v) => new hvec2(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static hmat3x2 CompMul(hmat3x2 A, hmat3x2 B) => new hmat3x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static hmat3x2 CompDiv(hmat3x2 A, hmat3x2 B) => new hmat3x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static hmat3x2 CompAdd(hmat3x2 A, hmat3x2 B) => new hmat3x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static hmat3x2 CompSub(hmat3x2 A, hmat3x2 B) => new hmat3x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static hmat3x2 operator+(hmat3x2 lhs, hmat3x2 rhs) => new hmat3x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static hmat3x2 operator+(hmat3x2 lhs, Half rhs) => new hmat3x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static hmat3x2 operator+(Half lhs, hmat3x2 rhs) => new hmat3x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static hmat3x2 operator-(hmat3x2 lhs, hmat3x2 rhs) => new hmat3x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static hmat3x2 operator-(hmat3x2 lhs, Half rhs) => new hmat3x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static hmat3x2 operator-(Half lhs, hmat3x2 rhs) => new hmat3x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static hmat3x2 operator/(hmat3x2 lhs, Half rhs) => new hmat3x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static hmat3x2 operator/(Half lhs, hmat3x2 rhs) => new hmat3x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static hmat3x2 operator*(hmat3x2 lhs, Half rhs) => new hmat3x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static hmat3x2 operator*(Half lhs, hmat3x2 rhs) => new hmat3x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat3x2 operator<(hmat3x2 lhs, hmat3x2 rhs) => new bmat3x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(hmat3x2 lhs, Half rhs) => new bmat3x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(Half lhs, hmat3x2 rhs) => new bmat3x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat3x2 operator<=(hmat3x2 lhs, hmat3x2 rhs) => new bmat3x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(hmat3x2 lhs, Half rhs) => new bmat3x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(Half lhs, hmat3x2 rhs) => new bmat3x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat3x2 operator>(hmat3x2 lhs, hmat3x2 rhs) => new bmat3x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(hmat3x2 lhs, Half rhs) => new bmat3x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(Half lhs, hmat3x2 rhs) => new bmat3x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat3x2 operator>=(hmat3x2 lhs, hmat3x2 rhs) => new bmat3x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(hmat3x2 lhs, Half rhs) => new bmat3x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(Half lhs, hmat3x2 rhs) => new bmat3x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21);
}
}
| |
/*
-----------------------------------------------------------------------------
This source file is part of ViewpointComputationLib (a viewpoint computation library)
For more info on the project, contact Roberto Ranon at roberto.ranon@uniud.it.
Copyright (c) 2013- University of Udine, Italy - http://hcilab.uniud.it
-----------------------------------------------------------------------------
CLCameraMan.cs: file defining classes for representing a camera man, i.e. an object that is
able to evaluate how much a specific unity camera satisfies a VC problem specification (satisfaction function +
camera parameter bounds).
-----------------------------------------------------------------------------
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
/// <summary>
/// Abstract class defining the camera man. Subclasses then define specific camera men based on the representation
/// used for the camera parameters (e.g. position + lookAt point, or spherical coordinates, or else).
/// </summary>
public abstract class CLCameraMan
{
/// <summary>
/// Associated unity camera (for projections, etc.)
/// </summary>
public Camera unityCamera;
/// <summary>
/// The camera parameters domain, instantiate depending on the specific camera representation.
/// </summary>
public VCCameraDomain cameraDomain;
/// <summary>
/// List of visual properties, the first one is the objective function
/// </summary>
public List<CLVisualProperty> properties = new List<CLVisualProperty>();
/// <summary>
/// List of targets mentioned by the properties
/// </summary>
public List<CLTarget> targets = new List<CLTarget>();
/// <summary>
/// a special CLTarget, which contains all targets renderables, colliders, and properties
/// </summary>
public CLTarget allTargets = new CLTarget();
/// <summary>
/// Clip rectangle of the camera (defaults to entire viewport).
/// </summary>
public Rectangle clipRectangle = new Rectangle (0.0f, 1.0f, 0.0f, 1.0f);
/// <summary>
/// Sets the VC visual properties.
/// </summary>
/// <param name='propertyList'>List of visual properties. The first one is the problem objective function.</param>
public void SetSpecification (List<CLVisualProperty> propertyList)
{
properties.Clear();
targets.Clear();
targets.AddRange (propertyList[0].targets);
properties.AddRange (propertyList);
foreach (CLTarget t in targets) {
t.groundProperties.Clear();
}
// finds associations between targets and ground properties
foreach (CLVisualProperty p in propertyList) {
if ( p is CLGroundProperty ) {
CLGroundProperty gp = (CLGroundProperty) p;
foreach ( CLTarget t in gp.targets ) {
t.groundProperties.Add ( gp );
}
}
}
}
/// <summary>
/// Sets camera parameters using the provided parameters, and computes and returns the satisfaction of the objective function.
/// </summary>
/// <returns>The satisfaction.</returns>
/// <param name="cameraParams">Camera parameters.</param>
/// <param name="lazyThreshold">Lazy threshold. Evaluation stops and returns -1 when it realizes it cannot reach lazyThreshold.</param>
public float EvaluateSatisfaction (float[] cameraParams, float lazyThreshold) {
this.updateCamera (cameraParams);
return EvaluateSatisfaction (lazyThreshold);
}
/// <summary>
/// Computes and returns the satisfaction of the objective function.
/// </summary>
/// <returns>The satisfaction.</returns>
/// <param name="lazyThreshold">Lazy threshold. Evaluation stops and returns -1 when it realizes it cannot reach lazyThreshold.</param>
public float EvaluateSatisfaction (float lazyThreshold=-0.01f) {
foreach (CLVisualProperty p in properties) {
p.evaluated = false;
}
foreach (CLTarget t in targets) {
t.rendered = false;
}
// performs recursive evaluation of all properties
return properties[0].EvaluateSatisfaction( this, lazyThreshold );
}
/// <summary>
/// Updates the camera with the provided parameters
/// </summary>
/// <param name="cameraParams">Camera parameters.</param>
public abstract void updateCamera (float[] cameraParams);
/// <summary>
/// Updates the properties targets, computing and setting each target AABB, and returning the AABB of all targets.
/// </summary>
/// <returns>The AABB of the targets AABBs</returns>
public Bounds UpdateTargets ()
{
Bounds startingAABB = targets [0].UpdateBounds ();
targets [0].UpdateVisibilityInfo (false);
Bounds allBounds = new Bounds (startingAABB.center, startingAABB.size);
foreach (CLTarget t in targets.Skip(1 )) {
allBounds.Encapsulate( t.UpdateBounds() );
t.UpdateVisibilityInfo (false);
}
allTargets.boundingBox = allBounds;
return allBounds;
}
/// <summary>
/// checks if the provided viewpoint is in the search space
/// </summary>
/// <returns><c>true</c>, if it is in search space, <c>false</c> otherwise.</returns>
/// <param name="cameraParams">Viewpoint parameters</param>
public bool InSearchSpace (float[] cameraParams) {
return cameraDomain.InSearchSpace (cameraParams);
}
/// <summary>
/// Returns a random viewpoint in search space, expressed as parameters (the value depends on the specific CLCameraMan subclass).
/// If smart = true, the viewpoint is randomly computed according to the current properties (i.e. with more probability where
/// the properties are more likely to be satisfied)
/// </summary>
/// <param name="dimension">dimension of the viewpoint to be generated</param>
/// <param name="smart">whether to use smart initialization or not</param>
/// <param name="t">Target provided for smart initialization or not. If it is provided, we initialize according to
/// that target properties. If it is null, we instead initialize according to all targets </param>
/// <returns>The candidate.</returns>
public abstract float[] ComputeRandomViewpoint ( int dimension, bool smart = false, CLTarget t = null);
/// <summary>
/// Returns the range between each camera parameter. The meaning of parameters depend on the specific CLCameraMan subclass */
/// </summary>
/// <param name="dimension">candidate dimension</param>
public float[] GetParametersRange (int dimension) {
return cameraDomain.GetParametersRange (dimension);
}
/// <summary>
/// Returns the minimum value of each camera parameter. The meaning of parameters depend on the specific CLCameraMan subclass */
/// </summary>
/// <param name="dimension">candidate dimension</param>
public float[] GetMinCameraParameters(int dimension) {
return cameraDomain.GetMinParameters (dimension);
}
/// <summary>
/// Returns the maximum value of each camera parameter. The meaning of parameters depend on the specific CLCameraMan subclass */
/// </summary>
/// <param name="dimension">candidate dimension</param>
public float[] GetMaxCameraParameters(int dimension) {
return cameraDomain.GetMaxParameters (dimension);
}
/// <summary>
/// Computes the YFOV from focal lenght.
/// </summary>
/// <returns>The YFOV from focal lenght.</returns>
/// <param name="filmWidthInMM">Film width in millimiters (e.g. 35 mm).</param>
/// <param name="focalLenght">Focal lenght.</param>
public float ComputeYFOVFromFocalLenght( float focalLength, float filmWidthInMM = 35.0f ) {
float fovX = 2.0f * Mathf.Atan2(0.5f * filmWidthInMM, focalLength);
float fovY = 2.0f * Mathf.Atan( Mathf.Tan( fovX / 2.0f ) / unityCamera.aspect );
return Mathf.Rad2Deg * fovY;
}
/// <summary>
/// finds max camera forward translation that keeps the target (allTarget) inside viewport with respect to x and y dimensions
/// (take the min of the two for ensuring the target stays inside). border diminishes the YFOV used to make computations, effectively
/// ensuring we stay clear of the viewport border by a certain percentage amount. WARNING: does not check for collisions of camera with objects
/// </summary>
/// <returns>The max zoom in viewport.</returns>
/// <param name="border">Border.</param>
public Vector2 FindMaxZoomInViewport ( float border=0.0f ) {
float vFOVrad = Mathf.Deg2Rad * unityCamera.fieldOfView * (1f - 2f*border);
float cameraHeightAt1 = Mathf.Tan(vFOVrad * 0.5f);
float hFOVrad = Mathf.Atan(cameraHeightAt1 * unityCamera.aspect) * 2f;
float cameraWidthAt1 = Mathf.Tan(hFOVrad * 0.5f);
allTargets.Render (this, true);
Vector2 result = new Vector2 (float.MaxValue, float.MaxValue);
foreach (Vector3 v in allTargets.visibleBBVertices) {
// find coordinates in camera space (v is in world space)
Vector3 v_Camera = unityCamera.transform.InverseTransformPoint( v ); // now v is in camera space
result.y = Mathf.Min (result.y, v_Camera.z - Mathf.Abs(v_Camera.y / cameraHeightAt1));
result.x = Mathf.Min (result.x, v_Camera.z - Mathf.Abs(v_Camera.x / cameraWidthAt1));
}
return result;
}
}
/// <summary>
/// A CLookAtCameraMan uses position, look at point, roll and YFOV to represent the camera configuration.
/// </summary>
public class CLLookAtCameraMan : CLCameraMan
{
/// <summary>
/// Blocks camera orientation to the one that the internal camera has initially
/// </summary>
public bool blockOrientation = false;
/// <summary>
/// Updates the camera with the provided parameters
/// </summary>
/// <param name='parameters'>
/// array of 8 floats: position.x, position.y, position.z, lookAtPoint.x, lookAtPoint.y, lookAtPoint.z, roll angle, vertical fov angle (degrees)
/// </param>
public override void updateCamera (float[] parameters)
{
this.unityCamera.transform.position = new Vector3 (parameters [0], parameters [1], parameters [2]);
//this.unityCamera.transform.rotation = Quaternion.identity;
if (!blockOrientation)
this.unityCamera.transform.LookAt (new Vector3 (parameters [3], parameters [4], parameters [5]));
//this.unityCamera.ResetWorldToCameraMatrix();
if (parameters.Length > 6) {
if (! Mathf.Approximately (parameters [6], 0.0f))
unityCamera.transform.Rotate (parameters [6], 0.0f, 0.0f);
}
// vertical FOV in degrees
if ( parameters.Length > 7 )
unityCamera.fieldOfView = parameters[7];
}
/// <summary>
/// Returns a random viewpoint in search space
/// </summary>
/// <returns>The viewpoint, expressed as an array of float parameters</returns>
/// <param name="dimension">viewpoint dimension (3 for just position, 6 for position + lookAt, etc)</param>
/// <param name="smart">whether to use smart random generation or not</param>
/// <param name="t">target to use in case of smart initialization</param>
public override float[] ComputeRandomViewpoint ( int dimension, bool smart = false, CLTarget t = null)
{
float[] candidatePos = cameraDomain.ComputeRandomViewpoint (dimension);
if (smart) {
// in this case we use some of the provided target properties to control randomness, i.e. size and orientation, if present.
// Look-at point is set randomly inside target AABB. If a target is not provided, we use all targets as a target
// XXX Warning: we are not handling cases where e.g. the search space is only one or two-dimensional ...
bool useOrientation = true;
if ( t==null ) {
t = allTargets;
useOrientation = false;
}
// this will give up after n tries, so we default to random initialization if there are problems
Vector3 pos = t.GenerateRandomSatisfyingPosition ( this, useOrientation );
candidatePos [0] = pos.x;
candidatePos [1] = pos.y;
candidatePos [2] = pos.z;
candidatePos [3] = UnityEngine.Random.Range( t.boundingBox.min.x, t.boundingBox.max.x );
candidatePos [4] = UnityEngine.Random.Range( t.boundingBox.min.y, t.boundingBox.max.y );
candidatePos [5] = UnityEngine.Random.Range( t.boundingBox.min.z, t.boundingBox.max.z );
}
return candidatePos;
}
}
/// <summary>
/// A CLOrbitCameraMan uses pivot, distance, theta, phi, roll and YFOV to represent the camera configuration.
/// </summary>
public class CLOrbitCameraMan : CLCameraMan
{
/// <summary>
/// pivot of the Camera
/// </summary>
public Vector3 pivot;
/// <summary>
/// Updates the camera with the provided parameters
/// </summary>
/// <param name='parameters'>
/// array of 5 floats: distance, theta, phi, roll angle, vertical fov angle (degrees)
/// </param>
public override void updateCamera (float[] parameters)
{
float x = parameters[0] * Mathf.Sin (Mathf.Deg2Rad*parameters[1]) * Mathf.Cos (Mathf.Deg2Rad*parameters[2]);
float z = -parameters[0] * Mathf.Sin (Mathf.Deg2Rad*parameters[1]) * Mathf.Sin (Mathf.Deg2Rad*parameters[2]);
float y = parameters[0] * Mathf.Cos (Mathf.Deg2Rad*parameters[1]);
this.unityCamera.transform.position = new Vector3 (x,y,z) + pivot;
//this.unityCamera.transform.rotation = Quaternion.identity;
this.unityCamera.transform.LookAt (pivot);
//this.unityCamera.ResetWorldToCameraMatrix();
if ( ! Mathf.Approximately(parameters[3], 0.0f ))
unityCamera.transform.Rotate( parameters[3], 0.0f, 0.0f );
// vertical FOV in degrees
unityCamera.fieldOfView = parameters[4];
}
/// <summary>
/// Returns a random viewpoint in search space
/// </summary>
/// <returns>The viewpoint, expressed as an array of float parameters</returns>
/// <param name="dimension">viewpoint dimension (3 for just position, 6 for position + lookAt, etc)</param>
/// <param name="smart">whether to use smart random generation or not</param>
/// <param name="t">target to use in case of smart initialization</param>
public override float[] ComputeRandomViewpoint ( int dimension, bool smart = false, CLTarget t = null)
{
float[] candidatePos = cameraDomain.ComputeRandomViewpoint (dimension);
return candidatePos;
}
// given a property p whose sat>minSat for the current vcCam position and orientation, find max rotation interval [-v0,v1] such
// that rotating around cameraPivot will keep satisfaction above minSat (assumes that satisfaction of
// property is monotonic in the interval maxAngles
public Vector2 FindMaxYRotation( CLVisualProperty property, float minSat, Vector2 maxAngles, int steps = 10 ) {
// we will initially try to go from rotation 0 to maxAngles[1]; then, we go from 0 to maxAngles[0] (which should then
// be negative. For each interval, we rotate maxSteps times. As soon as the property is not enough satisfied for
// two consecutive steps, we stop.
Vector2 result = new Vector2 (0f, 0f);
bool satisfied = true;
float increment = (maxAngles [1] - maxAngles [0]) / steps;
float angle = 0f;
Vector3 startingPos = unityCamera.transform.position;
Quaternion startingOr = unityCamera.transform.rotation;
while (satisfied && angle < maxAngles [1]) {
angle += increment;
unityCamera.transform.position = startingPos;
unityCamera.transform.rotation = startingOr;
unityCamera.transform.RotateAround (pivot, Vector3.up, increment);
float sat = property.EvaluateSatisfaction( this, true);
if (sat < minSat) {
satisfied = false;
}
}
result [1] = angle-increment;
satisfied = true;
angle = 0f;
while (satisfied && angle > maxAngles [0]) {
angle -= increment;
unityCamera.transform.position = startingPos;
unityCamera.transform.rotation = startingOr;
unityCamera.transform.RotateAround (pivot, Vector3.up, increment);
float sat = property.EvaluateSatisfaction (this, true);
if (sat < minSat) {
satisfied = false;
}
}
result [0] = angle+increment;
return result;
}
}
/// <summary>
/// Abstract class defining the domain of a VC problem. Subclasses then define specific representations
/// depending on how we represent camera parameters (e.g. position + lookAt point, or spherical coordinates, or else).
/// </summary>
public abstract class VCCameraDomain
{
/// <summary>
/// Camera YFOV bounds
/// </summary>
public Vector2 yFOVBounds;
/// <summary>
/// Camera roll bounds of the VC problem
/// </summary>
public Vector2 rollBounds;
/// <summary>
/// Minimum distance the camera should have wrt any geometry (any collider). If equal to 0.0, no check is performed.
/// </summary>
public float minGeometryDistance = 0.0f;
/// <summary>
/// bitmask of Unity layers to be excluded when checking minimum geometry distance.
/// </summary>
public int layersToExclude;
/// <summary>
/// The ground y value. If
/// </summary>
public float ground = float.MinValue;
/// <summary>
/// checks if the provided viewpoint is in the problem domain
/// </summary>
/// <returns><c>true</c>, if it is in search space, <c>false</c> otherwise.</returns>
/// <param name="cameraParams">viewpoint parameters (depend on specific viewpoint representation)</param>
public virtual bool InSearchSpace (float[] cameraParams) {
// check camera above ground
if (cameraParams [1] > ground) {
if (minGeometryDistance > 0.000001f) {
return !(Physics.CheckSphere (new Vector3 (cameraParams [0], cameraParams [1], cameraParams [2]), minGeometryDistance, ~layersToExclude));
} else
return true;
}
return false;
}
/// <summary>
/// Computes a random viewpoint inside the domain.
/// </summary>
/// <returns>The random viewpoint, according to the specific viewpoint representation</returns>
/// <param name="dimension">dimensions of the viewpoint (i.e. 3 for just position)</param>
public abstract float[] ComputeRandomViewpoint (int dimension);
/// <summary>
/// Returns the range between each camera parameter. */
/// </summary>
/// <returns>The parameters range.</returns>
/// <param name="dimension">parameters dimension.</param>
public abstract float[] GetParametersRange (int dimension);
/// <summary>
/// Gets the minimum parameters value in the domain
/// </summary>
/// <returns>The minimum parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public abstract float[] GetMinParameters( int dimension);
/// <summary>
/// Gets the max parameters value in the domain
/// </summary>
/// <returns>The max parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public abstract float[] GetMaxParameters( int dimension);
}
/// <summary>
/// Class defining the domain of a VC problem when camera parameters are expressed as position, lookAt point,
/// roll, YFOV
/// </summary>
public class VCLookAtProblemDomain : VCCameraDomain
{
/// <summary>
/// Position bounds of the VC problem
/// </summary>
public Bounds positionBounds;
/// <summary>
/// Look-at bounds of the VC problem
/// </summary>
public Bounds lookAtBounds;
/// <summary>
/// checks if the provided viewpoint is in the problem domain
/// </summary>
/// <returns>true</returns>, if it is in search space, <c>false</c> otherwise.</returns>
/// <param name="cameraParams">viewpoint parameters</param>
public override bool InSearchSpace (float[] cameraParams)
{
bool inSpace = base.InSearchSpace( cameraParams );
if (cameraParams.Length >= 3) { // i.e. we have just camera position
inSpace = positionBounds.Contains (new Vector3 (cameraParams [0], cameraParams [1], cameraParams [2]));
if (!inSpace)
return false;
}
if (cameraParams.Length >= 6) { // i.e. we have also look at point
inSpace = inSpace && lookAtBounds.Contains (new Vector3 (cameraParams [3], cameraParams [4], cameraParams [5]));
if (!inSpace)
return false;
}
if (cameraParams.Length >= 7) { // i.e. we have also roll
inSpace = inSpace && (rollBounds.x <= cameraParams [6]) && (cameraParams [6] <= rollBounds.y);
if (!inSpace)
return false;
}
if (cameraParams.Length == 8) { // i.e. we have also fov
inSpace = inSpace && (yFOVBounds.x <= cameraParams [7]) && (cameraParams [7] <= yFOVBounds.y);
if (!inSpace)
return false;
}
if (inSpace && minGeometryDistance > 0.0f) {
inSpace = !(Physics.CheckSphere( new Vector3( cameraParams[0], cameraParams[1], cameraParams[2] ), minGeometryDistance, ~layersToExclude ));
}
return inSpace;
}
/// <summary>
/// Computes a random viewpoint inside the domain.
/// </summary>
/// <returns>The random viewpoint, according to the specific viewpoint representation</returns>
/// <param name="dimension">dimensions of the viewpoint (i.e. 3 for just position)</param>
public override float[] ComputeRandomViewpoint (int dimension) {
float[] viewpointResult = new float[dimension];
viewpointResult [0] = UnityEngine.Random.Range (positionBounds.min.x, positionBounds.max.x);
viewpointResult [1] = UnityEngine.Random.Range (positionBounds.min.y, positionBounds.max.y);
viewpointResult [2] = UnityEngine.Random.Range (positionBounds.min.z, positionBounds.max.z);
if (dimension >= 4) {
viewpointResult [3] = UnityEngine.Random.Range (lookAtBounds.min.x, lookAtBounds.max.x);
viewpointResult [4] = UnityEngine.Random.Range (lookAtBounds.min.y, lookAtBounds.max.y);
viewpointResult [5] = UnityEngine.Random.Range (lookAtBounds.min.z, lookAtBounds.max.z);
}
if (dimension >= 7) {
viewpointResult [6] = UnityEngine.Random.Range (rollBounds.x, rollBounds.y);
}
if (dimension == 8) {
viewpointResult [7] = UnityEngine.Random.Range (yFOVBounds.x, yFOVBounds.y);
}
return viewpointResult;
}
/// <summary>
/// Returns the range between each camera parameter. */
/// </summary>
/// <returns>The parameters range.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetParametersRange (int dimension) {
float[] result = new float[dimension];
result [0] = positionBounds.size.x;
result [1] = positionBounds.size.y;
result [2] = positionBounds.size.z;
if (dimension > 3) {
result [3] = lookAtBounds.size.x;
result [4] = lookAtBounds.size.y;
result [5] = lookAtBounds.size.z;
}
if (dimension > 6) {
result [6] = rollBounds.y - rollBounds.x;
}
if (dimension > 7) {
result [7] = yFOVBounds.y - yFOVBounds.x;
}
return result;
}
/// <summary>
/// Gets the minimum parameters value in the domain
/// </summary>
/// <returns>The minimum parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetMinParameters( int dimension) {
float[] result = new float[dimension];
result [0] = positionBounds.min.x;
result [1] = positionBounds.min.y;
result [2] = positionBounds.min.z;
if (dimension > 3) {
result [3] = lookAtBounds.min.x;
result [4] = lookAtBounds.min.y;
result [5] = lookAtBounds.min.z;
}
if (dimension > 6) {
result [6] = rollBounds.x;
}
if (dimension > 7) {
result [7] = yFOVBounds.x;
}
return result;
}
/// <summary>
/// Gets the max parameters value in the domain
/// </summary>
/// <returns>The max parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetMaxParameters( int dimension) {
float[] result = new float[dimension];
result [0] = positionBounds.max.x;
result [1] = positionBounds.max.y;
result [2] = positionBounds.max.z;
if (dimension > 3) {
result [3] = lookAtBounds.max.x;
result [4] = lookAtBounds.max.y;
result [5] = lookAtBounds.max.z;
}
if (dimension > 6) {
result [6] = rollBounds.y;
}
if (dimension > 7) {
result [7] = yFOVBounds.y;
}
return result;
}
}
/// <summary>
/// Class defining the domain of a VC problem when camera parameters are expressed as pivot, distance, phi, theta, roll, YFOV
/// </summary>
public class VCOrbitProblemDomain: VCCameraDomain
{
/// <summary>
/// min and max distance from pivot
/// </summary>
public Vector2 distanceBounds;
/// <summary>
/// min and max polar angle
/// </summary>
public Vector2 thetaBounds;
/// <summary>
/// min and max azimuthal angle
/// </summary>
public Vector2 phiBounds;
/// <summary>
/// checks if the provided viewpoint is in the problem domain
/// </summary>
/// <returns>true</returns>, if it is in search space, <c>false</c> otherwise.</returns>
/// <param name="parameters">viewpoint parameters</param>
public override bool InSearchSpace (float[] parameters)
{
bool inSpace = base.InSearchSpace( parameters );
inSpace = ((distanceBounds.x <= parameters [0]) && (parameters [0] <= distanceBounds.y) &&
(thetaBounds.x <= parameters [1]) && (parameters [1] <= thetaBounds.y) &&
(phiBounds.x <= parameters [2]) && (parameters [2] <= phiBounds.y));
if (!inSpace)
return false;
if (parameters.Length >= 4) { // i.e. there is roll
inSpace = inSpace && (rollBounds.x <= parameters [3]) && (parameters [3] <= rollBounds.y);
if (!inSpace)
return false;
}
if (parameters.Length >=5) { // i.e. there is fov
inSpace = inSpace && (yFOVBounds.x <= parameters [4]) && (parameters [4] <= yFOVBounds.y);
if (!inSpace)
return false;
}
if (inSpace && minGeometryDistance > 0.0f) {
inSpace = !(Physics.CheckSphere( new Vector3( parameters[0], parameters[1], parameters[2] ), minGeometryDistance, ~layersToExclude ));
}
return inSpace;
}
/// <summary>
/// Computes a random viewpoint inside the domain.
/// </summary>
/// <returns>The random viewpoint, according to the specific viewpoint representation</returns>
/// <param name="dimension">dimensions of the viewpoint (i.e. 3 for just position)</param>
public override float[] ComputeRandomViewpoint (int dimension) {
float[] viewpointResult = new float[dimension];
viewpointResult [0] = UnityEngine.Random.Range (distanceBounds.x, distanceBounds.y);
if (dimension > 1) { // theta and phi go together
viewpointResult [1] = UnityEngine.Random.Range (thetaBounds.x, thetaBounds.y);
viewpointResult [2] = UnityEngine.Random.Range (phiBounds.x, phiBounds.y);
}
if (dimension > 3) {
viewpointResult [3] = UnityEngine.Random.Range (rollBounds.x, rollBounds.y);
}
if (dimension > 4) {
viewpointResult [4] = UnityEngine.Random.Range (yFOVBounds.x, yFOVBounds.y);
}
return viewpointResult;
}
/// <summary>
/// Returns the range between each camera parameter. */
/// </summary>
/// <returns>The parameters range.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetParametersRange( int dimension ) {
float[] result = new float[dimension];
result [0] = distanceBounds.y - distanceBounds.x;
if (dimension > 1) {
result [1] = thetaBounds.y - thetaBounds.x;
result [2] = phiBounds.y - phiBounds.x;
}
if (dimension > 3) {
result [3] = rollBounds.y - rollBounds.x;
}
if (dimension > 4) {
result [4] = yFOVBounds.y - yFOVBounds.x;
}
return result;
}
/// <summary>
/// Gets the minimum parameters value in the domain
/// </summary>
/// <returns>The minimum parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetMinParameters( int dimension) {
float[] result = new float[dimension];
result [0] = distanceBounds.x;
if (dimension > 1) {
result [1] = thetaBounds.x;
result [2] = phiBounds.x;
}
if (dimension > 3) {
result [3] = rollBounds.x;
}
if (dimension > 4) {
result [4] = yFOVBounds.x;
}
return result;
}
/// <summary>
/// Gets the max parameters value in the domain
/// </summary>
/// <returns>The max parameters.</returns>
/// <param name="dimension">parameters dimension.</param>
public override float[] GetMaxParameters( int dimension) {
float[] result = new float[dimension];
result [0] = distanceBounds.y;
if (dimension > 1) {
result [1] = thetaBounds.y;
result [2] = phiBounds.y;
}
if (dimension > 3) {
result [3] = rollBounds.y;
}
if (dimension > 4) {
result [4] = yFOVBounds.y;
}
return result;
}
}
| |
// file: Supervised\NeuralNetwork\Network.cs
//
// summary: Implements the network class
using System;
using System.Linq;
using System.Collections.Generic;
using numl.Math.Functions;
using numl.Math.Functions.Loss;
using numl.Math.LinearAlgebra;
using numl.Model;
using numl.Utils;
namespace numl.Supervised.NeuralNetwork
{
/// <summary>
/// Node Type
/// </summary>
public enum NodeType
{
/// <summary>
/// Input layer node.
/// </summary>
Input,
/// <summary>
/// Bias node
/// </summary>
Bias,
/// <summary>
/// Hidden node.
/// </summary>
Hidden,
/// <summary>
/// Output layer node.
/// </summary>
Output
}
/// <summary>A network.</summary>
public static class NetworkOps
{
/// <summary>Defaults.</summary>
/// <param name="d">The Descriptor to process.</param>
/// <param name="x">The Vector to process.</param>
/// <param name="y">The Vector to process.</param>
/// <param name="activationFunction">The activation.</param>
/// <param name="outputFunction">The ouput function for hidden nodes (Optional).</param>
/// <param name="epsilon">epsilon</param>
/// <returns>A Network.</returns>
public static Network Create(this Network network, Descriptor d, Matrix x, Vector y, IFunction activationFunction, IFunction outputFunction = null,
double epsilon = double.NaN, ILossFunction lossFunction = null)
{
// set output to number of choices of available
// 1 if only two choices
int distinct = y.Distinct().Count();
int output = distinct > 2 ? distinct : 1;
// identity funciton for bias nodes
IFunction ident = new Ident();
// set number of hidden units to (Input + Hidden) * 2/3 as basic best guess.
int hidden = (int)System.Math.Ceiling((double)(x.Cols + output) * 2.0 / 3.0);
return network.Create(x.Cols, output, activationFunction, outputFunction,
fnNodeInitializer: new Func<int, int, NodeType, Neuron>((l, i, type) =>
{
if (type == NodeType.Input) return new Neuron(false) { Label = d.ColumnAt(i - 1), ActivationFunction = activationFunction, NodeId = i, LayerId = l };
else if (type == NodeType.Output) return new Neuron(false) { Label = Network.GetLabel(i, d), ActivationFunction = activationFunction, NodeId = i, LayerId = l };
else return new Neuron(false) { ActivationFunction = activationFunction, NodeId = i, LayerId = l };
}), lossFunction: lossFunction, hiddenLayers: hidden);
}
/// <summary>
/// Creates a new fully connected deep neural network based on the supplied size and depth parameters.
/// </summary>
/// <param name="network">New network instance.</param>
/// <param name="inputLayer">Neurons in the input layer.</param>
/// <param name="outputLayer">Neurons in the output layer.</param>
/// <param name="activationFunction">Activation function for the hidden and output layers.</param>
/// <param name="outputFunction">(Optional) Output function of the the Nodes in the output layer (overrides the Activation function).</param>
/// <param name="fnNodeInitializer">(Optional) Function to call for initializing new Nodes, where int1: layer, int2: node index, NodeType: node type.</param>
/// <param name="fnWeightInitializer">(Optional) Function to call for initializing the weights of each connection (including bias nodes).
/// <para>Where int1 = Source layer (0 is input layer), int2 = Source Node, int3 = Target node in the next layer.</para></param>
/// <param name="lossFunction">Loss function to apply in computing the error cost.</param>
/// <param name="epsilon">Weight initialization parameter for random weight selection. Weight will be in the range of: -epsilon to +epsilon.</param>
/// <param name="hiddenLayers">An array of hidden neuron dimensions, where each element is the size of each layer (excluding bias nodes).</param>
/// <returns>Returns an untrained neural network model.</returns>
public static Network Create(this Network network, int inputLayer, int outputLayer, IFunction activationFunction, IFunction outputFunction = null, Func<int, int, NodeType, Neuron> fnNodeInitializer = null,
Func<int, int, int, double> fnWeightInitializer = null, ILossFunction lossFunction = null, double epsilon = double.NaN, params int[] hiddenLayers)
{
IFunction ident = new Ident();
if (hiddenLayers == null || hiddenLayers.Length == 0)
hiddenLayers = new int[] { (int) System.Math.Ceiling((inputLayer + outputLayer + 1) * (2.0 / 3.0)) };
List<double> layers = new List<double>();
layers.Add(inputLayer);
foreach (int l in hiddenLayers)
layers.Add(l + 1);
layers.Add(outputLayer);
if (fnNodeInitializer == null)
fnNodeInitializer = new Func<int, int, NodeType, Neuron>((i, j, type) => new Neuron());
if (fnWeightInitializer == null)
fnWeightInitializer = new Func<int, int, int, double>((l, i, j) => {
double inputs = (l > 0 ? layers[l - 1] : 0);
double outputs = (l < layers.Count - 1 ? layers[l + 1] : 0);
double eps = (double.IsNaN(epsilon) ? Edge.GetEpsilon(activationFunction.Minimum, activationFunction.Maximum, inputs, outputs) : epsilon);
return Edge.GetWeight(eps);
});
// creating input nodes
network.In = new Neuron[inputLayer + 1];
network.In[0] = network.AddNode(new Neuron(true) { Label = "B0", ActivationFunction = ident, NodeId = 0, LayerId = 0 });
for (int i = 1; i < inputLayer + 1; i++)
{
network.In[i] = fnNodeInitializer(0, i, NodeType.Input);
network.In[i].Label = (network.In[i].Label ?? string.Format("I{0}", i));
network.In[i].ActivationFunction = (network.In[i].ActivationFunction ?? ident);
network.In[i].LayerId = 0;
network.In[i].NodeId = i;
network.AddNode(network.In[i]);
}
Neuron[] last = null;
for (int layerIdx = 0; layerIdx < hiddenLayers.Length; layerIdx++)
{
// creating hidden nodes
Neuron[] layer = new Neuron[hiddenLayers[layerIdx] + 1];
layer[0] = network.AddNode(new Neuron(true) { Label = $"B{layerIdx + 1}", ActivationFunction = ident, LayerId = layerIdx + 1, NodeId = 0 });
for (int i = 1; i < layer.Length; i++)
{
layer[i] = fnNodeInitializer(layerIdx + 1, i, NodeType.Hidden);
layer[i].Label = (layer[i].Label ?? String.Format("H{0}.{1}", layerIdx + 1, i));
layer[i].ActivationFunction = (layer[i].ActivationFunction ?? activationFunction);
layer[i].LayerId = layerIdx + 1;
layer[i].NodeId = i;
network.AddNode(layer[i]);
}
if (layerIdx > 0 && layerIdx < hiddenLayers.Length)
{
// create hidden to hidden (full)
for (int i = 0; i < last.Length; i++)
for (int x = 1; x < layer.Length; x++)
network.AddEdge(Edge.Create(last[i], layer[x], weight: fnWeightInitializer(layerIdx, i, x), epsilon: epsilon));
}
else if (layerIdx == 0)
{
// create input to hidden (full)
for (int i = 0; i < network.In.Length; i++)
for (int j = 1; j < layer.Length; j++)
network.AddEdge(Edge.Create(network.In[i], layer[j], weight: fnWeightInitializer(layerIdx, i, j), epsilon: epsilon));
}
last = layer;
}
// creating output nodes
network.Out = new Neuron[outputLayer];
for (int i = 0; i < outputLayer; i++)
{
network.Out[i] = fnNodeInitializer(hiddenLayers.Length + 1, i, NodeType.Output);
network.Out[i].Label = (network.Out[i].Label ?? String.Format("O{0}", i));
network.Out[i].ActivationFunction = (network.Out[i].ActivationFunction ?? activationFunction);
network.Out[i].LayerId = hiddenLayers.Length + 1;
network.Out[i].NodeId = i;
network.AddNode(network.Out[i]);
}
// link from (last) hidden to output (full)
for (int i = 0; i < network.Out.Length; i++)
for (int j = 0; j < last.Length; j++)
network.AddEdge(Edge.Create(last[j], network.Out[i], weight: fnWeightInitializer(hiddenLayers.Length, j, i), epsilon: epsilon));
network.OutputFunction = outputFunction;
network.LossFunction = (lossFunction ?? network.LossFunction);
return network;
}
/// <summary>
/// Adds new connections for the specified node for the parent and child nodes.
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="node">Neuron being added.</param>
/// <param name="parentNodes">Parent nodes that this neuron is connected with.</param>
/// <param name="childNodes">Child nodes that this neuron is connected to.</param>
/// <param name="epsilon">Weight initialization parameter.</param>
/// <returns></returns>
public static Network AddConnections(this Network network, Neuron node, IEnumerable<Neuron> parentNodes, IEnumerable<Neuron> childNodes, double epsilon = double.NaN)
{
if (epsilon == double.NaN)
epsilon = Edge.GetEpsilon(node.ActivationFunction.Minimum, node.ActivationFunction.Maximum, parentNodes.Count(), childNodes.Count());
if (parentNodes != null)
{
for (int i = 0; i < parentNodes.Count(); i++)
network.AddEdge(Edge.Create(parentNodes.ElementAt(i), node, epsilon: epsilon));
}
if (childNodes != null)
{
for (int j = 0; j < childNodes.Count(); j++)
network.AddEdge(Edge.Create(node, childNodes.ElementAt(j), epsilon: epsilon));
}
return network;
}
/// <summary>
/// Gets the weight values as an [i x j] weight matrix. Where i represents the node in the next layer (layer + 1) and j represents the node in the specified <paramref name="layer"/>.
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="layer">The layer to retrieve weights for. The layer should be between 0 and the last hidden layer.</param>
/// <param name="includeBiases">Indicates whether bias weights are included in the output.</param>
/// <returns>Matrix.</returns>
public static Matrix GetWeights(this Network network, int layer = 0, bool includeBiases = false)
{
if (layer >= network.Layers - 1)
throw new ArgumentOutOfRangeException(nameof(layer), $"There are no weights from the output layer [{layer}].");
var nodes = network.GetNodes(layer + 1).ToArray();
int pos = ((network.Layers - 1 == layer + 1) ? 0 : 1);
int bpos = (includeBiases ? 0 : 1);
Matrix weights = Matrix.Zeros(nodes.Length - pos, network.GetNodes(layer).Count() - bpos);
for (int i = pos; i < nodes.Length; i++)
{
for (int j = bpos; j < nodes[i].In.Count; j++)
{
if (!nodes[i].In[j].Source.IsBias || (nodes[i].In[j].Source.IsBias && includeBiases))
{
weights[i - pos, j - bpos] = nodes[i].In[j].Weight;
}
}
}
return weights;
}
/// <summary>
/// Gets a bias input vector for the specified layer. Each item is the bias weight on the connecting node in the next layer.
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="layer">Forward layer of biases and their weights. The layer should be between 0 (first hidden layer) and the last hidden layer.</param>
/// <returns>Vector.</returns>
public static Vector GetBiases(this Network network, int layer = 0)
{
if (layer > network.Layers - 1)
throw new ArgumentOutOfRangeException(nameof(layer), $"There are no bias nodes from the output layer [{layer}].");
var nodes = network.GetNodes(layer + 1).ToArray();
Vector biases = Vector.Zeros(nodes.Where(w => !w.IsBias).Count());
for (int i = 0; i < nodes.Length; i++)
{
if (!nodes[i].IsBias)
{
var bias = nodes[i].In.FirstOrDefault(f => f.Source.IsBias);
biases[i] = bias.Weight;
}
}
return biases;
}
/// <summary>
/// Links a Network from nodes and edges.
/// </summary>
/// <param name="nodes">An array of nodes in the network</param>
/// <param name="edges">An array of edges between the nodes in the network.</param>
public static Network LinkNodes(this Network network, IEnumerable<Neuron> nodes, IEnumerable<Edge> edges)
{
int inputLayerId = nodes.Min(m => m.LayerId);
int outputLayerId = nodes.Max(m => m.LayerId);
network.In = nodes.Where(w => w.LayerId == inputLayerId).ToArray();
foreach (var node in network.In)
network.AddNode(node);
int hiddenLayer = inputLayerId + 1;
// relink nodes
Neuron[] last = null;
for (int layerIdx = hiddenLayer; layerIdx < outputLayerId; layerIdx++)
{
Neuron[] layer = nodes.Where(w => w.LayerId == layerIdx).ToArray();
foreach (var node in layer)
network.AddNode(node);
if (layerIdx > hiddenLayer)
{
// create hidden to hidden (full)
for (int i = 0; i < last.Length; i++)
for (int x = 1; x < layer.Length; x++)
network.AddEdge(Edge.Create(last[i], layer[x],
weight: edges.First(f => f.ParentId == last[i].Id && f.ChildId == layer[x].Id).Weight));
}
else if (layerIdx == hiddenLayer)
{
// create input to hidden (full)
for (int i = 0; i < network.In.Length; i++)
for (int j = 1; j < layer.Length; j++)
network.AddEdge(Edge.Create(network.In[i], layer[j],
weight: edges.First(f => f.ParentId == network.In[i].Id && f.ChildId == layer[j].Id).Weight));
}
last = layer;
}
network.Out = nodes.Where(w => w.LayerId == outputLayerId).ToArray();
foreach (var node in network.Out)
network.AddNode(node);
for (int i = 0; i < network.Out.Length; i++)
for (int j = 0; j < last.Length; j++)
network.AddEdge(Edge.Create(last[j], network.Out[i],
weight: edges.First(f => f.ParentId == last[j].Id && f.ChildId == network.Out[i].Id).Weight));
return network;
}
/// <summary>
/// Constrains the weights in the specified layer from being updated. This prevents weights in pretrained layers from being updated.
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="layer">The layer of weights to constrain. To prevent all weights from being changed specify the global value of -1.</param>
/// <param name="constrain">Sets the <see cref="Neuron.Constrained"/> value to true/false.</param>
/// <returns></returns>
public static Network Constrain(this Network network, int layer = -1, bool constrain = true)
{
var nodes = (layer >= 0 ? network.GetNodes(layer) : network.GetVertices());
foreach (Neuron node in nodes)
{
node.Constrained = constrain;
}
return network;
}
/// <summary>
/// Reindexes each node's layer and label in the network, starting from 0 (input layer).
/// </summary>
/// <param name="network">Network to reindex.</param>
/// <returns></returns>
public static Network Reindex(this Network network)
{
var nodes = network.GetVertices().OfType<Neuron>()
.GroupBy(g => g.LayerId)
.OrderBy(o => o.Key)
.ToArray();
int layer = 0;
foreach (var group in nodes)
{
int count = 0;
foreach (var node in group)
{
node.LayerId = layer;
// update labels.
if (node.IsInput) node.Label = $"I{count}";
if (node.IsBias) node.Label = $"B{layer}";
if (node.IsHidden) node.Label = $"H{layer}.{count}";
if (node.IsOutput) node.Label = $"O{count}";
count++;
}
layer++;
}
return network;
}
/// <summary>
/// Prunes the network in the given direction for the specified number of layers.
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="backwards">If true, removes layer by layer in reverse order (i.e. output layer first).</param>
/// <param name="layers">Number of layers to prune from the network.</param>
public static Network Prune(this Network network, bool backwards = true, int layers = 1)
{
int count = layers;
int layer = (backwards ? (network.Layers - 1) : 0);
while (count > 0)
{
count--;
var nodes = network.GetNodes(layer);
for (int i = 0; i < nodes.Count(); i++)
network.RemoveNode(nodes.ElementAt(i));
layer = (backwards ? --layer : ++layer);
}
network.Reindex();
// remove bias outputs
var outputs = network.GetNodes(network.Layers - 1).Where(w => w.IsBias);
for (int x = 0; x < outputs.Count(); x++)
network.RemoveNode(outputs.ElementAt(x));
for (int i = 0; i < network.GetNodes(0).Count(); i++)
network.GetNodes(0).ElementAt(i).In.Clear();
network.In = network.GetNodes(0).ToArray();
for (int i = 0; i < network.GetNodes(network.Layers - 1).Count(); i++)
network.GetNodes(network.Layers - 1).ElementAt(i).Out.Clear();
network.Out = network.GetNodes(network.Layers - 1).ToArray();
return network;
}
/// <summary>
/// Stacks the given networks in order, on top of the current network, to create a fully connected deep neural network.
/// <para>This is useful in building pretrained multi-layered neural networks, where each layer is partially trained prior to stacking.</para>
/// </summary>
/// <param name="network">Current network.</param>
/// <param name="removeInputs">If true, the input nodes in additional layers are removed prior to stacking.
/// <para>This will link the previous network's output layer with the hidden units of the next layer.</para>
/// </param>
/// <param name="removeOutputs">If true, output nodes in the input and middle layers are removed prior to stacking.
/// <para>This will link the previous network's hidden or output layer with the input or hidden units (when <paramref name="removeInputs"/> is true) in the next layer.</para>
/// </param>
/// <param name="addBiases">If true, missing bias nodes are automatically added within new hidden layers.</param>
/// <param name="constrain">If true, the weights within each network are constrained leaving the new interconnecting network weights for training.</param>
/// <param name="networks">Network objects to stack on top of the current network. Each network is added downstream from the input nodes.</param>
public static Network Stack(this Network network, bool removeInputs = false, bool removeOutputs = false, bool addBiases = true,
bool constrain = true, params Network[] networks)
{
IFunction ident = new Ident();
// prune output layer on first (if pruning)
Network deep = (removeOutputs ? network.Prune(true, 1) : network);
if (constrain) deep.Constrain();
// get the current network's output layer
List<Neuron> prevOutput = deep.Out.ToList();
for (int x = 0; x < networks.Length; x++)
{
Network net = networks[x];
if (constrain) net.Constrain();
// remove input layer on next network (if pruning)
if (removeInputs) net = net.Prune(false, 1);
// remove output layer on next (middle) network (if pruning)
if (removeOutputs && x < networks.Length - 1) net = net.Prune(true, 1);
// add biases (for hidden network layers)
if (addBiases)
{
if (!prevOutput.Any(a => a.IsBias == true))
{
int layerId = prevOutput.First().LayerId;
var bias = new Neuron(true)
{
Label = $"B{layerId}",
ActivationFunction = ident,
NodeId = 0,
LayerId = layerId
};
// add to graph
deep.AddNode(bias);
// copy to previous network's output layer (for reference)
prevOutput.Insert(0, bias);
}
}
int deepLayers = deep.Layers;
Neuron[] prevLayer = null;
var layers = net.GetVertices().OfType<Neuron>()
.GroupBy(g => g.LayerId)
.ToArray();
for (int layer = 0; layer < layers.Count(); layer++)
{
// get nodes in current layer of current network
var nodes = layers.ElementAt(layer).ToArray();
// set new layer ID (relative to pos. in resulting graph)
int layerId = layer + deepLayers;
foreach (var node in nodes)
{
// set the new layer ID
node.LayerId = layerId;
// add to graph
deep.AddNode(node);
if (!node.IsBias)
{
// if not input layer in current network
if (layer > 0)
{
// add afferent edges to graph for current node
deep.AddEdges(net.GetInEdges(node).ToArray());
}
else
{
// add connections from previous network output layer to next input layer
foreach (var onode in prevOutput)
deep.AddEdge(Edge.Create(onode, node));
}
}
}
// nodes in last layer
if (prevLayer != null)
{
// add outgoing connections for each node in previous layer
foreach (var inode in prevLayer)
{
deep.AddEdges(net.GetOutEdges(inode).ToArray());
}
}
// remember last layer
prevLayer = nodes.ToArray();
}
// remember last network output nodes
prevOutput = deep.GetNodes(deep.Layers - 1).ToList();
}
deep.Reindex();
deep.In = deep.GetNodes(0).ToArray();
deep.Out = deep.GetNodes(deep.Layers - 1).ToArray();
return deep;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.ParameterInfos;
using System.Reflection.Runtime.BindingFlagSupport;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
namespace System.Reflection.Runtime.MethodInfos
{
//
// Abstract base class for RuntimeNamedMethodInfo, RuntimeConstructedGenericMethodInfo.
//
[DebuggerDisplay("{_debugName}")]
internal abstract partial class RuntimeMethodInfo : MethodInfo, ITraceableTypeMember
{
protected RuntimeMethodInfo()
{
}
public abstract override MethodAttributes Attributes
{
get;
}
public abstract override CallingConventions CallingConvention
{
get;
}
public sealed override bool ContainsGenericParameters
{
get
{
if (DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
// V4.5 api - Creates open delegates over static or instance methods.
public sealed override Delegate CreateDelegate(Type delegateType)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_CreateDelegate(this, delegateType);
#endif
return CreateDelegateWorker(delegateType, null, allowClosed: false);
}
// V4.5 api - Creates open or closed delegates over static or instance methods.
public sealed override Delegate CreateDelegate(Type delegateType, Object target)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_CreateDelegate(this, delegateType, target);
#endif
return CreateDelegateWorker(delegateType, target, allowClosed: true);
}
private Delegate CreateDelegateWorker(Type delegateType, object target, bool allowClosed)
{
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
if (!(delegateType is RuntimeTypeInfo runtimeDelegateType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
if (!runtimeDelegateType.IsDelegate)
throw new ArgumentException(SR.Arg_MustBeDelegate);
Delegate result = CreateDelegateNoThrowOnBindFailure(runtimeDelegateType, target, allowClosed);
if (result == null)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return result;
}
public abstract override IEnumerable<CustomAttributeData> CustomAttributes
{
get;
}
public sealed override Type DeclaringType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_DeclaringType(this);
#endif
return this.RuntimeDeclaringType;
}
}
public abstract override bool Equals(object obj);
public abstract override int GetHashCode();
public sealed override MethodInfo GetBaseDefinition()
{
// This check is for compatibility. Yes, it happens before we normalize constructed generic methods back to their backing definition.
Type declaringType = DeclaringType;
if (!IsVirtual || IsStatic || declaringType == null || declaringType.IsInterface)
return this;
MethodInfo method = this;
// For compat: Remove any instantation on generic methods.
if (method.IsConstructedGenericMethod)
method = method.GetGenericMethodDefinition();
while (true)
{
MethodInfo next = method.GetImplicitlyOverriddenBaseClassMember();
if (next == null)
return ((RuntimeMethodInfo)method).WithReflectedTypeSetToDeclaringType;
method = next;
}
}
public sealed override Type[] GetGenericArguments()
{
return RuntimeGenericArgumentsOrParameters.CloneTypeArray();
}
public abstract override int GenericParameterCount { get; }
public abstract override MethodInfo GetGenericMethodDefinition();
public sealed override MethodBody GetMethodBody()
{
throw new PlatformNotSupportedException();
}
public sealed override ParameterInfo[] GetParameters()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_GetParameters(this);
#endif
RuntimeParameterInfo[] runtimeParameterInfos = RuntimeParameters;
if (runtimeParameterInfos.Length == 0)
return Array.Empty<ParameterInfo>();
ParameterInfo[] result = new ParameterInfo[runtimeParameterInfos.Length];
for (int i = 0; i < result.Length; i++)
result[i] = runtimeParameterInfos[i];
return result;
}
public sealed override ParameterInfo[] GetParametersNoCopy()
{
return RuntimeParameters;
}
public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other);
[DebuggerGuidedStepThroughAttribute]
public sealed override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_Invoke(this, obj, parameters);
#endif
if (parameters == null)
parameters = Array.Empty<Object>();
MethodInvoker methodInvoker = this.MethodInvoker;
object result = methodInvoker.Invoke(obj, parameters, binder, invokeAttr, culture);
System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
public abstract override bool IsConstructedGenericMethod
{
get;
}
public abstract override bool IsGenericMethod
{
get;
}
public abstract override bool IsGenericMethodDefinition
{
get;
}
public abstract override MethodInfo MakeGenericMethod(params Type[] typeArguments);
public abstract override MethodBase MetadataDefinitionMethod { get; }
public abstract override int MetadataToken
{
get;
}
public abstract override MethodImplAttributes MethodImplementationFlags
{
get;
}
public abstract override Module Module
{
get;
}
public sealed override String Name
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_Name(this);
#endif
return this.RuntimeName;
}
}
public abstract override Type ReflectedType { get; }
public sealed override ParameterInfo ReturnParameter
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_ReturnParameter(this);
#endif
return this.RuntimeReturnParameter;
}
}
public sealed override Type ReturnType
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_ReturnType(this);
#endif
return ReturnParameter.ParameterType;
}
}
public abstract override String ToString();
public abstract override RuntimeMethodHandle MethodHandle { get; }
Type ITraceableTypeMember.ContainingType
{
get
{
return this.RuntimeDeclaringType;
}
}
String ITraceableTypeMember.MemberName
{
get
{
return this.RuntimeName;
}
}
internal abstract RuntimeTypeInfo RuntimeDeclaringType
{
get;
}
internal abstract String RuntimeName
{
get;
}
internal abstract RuntimeMethodInfo WithReflectedTypeSetToDeclaringType { get; }
protected abstract MethodInvoker UncachedMethodInvoker { get; }
//
// The non-public version of MethodInfo.GetGenericArguments() (does not array-copy and has a more truthful name.)
//
internal abstract RuntimeTypeInfo[] RuntimeGenericArgumentsOrParameters { get; }
internal abstract RuntimeParameterInfo[] GetRuntimeParameters(RuntimeMethodInfo contextMethod, out RuntimeParameterInfo returnParameter);
//
// The non-public version of MethodInfo.GetParameters() (does not array-copy.)
//
internal RuntimeParameterInfo[] RuntimeParameters
{
get
{
RuntimeParameterInfo[] parameters = _lazyParameters;
if (parameters == null)
{
RuntimeParameterInfo returnParameter;
parameters = _lazyParameters = GetRuntimeParameters(this, out returnParameter);
_lazyReturnParameter = returnParameter; // Opportunistically initialize the _lazyReturnParameter latch as well.
}
return parameters;
}
}
internal RuntimeParameterInfo RuntimeReturnParameter
{
get
{
RuntimeParameterInfo returnParameter = _lazyReturnParameter;
if (returnParameter == null)
{
// Though the returnParameter is our primary objective, we can opportunistically initialize the _lazyParameters latch too.
_lazyParameters = GetRuntimeParameters(this, out returnParameter);
_lazyReturnParameter = returnParameter;
}
return returnParameter;
}
}
private volatile RuntimeParameterInfo[] _lazyParameters;
private volatile RuntimeParameterInfo _lazyReturnParameter;
internal MethodInvoker MethodInvoker
{
get
{
MethodInvoker methodInvoker = _lazyMethodInvoker;
if (methodInvoker == null)
{
if (ReturnType.IsByRef)
{
// The invoker is going to dereference and box (for structs) the result of the invocation
// on behalf of the caller. Can't box byref-like types and can't box void.
if (ReturnType.GetElementType().IsByRefLike || ReturnType.GetElementType() == CommonRuntimeTypes.Void)
throw new NotSupportedException();
}
methodInvoker = _lazyMethodInvoker = this.UncachedMethodInvoker;
}
return methodInvoker;
}
}
internal IntPtr LdFtnResult => MethodInvoker.LdFtnResult;
private volatile MethodInvoker _lazyMethodInvoker = null;
/// <summary>
/// Common CreateDelegate worker. NOTE: If the method signature is not compatible, this method returns null rather than throwing an ArgumentException.
/// This is needed to support the api overloads that have a "throwOnBindFailure" parameter.
/// </summary>
internal Delegate CreateDelegateNoThrowOnBindFailure(RuntimeTypeInfo runtimeDelegateType, Object target, bool allowClosed)
{
Debug.Assert(runtimeDelegateType.IsDelegate);
ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
MethodInfo invokeMethod = runtimeDelegateType.GetInvokeMethod();
// Make sure the return type is assignment-compatible.
Type expectedReturnType = ReturnParameter.ParameterType;
Type actualReturnType = invokeMethod.ReturnParameter.ParameterType;
if (!IsAssignableFrom(executionEnvironment, actualReturnType, expectedReturnType))
return null;
if (expectedReturnType.IsValueType && !actualReturnType.IsValueType)
{
// For value type returning methods, conversions between enums and primitives are allowed (and screened by the above call to IsAssignableFrom)
// but conversions to Object or interfaces implemented by the value type are not.
return null;
}
IList<ParameterInfo> delegateParameters = invokeMethod.GetParametersNoCopy();
IList<ParameterInfo> targetParameters = this.GetParametersNoCopy();
IEnumerator<ParameterInfo> delegateParameterEnumerator = delegateParameters.GetEnumerator();
IEnumerator<ParameterInfo> targetParameterEnumerator = targetParameters.GetEnumerator();
bool isStatic = this.IsStatic;
bool isOpen;
if (isStatic)
{
if (delegateParameters.Count == targetParameters.Count)
{
// Open static: This is the "typical" case of calling a static method.
isOpen = true;
if (target != null)
return null;
}
else
{
// Closed static: This is the "weird" v2.0 case where the delegate is closed over the target method's first parameter.
// (it make some kinda sense if you think of extension methods.)
if (!allowClosed)
return null;
isOpen = false;
if (!targetParameterEnumerator.MoveNext())
return null;
if (target != null && !IsAssignableFrom(executionEnvironment, targetParameterEnumerator.Current.ParameterType, target.GetType()))
return null;
}
}
else
{
if (delegateParameters.Count == targetParameters.Count)
{
// Closed instance: This is the "typical" case of invoking an instance method.
isOpen = false;
if (!allowClosed)
return null;
if (target != null && !IsAssignableFrom(executionEnvironment, this.DeclaringType, target.GetType()))
return null;
}
else
{
// Open instance: This is the "weird" v2.0 case where the delegate has a leading extra parameter that's assignable to the target method's
// declaring type.
if (!delegateParameterEnumerator.MoveNext())
return null;
isOpen = true;
Type firstParameterOfMethodType = this.DeclaringType;
if (firstParameterOfMethodType.IsValueType)
firstParameterOfMethodType = firstParameterOfMethodType.MakeByRefType();
if (!IsAssignableFrom(executionEnvironment, firstParameterOfMethodType, delegateParameterEnumerator.Current.ParameterType))
return null;
if (target != null)
return null;
}
}
// Verify that the parameters that the delegate and method have in common are assignment-compatible.
while (delegateParameterEnumerator.MoveNext())
{
if (!targetParameterEnumerator.MoveNext())
return null;
if (!IsAssignableFrom(executionEnvironment, targetParameterEnumerator.Current.ParameterType, delegateParameterEnumerator.Current.ParameterType))
return null;
}
if (targetParameterEnumerator.MoveNext())
return null;
return CreateDelegateWithoutSignatureValidation(runtimeDelegateType, target, isStatic: isStatic, isOpen: isOpen);
}
internal Delegate CreateDelegateWithoutSignatureValidation(Type delegateType, object target, bool isStatic, bool isOpen)
{
return MethodInvoker.CreateDelegate(delegateType.TypeHandle, target, isStatic: isStatic, isVirtual: false, isOpen: isOpen);
}
private static bool IsAssignableFrom(ExecutionEnvironment executionEnvironment, Type dstType, Type srcType)
{
// byref types do not have a TypeHandle so we must treat these separately.
if (dstType.IsByRef && srcType.IsByRef)
{
if (!dstType.Equals(srcType))
return false;
}
// Enable pointers (which don't necessarily have typehandles). todo:be able to handle intptr <-> pointer, check if we need to handle
// casts via pointer where the pointer types aren't identical
if (dstType.Equals(srcType))
{
return true;
}
// If assignment compatible in the normal way, allow
if (executionEnvironment.IsAssignableFrom(dstType.TypeHandle, srcType.TypeHandle))
{
return true;
}
// they are not compatible yet enums can go into each other if their underlying element type is the same
// or into their equivalent integral type
Type dstTypeUnderlying = dstType;
if (dstType.IsEnum)
{
dstTypeUnderlying = Enum.GetUnderlyingType(dstType);
}
Type srcTypeUnderlying = srcType;
if (srcType.IsEnum)
{
srcTypeUnderlying = Enum.GetUnderlyingType(srcType);
}
if (dstTypeUnderlying.Equals(srcTypeUnderlying))
{
return true;
}
return false;
}
protected RuntimeMethodInfo WithDebugName()
{
bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled;
#if DEBUG
populateDebugNames = true;
#endif
if (!populateDebugNames)
return this;
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
_debugName = ((ITraceableTypeMember)this).MemberName;
}
return this;
}
private String _debugName;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Yengine;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
/**
* @brief Generate script object code to perform type casting
*/
namespace OpenSim.Region.ScriptEngine.Yengine
{
public class TypeCast
{
private delegate void CastDelegate(IScriptCodeGen scg, Token errorAt);
private static ConstructorInfo floatConstructorStringInfo = typeof(LSL_Float).GetConstructor(new Type[] { typeof(string) });
private static ConstructorInfo integerConstructorStringInfo = typeof(LSL_Integer).GetConstructor(new Type[] { typeof(string) });
private static ConstructorInfo lslFloatConstructorInfo = typeof(LSL_Float).GetConstructor(new Type[] { typeof(double) });
private static ConstructorInfo lslIntegerConstructorInfo = typeof(LSL_Integer).GetConstructor(new Type[] { typeof(int) });
private static ConstructorInfo lslStringConstructorInfo = typeof(LSL_String).GetConstructor(new Type[] { typeof(string) });
private static ConstructorInfo rotationConstrucorStringInfo = typeof(LSL_Rotation).GetConstructor(new Type[] { typeof(string) });
private static ConstructorInfo vectorConstrucorStringInfo = typeof(LSL_Vector).GetConstructor(new Type[] { typeof(string) });
private static FieldInfo lslFloatValueFieldInfo = typeof(LSL_Float).GetField("value");
private static FieldInfo lslIntegerValueFieldInfo = typeof(LSL_Integer).GetField("value");
private static FieldInfo lslStringValueFieldInfo = typeof(LSL_String).GetField("m_string");
private static FieldInfo sdtcITableFieldInfo = typeof(XMRSDTypeClObj).GetField("sdtcITable");
private static MethodInfo boolToListMethodInfo = typeof(TypeCast).GetMethod("BoolToList", new Type[] { typeof(bool) });
private static MethodInfo boolToStringMethodInfo = typeof(TypeCast).GetMethod("BoolToString", new Type[] { typeof(bool) });
private static MethodInfo charToStringMethodInfo = typeof(TypeCast).GetMethod("CharToString", new Type[] { typeof(char) });
private static MethodInfo excToStringMethodInfo = typeof(TypeCast).GetMethod("ExceptionToString", new Type[] { typeof(Exception), typeof(XMRInstAbstract) });
private static MethodInfo floatToStringMethodInfo = typeof(TypeCast).GetMethod("FloatToString", new Type[] { typeof(double) });
private static MethodInfo intToStringMethodInfo = typeof(TypeCast).GetMethod("IntegerToString", new Type[] { typeof(int) });
private static MethodInfo keyToBoolMethodInfo = typeof(TypeCast).GetMethod("KeyToBool", new Type[] { typeof(string) });
private static MethodInfo listToBoolMethodInfo = typeof(TypeCast).GetMethod("ListToBool", new Type[] { typeof(LSL_List) });
private static MethodInfo listToStringMethodInfo = typeof(TypeCast).GetMethod("ListToString", new Type[] { typeof(LSL_List) });
private static MethodInfo objectToFloatMethodInfo = typeof(TypeCast).GetMethod("ObjectToFloat", new Type[] { typeof(object) });
private static MethodInfo objectToIntegerMethodInfo = typeof(TypeCast).GetMethod("ObjectToInteger", new Type[] { typeof(object) });
private static MethodInfo objectToListMethodInfo = typeof(TypeCast).GetMethod("ObjectToList", new Type[] { typeof(object) });
private static MethodInfo objectToRotationMethodInfo = typeof(TypeCast).GetMethod("ObjectToRotation", new Type[] { typeof(object) });
private static MethodInfo objectToStringMethodInfo = typeof(TypeCast).GetMethod("ObjectToString", new Type[] { typeof(object) });
private static MethodInfo objectToVectorMethodInfo = typeof(TypeCast).GetMethod("ObjectToVector", new Type[] { typeof(object) });
private static MethodInfo rotationToBoolMethodInfo = typeof(TypeCast).GetMethod("RotationToBool", new Type[] { typeof(LSL_Rotation) });
private static MethodInfo rotationToStringMethodInfo = typeof(TypeCast).GetMethod("RotationToString", new Type[] { typeof(LSL_Rotation) });
private static MethodInfo stringToBoolMethodInfo = typeof(TypeCast).GetMethod("StringToBool", new Type[] { typeof(string) });
private static MethodInfo vectorToBoolMethodInfo = typeof(TypeCast).GetMethod("VectorToBool", new Type[] { typeof(LSL_Vector) });
private static MethodInfo vectorToStringMethodInfo = typeof(TypeCast).GetMethod("VectorToString", new Type[] { typeof(LSL_Vector) });
private static MethodInfo sdTypeClassCastClass2ClassMethodInfo = typeof(XMRSDTypeClObj).GetMethod("CastClass2Class", new Type[] { typeof(object), typeof(int) });
private static MethodInfo sdTypeClassCastIFace2ClassMethodInfo = typeof(XMRSDTypeClObj).GetMethod("CastIFace2Class", new Type[] { typeof(Delegate[]), typeof(int) });
private static MethodInfo sdTypeClassCastObj2IFaceMethodInfo = typeof(XMRSDTypeClObj).GetMethod("CastObj2IFace", new Type[] { typeof(object), typeof(string) });
private static MethodInfo charToListMethodInfo = typeof(TypeCast).GetMethod("CharToList", new Type[] { typeof(char) });
private static MethodInfo excToListMethodInfo = typeof(TypeCast).GetMethod("ExcToList", new Type[] { typeof(Exception) });
private static MethodInfo vectorToListMethodInfo = typeof(TypeCast).GetMethod("VectorToList", new Type[] { typeof(LSL_Vector) });
private static MethodInfo floatToListMethodInfo = typeof(TypeCast).GetMethod("FloatToList", new Type[] { typeof(double) });
private static MethodInfo integerToListMethodInfo = typeof(TypeCast).GetMethod("IntegerToList", new Type[] { typeof(int) });
private static MethodInfo rotationToListMethodInfo = typeof(TypeCast).GetMethod("RotationToList", new Type[] { typeof(LSL_Rotation) });
private static MethodInfo stringToListMethodInfo = typeof(TypeCast).GetMethod("StringToList", new Type[] { typeof(string) });
/*
* List of all allowed type casts and how to perform the casting.
*/
private static Dictionary<string, CastDelegate> legalTypeCasts = CreateLegalTypeCasts();
/**
* @brief create a dictionary of legal type casts.
* Defines what EXPLICIT type casts are allowed in addition to the IMPLICIT ones.
* Key is of the form <oldtype> <newtype> for IMPLICIT casting.
* Key is of the form <oldtype>*<newtype> for EXPLICIT casting.
* Value is a delegate that generates code to perform the type cast.
*/
private static Dictionary<string, CastDelegate> CreateLegalTypeCasts()
{
Dictionary<string, CastDelegate> ltc = new Dictionary<string, CastDelegate>();
// IMPLICIT type casts (a space is in middle of the key)
// EXPLICIT type casts (an * is in middle of the key)
// In general, only mark explicit if it might throw an exception
ltc.Add("array object", TypeCastArray2Object);
ltc.Add("bool float", TypeCastBool2Float);
ltc.Add("bool integer", TypeCastBool2Integer);
ltc.Add("bool list", TypeCastBool2List);
ltc.Add("bool object", TypeCastBool2Object);
ltc.Add("bool string", TypeCastBool2String);
ltc.Add("char integer", TypeCastChar2Integer);
ltc.Add("char list", TypeCastChar2List);
ltc.Add("char object", TypeCastChar2Object);
ltc.Add("char string", TypeCastChar2String);
ltc.Add("exception list", TypeCastExc2List);
ltc.Add("exception object", TypeCastExc2Object);
ltc.Add("exception string", TypeCastExc2String);
ltc.Add("float bool", TypeCastFloat2Bool);
ltc.Add("float integer", TypeCastFloat2Integer);
ltc.Add("float list", TypeCastFloat2List);
ltc.Add("float object", TypeCastFloat2Object);
ltc.Add("float string", TypeCastFloat2String);
ltc.Add("integer bool", TypeCastInteger2Bool);
ltc.Add("integer char", TypeCastInteger2Char);
ltc.Add("integer float", TypeCastInteger2Float);
ltc.Add("integer list", TypeCastInteger2List);
ltc.Add("integer object", TypeCastInteger2Object);
ltc.Add("integer string", TypeCastInteger2String);
ltc.Add("list bool", TypeCastList2Bool);
ltc.Add("list object", TypeCastList2Object);
ltc.Add("list string", TypeCastList2String);
ltc.Add("object*array", TypeCastObject2Array);
ltc.Add("object*bool", TypeCastObject2Bool);
ltc.Add("object*char", TypeCastObject2Char);
ltc.Add("object*exception", TypeCastObject2Exc);
ltc.Add("object*float", TypeCastObject2Float);
ltc.Add("object*integer", TypeCastObject2Integer);
ltc.Add("object*list", TypeCastObject2List);
ltc.Add("object*rotation", TypeCastObject2Rotation);
ltc.Add("object string", TypeCastObject2String);
ltc.Add("object*vector", TypeCastObject2Vector);
ltc.Add("rotation bool", TypeCastRotation2Bool);
ltc.Add("rotation list", TypeCastRotation2List);
ltc.Add("rotation object", TypeCastRotation2Object);
ltc.Add("rotation string", TypeCastRotation2String);
ltc.Add("string bool", TypeCastString2Bool);
ltc.Add("string float", TypeCastString2Float);
ltc.Add("string integer", TypeCastString2Integer);
ltc.Add("string list", TypeCastString2List);
ltc.Add("string object", TypeCastString2Object);
ltc.Add("string rotation", TypeCastString2Rotation);
ltc.Add("string vector", TypeCastString2Vector);
ltc.Add("vector bool", TypeCastVector2Bool);
ltc.Add("vector list", TypeCastVector2List);
ltc.Add("vector object", TypeCastVector2Object);
ltc.Add("vector string", TypeCastVector2String);
return ltc;
}
/**
* @brief See if the given type can be cast to the other implicitly.
* @param dstType = type being cast to
* @param srcType = type being cast from
* @returns false: implicit cast not allowed
* true: implicit cast allowed
*/
public static bool IsAssignableFrom(TokenType dstType, TokenType srcType)
{
// Do a 'dry run' of the casting operation, discarding any emits and not printing any errors.
// But if the casting tries to print error(s), return false.
// Otherwise assume the cast is allowed and return true.
SCGIAF scg = new SCGIAF();
scg.ok = true;
scg._ilGen = migiaf;
CastTopOfStack(scg, null, srcType, dstType, false);
return scg.ok;
}
private struct SCGIAF: IScriptCodeGen
{
public bool ok;
public ScriptMyILGen _ilGen;
// IScriptCodeGen
public ScriptMyILGen ilGen
{
get
{
return _ilGen;
}
}
public void ErrorMsg(Token token, string message)
{
ok = false;
}
public void PushDefaultValue(TokenType type)
{
}
public void PushXMRInst()
{
}
}
private static readonly MIGIAF migiaf = new MIGIAF();
private struct MIGIAF: ScriptMyILGen
{
// ScriptMyILGen
public string methName
{
get
{
return null;
}
}
public ScriptMyLocal DeclareLocal(Type type, string name)
{
return null;
}
public ScriptMyLabel DefineLabel(string name)
{
return null;
}
public void BeginExceptionBlock()
{
}
public void BeginCatchBlock(Type excType)
{
}
public void BeginFinallyBlock()
{
}
public void EndExceptionBlock()
{
}
public void Emit(Token errorAt, OpCode opcode)
{
}
public void Emit(Token errorAt, OpCode opcode, FieldInfo field)
{
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLocal myLocal)
{
}
public void Emit(Token errorAt, OpCode opcode, Type type)
{
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel myLabel)
{
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels)
{
}
public void Emit(Token errorAt, OpCode opcode, ScriptObjWriter method)
{
}
public void Emit(Token errorAt, OpCode opcode, MethodInfo method)
{
}
public void Emit(Token errorAt, OpCode opcode, ConstructorInfo ctor)
{
}
public void Emit(Token errorAt, OpCode opcode, double value)
{
}
public void Emit(Token errorAt, OpCode opcode, float value)
{
}
public void Emit(Token errorAt, OpCode opcode, int value)
{
}
public void Emit(Token errorAt, OpCode opcode, string value)
{
}
public void MarkLabel(ScriptMyLabel myLabel)
{
}
}
/**
* @brief Emit code that converts the top stack item from 'oldType' to 'newType'
* @param scg = what script we are compiling
* @param errorAt = token used for source location for error messages
* @param oldType = type of item currently on the stack
* @param newType = type to convert it to
* @param explicitAllowed = false: only consider implicit casts
* true: consider both implicit and explicit casts
* @returns with code emitted for conversion (or error message output if not allowed, and stack left unchanged)
*/
public static void CastTopOfStack(IScriptCodeGen scg, Token errorAt, TokenType oldType, TokenType newType, bool explicitAllowed)
{
CastDelegate castDelegate;
string oldString = oldType.ToString();
string newString = newType.ToString();
// 'key' -> 'bool' is the only time we care about key being different than string.
if((oldString == "key") && (newString == "bool"))
{
LSLUnwrap(scg, errorAt, oldType);
scg.ilGen.Emit(errorAt, OpCodes.Call, keyToBoolMethodInfo);
LSLWrap(scg, errorAt, newType);
return;
}
// Treat key and string as same type for all other type casts.
if(oldString == "key")
oldString = "string";
if(newString == "key")
newString = "string";
// If the types are the same, there is no conceptual casting needed.
// However, there may be wraping/unwraping to/from the LSL wrappers.
if(oldString == newString)
{
if(oldType.ToLSLWrapType() != newType.ToLSLWrapType())
{
LSLUnwrap(scg, errorAt, oldType);
LSLWrap(scg, errorAt, newType);
}
return;
}
// Script-defined classes can be cast up and down the tree.
if((oldType is TokenTypeSDTypeClass) && (newType is TokenTypeSDTypeClass))
{
TokenDeclSDTypeClass oldSDTC = ((TokenTypeSDTypeClass)oldType).decl;
TokenDeclSDTypeClass newSDTC = ((TokenTypeSDTypeClass)newType).decl;
// implicit cast allowed from leaf toward root
for(TokenDeclSDTypeClass sdtc = oldSDTC; sdtc != null; sdtc = sdtc.extends)
{
if(sdtc == newSDTC)
return;
}
// explicit cast allowed from root toward leaf
for(TokenDeclSDTypeClass sdtc = newSDTC; sdtc != null; sdtc = sdtc.extends)
{
if(sdtc == oldSDTC)
{
ExplCheck(scg, errorAt, explicitAllowed, oldString, newString);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, newSDTC.sdTypeIndex);
scg.ilGen.Emit(errorAt, OpCodes.Call, sdTypeClassCastClass2ClassMethodInfo);
return;
}
}
// not on same branch
goto illcast;
}
// One script-defined interface type cannot be cast to another script-defined interface type,
// unless the old interface declares that it implements the new interface. That proves that
// the underlying object, no matter what type, implements the new interface.
if((oldType is TokenTypeSDTypeInterface) && (newType is TokenTypeSDTypeInterface))
{
TokenDeclSDTypeInterface oldDecl = ((TokenTypeSDTypeInterface)oldType).decl;
TokenDeclSDTypeInterface newDecl = ((TokenTypeSDTypeInterface)newType).decl;
if(!oldDecl.Implements(newDecl))
goto illcast;
scg.ilGen.Emit(errorAt, OpCodes.Ldstr, newType.ToString());
scg.ilGen.Emit(errorAt, OpCodes.Call, sdTypeClassCastObj2IFaceMethodInfo);
return;
}
// A script-defined class type can be implicitly cast to a script-defined interface type that it
// implements. The result is an array of delegates that give the class's implementation of the
// various methods defined by the interface.
if((oldType is TokenTypeSDTypeClass) && (newType is TokenTypeSDTypeInterface))
{
TokenDeclSDTypeClass oldSDTC = ((TokenTypeSDTypeClass)oldType).decl;
int intfIndex;
if(!oldSDTC.intfIndices.TryGetValue(newType.ToString(), out intfIndex))
goto illcast;
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, sdtcITableFieldInfo);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, intfIndex);
scg.ilGen.Emit(errorAt, OpCodes.Ldelem, typeof(Delegate[]));
return;
}
// A script-defined interface type can be explicitly cast to a script-defined class type by
// extracting the Target property from element 0 of the delegate array that is the interface
// object and making sure it casts to the correct script-defined class type.
//
// But then only if the class type implements the interface type.
if((oldType is TokenTypeSDTypeInterface) && (newType is TokenTypeSDTypeClass))
{
TokenTypeSDTypeInterface oldSDTI = (TokenTypeSDTypeInterface)oldType;
TokenTypeSDTypeClass newSDTC = (TokenTypeSDTypeClass)newType;
if(!newSDTC.decl.CanCastToIntf(oldSDTI.decl))
goto illcast;
ExplCheck(scg, errorAt, explicitAllowed, oldString, newString);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, newSDTC.decl.sdTypeIndex);
scg.ilGen.Emit(errorAt, OpCodes.Call, sdTypeClassCastIFace2ClassMethodInfo);
return;
}
// A script-defined interface type can be implicitly cast to object.
if((oldType is TokenTypeSDTypeInterface) && (newType is TokenTypeObject))
{
return;
}
// An object can be explicitly cast to a script-defined interface.
if((oldType is TokenTypeObject) && (newType is TokenTypeSDTypeInterface))
{
ExplCheck(scg, errorAt, explicitAllowed, oldString, newString);
scg.ilGen.Emit(errorAt, OpCodes.Ldstr, newString);
scg.ilGen.Emit(errorAt, OpCodes.Call, sdTypeClassCastObj2IFaceMethodInfo);
return;
}
// Cast to void is always allowed, such as discarding value from 'i++' or function return value.
if(newType is TokenTypeVoid)
{
scg.ilGen.Emit(errorAt, OpCodes.Pop);
return;
}
// Cast from undef to object or script-defined type is always allowed.
if((oldType is TokenTypeUndef) &&
((newType is TokenTypeObject) ||
(newType is TokenTypeSDTypeClass) ||
(newType is TokenTypeSDTypeInterface)))
{
return;
}
// Script-defined classes can be implicitly cast to objects.
if((oldType is TokenTypeSDTypeClass) && (newType is TokenTypeObject))
{
return;
}
// Script-defined classes can be explicitly cast from objects and other script-defined classes.
// Note that we must manually check that it is the correct SDTypeClass however because as far as
// mono is concerned, all SDTypeClass's are the same.
if((oldType is TokenTypeObject) && (newType is TokenTypeSDTypeClass))
{
ExplCheck(scg, errorAt, explicitAllowed, oldString, newString);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, ((TokenTypeSDTypeClass)newType).decl.sdTypeIndex);
scg.ilGen.Emit(errorAt, OpCodes.Call, sdTypeClassCastClass2ClassMethodInfo);
return;
}
// Delegates can be implicitly cast to/from objects.
if((oldType is TokenTypeSDTypeDelegate) && (newType is TokenTypeObject))
{
return;
}
if((oldType is TokenTypeObject) && (newType is TokenTypeSDTypeDelegate))
{
scg.ilGen.Emit(errorAt, OpCodes.Castclass, newType.ToSysType());
return;
}
// Some actual conversion is needed, see if it is in table of legal casts.
string key = oldString + " " + newString;
if(!legalTypeCasts.TryGetValue(key, out castDelegate))
{
key = oldString + "*" + newString;
if(!legalTypeCasts.TryGetValue(key, out castDelegate))
goto illcast;
ExplCheck(scg, errorAt, explicitAllowed, oldString, newString);
}
// Ok, output cast. But make sure it is in native form without any LSL wrapping
// before passing to our casting routine. Then if caller is expecting an LSL-
// wrapped value on the stack upon return, wrap it up after our casting.
LSLUnwrap(scg, errorAt, oldType);
castDelegate(scg, errorAt);
LSLWrap(scg, errorAt, newType);
return;
illcast:
scg.ErrorMsg(errorAt, "illegal to cast from " + oldString + " to " + newString);
if(!(oldType is TokenTypeVoid))
scg.ilGen.Emit(errorAt, OpCodes.Pop);
scg.PushDefaultValue(newType);
}
private static void ExplCheck(IScriptCodeGen scg, Token errorAt, bool explicitAllowed, string oldString, string newString)
{
if(!explicitAllowed)
{
scg.ErrorMsg(errorAt, "must explicitly cast from " + oldString + " to " + newString);
}
}
/**
* @brief If value on the stack is an LSL-style wrapped value, unwrap it.
*/
public static void LSLUnwrap(IScriptCodeGen scg, Token errorAt, TokenType type)
{
if(type.ToLSLWrapType() == typeof(LSL_Float))
{
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, lslFloatValueFieldInfo);
}
if(type.ToLSLWrapType() == typeof(LSL_Integer))
{
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, lslIntegerValueFieldInfo);
}
if(type.ToLSLWrapType() == typeof(LSL_String))
{
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, lslStringValueFieldInfo);
}
}
/**
* @brief If caller wants the unwrapped value on stack wrapped LSL-style, wrap it.
*/
private static void LSLWrap(IScriptCodeGen scg, Token errorAt, TokenType type)
{
if(type.ToLSLWrapType() == typeof(LSL_Float))
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, lslFloatConstructorInfo);
}
if(type.ToLSLWrapType() == typeof(LSL_Integer))
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, lslIntegerConstructorInfo);
}
if(type.ToLSLWrapType() == typeof(LSL_String))
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, lslStringConstructorInfo);
}
}
/**
* @brief These routines output code to perform casting.
* They can assume there are no LSL wrapped values on input
* and they should not output an LSL wrapped value.
*/
private static void TypeCastArray2Object(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastBool2Float(IScriptCodeGen scg, Token errorAt)
{
if(typeof(double) == typeof(float))
{
scg.ilGen.Emit(errorAt, OpCodes.Conv_R4);
}
else if(typeof(double) == typeof(double))
{
scg.ilGen.Emit(errorAt, OpCodes.Conv_R8);
}
else
{
throw new Exception("unknown type");
}
}
private static void TypeCastBool2Integer(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastBool2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(bool));
}
private static void TypeCastChar2Integer(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastChar2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, charToListMethodInfo);
}
private static void TypeCastChar2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(char));
}
private static void TypeCastChar2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, charToStringMethodInfo);
}
private static void TypeCastExc2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, excToListMethodInfo);
}
private static void TypeCastExc2Object(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastExc2String(IScriptCodeGen scg, Token errorAt)
{
scg.PushXMRInst();
scg.ilGen.Emit(errorAt, OpCodes.Call, excToStringMethodInfo);
}
private static void TypeCastFloat2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Ldc_R4, 0.0f);
scg.ilGen.Emit(errorAt, OpCodes.Ceq);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4_1);
scg.ilGen.Emit(errorAt, OpCodes.Xor);
}
private static void TypeCastFloat2Integer(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Conv_I4);
}
private static void TypeCastFloat2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(double));
}
private static void TypeCastInteger2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4_0);
scg.ilGen.Emit(errorAt, OpCodes.Ceq);
scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4_1);
scg.ilGen.Emit(errorAt, OpCodes.Xor);
}
private static void TypeCastInteger2Char(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastInteger2Float(IScriptCodeGen scg, Token errorAt)
{
if(typeof(double) == typeof(float))
{
scg.ilGen.Emit(errorAt, OpCodes.Conv_R4);
}
else if(typeof(double) == typeof(double))
{
scg.ilGen.Emit(errorAt, OpCodes.Conv_R8);
}
else
{
throw new Exception("unknown type");
}
}
private static void TypeCastInteger2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(int));
}
private static void TypeCastList2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, listToBoolMethodInfo);
}
private static void TypeCastList2Object(IScriptCodeGen scg, Token errorAt)
{
if(typeof(LSL_List).IsValueType)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(LSL_List));
}
}
private static void TypeCastObject2Array(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Castclass, typeof(XMR_Array));
}
private static void TypeCastObject2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Unbox_Any, typeof(bool));
}
private static void TypeCastObject2Char(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Unbox_Any, typeof(char));
}
private static void TypeCastObject2Exc(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Castclass, typeof(Exception));
}
private static void TypeCastObject2Float(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToFloatMethodInfo);
}
private static void TypeCastObject2Integer(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToIntegerMethodInfo);
}
private static void TypeCastObject2List(IScriptCodeGen scg, Token errorAt)
{
if(typeof(LSL_List).IsValueType)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToListMethodInfo);
}
else
{
scg.ilGen.Emit(errorAt, OpCodes.Castclass, typeof(LSL_List));
}
}
private static void TypeCastObject2Rotation(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToRotationMethodInfo);
}
private static void TypeCastObject2Vector(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToVectorMethodInfo);
}
private static void TypeCastRotation2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, rotationToBoolMethodInfo);
}
private static void TypeCastRotation2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(LSL_Rotation));
}
private static void TypeCastString2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, stringToBoolMethodInfo);
}
private static void TypeCastString2Object(IScriptCodeGen scg, Token errorAt)
{
}
private static void TypeCastString2Rotation(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, rotationConstrucorStringInfo);
}
private static void TypeCastString2Vector(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, vectorConstrucorStringInfo);
}
private static void TypeCastVector2Bool(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, vectorToBoolMethodInfo);
}
private static void TypeCastVector2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, vectorToListMethodInfo);
}
private static void TypeCastVector2Object(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Box, typeof(LSL_Vector));
}
private static void TypeCastBool2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, boolToListMethodInfo);
}
private static void TypeCastBool2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, boolToStringMethodInfo);
}
private static void TypeCastFloat2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, floatToListMethodInfo);
}
private static void TypeCastFloat2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, floatToStringMethodInfo);
}
private static void TypeCastInteger2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, integerToListMethodInfo);
}
private static void TypeCastInteger2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, intToStringMethodInfo);
}
private static void TypeCastList2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, listToStringMethodInfo);
}
private static void TypeCastObject2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, objectToStringMethodInfo);
}
private static void TypeCastRotation2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, rotationToListMethodInfo);
}
private static void TypeCastRotation2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, rotationToStringMethodInfo);
}
private static void TypeCastString2Float(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, floatConstructorStringInfo);
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, lslFloatValueFieldInfo);
}
private static void TypeCastString2Integer(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Newobj, integerConstructorStringInfo);
scg.ilGen.Emit(errorAt, OpCodes.Ldfld, lslIntegerValueFieldInfo);
}
private static void TypeCastString2List(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, stringToListMethodInfo);
}
private static void TypeCastVector2String(IScriptCodeGen scg, Token errorAt)
{
scg.ilGen.Emit(errorAt, OpCodes.Call, vectorToStringMethodInfo);
}
/*
* Because the calls are funky, let the compiler handle them.
*/
public static bool RotationToBool(LSL_Rotation x)
{
return !x.Equals(ScriptBaseClass.ZERO_ROTATION);
}
public static bool StringToBool(string x)
{
return x.Length > 0;
}
public static bool VectorToBool(LSL_Vector x)
{
return !x.Equals(ScriptBaseClass.ZERO_VECTOR);
}
public static string BoolToString(bool x)
{
return x ? "1" : "0";
}
public static string CharToString(char x)
{
return x.ToString();
}
public static string FloatToString(double x)
{
return x.ToString("0.000000");
}
public static string IntegerToString(int x)
{
return x.ToString();
}
public static bool KeyToBool(string x)
{
return (x != "") && (x != ScriptBaseClass.NULL_KEY);
}
public static bool ListToBool(LSL_List x)
{
return x.Length != 0;
}
public static string ListToString(LSL_List x)
{
return x.ToString();
}
public static string ObjectToString(object x)
{
return (x == null) ? null : x.ToString();
}
public static string RotationToString(LSL_Rotation x)
{
return x.ToString();
}
public static string VectorToString(LSL_Vector x)
{
return x.ToString();
}
public static LSL_List BoolToList(bool b)
{
return new LSL_List(new object[] { new LSL_Integer(b ? 1 : 0) });
}
public static LSL_List CharToList(char c)
{
return new LSL_List(new object[] { new LSL_Integer(c) });
}
public static LSL_List ExcToList(Exception e)
{
return new LSL_List(new object[] { e });
}
public static LSL_List VectorToList(LSL_Vector v)
{
return new LSL_List(new object[] { v });
}
public static LSL_List FloatToList(double f)
{
return new LSL_List(new object[] { new LSL_Float(f) });
}
public static LSL_List IntegerToList(int i)
{
return new LSL_List(new object[] { new LSL_Integer(i) });
}
public static LSL_List RotationToList(LSL_Rotation r)
{
return new LSL_List(new object[] { r });
}
public static LSL_List StringToList(string s)
{
return new LSL_List(new object[] { new LSL_String(s) });
}
public static double ObjectToFloat(object x)
{
if(x is LSL_String)
return double.Parse(((LSL_String)x).m_string);
if(x is string)
return double.Parse((string)x);
if(x is LSL_Float)
return (double)(LSL_Float)x;
if(x is LSL_Integer)
return (double)(int)(LSL_Integer)x;
if(x is int)
return (double)(int)x;
return (double)x;
}
public static int ObjectToInteger(object x)
{
if(x is LSL_String)
return int.Parse(((LSL_String)x).m_string);
if(x is string)
return int.Parse((string)x);
if(x is LSL_Integer)
return (int)(LSL_Integer)x;
return (int)x;
}
public static LSL_List ObjectToList(object x)
{
return (LSL_List)x;
}
public static LSL_Rotation ObjectToRotation(object x)
{
if(x is LSL_String)
return new LSL_Rotation(((LSL_String)x).m_string);
if(x is string)
return new LSL_Rotation((string)x);
return (LSL_Rotation)x;
}
public static LSL_Vector ObjectToVector(object x)
{
if(x is LSL_String)
return new LSL_Vector(((LSL_String)x).m_string);
if(x is string)
return new LSL_Vector((string)x);
return (LSL_Vector)x;
}
public static string ExceptionToString(Exception x, XMRInstAbstract inst)
{
return XMRInstAbstract.xmrExceptionTypeName(x) + ": " + XMRInstAbstract.xmrExceptionMessage(x) +
"\n" + inst.xmrExceptionStackTrace(x);
}
/*
* These are used by event handler entrypoints to remove any LSL wrapping
* from the argument list and return the unboxed/unwrapped value.
*/
public static double EHArgUnwrapFloat(object x)
{
if(x is LSL_Float)
return (double)(LSL_Float)x;
return (double)x;
}
public static int EHArgUnwrapInteger(object x)
{
if(x is LSL_Integer)
return (int)(LSL_Integer)x;
return (int)x;
}
public static LSL_Rotation EHArgUnwrapRotation(object x)
{
if(x is OpenMetaverse.Quaternion)
{
OpenMetaverse.Quaternion q = (OpenMetaverse.Quaternion)x;
return new LSL_Rotation(q.X, q.Y, q.Z, q.W);
}
return (LSL_Rotation)x;
}
public static string EHArgUnwrapString(object x)
{
if(x is LSL_Key)
return (string)(LSL_Key)x;
if(x is LSL_String)
return (string)(LSL_String)x;
return (string)x;
}
public static LSL_Vector EHArgUnwrapVector(object x)
{
if(x is OpenMetaverse.Vector3)
{
OpenMetaverse.Vector3 v = (OpenMetaverse.Vector3)x;
return new LSL_Vector(v.X, v.Y, v.Z);
}
return (LSL_Vector)x;
}
}
}
| |
namespace LeetABit.Binary
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
public readonly struct ReadOnlyBitwiseMemory<T> : IEquatable<ReadOnlyBitwiseMemory<T>>, IBitBlock
{
private readonly object _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveFlagsBitMask = int.MaxValue;
public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>);
public int Length => _length;
public bool IsEmpty => _length == 0;
public unsafe ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref T ptr = ref Unsafe.NullRef<T>();
int length = 0;
object @object = _object;
if (@object != null)
{
if (typeof(T) == typeof(char) && @object.GetType() == typeof(string))
{
ptr = ref Unsafe.As<char, T>(ref Unsafe.As<string>(@object).GetRawStringData());
length = Unsafe.As<string>(@object).Length;
}
else if (RuntimeHelpers.ObjectHasComponentSize(@object))
{
ptr = ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(@object));
length = Unsafe.As<T[]>(@object).Length;
}
else
{
Span<T> span = Unsafe.As<MemoryManager<T>>(@object).GetSpan();
ptr = ref MemoryMarshal.GetReference(span);
length = span.Length;
}
nuint num = (uint)_index & 0x7FFFFFFFu;
int length2 = _length;
if ((ulong)((long)num + (long)(uint)length2) > (ulong)(uint)length)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
ptr = ref Unsafe.Add(ref ptr, (IntPtr)(void*)num);
length = length2;
}
return new ReadOnlySpan<T>(ref ptr, length);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array)
{
if (array == null)
{
this = default(ReadOnlyMemory<T>);
return;
}
_object = array;
_index = 0;
_length = array!.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
this = default(ReadOnlyMemory<T>);
return;
}
if ((ulong)((long)(uint)start + (long)(uint)length) > (ulong)(uint)array!.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
_object = array;
_index = start;
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object obj, int start, int length)
{
_object = obj;
_index = start;
_length = length;
}
public static implicit operator ReadOnlyMemory<T>(T[]? array)
{
return new ReadOnlyMemory<T>(array);
}
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment)
{
return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
}
public override string ToString()
{
if (typeof(T) == typeof(char))
{
string text = _object as string;
if (text == null)
{
return Span.ToString();
}
return text.Substring(_index, _length);
}
return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length}]";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
return new ReadOnlyMemory<T>(_object, _index + start, _length - start);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
if ((ulong)((long)(uint)start + (long)(uint)length) > (ulong)(uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
public void CopyTo(Memory<T> destination)
{
Span.CopyTo(destination.Span);
}
public bool TryCopyTo(Memory<T> destination)
{
return Span.TryCopyTo(destination.Span);
}
public unsafe MemoryHandle Pin()
{
object @object = _object;
if (@object != null)
{
if (typeof(T) == typeof(char))
{
string text = @object as string;
if (text != null)
{
GCHandle handle = GCHandle.Alloc(@object, GCHandleType.Pinned);
return new MemoryHandle(Unsafe.AsPointer(ref Unsafe.Add(ref text.GetRawStringData(), _index)), handle);
}
}
if (RuntimeHelpers.ObjectHasComponentSize(@object))
{
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(@object))), _index & 0x7FFFFFFF);
return new MemoryHandle(pointer);
}
GCHandle handle2 = GCHandle.Alloc(@object, GCHandleType.Pinned);
void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(@object))), _index);
return new MemoryHandle(pointer2, handle2);
}
return Unsafe.As<MemoryManager<T>>(@object).Pin(_index);
}
return default(MemoryHandle);
}
public T[] ToArray()
{
return Span.ToArray();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals([NotNullWhen(true)] object? obj)
{
if (obj is ReadOnlyMemory<T>)
{
ReadOnlyMemory<T> other = (ReadOnlyMemory<T>)obj;
return Equals(other);
}
if (obj is Memory<T>)
{
Memory<T> memory = (Memory<T>)obj;
return Equals(memory);
}
return false;
}
public bool Equals(ReadOnlyMemory<T> other)
{
if (_object == other._object && _index == other._index)
{
return _length == other._length;
}
return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
if (_object == null)
{
return 0;
}
return HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Knot
{
public float distanceFromStart = -1f;
public CatmullRomSpline.SubKnot[] subKnots = new CatmullRomSpline.SubKnot[CatmullRomSpline.NbSubSegmentPerSegment+1]; //[0, 1]
public Vector3 position;
public Knot(Vector3 position)
{
this.position = position;
}
public void Invalidate()
{
distanceFromStart = -1f;
}
}
public class CatmullRomSpline
{
public struct SubKnot
{
public float distanceFromStart;
public Vector3 position;
public Vector3 tangent;
}
public class Marker
{
public int segmentIndex;
public int subKnotAIndex;
public int subKnotBIndex;
public float lerpRatio;
}
public List<Knot> knots = new List<Knot>();
public const int NbSubSegmentPerSegment = 10;
private const int MinimumKnotNb = 4;
private const int FirstSegmentKnotIndex = 2;
public int NbSegments { get { return System.Math.Max(0, knots.Count - 3); } }
public Vector3 FindPositionFromDistance(float distance)
{
Vector3 tangent = Vector3.zero;
Marker result = new Marker();
bool foundSegment = PlaceMarker(result, distance);
if(foundSegment)
{
tangent = GetPosition(result);
}
return tangent;
}
public Vector3 FindTangentFromDistance(float distance)
{
Vector3 tangent = Vector3.zero;
Marker result = new Marker();
bool foundSegment = PlaceMarker(result, distance);
if(foundSegment)
{
tangent = GetTangent(result);
}
return tangent;
}
public static Vector3 ComputeBinormal(Vector3 tangent, Vector3 normal)
{
return Vector3.Cross(tangent, normal).normalized;
}
public float Length()
{
if(NbSegments == 0) return 0f;
//Parametrize();
return System.Math.Max(0, GetSegmentDistanceFromStart(NbSegments-1));
}
public void Clear()
{
knots.Clear();
}
public void MoveMarker(Marker marker, float distance) //in Unity units
{
PlaceMarker(marker, distance, marker);
}
public Vector3 GetPosition(Marker marker)
{
Vector3 pos = Vector3.zero;
if(NbSegments == 0) return pos;
SubKnot[] subKnots = GetSegmentSubKnots(marker.segmentIndex);
pos = Vector3.Lerp(subKnots[marker.subKnotAIndex].position,
subKnots[marker.subKnotBIndex].position, marker.lerpRatio);
return pos;
}
public Vector3 GetTangent(Marker marker)
{
Vector3 tangent = Vector3.zero;
if(NbSegments == 0) return tangent;
SubKnot[] subKnots = GetSegmentSubKnots(marker.segmentIndex);
tangent = Vector3.Lerp(subKnots[marker.subKnotAIndex].tangent,
subKnots[marker.subKnotBIndex].tangent, marker.lerpRatio);
return tangent;
}
private float Epsilon { get { return 1f / NbSubSegmentPerSegment; } }
private SubKnot[] GetSegmentSubKnots(int i)
{
return knots[FirstSegmentKnotIndex+i].subKnots;
}
public float GetSegmentDistanceFromStart(int i)
{
return knots[FirstSegmentKnotIndex+i].distanceFromStart;
}
private bool IsSegmentValid(int i)
{
return knots[i].distanceFromStart != -1f && knots[i+1].distanceFromStart != -1f &&
knots[i+2].distanceFromStart != -1f && knots[i+3].distanceFromStart != -1f;
}
private bool OutOfBoundSegmentIndex(int i)
{
return i < 0 || i >= NbSegments;
}
public void Parametrize()
{
Parametrize(0, NbSegments-1);
}
public void Parametrize(int fromSegmentIndex, int toSegmentIndex)
{
if(knots.Count < MinimumKnotNb) return;
int nbSegments = System.Math.Min(toSegmentIndex+1, NbSegments);
fromSegmentIndex = System.Math.Max(0, fromSegmentIndex);
float totalDistance = 0;
if(fromSegmentIndex > 0)
{
totalDistance = GetSegmentDistanceFromStart(fromSegmentIndex-1);
}
for(int i=fromSegmentIndex; i<nbSegments; i++)
{
/*if(IsSegmentValid(i) && !force)
{
totalDistance = GetSegmentDistanceFromStart(i);
continue;
}*/
SubKnot[] subKnots = GetSegmentSubKnots(i);
for(int j=0; j<subKnots.Length; j++)
{
SubKnot sk = new SubKnot();
sk.distanceFromStart = totalDistance += ComputeLengthOfSegment(i, (j-1)*Epsilon, j*Epsilon);
sk.position = GetPositionOnSegment(i, j*Epsilon);
sk.tangent = GetTangentOnSegment(i, j*Epsilon);
subKnots[j] = sk;
}
knots[FirstSegmentKnotIndex+i].distanceFromStart = totalDistance;
}
}
public bool PlaceMarker(Marker result, float distance, Marker from = null)
{
//result = new Marker();
SubKnot[] subKnots;
int nbSegments = NbSegments;
if(nbSegments == 0) return false;
//Parametrize();
if(distance <= 0)
{
result.segmentIndex = 0;
result.subKnotAIndex = 0;
result.subKnotBIndex = 1;
result.lerpRatio = 0f;
return true;
}
else if(distance >= Length())
{
subKnots = GetSegmentSubKnots(nbSegments-1);
result.segmentIndex = nbSegments-1;
result.subKnotAIndex = subKnots.Length-2;
result.subKnotBIndex = subKnots.Length-1;
result.lerpRatio = 1f;
return true;
}
int fromSegmentIndex = 0;
int fromSubKnotIndex = 1;
if(from != null)
{
fromSegmentIndex = from.segmentIndex;
//fromSubKnotIndex = from.subKnotAIndex;
}
for(int i=fromSegmentIndex; i<nbSegments; i++)
{
if(distance > GetSegmentDistanceFromStart(i)) continue;
subKnots = GetSegmentSubKnots(i);
for(int j=fromSubKnotIndex; j<subKnots.Length; j++)
{
SubKnot sk = subKnots[j];
if(distance > sk.distanceFromStart) continue;
result.segmentIndex = i;
result.subKnotAIndex = j-1;
result.subKnotBIndex = j;
result.lerpRatio = 1f - ((sk.distanceFromStart - distance) /
(sk.distanceFromStart - subKnots[j-1].distanceFromStart));
break;
}
break;
}
return true;
}
private float ComputeLength()
{
if(knots.Count < 4) return 0;
float length = 0;
int nbSegments = NbSegments;
for(int i=0; i<nbSegments; i++)
{
length += ComputeLengthOfSegment(i, 0f, 1f);
}
return length;
}
private float ComputeLengthOfSegment(int segmentIndex, float from, float to)
{
float length = 0;
from = Mathf.Clamp01(from);
to = Mathf.Clamp01(to);
Vector3 lastPoint = GetPositionOnSegment(segmentIndex, from);
for(float j=from+Epsilon; j<to+Epsilon/2f; j+=Epsilon)
{
Vector3 point = GetPositionOnSegment(segmentIndex, j);
length += Vector3.Distance(point, lastPoint);
lastPoint = point;
}
return length;
}
public void DebugDrawEquallySpacedDots()
{
Gizmos.color = Color.red;
int nbPoints = NbSubSegmentPerSegment*NbSegments;
float length = Length();
Marker marker = new Marker();
PlaceMarker(marker, 0f);
for(int i=0; i<=nbPoints; i++)
{
MoveMarker(marker, i*(length/nbPoints));
Vector3 position = GetPosition(marker);
//Vector3 tangent = GetTangent(marker);
//Vector3 position = FindPositionFromDistance(i*(length/nbPoints));
//Vector3 tangent = FindTangentFromDistance(i*(length/nbPoints));
//Vector3 binormal = ComputeBinormal(tangent, new Vector3(0, 0, 1));
Gizmos.DrawWireSphere(position, 0.025f);
//Debug.DrawRay(position, binormal * 0.2f, Color.green);
}
}
public void DebugDrawSubKnots()
{
Gizmos.color = Color.yellow;
int nbSegments = NbSegments;
for(int i=0; i<nbSegments; i++)
{
SubKnot[] subKnots = GetSegmentSubKnots(i);
for(int j=0; j<subKnots.Length; j++)
{
Gizmos.DrawWireSphere(subKnots[j].position, 0.025f);
//Gizmos.DrawWireSphere(new Vector3(segments[i].subSegments[j].length, 0, 0), 0.025f);
}
}
}
public void DebugDrawSpline()
{
if(knots.Count >= 4)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(knots[0].position, 0.2f);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(knots[knots.Count-1].position, 0.2f);
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(knots[knots.Count-2].position, 0.2f);
int nbSegments = NbSegments;
for(int i=0; i<nbSegments; i++)
{
Vector3 lastPoint = GetPositionOnSegment(i, 0f);
Gizmos.DrawWireSphere(lastPoint, 0.2f);
for(float j=Epsilon; j<1f+Epsilon/2f; j+=Epsilon)
{
Vector3 point = GetPositionOnSegment(i, j);
Debug.DrawLine(lastPoint, point, Color.white);
lastPoint = point;
}
}
}
}
private Vector3 GetPositionOnSegment(int segmentIndex, float t)
{
return FindSplinePoint(knots[segmentIndex].position, knots[segmentIndex+1].position,
knots[segmentIndex+2].position, knots[segmentIndex+3].position, t);
}
private Vector3 GetTangentOnSegment(int segmentIndex, float t)
{
return FindSplineTangent(knots[segmentIndex].position, knots[segmentIndex+1].position,
knots[segmentIndex+2].position, knots[segmentIndex+3].position, t).normalized;
}
private static Vector3 FindSplinePoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Vector3 ret = new Vector3();
float t2 = t * t;
float t3 = t2 * t;
ret.x = 0.5f * ((2.0f * p1.x) +
(-p0.x + p2.x) * t +
(2.0f * p0.x - 5.0f * p1.x + 4 * p2.x - p3.x) * t2 +
(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) * t3);
ret.y = 0.5f * ((2.0f * p1.y) +
(-p0.y + p2.y) * t +
(2.0f * p0.y - 5.0f * p1.y + 4 * p2.y - p3.y) * t2 +
(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) * t3);
ret.z = 0.5f * ((2.0f * p1.z) +
(-p0.z + p2.z) * t +
(2.0f * p0.z - 5.0f * p1.z + 4 * p2.z - p3.z) * t2 +
(-p0.z + 3.0f * p1.z - 3.0f * p2.z + p3.z) * t3);
return ret;
}
private static Vector3 FindSplineTangent(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Vector3 ret = new Vector3();
float t2 = t * t;
ret.x = 0.5f * (-p0.x + p2.x) +
(2.0f * p0.x - 5.0f * p1.x + 4 * p2.x - p3.x) * t +
(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) * t2 * 1.5f;
ret.y = 0.5f * (-p0.y + p2.y) +
(2.0f * p0.y - 5.0f * p1.y + 4 * p2.y - p3.y) * t +
(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) * t2 * 1.5f;
ret.z = 0.5f * (-p0.z + p2.z) +
(2.0f * p0.z - 5.0f * p1.z + 4 * p2.z - p3.z) * t +
(-p0.z + 3.0f * p1.z - 3.0f * p2.z + p3.z) * t2 * 1.5f;
return ret;
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
namespace NAudio.Wave
{
/// <summary>
/// Represents a wave out device
/// </summary>
public class WaveOut : IWavePlayer
{
private IntPtr hWaveOut;
private WaveOutBuffer[] buffers;
private IWaveProvider waveStream;
private volatile PlaybackState playbackState;
private WaveInterop.WaveCallback callback;
private float volume = 1;
private WaveCallbackInfo callbackInfo;
private object waveOutLock;
private int queuedBuffers;
private SynchronizationContext syncContext;
/// <summary>
/// Indicates playback has stopped automatically
/// </summary>
public event EventHandler<StoppedEventArgs> PlaybackStopped;
/// <summary>
/// Retrieves the capabilities of a waveOut device
/// </summary>
/// <param name="devNumber">Device to test</param>
/// <returns>The WaveOut device capabilities</returns>
public static WaveOutCapabilities GetCapabilities(int devNumber)
{
WaveOutCapabilities caps = new WaveOutCapabilities();
int structSize = Marshal.SizeOf(caps);
MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, out caps, structSize), "waveOutGetDevCaps");
return caps;
}
/// <summary>
/// Returns the number of Wave Out devices available in the system
/// </summary>
public static Int32 DeviceCount
{
get
{
return WaveInterop.waveOutGetNumDevs();
}
}
/// <summary>
/// Gets or sets the desired latency in milliseconds
/// Should be set before a call to Init
/// </summary>
public int DesiredLatency { get; set; }
/// <summary>
/// Gets or sets the number of buffers used
/// Should be set before a call to Init
/// </summary>
public int NumberOfBuffers { get; set; }
/// <summary>
/// Gets or sets the device number
/// Should be set before a call to Init
/// This must be between 0 and <see>DeviceCount</see> - 1.
/// </summary>
public int DeviceNumber { get; set; }
/// <summary>
/// Creates a default WaveOut device
/// Will use window callbacks if called from a GUI thread, otherwise function
/// callbacks
/// </summary>
public WaveOut()
: this(SynchronizationContext.Current == null ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow())
{
}
/// <summary>
/// Creates a WaveOut device using the specified window handle for callbacks
/// </summary>
/// <param name="windowHandle">A valid window handle</param>
public WaveOut(IntPtr windowHandle)
: this(WaveCallbackInfo.ExistingWindow(windowHandle))
{
}
/// <summary>
/// Opens a WaveOut device
/// </summary>
public WaveOut(WaveCallbackInfo callbackInfo)
{
this.syncContext = SynchronizationContext.Current;
// set default values up
this.DeviceNumber = 0;
this.DesiredLatency = 300;
this.NumberOfBuffers = 2;
this.callback = new WaveInterop.WaveCallback(Callback);
this.waveOutLock = new object();
this.callbackInfo = callbackInfo;
callbackInfo.Connect(this.callback);
}
/// <summary>
/// Initialises the WaveOut device
/// </summary>
/// <param name="waveProvider">WaveProvider to play</param>
public void Init(IWaveProvider waveProvider)
{
this.waveStream = waveProvider;
int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers);
MmResult result;
lock (waveOutLock)
{
result = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback);
}
MmException.Try(result, "waveOutOpen");
buffers = new WaveOutBuffer[NumberOfBuffers];
playbackState = PlaybackState.Stopped;
for (int n = 0; n < NumberOfBuffers; n++)
{
buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
}
}
/// <summary>
/// Start playing the audio from the WaveStream
/// </summary>
public void Play()
{
if (playbackState == PlaybackState.Stopped)
{
playbackState = PlaybackState.Playing;
Debug.Assert(queuedBuffers == 0, "Buffers already queued on play");
EnqueueBuffers();
}
else if (playbackState == PlaybackState.Paused)
{
EnqueueBuffers();
Resume();
playbackState = PlaybackState.Playing;
}
}
private void EnqueueBuffers()
{
for (int n = 0; n < NumberOfBuffers; n++)
{
if (!buffers[n].InQueue)
{
if (buffers[n].OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
else
{
playbackState = PlaybackState.Stopped;
break;
}
//Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] requeued", n));
}
else
{
//Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] already queued", n));
}
}
}
/// <summary>
/// Pause the audio
/// </summary>
public void Pause()
{
if (playbackState == PlaybackState.Playing)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutPause(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutPause");
}
playbackState = PlaybackState.Paused;
}
}
/// <summary>
/// Resume playing after a pause from the same position
/// </summary>
public void Resume()
{
if (playbackState == PlaybackState.Paused)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutRestart(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutRestart");
}
playbackState = PlaybackState.Playing;
}
}
/// <summary>
/// Stop and reset the WaveOut device
/// </summary>
public void Stop()
{
if (playbackState != PlaybackState.Stopped)
{
// in the call to waveOutReset with function callbacks
// some drivers will block here until OnDone is called
// for every buffer
playbackState = PlaybackState.Stopped; // set this here to avoid a problem with some drivers whereby
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutReset(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutReset");
}
// with function callbacks, waveOutReset will call OnDone,
// and so PlaybackStopped must not be raised from the handler
// we know playback has definitely stopped now, so raise callback
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback)
{
RaisePlaybackStoppedEvent(null);
}
}
}
/// <summary>
/// Gets the current position in bytes from the wave output device.
/// (n.b. this is not the same thing as the position within your reader
/// stream - it calls directly into waveOutGetPosition)
/// </summary>
/// <returns>Position in bytes</returns>
public long GetPosition()
{
lock (waveOutLock)
{
MmTime mmTime = new MmTime();
mmTime.wType = MmTime.TIME_BYTES; // request results in bytes, TODO: perhaps make this a little more flexible and support the other types?
MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, out mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition");
if (mmTime.wType != MmTime.TIME_BYTES)
throw new Exception(string.Format("waveOutGetPosition: wType -> Expected {0}, Received {1}", MmTime.TIME_BYTES, mmTime.wType));
return mmTime.cb;
}
}
/// <summary>
/// Playback State
/// </summary>
public PlaybackState PlaybackState
{
get { return playbackState; }
}
/// <summary>
/// Volume for this device 1.0 is full scale
/// </summary>
public float Volume
{
get
{
return volume;
}
set
{
volume = value;
float left = volume;
float right = volume;
int stereoVolume = (int)(left * 0xFFFF) + ((int)(right * 0xFFFF) << 16);
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutSetVolume(hWaveOut, stereoVolume);
}
MmException.Try(result,"waveOutSetVolume");
}
}
#region Dispose Pattern
/// <summary>
/// Closes this WaveOut device
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
/// <summary>
/// Closes the WaveOut device and disposes of buffers
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
protected void Dispose(bool disposing)
{
Stop();
if (disposing)
{
if (buffers != null)
{
for (int n = 0; n < buffers.Length; n++)
{
if (buffers[n] != null)
{
buffers[n].Dispose();
}
}
buffers = null;
}
}
lock (waveOutLock)
{
WaveInterop.waveOutClose(hWaveOut);
}
if (disposing)
{
callbackInfo.Disconnect();
}
}
/// <summary>
/// Finalizer. Only called when user forgets to call <see>Dispose</see>
/// </summary>
~WaveOut()
{
System.Diagnostics.Debug.Assert(false, "WaveOut device was not closed");
Dispose(false);
}
#endregion
// made non-static so that playing can be stopped here
private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved)
{
if (uMsg == WaveInterop.WaveMessage.WaveOutDone)
{
GCHandle hBuffer = (GCHandle)wavhdr.userData;
WaveOutBuffer buffer = (WaveOutBuffer)hBuffer.Target;
Interlocked.Decrement(ref queuedBuffers);
Exception exception = null;
// check that we're not here through pressing stop
if (PlaybackState == PlaybackState.Playing)
{
// to avoid deadlocks in Function callback mode,
// we lock round this whole thing, which will include the
// reading from the stream.
// this protects us from calling waveOutReset on another
// thread while a WaveOutWrite is in progress
lock (waveOutLock)
{
try
{
if (buffer.OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
}
catch (Exception e)
{
// one likely cause is soundcard being unplugged
exception = e;
}
}
}
if (queuedBuffers == 0)
{
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback && playbackState == Wave.PlaybackState.Stopped)
{
// the user has pressed stop
// DO NOT raise the playback stopped event from here
// since on the main thread we are still in the waveOutReset function
// Playback stopped will be raised elsewhere
}
else
{
RaisePlaybackStoppedEvent(exception);
}
}
}
}
private void RaisePlaybackStoppedEvent(Exception e)
{
var handler = PlaybackStopped;
if (handler != null)
{
if (this.syncContext == null)
{
handler(this, new StoppedEventArgs(e));
}
else
{
this.syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null);
}
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Python.Parsing;
using Microsoft.VisualStudio.Debugger;
namespace Microsoft.PythonTools.Debugger.Concord.Proxies {
[DebuggerDisplay("& {Read()}")]
internal struct ByteProxy : IWritableDataProxy<Byte> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public ByteProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Byte); }
}
public unsafe Byte Read() {
Byte result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Byte));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Byte value) {
Process.WriteMemory(Address, new[] { value });
}
void IWritableDataProxy.Write(object value) {
Write((Byte)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct SByteProxy : IWritableDataProxy<SByte> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public SByteProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(SByte); }
}
public unsafe SByte Read() {
SByte result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(SByte));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(SByte value) {
Process.WriteMemory(Address, new[] { (byte)value });
}
void IWritableDataProxy.Write(object value) {
Write((SByte)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct Int16Proxy : IWritableDataProxy<Int16> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public Int16Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Int16); }
}
public unsafe Int16 Read() {
Int16 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int16));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Int16 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((Int16)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct UInt16Proxy : IWritableDataProxy<UInt16> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public UInt16Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(UInt16); }
}
public unsafe UInt16 Read() {
UInt16 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt16));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(UInt16 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((UInt16)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct Int32Proxy : IWritableDataProxy<Int32> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public Int32Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Int32); }
}
public unsafe Int32 Read() {
Int32 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int32));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Int32 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((Int32)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct UInt32Proxy : IWritableDataProxy<UInt32> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public UInt32Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(UInt32); }
}
public unsafe UInt32 Read() {
UInt32 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt32));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(UInt32 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((UInt32)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct Int32EnumProxy<TEnum> : IWritableDataProxy<TEnum> {
public Int32Proxy UnderlyingProxy { get; private set; }
[SuppressMessage("Microsoft.Usage", "CA2207:InitializeValueTypeStaticFieldsInline",
Justification = ".cctor used for debug check, not initialization")]
static Int32EnumProxy() {
Debug.Assert(typeof(TEnum).IsSubclassOf(typeof(Enum)));
}
public Int32EnumProxy(DkmProcess process, ulong address)
: this() {
UnderlyingProxy = new Int32Proxy(process, address);
}
public DkmProcess Process {
get { return UnderlyingProxy.Process; }
}
public ulong Address {
get { return UnderlyingProxy.Address; }
}
public long ObjectSize {
get { return UnderlyingProxy.ObjectSize; }
}
public unsafe TEnum Read() {
return (TEnum)Enum.ToObject(typeof(TEnum), UnderlyingProxy.Read());
}
object IValueStore.Read() {
return Read();
}
public void Write(TEnum value) {
UnderlyingProxy.Write(Convert.ToInt32(value));
}
void IWritableDataProxy.Write(object value) {
Write((TEnum)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct Int64Proxy : IWritableDataProxy<Int64> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public Int64Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Int64); }
}
public unsafe Int64 Read() {
Int64 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int64));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Int64 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((Int64)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct UInt64Proxy : IWritableDataProxy<UInt64> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public UInt64Proxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(UInt64); }
}
public unsafe UInt64 Read() {
UInt64 result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt64));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(UInt64 value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((UInt64)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct SingleProxy : IWritableDataProxy<Single> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public SingleProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Single); }
}
public unsafe Single Read() {
Single result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Single));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Single value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((Single)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct DoubleProxy : IWritableDataProxy<Double> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public DoubleProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(Double); }
}
public unsafe Double Read() {
Double result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Double));
return result;
}
object IValueStore.Read() {
return Read();
}
public void Write(Double value) {
byte[] buf = BitConverter.GetBytes(value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((Double)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct SSizeTProxy : IWritableDataProxy<long> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public SSizeTProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return Process.GetPointerSize(); }
}
public unsafe long Read() {
if (Process.Is64Bit()) {
long result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(long));
return result;
} else {
int result;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(int));
return result;
}
}
object IValueStore.Read() {
return Read();
}
public void Write(long value) {
byte[] buf = Process.Is64Bit() ? BitConverter.GetBytes(value) : BitConverter.GetBytes((int)value);
Process.WriteMemory(Address, buf);
}
void IWritableDataProxy.Write(object value) {
Write((long)value);
}
public void Increment(long amount = 1) {
Write(Read() + amount);
}
public void Decrement(long amount = 1) {
Increment(-amount);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct BoolProxy : IWritableDataProxy<bool> {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public BoolProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(byte); }
}
public unsafe bool Read() {
byte b;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &b, sizeof(byte));
return b != 0;
}
object IValueStore.Read() {
return Read();
}
public void Write(bool value) {
Process.WriteMemory(Address, new[] { value ? (byte)1 : (byte)0 });
}
void IWritableDataProxy.Write(object value) {
Write((bool)value);
}
}
[DebuggerDisplay("& {Read()}")]
internal struct CharProxy : IDataProxy {
public DkmProcess Process { get; private set; }
public ulong Address { get; private set; }
public CharProxy(DkmProcess process, ulong address)
: this() {
Debug.Assert(process != null && address != 0);
Process = process;
Address = address;
}
public long ObjectSize {
get { return sizeof(byte); }
}
unsafe object IValueStore.Read() {
byte b;
Process.ReadMemory(Address, DkmReadMemoryFlags.None, &b, sizeof(byte));
string s = ((char)b).ToString();
if (Process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V27) {
return new AsciiString(new[] { b }, s);
} else {
return s;
}
}
}
}
| |
namespace Nancy.ViewEngines.Spark
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Nancy.Responses.Negotiation;
using global::Spark.FileSystem;
/// <summary>
/// Implementation of the IViewFolder interface to have Spark use views that's been discovered by Nancy's view locator.
/// </summary>
public class NancyViewFolder : IViewFolder
{
private readonly ViewEngineStartupContext viewEngineStartupContext;
private List<ViewLocationResult> currentlyLocatedViews;
private ReaderWriterLockSlim padlock = new ReaderWriterLockSlim();
private readonly ConcurrentDictionary<string, IViewFile> cachedFiles = new ConcurrentDictionary<string, IViewFile>();
/// <summary>
/// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided
/// <see cref="viewEngineStartupContext"/> instance.
/// </summary>
/// <param name="viewEngineStartupContext"></param>
public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext)
{
this.viewEngineStartupContext = viewEngineStartupContext;
// No need to lock here
this.currentlyLocatedViews =
new List<ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews());
}
/// <summary>
/// Gets the source of the requested view.
/// </summary>
/// <param name="path">The view to get the source for</param>
/// <returns>A <see cref="IViewFile"/> instance.</returns>
public IViewFile GetViewSource(string path)
{
var searchPath = ConvertPath(path);
IViewFile fileResult;
if (this.cachedFiles.TryGetValue(searchPath, out fileResult))
{
return fileResult;
}
ViewLocationResult result = null;
this.padlock.EnterUpgradeableReadLock();
try
{
result = this.currentlyLocatedViews
.FirstOrDefault(v => CompareViewPaths(GetSafeViewPath(v), searchPath));
if (result == null && StaticConfiguration.Caching.EnableRuntimeViewDiscovery)
{
result = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext());
this.padlock.EnterWriteLock();
try
{
this.currentlyLocatedViews.Add(result);
}
finally
{
this.padlock.ExitWriteLock();
}
}
}
finally
{
this.padlock.ExitUpgradeableReadLock();
}
if (result == null)
{
throw new FileNotFoundException(string.Format("Template {0} not found", path), path);
}
fileResult = new NancyViewFile(result);
this.cachedFiles.AddOrUpdate(searchPath, s => fileResult, (s, o) => fileResult);
return fileResult;
}
/// <summary>
/// Lists all view for the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to return views for.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the matched views.</returns>
public IList<string> ListViews(string path)
{
this.padlock.EnterReadLock();
try
{
return currentlyLocatedViews.
Where(v => v.Location.StartsWith(path, StringComparison.OrdinalIgnoreCase)).
Select(v =>
v.Location.Length == path.Length ?
v.Name + "." + v.Extension :
v.Location.Substring(path.Length) + "/" + v.Name + "." + v.Extension).
ToList();
}
finally
{
this.padlock.ExitReadLock();
}
}
/// <summary>
/// Gets a value that indicates whether or not the view folder contains a specific view.
/// </summary>
/// <param name="path">The view to check for.</param>
/// <returns><see langword="true"/> if the view exists in the view folder; otherwise <see langword="false"/>.</returns>
public bool HasView(string path)
{
var searchPath =
ConvertPath(path);
this.padlock.EnterUpgradeableReadLock();
try
{
var hasCached = this.currentlyLocatedViews.Any(v => CompareViewPaths(GetSafeViewPath(v), searchPath));
if (hasCached || !StaticConfiguration.Caching.EnableRuntimeViewDiscovery)
{
return hasCached;
}
var newView = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext());
if (newView == null)
{
return false;
}
this.padlock.EnterWriteLock();
try
{
this.currentlyLocatedViews.Add(newView);
return true;
}
finally
{
this.padlock.ExitWriteLock();
}
}
finally
{
this.padlock.ExitUpgradeableReadLock();
}
}
private static bool CompareViewPaths(string storedViewPath, string requestedViewPath)
{
return string.Equals(storedViewPath, requestedViewPath, StringComparison.OrdinalIgnoreCase);
}
private static string ConvertPath(string path)
{
return path.Replace(@"\", "/");
}
private static string GetSafeViewPath(ViewLocationResult result)
{
return string.IsNullOrEmpty(result.Location) ?
string.Concat(result.Name, ".", result.Extension) :
string.Concat(result.Location, "/", result.Name, ".", result.Extension);
}
// Horrible hack, but we have no way to get a context
private static NancyContext GetFakeContext()
{
return new NancyContext { Request = new Request("GET", "/", "http") };
}
public class NancyViewFile : IViewFile
{
private readonly object updateLock = new object();
private readonly ViewLocationResult viewLocationResult;
private string contents;
private long lastUpdated;
public NancyViewFile(ViewLocationResult viewLocationResult)
{
this.viewLocationResult = viewLocationResult;
this.UpdateContents();
}
public long LastModified
{
get
{
if (StaticConfiguration.Caching.EnableRuntimeViewUpdates && this.viewLocationResult.IsStale())
{
this.UpdateContents();
}
return this.lastUpdated;
}
}
public Stream OpenViewStream()
{
if (StaticConfiguration.Caching.EnableRuntimeViewUpdates && this.viewLocationResult.IsStale())
{
this.UpdateContents();
}
return new MemoryStream(Encoding.UTF8.GetBytes(this.contents));
}
private void UpdateContents()
{
lock (this.updateLock)
{
using (var reader = this.viewLocationResult.Contents.Invoke())
{
this.contents = reader.ReadToEnd();
}
this.lastUpdated = DateTime.Now.Ticks;
}
}
}
}
}
| |
/*
* 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.IO
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
/// <summary>
/// Binary onheap stream.
/// </summary>
internal unsafe class BinaryHeapStream : BinaryStreamBase
{
/** Data array. */
private byte[] _data;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cap">Initial capacity.</param>
public BinaryHeapStream(int cap)
{
Debug.Assert(cap >= 0);
_data = new byte[cap];
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="data">Data array.</param>
public BinaryHeapStream(byte[] data)
{
Debug.Assert(data != null);
_data = data;
}
/** <inheritdoc /> */
public override void WriteByte(byte val)
{
int pos0 = EnsureWriteCapacityAndShift(1);
_data[pos0] = val;
}
/** <inheritdoc /> */
public override byte ReadByte()
{
int pos0 = EnsureReadCapacityAndShift(1);
return _data[pos0];
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteByteArray(byte[] val)
{
int pos0 = EnsureWriteCapacityAndShift(val.Length);
fixed (byte* data0 = _data)
{
WriteByteArray0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override byte[] ReadByteArray(int cnt)
{
int pos0 = EnsureReadCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
return ReadByteArray0(cnt, data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteBoolArray(bool[] val)
{
int pos0 = EnsureWriteCapacityAndShift(val.Length);
fixed (byte* data0 = _data)
{
WriteBoolArray0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override bool[] ReadBoolArray(int cnt)
{
int pos0 = EnsureReadCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
return ReadBoolArray0(cnt, data0 + pos0);
}
}
/** <inheritdoc /> */
public override void WriteShort(short val)
{
int pos0 = EnsureWriteCapacityAndShift(2);
fixed (byte* data0 = _data)
{
WriteShort0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override short ReadShort()
{
int pos0 = EnsureReadCapacityAndShift(2);
fixed (byte* data0 = _data)
{
return ReadShort0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteShortArray(short[] val)
{
int cnt = val.Length << 1;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteShortArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override short[] ReadShortArray(int cnt)
{
int cnt0 = cnt << 1;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadShortArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteCharArray(char[] val)
{
int cnt = val.Length << 1;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteCharArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override char[] ReadCharArray(int cnt)
{
int cnt0 = cnt << 1;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadCharArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override void WriteInt(int val)
{
int pos0 = EnsureWriteCapacityAndShift(4);
fixed (byte* data0 = _data)
{
WriteInt0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override void WriteInt(int writePos, int val)
{
EnsureWriteCapacity(writePos + 4);
fixed (byte* data0 = _data)
{
WriteInt0(val, data0 + writePos);
}
}
/** <inheritdoc /> */
public override int ReadInt()
{
int pos0 = EnsureReadCapacityAndShift(4);
fixed (byte* data0 = _data)
{
return ReadInt0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteIntArray(int[] val)
{
int cnt = val.Length << 2;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteIntArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override int[] ReadIntArray(int cnt)
{
int cnt0 = cnt << 2;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadIntArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteFloatArray(float[] val)
{
int cnt = val.Length << 2;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteFloatArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override float[] ReadFloatArray(int cnt)
{
int cnt0 = cnt << 2;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadFloatArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override void WriteLong(long val)
{
int pos0 = EnsureWriteCapacityAndShift(8);
fixed (byte* data0 = _data)
{
WriteLong0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override long ReadLong()
{
int pos0 = EnsureReadCapacityAndShift(8);
fixed (byte* data0 = _data)
{
return ReadLong0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteLongArray(long[] val)
{
int cnt = val.Length << 3;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteLongArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override long[] ReadLongArray(int cnt)
{
int cnt0 = cnt << 3;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadLongArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteDoubleArray(double[] val)
{
int cnt = val.Length << 3;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteDoubleArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override double[] ReadDoubleArray(int cnt)
{
int cnt0 = cnt << 3;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadDoubleArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding)
{
int pos0 = EnsureWriteCapacityAndShift(byteCnt);
int written;
fixed (byte* data0 = _data)
{
written = WriteString0(chars, charCnt, byteCnt, encoding, data0 + pos0);
}
return written;
}
/** <inheritdoc /> */
public override void Write(byte* src, int cnt)
{
EnsureWriteCapacity(Pos + cnt);
fixed (byte* data0 = _data)
{
WriteInternal(src, cnt, data0);
}
ShiftWrite(cnt);
}
/** <inheritdoc /> */
public override void Read(byte* dest, int cnt)
{
fixed (byte* data0 = _data)
{
ReadInternal(data0, dest, cnt);
}
}
/** <inheritdoc /> */
public override int Remaining
{
get { return _data.Length - Pos; }
}
/** <inheritdoc /> */
public override byte[] GetArray()
{
return _data;
}
/** <inheritdoc /> */
public override byte[] GetArrayCopy()
{
byte[] copy = new byte[Pos];
Buffer.BlockCopy(_data, 0, copy, 0, Pos);
return copy;
}
/** <inheritdoc /> */
public override bool IsSameArray(byte[] arr)
{
return _data == arr;
}
/** <inheritdoc /> */
protected override void Dispose(bool disposing)
{
// No-op.
}
/// <summary>
/// Internal array.
/// </summary>
internal byte[] InternalArray
{
get { return _data; }
}
/** <inheritdoc /> */
protected override void EnsureWriteCapacity(int cnt)
{
if (cnt > _data.Length)
{
int newCap = Capacity(_data.Length, cnt);
byte[] data0 = new byte[newCap];
// Copy the whole initial array length here because it can be changed
// from Java without position adjusting.
Buffer.BlockCopy(_data, 0, data0, 0, _data.Length);
_data = data0;
}
}
/** <inheritdoc /> */
protected override void EnsureReadCapacity(int cnt)
{
if (_data.Length - Pos < cnt)
throw new EndOfStreamException("Not enough data in stream [expected=" + cnt +
", remaining=" + (_data.Length - Pos) + ']');
}
}
}
| |
// ParameterInformationWindowManager.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Collections;
using System.Collections.Generic;
using Gtk;
using Gdk;
namespace Moscrif.IDE.Completion
{
public class ParameterInformationWindowManager
{
static List<MethodData> methods = new List<MethodData> ();
static ParameterInformationWindow window;
public static bool IsWindowVisible {
get { return methods.Count > 0; }
}
// Called when a key is pressed in the editor.
// Returns false if the key press has to continue normal processing.
public static bool ProcessKeyEvent (ICompletionWidget widget, Gdk.Key key, Gdk.ModifierType modifier)
{
if (methods.Count == 0)
return false;
MethodData cmd = methods [methods.Count - 1];
if (key == Gdk.Key.Down) {
if (cmd.MethodProvider.OverloadCount <= 1)
return false;
if (cmd.CurrentOverload < cmd.MethodProvider.OverloadCount - 1)
cmd.CurrentOverload ++;
else
cmd.CurrentOverload = 0;
UpdateWindow (widget);
return true;
}
else if (key == Gdk.Key.Up) {
if (cmd.MethodProvider.OverloadCount <= 1)
return false;
if (cmd.CurrentOverload > 0)
cmd.CurrentOverload --;
else
cmd.CurrentOverload = cmd.MethodProvider.OverloadCount - 1;
UpdateWindow (widget);
return true;
}
else if (key == Gdk.Key.Escape) {
HideWindow (widget);
return true;
}
return false;
}
public static void PostProcessKeyEvent (ICompletionWidget widget, Gdk.Key key, Gdk.ModifierType modifier)
{
// Called after the key has been processed by the editor
if (methods.Count == 0)
return;
for (int n=0; n<methods.Count; n++) {
// If the cursor is outside of any of the methods parameter list, discard the
// information window for that method.
MethodData md = methods [n];
int pos = md.MethodProvider.GetCurrentParameterIndex (widget, md.CompletionContext);
if (pos == -1) {
methods.RemoveAt (n);
n--;
}
}
// If the user enters more parameters than the current overload has,
// look for another overload with more parameters.
UpdateOverload (widget);
// Refresh.
UpdateWindow (widget);
}
public static void ShowWindow (ICompletionWidget widget, IParameterDataProvider provider)//, CodeCompletionContext ctx, IParameterDataProvider provider)
{
if (provider.OverloadCount == 0)
return;
// There can be several method parameter lists open at the same time, so
// they have to be queued. The last one of queue is the one being shown
// in the information window.
MethodData md = new MethodData ();
md.MethodProvider = provider;
md.CurrentOverload = 0;
md.CompletionContext = widget.CreateCodeCompletionContext(); //ctx;
methods.Add (md);
UpdateWindow (widget);
}
public static void HideWindow (ICompletionWidget widget)
{
methods.Clear ();
UpdateWindow (widget);
}
public static int GetCurrentOverload ()
{
if (methods.Count == 0)
return -1;
return methods [methods.Count - 1].CurrentOverload;
}
public static IParameterDataProvider GetCurrentProvider ()
{
if (methods.Count == 0)
return null;
return methods [methods.Count - 1].MethodProvider;
}
static void UpdateOverload (ICompletionWidget widget)
{
if (methods.Count == 0)
return;
// If the user enters more parameters than the current overload has,
// look for another overload with more parameters.
MethodData md = methods [methods.Count - 1];
int cparam = md.MethodProvider.GetCurrentParameterIndex (widget, md.CompletionContext);
if (cparam > md.MethodProvider.GetParameterCount (md.CurrentOverload)) {
// Look for an overload which has more parameters
int bestOverload = -1;
int bestParamCount = int.MaxValue;
for (int n=0; n<md.MethodProvider.OverloadCount; n++) {
int pc = md.MethodProvider.GetParameterCount (n);
if (pc < bestParamCount && pc >= cparam) {
bestOverload = n;
bestParamCount = pc;
}
}
if (bestOverload != -1)
md.CurrentOverload = bestOverload;
}
}
public static int X { get; private set; }
public static int Y { get; private set; }
public static bool wasAbove = false;
internal static void UpdateWindow (ICompletionWidget widget)
{
// Updates the parameter information window from the information
// of the current method overload
if (window == null && methods.Count > 0) {
window = new ParameterInformationWindow ();
wasAbove = false;
}
if (methods.Count == 0) {
if (window != null) {
window.Hide ();
wasAbove = false;
}
return;
}
var ctx = widget.CreateCodeCompletionContext();
MethodData md = methods[methods.Count - 1];
int cparam = md.MethodProvider.GetCurrentParameterIndex (widget, md.CompletionContext);
Gtk.Requisition reqSize = window.ShowParameterInfo (md.MethodProvider, md.CurrentOverload, cparam - 1);
X = md.CompletionContext.TriggerXCoord;
if (CompletionWindowManager.IsVisible) {
// place above
Y = ctx.TriggerYCoord - ctx.TriggerTextHeight - reqSize.Height - 10;
} else {
// place below
Y = ctx.TriggerYCoord;
}
Gdk.Rectangle geometry = window.Screen.GetMonitorGeometry (window.Screen.GetMonitorAtPoint (X, Y));
if (X + reqSize.Width > geometry.Right)
X = geometry.Right - reqSize.Width;
if (Y < geometry.Top)
Y = ctx.TriggerYCoord;
if (wasAbove || Y + reqSize.Height > geometry.Bottom) {
Y = Y - ctx.TriggerTextHeight - reqSize.Height - 4;
wasAbove = true;
}
if (CompletionWindowManager.IsVisible) {
Rectangle completionWindow = new Rectangle (CompletionWindowManager.X, CompletionWindowManager.Y,
CompletionWindowManager.Wnd.Allocation.Width, CompletionWindowManager.Wnd.Allocation.Height);
if (completionWindow.IntersectsWith (new Rectangle (X, Y, reqSize.Width, reqSize.Height))) {
X = completionWindow.X;
Y = completionWindow.Y - reqSize.Height - 6;
if (Y < 0)
Y = completionWindow.Bottom + 6;
}
}
window.Move (X, Y);
window.Show ();
}
}
class MethodData
{
public IParameterDataProvider MethodProvider;
public CodeCompletionContext CompletionContext;
public int CurrentOverload;
}
}
| |
/*
* NativeMethods - All the Windows SDK structures and imports
*
* Author: Phillip Piper
* Date: 10/10/2006
*
* Change log:
* v2.3
* 2006-10-10 JPP - Initial version
*
* To do:
*
* Copyright (C) 2006-2012 Phillip Piper
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com.
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace BrightIdeasSoftware
{
/// <summary>
/// Wrapper for all native method calls on ListView controls
/// </summary>
internal static class NativeMethods
{
#region Constants
private const int LVM_FIRST = 0x1000;
private const int LVM_GETCOLUMN = LVM_FIRST + 95;
private const int LVM_GETCOUNTPERPAGE = LVM_FIRST + 40;
private const int LVM_GETGROUPINFO = LVM_FIRST + 149;
private const int LVM_GETGROUPSTATE = LVM_FIRST + 92;
private const int LVM_GETHEADER = LVM_FIRST + 31;
private const int LVM_GETTOOLTIPS = LVM_FIRST + 78;
private const int LVM_HITTEST = LVM_FIRST + 18;
private const int LVM_INSERTGROUP = LVM_FIRST + 145;
private const int LVM_REMOVEALLGROUPS = LVM_FIRST + 160;
private const int LVM_SCROLL = LVM_FIRST + 20;
private const int LVM_SETBKIMAGE = LVM_FIRST + 0x8A;
private const int LVM_SETCOLUMN = LVM_FIRST + 96;
private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
private const int LVM_SETGROUPINFO = LVM_FIRST + 147;
private const int LVM_SETGROUPMETRICS = LVM_FIRST + 155;
private const int LVM_SETIMAGELIST = LVM_FIRST + 3;
private const int LVM_SETITEM = LVM_FIRST + 76;
private const int LVM_SETITEMCOUNT = LVM_FIRST + 47;
private const int LVM_SETITEMSTATE = LVM_FIRST + 43;
private const int LVM_SETSELECTEDCOLUMN = LVM_FIRST + 140;
private const int LVM_SETTOOLTIPS = LVM_FIRST + 74;
private const int LVM_SUBITEMHITTEST = LVM_FIRST + 57;
private const int LVS_EX_SUBITEMIMAGES = 0x0002;
private const int LVIF_TEXT = 0x0001;
private const int LVIF_IMAGE = 0x0002;
private const int LVIF_PARAM = 0x0004;
private const int LVIF_STATE = 0x0008;
private const int LVIF_INDENT = 0x0010;
private const int LVIF_NORECOMPUTE = 0x0800;
private const int LVCF_FMT = 0x0001;
private const int LVCF_WIDTH = 0x0002;
private const int LVCF_TEXT = 0x0004;
private const int LVCF_SUBITEM = 0x0008;
private const int LVCF_IMAGE = 0x0010;
private const int LVCF_ORDER = 0x0020;
private const int LVCFMT_LEFT = 0x0000;
private const int LVCFMT_RIGHT = 0x0001;
private const int LVCFMT_CENTER = 0x0002;
private const int LVCFMT_JUSTIFYMASK = 0x0003;
private const int LVCFMT_IMAGE = 0x0800;
private const int LVCFMT_BITMAP_ON_RIGHT = 0x1000;
private const int LVCFMT_COL_HAS_IMAGES = 0x8000;
private const int LVBKIF_SOURCE_NONE = 0x0;
private const int LVBKIF_SOURCE_HBITMAP = 0x1;
private const int LVBKIF_SOURCE_URL = 0x2;
private const int LVBKIF_SOURCE_MASK = 0x3;
private const int LVBKIF_STYLE_NORMAL = 0x0;
private const int LVBKIF_STYLE_TILE = 0x10;
private const int LVBKIF_STYLE_MASK = 0x10;
private const int LVBKIF_FLAG_TILEOFFSET = 0x100;
private const int LVBKIF_TYPE_WATERMARK = 0x10000000;
private const int LVBKIF_FLAG_ALPHABLEND = 0x20000000;
private const int LVSICF_NOINVALIDATEALL = 1;
private const int LVSICF_NOSCROLL = 2;
private const int HDM_FIRST = 0x1200;
private const int HDM_HITTEST = HDM_FIRST + 6;
private const int HDM_GETITEMRECT = HDM_FIRST + 7;
private const int HDM_GETITEM = HDM_FIRST + 11;
private const int HDM_SETITEM = HDM_FIRST + 12;
private const int HDI_WIDTH = 0x0001;
private const int HDI_TEXT = 0x0002;
private const int HDI_FORMAT = 0x0004;
private const int HDI_BITMAP = 0x0010;
private const int HDI_IMAGE = 0x0020;
private const int HDF_LEFT = 0x0000;
private const int HDF_RIGHT = 0x0001;
private const int HDF_CENTER = 0x0002;
private const int HDF_JUSTIFYMASK = 0x0003;
private const int HDF_RTLREADING = 0x0004;
private const int HDF_STRING = 0x4000;
private const int HDF_BITMAP = 0x2000;
private const int HDF_BITMAP_ON_RIGHT = 0x1000;
private const int HDF_IMAGE = 0x0800;
private const int HDF_SORTUP = 0x0400;
private const int HDF_SORTDOWN = 0x0200;
private const int SB_HORZ = 0;
private const int SB_VERT = 1;
private const int SB_CTL = 2;
private const int SB_BOTH = 3;
private const int SIF_RANGE = 0x0001;
private const int SIF_PAGE = 0x0002;
private const int SIF_POS = 0x0004;
private const int SIF_DISABLENOSCROLL = 0x0008;
private const int SIF_TRACKPOS = 0x0010;
private const int SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS);
private const int ILD_NORMAL = 0x0;
private const int ILD_TRANSPARENT = 0x1;
private const int ILD_MASK = 0x10;
private const int ILD_IMAGE = 0x20;
private const int ILD_BLEND25 = 0x2;
private const int ILD_BLEND50 = 0x4;
const int SWP_NOSIZE = 1;
const int SWP_NOMOVE = 2;
const int SWP_NOZORDER = 4;
const int SWP_NOREDRAW = 8;
const int SWP_NOACTIVATE = 16;
public const int SWP_FRAMECHANGED = 32;
const int SWP_ZORDERONLY = SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOACTIVATE;
const int SWP_SIZEONLY = SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER | SWP_NOACTIVATE;
const int SWP_UPDATE_FRAME = SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED;
#endregion
#region Structures
[StructLayout(LayoutKind.Sequential)]
public struct HDITEM
{
public int mask;
public int cxy;
public IntPtr pszText;
public IntPtr hbm;
public int cchTextMax;
public int fmt;
public IntPtr lParam;
public int iImage;
public int iOrder;
//if (_WIN32_IE >= 0x0500)
public int type;
public IntPtr pvFilter;
}
[StructLayout(LayoutKind.Sequential)]
public class HDHITTESTINFO
{
public int pt_x;
public int pt_y;
public int flags;
public int iItem;
}
[StructLayout(LayoutKind.Sequential)]
public class HDLAYOUT
{
public IntPtr prc;
public IntPtr pwpos;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LVBKIMAGE
{
public int ulFlags;
public IntPtr hBmp;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszImage;
public int cchImageMax;
public int xOffset;
public int yOffset;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LVCOLUMN
{
public int mask;
public int fmt;
public int cx;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszText;
public int cchTextMax;
public int iSubItem;
// These are available in Common Controls >= 0x0300
public int iImage;
public int iOrder;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LVFINDINFO
{
public int flags;
public string psz;
public IntPtr lParam;
public int ptX;
public int ptY;
public int vkDirection;
}
[StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct LVGROUP
{
public uint cbSize;
public uint mask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszHeader;
public int cchHeader;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszFooter;
public int cchFooter;
public int iGroupId;
public uint stateMask;
public uint state;
public uint uAlign;
}
[StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct LVGROUP2
{
public uint cbSize;
public uint mask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszHeader;
public uint cchHeader;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszFooter;
public int cchFooter;
public int iGroupId;
public uint stateMask;
public uint state;
public uint uAlign;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszSubtitle;
public uint cchSubtitle;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszTask;
public uint cchTask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszDescriptionTop;
public uint cchDescriptionTop;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszDescriptionBottom;
public uint cchDescriptionBottom;
public int iTitleImage;
public int iExtendedImage;
public int iFirstItem; // Read only
public int cItems; // Read only
[MarshalAs(UnmanagedType.LPTStr)]
public string pszSubsetTitle; // NULL if group is not subset
public uint cchSubsetTitle;
}
[StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct LVGROUPMETRICS
{
public uint cbSize;
public uint mask;
public uint Left;
public uint Top;
public uint Right;
public uint Bottom;
public int crLeft;
public int crTop;
public int crRight;
public int crBottom;
public int crHeader;
public int crFooter;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LVHITTESTINFO
{
public int pt_x;
public int pt_y;
public int flags;
public int iItem;
public int iSubItem;
public int iGroup;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LVITEM
{
public int mask;
public int iItem;
public int iSubItem;
public int state;
public int stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszText;
public int cchTextMax;
public int iImage;
public IntPtr lParam;
// These are available in Common Controls >= 0x0300
public int iIndent;
// These are available in Common Controls >= 0x056
public int iGroupId;
public int cColumns;
public IntPtr puColumns;
};
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR
{
public IntPtr hwndFrom;
public IntPtr idFrom;
public int code;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMCUSTOMDRAW
{
public NativeMethods.NMHDR nmcd;
public int dwDrawStage;
public IntPtr hdc;
public NativeMethods.RECT rc;
public IntPtr dwItemSpec;
public int uItemState;
public IntPtr lItemlParam;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMHEADER
{
public NMHDR nhdr;
public int iItem;
public int iButton;
public IntPtr pHDITEM;
}
const int MAX_LINKID_TEXT = 48;
const int L_MAX_URL_LENGTH = 2048 + 32 + 4;
//#define L_MAX_URL_LENGTH (2048 + 32 + sizeof("://"))
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LITEM
{
public uint mask;
public int iLink;
public uint state;
public uint stateMask;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_LINKID_TEXT)]
public string szID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = L_MAX_URL_LENGTH)]
public string szUrl;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLISTVIEW
{
public NativeMethods.NMHDR hdr;
public int iItem;
public int iSubItem;
public int uNewState;
public int uOldState;
public int uChanged;
public IntPtr lParam;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVCUSTOMDRAW
{
public NativeMethods.NMCUSTOMDRAW nmcd;
public int clrText;
public int clrTextBk;
public int iSubItem;
public int dwItemType;
public int clrFace;
public int iIconEffect;
public int iIconPhase;
public int iPartId;
public int iStateId;
public NativeMethods.RECT rcText;
public uint uAlign;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVFINDITEM
{
public NativeMethods.NMHDR hdr;
public int iStart;
public NativeMethods.LVFINDINFO lvfi;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVGETINFOTIP
{
public NativeMethods.NMHDR hdr;
public int dwFlags;
public string pszText;
public int cchTextMax;
public int iItem;
public int iSubItem;
public IntPtr lParam;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVGROUP
{
public NMHDR hdr;
public int iGroupId; // which group is changing
public uint uNewState; // LVGS_xxx flags
public uint uOldState;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVLINK
{
public NMHDR hdr;
public LITEM link;
public int iItem;
public int iSubItem;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVSCROLL
{
public NativeMethods.NMHDR hdr;
public int dx;
public int dy;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct NMTTDISPINFO
{
public NativeMethods.NMHDR hdr;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szText;
public IntPtr hinst;
public int uFlags;
public IntPtr lParam;
//public int hbmp; This is documented but doesn't work
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
public class SCROLLINFO
{
public int cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO));
public int fMask;
public int nMin;
public int nMax;
public int nPage;
public int nPos;
public int nTrackPos;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class TOOLINFO
{
public int cbSize = Marshal.SizeOf(typeof(NativeMethods.TOOLINFO));
public int uFlags;
public IntPtr hwnd;
public IntPtr uId;
public NativeMethods.RECT rect;
public IntPtr hinst = IntPtr.Zero;
public IntPtr lpszText;
public IntPtr lParam = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public int flags;
}
#endregion
#region Entry points
// Various flavours of SendMessage: plain vanilla, and passing references to various structures
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVHITTESTINFO ht);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageRECT(IntPtr hWnd, int msg, int wParam, ref RECT r);
//[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
//private static extern IntPtr SendMessageLVColumn(IntPtr hWnd, int m, int wParam, ref LVCOLUMN lvc);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessageHDItem(IntPtr hWnd, int msg, int wParam, ref HDITEM hdi);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageHDHITTESTINFO(IntPtr hWnd, int Msg, IntPtr wParam, [In, Out] HDHITTESTINFO lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTOOLINFO(IntPtr hWnd, int Msg, int wParam, NativeMethods.TOOLINFO lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageLVBKIMAGE(IntPtr hWnd, int Msg, int wParam, ref NativeMethods.LVBKIMAGE lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageString(IntPtr hWnd, int Msg, int wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageIUnknown(IntPtr hWnd, int msg,
[MarshalAs(UnmanagedType.IUnknown)] object wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUP2 lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref LVGROUPMETRICS lParam);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr objectHandle);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool GetClientRect(IntPtr hWnd, ref Rectangle r);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo);
[DllImport("user32.dll", EntryPoint = "GetUpdateRect", CharSet = CharSet.Auto)]
private static extern int GetUpdateRectInternal(IntPtr hWnd, ref Rectangle r, bool eraseBackground);
[DllImport("comctl32.dll", CharSet = CharSet.Auto)]
private static extern bool ImageList_Draw(IntPtr himl, int i, IntPtr hdcDst, int x, int y, int fStyle);
//[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
//public static extern bool SetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo, bool fRedraw);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", EntryPoint = "ValidateRect", CharSet = CharSet.Auto)]
private static extern IntPtr ValidatedRectInternal(IntPtr hWnd, ref Rectangle r);
#endregion
//[DllImport("user32.dll", EntryPoint = "LockWindowUpdate", CharSet = CharSet.Auto)]
//private static extern int LockWindowUpdateInternal(IntPtr hWnd);
//public static void LockWindowUpdate(IWin32Window window) {
// if (window == null)
// NativeMethods.LockWindowUpdateInternal(IntPtr.Zero);
// else
// NativeMethods.LockWindowUpdateInternal(window.Handle);
//}
/// <summary>
/// Put an image under the ListView.
/// </summary>
/// <remarks>
/// <para>
/// The ListView must have its handle created before calling this.
/// </para>
/// <para>
/// This doesn't work very well. Specifically, it doesn't play well with owner drawn,
/// and grid lines are drawn over it.
/// </para>
/// </remarks>
/// <param name="lv"></param>
/// <param name="image">The image to be used as the background. If this is null, any existing background image will be cleared.</param>
/// <param name="isWatermark">If this is true, the image is pinned to the bottom right and does not scroll. The other parameters are ignored</param>
/// <param name="isTiled">If this is true, the image will be tiled to fill the whole control background. The offset parameters will be ignored.</param>
/// <param name="xOffset">If both watermark and tiled are false, this indicates the horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right.</param>
/// <param name="yOffset">If both watermark and tiled are false, this indicates the vertical percentage where the image will be placed.</param>
/// <returns></returns>
public static bool SetBackgroundImage(ListView lv, Image image, bool isWatermark, bool isTiled, int xOffset, int yOffset) {
LVBKIMAGE lvbkimage = new LVBKIMAGE();
// We have to clear any pre-existing background image, otherwise the attempt to set the image will fail.
// We don't know which type may already have been set, so we just clear both the watermark and the image.
lvbkimage.ulFlags = LVBKIF_TYPE_WATERMARK;
IntPtr result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage);
lvbkimage.ulFlags = LVBKIF_SOURCE_HBITMAP;
result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage);
Bitmap bm = image as Bitmap;
if (bm != null) {
lvbkimage.hBmp = bm.GetHbitmap();
lvbkimage.ulFlags = isWatermark ? LVBKIF_TYPE_WATERMARK : (isTiled ? LVBKIF_SOURCE_HBITMAP | LVBKIF_STYLE_TILE : LVBKIF_SOURCE_HBITMAP);
lvbkimage.xOffset = xOffset;
lvbkimage.yOffset = yOffset;
result = NativeMethods.SendMessageLVBKIMAGE(lv.Handle, LVM_SETBKIMAGE, 0, ref lvbkimage);
}
return (result != IntPtr.Zero);
}
public static bool DrawImageList(Graphics g, ImageList il, int index, int x, int y, bool isSelected) {
int flags = ILD_TRANSPARENT;
if (isSelected)
flags |= ILD_BLEND25;
bool result = ImageList_Draw(il.Handle, index, g.GetHdc(), x, y, flags);
g.ReleaseHdc();
return result;
}
/// <summary>
/// Make sure the ListView has the extended style that says to display subitem images.
/// </summary>
/// <remarks>This method must be called after any .NET call that update the extended styles
/// since they seem to erase this setting.</remarks>
/// <param name="list">The listview to send a m to</param>
public static void ForceSubItemImagesExStyle(ListView list) {
SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES);
}
/// <summary>
/// Change the virtual list size of the given ListView (which must be in virtual mode)
/// </summary>
/// <remarks>This will not change the scroll position</remarks>
/// <param name="list">The listview to send a message to</param>
/// <param name="count">How many rows should the list have?</param>
public static void SetItemCount(ListView list, int count) {
SendMessage(list.Handle, LVM_SETITEMCOUNT, count, LVSICF_NOSCROLL);
}
/// <summary>
/// Make sure the ListView has the extended style that says to display subitem images.
/// </summary>
/// <remarks>This method must be called after any .NET call that update the extended styles
/// since they seem to erase this setting.</remarks>
/// <param name="list">The listview to send a m to</param>
/// <param name="style"></param>
/// <param name="styleMask"></param>
public static void SetExtendedStyle(ListView list, int style, int styleMask) {
SendMessage(list.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, style, styleMask);
}
/// <summary>
/// Calculates the number of items that can fit vertically in the visible area of a list-view (which
/// must be in details or list view.
/// </summary>
/// <param name="list">The listView</param>
/// <returns>Number of visible items per page</returns>
public static int GetCountPerPage(ListView list) {
return (int)SendMessage(list.Handle, LVM_GETCOUNTPERPAGE, 0, 0);
}
/// <summary>
/// For the given item and subitem, make it display the given image
/// </summary>
/// <param name="list">The listview to send a m to</param>
/// <param name="itemIndex">row number (0 based)</param>
/// <param name="subItemIndex">subitem (0 is the item itself)</param>
/// <param name="imageIndex">index into the image list</param>
public static void SetSubItemImage(ListView list, int itemIndex, int subItemIndex, int imageIndex) {
LVITEM lvItem = new LVITEM();
lvItem.mask = LVIF_IMAGE;
lvItem.iItem = itemIndex;
lvItem.iSubItem = subItemIndex;
lvItem.iImage = imageIndex;
SendMessageLVItem(list.Handle, LVM_SETITEM, 0, ref lvItem);
}
/// <summary>
/// Setup the given column of the listview to show the given image to the right of the text.
/// If the image index is -1, any previous image is cleared
/// </summary>
/// <param name="list">The listview to send a m to</param>
/// <param name="columnIndex">Index of the column to modifiy</param>
/// <param name="order"></param>
/// <param name="imageIndex">Index into the small image list</param>
public static void SetColumnImage(ListView list, int columnIndex, SortOrder order, int imageIndex) {
IntPtr hdrCntl = NativeMethods.GetHeaderControl(list);
if (hdrCntl.ToInt32() == 0)
return;
HDITEM item = new HDITEM();
item.mask = HDI_FORMAT;
IntPtr result = SendMessageHDItem(hdrCntl, HDM_GETITEM, columnIndex, ref item);
item.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN | HDF_IMAGE | HDF_BITMAP_ON_RIGHT);
if (NativeMethods.HasBuiltinSortIndicators()) {
if (order == SortOrder.Ascending)
item.fmt |= HDF_SORTUP;
if (order == SortOrder.Descending)
item.fmt |= HDF_SORTDOWN;
} else {
item.mask |= HDI_IMAGE;
item.fmt |= (HDF_IMAGE | HDF_BITMAP_ON_RIGHT);
item.iImage = imageIndex;
}
result = SendMessageHDItem(hdrCntl, HDM_SETITEM, columnIndex, ref item);
}
/// <summary>
/// Does this version of the operating system have builtin sort indicators?
/// </summary>
/// <returns>Are there builtin sort indicators</returns>
/// <remarks>XP and later have these</remarks>
public static bool HasBuiltinSortIndicators() {
return OSFeature.Feature.GetVersionPresent(OSFeature.Themes) != null;
}
/// <summary>
/// Return the bounds of the update region on the given control.
/// </summary>
/// <remarks>The BeginPaint() system call validates the update region, effectively wiping out this information.
/// So this call has to be made before the BeginPaint() call.</remarks>
/// <param name="cntl">The control whose update region is be calculated</param>
/// <returns>A rectangle</returns>
public static Rectangle GetUpdateRect(Control cntl) {
Rectangle r = new Rectangle();
GetUpdateRectInternal(cntl.Handle, ref r, false);
return r;
}
/// <summary>
/// Validate an area of the given control. A validated area will not be repainted at the next redraw.
/// </summary>
/// <param name="cntl">The control to be validated</param>
/// <param name="r">The area of the control to be validated</param>
public static void ValidateRect(Control cntl, Rectangle r) {
ValidatedRectInternal(cntl.Handle, ref r);
}
/// <summary>
/// Select all rows on the given listview
/// </summary>
/// <param name="list">The listview whose items are to be selected</param>
public static void SelectAllItems(ListView list) {
NativeMethods.SetItemState(list, -1, 2, 2);
}
/// <summary>
/// Deselect all rows on the given listview
/// </summary>
/// <param name="list">The listview whose items are to be deselected</param>
public static void DeselectAllItems(ListView list) {
NativeMethods.SetItemState(list, -1, 2, 0);
}
/// <summary>
/// Set the item state on the given item
/// </summary>
/// <param name="list">The listview whose item's state is to be changed</param>
/// <param name="itemIndex">The index of the item to be changed</param>
/// <param name="mask">Which bits of the value are to be set?</param>
/// <param name="value">The value to be set</param>
public static void SetItemState(ListView list, int itemIndex, int mask, int value) {
LVITEM lvItem = new LVITEM();
lvItem.stateMask = mask;
lvItem.state = value;
SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem);
}
/// <summary>
/// Scroll the given listview by the given deltas
/// </summary>
/// <param name="list"></param>
/// <param name="dx"></param>
/// <param name="dy"></param>
/// <returns>true if the scroll succeeded</returns>
public static bool Scroll(ListView list, int dx, int dy) {
return SendMessage(list.Handle, LVM_SCROLL, dx, dy) != IntPtr.Zero;
}
/// <summary>
/// Return the handle to the header control on the given list
/// </summary>
/// <param name="list">The listview whose header control is to be returned</param>
/// <returns>The handle to the header control</returns>
public static IntPtr GetHeaderControl(ListView list) {
return SendMessage(list.Handle, LVM_GETHEADER, 0, 0);
}
/// <summary>
/// Return the edges of the given column.
/// </summary>
/// <param name="lv"></param>
/// <param name="columnIndex"></param>
/// <returns>A Point holding the left and right co-ords of the column.
/// -1 means that the sides could not be retrieved.</returns>
public static Point GetColumnSides(ObjectListView lv, int columnIndex) {
Point sides = new Point(-1, -1);
IntPtr hdr = NativeMethods.GetHeaderControl(lv);
if (hdr == IntPtr.Zero)
return new Point(-1, -1);
RECT r = new RECT();
NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r);
return new Point(r.left, r.right);
}
/// <summary>
/// Return the edges of the given column.
/// </summary>
/// <param name="lv"></param>
/// <param name="columnIndex"></param>
/// <returns>A Point holding the left and right co-ords of the column.
/// -1 means that the sides could not be retrieved.</returns>
public static Point GetScrolledColumnSides(ListView lv, int columnIndex) {
IntPtr hdr = NativeMethods.GetHeaderControl(lv);
if (hdr == IntPtr.Zero)
return new Point(-1, -1);
RECT r = new RECT();
IntPtr result = NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r);
int scrollH = NativeMethods.GetScrollPosition(lv, true);
return new Point(r.left - scrollH, r.right - scrollH);
}
/// <summary>
/// Return the index of the column of the header that is under the given point.
/// Return -1 if no column is under the pt
/// </summary>
/// <param name="handle">The list we are interested in</param>
/// <param name="pt">The client co-ords</param>
/// <returns>The index of the column under the point, or -1 if no column header is under that point</returns>
public static int GetColumnUnderPoint(IntPtr handle, Point pt) {
const int HHT_ONHEADER = 2;
const int HHT_ONDIVIDER = 4;
return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONHEADER | HHT_ONDIVIDER);
}
private static int HeaderControlHitTest(IntPtr handle, Point pt, int flag) {
HDHITTESTINFO testInfo = new HDHITTESTINFO();
testInfo.pt_x = pt.X;
testInfo.pt_y = pt.Y;
IntPtr result = NativeMethods.SendMessageHDHITTESTINFO(handle, HDM_HITTEST, IntPtr.Zero, testInfo);
if ((testInfo.flags & flag) != 0)
return testInfo.iItem;
else
return -1;
}
/// <summary>
/// Return the index of the divider under the given point. Return -1 if no divider is under the pt
/// </summary>
/// <param name="handle">The list we are interested in</param>
/// <param name="pt">The client co-ords</param>
/// <returns>The index of the divider under the point, or -1 if no divider is under that point</returns>
public static int GetDividerUnderPoint(IntPtr handle, Point pt) {
const int HHT_ONDIVIDER = 4;
return NativeMethods.HeaderControlHitTest(handle, pt, HHT_ONDIVIDER);
}
/// <summary>
/// Get the scroll position of the given scroll bar
/// </summary>
/// <param name="lv"></param>
/// <param name="horizontalBar"></param>
/// <returns></returns>
public static int GetScrollPosition(ListView lv, bool horizontalBar) {
int fnBar = (horizontalBar ? SB_HORZ : SB_VERT);
SCROLLINFO scrollInfo = new SCROLLINFO();
scrollInfo.fMask = SIF_POS;
if (GetScrollInfo(lv.Handle, fnBar, scrollInfo))
return scrollInfo.nPos;
else
return -1;
}
/// <summary>
/// Change the z-order to the window 'toBeMoved' so it appear directly on top of 'reference'
/// </summary>
/// <param name="toBeMoved"></param>
/// <param name="reference"></param>
/// <returns></returns>
public static bool ChangeZOrder(IWin32Window toBeMoved, IWin32Window reference) {
return NativeMethods.SetWindowPos(toBeMoved.Handle, reference.Handle, 0, 0, 0, 0, SWP_ZORDERONLY);
}
/// <summary>
/// Make the given control/window a topmost window
/// </summary>
/// <param name="toBeMoved"></param>
/// <returns></returns>
public static bool MakeTopMost(IWin32Window toBeMoved) {
IntPtr HWND_TOPMOST = (IntPtr)(-1);
return NativeMethods.SetWindowPos(toBeMoved.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_ZORDERONLY);
}
public static bool ChangeSize(IWin32Window toBeMoved, int width, int height) {
return NativeMethods.SetWindowPos(toBeMoved.Handle, IntPtr.Zero, 0, 0, width, height, SWP_SIZEONLY);
}
/// <summary>
/// Show the given window without activating it
/// </summary>
/// <param name="win">The window to show</param>
static public void ShowWithoutActivate(IWin32Window win) {
const int SW_SHOWNA = 8;
NativeMethods.ShowWindow(win.Handle, SW_SHOWNA);
}
/// <summary>
/// Mark the given column as being selected.
/// </summary>
/// <param name="objectListView"></param>
/// <param name="value">The OLVColumn or null to clear</param>
/// <remarks>
/// This method works, but it prevents subitems in the given column from having
/// back colors.
/// </remarks>
static public void SetSelectedColumn(ListView objectListView, ColumnHeader value) {
NativeMethods.SendMessage(objectListView.Handle,
LVM_SETSELECTEDCOLUMN, (value == null) ? -1 : value.Index, 0);
}
static public IntPtr GetTooltipControl(ListView lv) {
return SendMessage(lv.Handle, LVM_GETTOOLTIPS, 0, 0);
}
static public IntPtr SetTooltipControl(ListView lv, ToolTipControl tooltip) {
return SendMessage(lv.Handle, LVM_SETTOOLTIPS, 0, tooltip.Handle);
}
static public bool HasHorizontalScrollBar(ListView lv) {
const int GWL_STYLE = -16;
const int WS_HSCROLL = 0x00100000;
return (NativeMethods.GetWindowLong(lv.Handle, GWL_STYLE) & WS_HSCROLL) != 0;
}
public static int GetWindowLong(IntPtr hWnd, int nIndex) {
if (IntPtr.Size == 4)
return (int)GetWindowLong32(hWnd, nIndex);
else
return (int)(long)GetWindowLongPtr64(hWnd, nIndex);
}
public static int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong) {
if (IntPtr.Size == 4)
return (int)SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
else
return (int)(long)SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
}
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int SetBkColor(IntPtr hDC, int clr);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int SetTextColor(IntPtr hDC, int crColor);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
[DllImport("uxtheme.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr SetWindowTheme(IntPtr hWnd, string subApp, string subIdList);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool InvalidateRect(IntPtr hWnd, int ignored, bool erase);
[StructLayout(LayoutKind.Sequential)]
public struct LVITEMINDEX
{
public int iItem;
public int iGroup;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
public static int GetGroupInfo(ObjectListView olv, int groupId, ref LVGROUP2 group) {
return (int)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPINFO, groupId, ref group);
}
public static GroupState GetGroupState(ObjectListView olv, int groupId, GroupState mask) {
return (GroupState)NativeMethods.SendMessage(olv.Handle, LVM_GETGROUPSTATE, groupId, (int)mask);
}
public static int InsertGroup(ObjectListView olv, LVGROUP2 group) {
return (int)NativeMethods.SendMessage(olv.Handle, LVM_INSERTGROUP, -1, ref group);
}
public static int SetGroupInfo(ObjectListView olv, int groupId, LVGROUP2 group) {
return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPINFO, groupId, ref group);
}
public static int SetGroupMetrics(ObjectListView olv, LVGROUPMETRICS metrics) {
return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETGROUPMETRICS, 0, ref metrics);
}
public static int ClearGroups(VirtualObjectListView virtualObjectListView) {
return (int)NativeMethods.SendMessage(virtualObjectListView.Handle, LVM_REMOVEALLGROUPS, 0, 0);
}
public static int SetGroupImageList(ObjectListView olv, ImageList il) {
const int LVSIL_GROUPHEADER = 3;
IntPtr handle = IntPtr.Zero;
if (il != null)
handle = il.Handle;
return (int)NativeMethods.SendMessage(olv.Handle, LVM_SETIMAGELIST, LVSIL_GROUPHEADER, handle);
}
public static int HitTest(ObjectListView olv, ref LVHITTESTINFO hittest)
{
return (int)NativeMethods.SendMessage(olv.Handle, olv.View == View.Details ? LVM_SUBITEMHITTEST : LVM_HITTEST, -1, ref hittest);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Reflection;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Runtime.Providers;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class GrainTypeManager
{
private IDictionary<string, GrainTypeData> grainTypes;
private Dictionary<SiloAddress, GrainInterfaceMap> grainInterfaceMapsBySilo;
private Dictionary<int, IList<SiloAddress>> supportedSilosByTypeCode;
private readonly Logger logger = LogManager.GetLogger("GrainTypeManager");
private readonly GrainInterfaceMap grainInterfaceMap;
private readonly Dictionary<int, InvokerData> invokers = new Dictionary<int, InvokerData>();
private readonly SiloAssemblyLoader loader;
private static readonly object lockable = new object();
private readonly PlacementStrategy defaultPlacementStrategy;
internal IReadOnlyDictionary<SiloAddress, GrainInterfaceMap> GrainInterfaceMapsBySilo
{
get { return grainInterfaceMapsBySilo; }
}
public static GrainTypeManager Instance { get; private set; }
public IEnumerable<KeyValuePair<string, GrainTypeData>> GrainClassTypeData { get { return grainTypes; } }
public GrainInterfaceMap ClusterGrainInterfaceMap { get; private set; }
public static void Stop()
{
Instance = null;
}
public GrainTypeManager(SiloInitializationParameters silo, SiloAssemblyLoader loader, DefaultPlacementStrategy defaultPlacementStrategy)
: this(silo.SiloAddress.Endpoint.Address.Equals(IPAddress.Loopback), loader, defaultPlacementStrategy)
{
}
public GrainTypeManager(bool localTestMode, SiloAssemblyLoader loader, DefaultPlacementStrategy defaultPlacementStrategy)
{
this.defaultPlacementStrategy = defaultPlacementStrategy.PlacementStrategy;
this.loader = loader;
grainInterfaceMap = new GrainInterfaceMap(localTestMode, this.defaultPlacementStrategy);
ClusterGrainInterfaceMap = grainInterfaceMap;
grainInterfaceMapsBySilo = new Dictionary<SiloAddress, GrainInterfaceMap>();
lock (lockable)
{
if (Instance != null)
throw new InvalidOperationException("An attempt to create a second insance of GrainTypeManager.");
Instance = this;
}
}
public void Start(bool strict = true)
{
// loading application assemblies now occurs in four phases.
// 1. We scan the file system for assemblies meeting pre-determined criteria, specified in SiloAssemblyLoader.LoadApplicationAssemblies (called by the constructor).
// 2. We load those assemblies into memory. In the official distribution of Orleans, this is usually 4 assemblies.
// (no more assemblies should be loaded into memory, so now is a good time to log all types registered with the serialization manager)
SerializationManager.LogRegisteredTypes();
// 3. We scan types in memory for GrainTypeData objects that describe grain classes and their corresponding grain state classes.
InitializeGrainClassData(loader, strict);
// 4. We scan types in memory for grain method invoker objects.
InitializeInvokerMap(loader, strict);
InitializeInterfaceMap();
}
public Dictionary<string, string> GetGrainInterfaceToClassMap()
{
return grainInterfaceMap.GetPrimaryImplementations();
}
internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass)
{
return grainInterfaceMap.TryGetPrimaryImplementation(grainInterface, out grainClass);
}
internal GrainTypeData this[string className]
{
get
{
string msg;
lock (this)
{
string grainType;
if (grainInterfaceMap.TryGetPrimaryImplementation(className, out grainType))
return grainTypes[grainType];
if (grainTypes.ContainsKey(className))
return grainTypes[className];
if (TypeUtils.IsGenericClass(className))
{
var templateName = TypeUtils.GetRawClassName(className);
if (grainInterfaceMap.TryGetPrimaryImplementation(templateName, out grainType))
templateName = grainType;
if (grainTypes.ContainsKey(templateName))
{
// Found the generic template class
try
{
// Instantiate the specific type from generic template
var genericGrainTypeData = (GenericGrainTypeData)grainTypes[templateName];
Type[] typeArgs = TypeUtils.GenericTypeArgsFromClassName(className);
var concreteTypeData = genericGrainTypeData.MakeGenericType(typeArgs);
// Add to lookup tables for next time
var grainClassName = concreteTypeData.GrainClass;
grainTypes.Add(grainClassName, concreteTypeData);
return concreteTypeData;
}
catch (Exception ex)
{
msg = "Cannot instantiate generic class " + className;
logger.Error(ErrorCode.Runtime_Error_100092, msg, ex);
throw new KeyNotFoundException(msg, ex);
}
}
}
}
msg = "Cannot find GrainTypeData for class " + className;
logger.Error(ErrorCode.Runtime_Error_100093, msg);
throw new TypeLoadException(msg);
}
}
internal void GetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
if (!ClusterGrainInterfaceMap.TryGetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments))
throw new OrleansException(String.Format("Unexpected: Cannot find an implementation class for grain interface {0}", typeCode));
}
internal void SetInterfaceMapsBySilo(Dictionary<SiloAddress, GrainInterfaceMap> value)
{
grainInterfaceMapsBySilo = value;
RebuildFullGrainInterfaceMap();
}
internal IList<SiloAddress> GetSupportedSilos(int typeCode)
{
return supportedSilosByTypeCode[typeCode];
}
private void InitializeGrainClassData(SiloAssemblyLoader loader, bool strict)
{
grainTypes = loader.GetGrainClassTypes(strict);
}
private void InitializeInvokerMap(SiloAssemblyLoader loader, bool strict)
{
IEnumerable<KeyValuePair<int, Type>> types = loader.GetGrainMethodInvokerTypes(strict);
foreach (var i in types)
{
int ifaceId = i.Key;
Type type = i.Value;
AddInvokerClass(ifaceId, type);
}
}
private void InitializeInterfaceMap()
{
foreach (GrainTypeData grainType in grainTypes.Values)
AddToGrainInterfaceToClassMap(grainType.Type, grainType.RemoteInterfaceTypes, grainType.IsStatelessWorker);
}
private void AddToGrainInterfaceToClassMap(Type grainClass, IEnumerable<Type> grainInterfaces, bool isUnordered)
{
var grainTypeInfo = grainClass.GetTypeInfo();
var grainClassCompleteName = TypeUtils.GetFullName(grainTypeInfo);
var isGenericGrainClass = grainTypeInfo.ContainsGenericParameters;
var grainClassTypeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainClass);
var placement = GrainTypeData.GetPlacementStrategy(grainClass, this.defaultPlacementStrategy);
var registrationStrategy = GrainTypeData.GetMultiClusterRegistrationStrategy(grainClass);
foreach (var iface in grainInterfaces)
{
var ifaceCompleteName = TypeUtils.GetFullName(iface);
var ifaceName = TypeUtils.GetRawClassName(ifaceCompleteName);
var isPrimaryImplementor = IsPrimaryImplementor(grainClass, iface);
var ifaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface);
grainInterfaceMap.AddEntry(ifaceId, iface, grainClassTypeCode, ifaceName, grainClassCompleteName,
grainTypeInfo.Assembly.CodeBase, isGenericGrainClass, placement, registrationStrategy, isPrimaryImplementor);
}
if (isUnordered)
grainInterfaceMap.AddToUnorderedList(grainClassTypeCode);
}
private static bool IsPrimaryImplementor(Type grainClass, Type iface)
{
// If the class name exactly matches the interface name, it is considered the primary (default)
// implementation of the interface, e.g. IFooGrain -> FooGrain
return (iface.Name.Substring(1) == grainClass.Name);
}
public bool TryGetData(string name, out GrainTypeData result)
{
return grainTypes.TryGetValue(name, out result);
}
internal GrainInterfaceMap GetTypeCodeMap()
{
// the map is immutable at this point
return grainInterfaceMap;
}
private void AddInvokerClass(int interfaceId, Type invoker)
{
lock (invokers)
{
if (!invokers.ContainsKey(interfaceId))
invokers.Add(interfaceId, new InvokerData(invoker));
}
}
/// <summary>
/// Returns a list of all graintypes in the system.
/// </summary>
/// <returns></returns>
internal string[] GetGrainTypeList()
{
return grainTypes.Keys.ToArray();
}
internal IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
try
{
InvokerData invokerData;
if (invokers.TryGetValue(interfaceId, out invokerData))
return invokerData.GetInvoker(genericGrainType);
}
catch (Exception ex)
{
throw new OrleansException(String.Format("Error finding invoker for interface ID: {0} (0x{0, 8:X8}). {1}", interfaceId, ex), ex);
}
Type type;
var interfaceName = grainInterfaceMap.TryGetServiceInterface(interfaceId, out type) ?
type.FullName : "*unavailable*";
throw new OrleansException(String.Format("Cannot find an invoker for interface {0} (ID={1},0x{1, 8:X8}).",
interfaceName, interfaceId));
}
private void RebuildFullGrainInterfaceMap()
{
var newClusterGrainInterfaceMap = new GrainInterfaceMap(false, defaultPlacementStrategy);
var newSupportedSilosByTypeCode = new Dictionary<int, IList<SiloAddress>>();
newClusterGrainInterfaceMap.AddMap(grainInterfaceMap);
foreach (var kvp in grainInterfaceMapsBySilo)
{
newClusterGrainInterfaceMap.AddMap(kvp.Value);
foreach (var grainType in kvp.Value.SupportedGrainTypes)
{
IList<SiloAddress> supportedSilos;
if (!newSupportedSilosByTypeCode.TryGetValue(grainType, out supportedSilos))
{
newSupportedSilosByTypeCode[grainType] = supportedSilos = new List<SiloAddress>();
}
supportedSilos.Add(kvp.Key);
}
}
ClusterGrainInterfaceMap = newClusterGrainInterfaceMap;
supportedSilosByTypeCode = newSupportedSilosByTypeCode;
}
private class InvokerData
{
private readonly Type baseInvokerType;
private IGrainMethodInvoker invoker;
private readonly Dictionary<string, IGrainMethodInvoker> cachedGenericInvokers;
private readonly object cachedGenericInvokersLockObj;
public InvokerData(Type invokerType)
{
baseInvokerType = invokerType;
if (invokerType.GetTypeInfo().IsGenericType)
{
cachedGenericInvokers = new Dictionary<string, IGrainMethodInvoker>();
cachedGenericInvokersLockObj = new object(); ;
}
}
public IGrainMethodInvoker GetInvoker(string genericGrainType = null)
{
// if the grain class is non-generic
if (cachedGenericInvokersLockObj == null)
{
return invoker ?? (invoker = (IGrainMethodInvoker)Activator.CreateInstance(baseInvokerType));
}
else
{
lock (cachedGenericInvokersLockObj)
{
if (cachedGenericInvokers.ContainsKey(genericGrainType))
return cachedGenericInvokers[genericGrainType];
}
var typeArgs = TypeUtils.GenericTypeArgsFromArgsString(genericGrainType);
var concreteType = baseInvokerType.MakeGenericType(typeArgs);
var inv = (IGrainMethodInvoker)Activator.CreateInstance(concreteType);
lock (cachedGenericInvokersLockObj)
{
if (!cachedGenericInvokers.ContainsKey(genericGrainType))
cachedGenericInvokers[genericGrainType] = inv;
}
return inv;
}
}
}
}
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="SectionFactory.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Sections
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Data;
using DomainModel.Configurations;
using DomainModel.Orders;
using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Items;
using Unity;
using Utils;
/// <summary>
/// The section factory class.
/// </summary>
public static class SectionFactory
{
/// <summary>
/// Gets the section.
/// </summary>
/// <param name="sectionItem">The section item.</param>
/// <param name="entity">The data entity.</param>
/// <returns>the section.</returns>
public static List<SectionTableRow> GetSection(Item sectionItem, object entity)
{
if (sectionItem != null)
{
ChildList childList = sectionItem.Children;
var tableRows = new List<SectionTableRow>();
foreach (Item sectionFieldItem in childList)
{
var sectionTableRow = new SectionTableRow();
string title = Utils.ItemUtil.GetTitleOrDictionaryEntry(sectionFieldItem, false);
sectionTableRow.Label = title;
string fieldID = sectionFieldItem["Field"];
string fieldName = title;
string value = fieldID;
object obj = new object();
if (!sectionFieldItem.TemplateName.Equals("Footer Section Multi-Line Text Field") &&
!sectionFieldItem.TemplateName.Equals("Footer Section Text Field") &&
!sectionFieldItem.TemplateName.Equals("Footer Section Link Field"))
{
fieldName = GetTemplateFieldName(fieldID);
obj = GetSourceObject(fieldID, entity);
value = GetPropertyValue(fieldName, obj);
}
sectionTableRow.FieldName = fieldName;
sectionTableRow.ShowLabelColumn = sectionFieldItem.Parent["Show Label Column"] == "1";
sectionTableRow.HideField = sectionFieldItem["Hide Field"] == "1";
sectionTableRow.ShowLabel = sectionFieldItem["Show Label"] == "1";
if (sectionFieldItem.TemplateName.Equals("Order Section Field") ||
sectionFieldItem.TemplateName.Equals("Footer Section Field") ||
sectionFieldItem.TemplateName.Equals("Footer Section Multi-Line Text Field") ||
sectionFieldItem.TemplateName.Equals("Footer Section Text Field"))
{
if (sectionTableRow.ShowLabel && !sectionTableRow.ShowLabelColumn)
{
sectionTableRow.Value = title + ": " + value;
}
else
{
sectionTableRow.Value = value;
}
}
else if (sectionFieldItem.TemplateName.Equals("Order Section Double Field") ||
sectionFieldItem.TemplateName.Equals("Footer Section Double Field"))
{
string fieldID2 = sectionFieldItem["Field2"];
string fieldName2 = GetTemplateFieldName(fieldID2);
string value2 = GetPropertyValue(fieldName2, obj);
sectionTableRow.FieldName2 = fieldName2;
if (sectionTableRow.ShowLabel && !sectionTableRow.ShowLabelColumn)
{
sectionTableRow.Value = title + ": " + value + ", " + value2;
}
else
{
sectionTableRow.Value = value + ", " + value2;
}
}
else if (sectionFieldItem.TemplateName.Equals("Footer Section Link Field"))
{
if (sectionTableRow.ShowLabel && !sectionTableRow.ShowLabelColumn)
{
sectionTableRow.Value = title + " " + "<a href=\"" + value + ".aspx\">" + title + "</a>";
}
else
{
sectionTableRow.Value = "<a href=\"" + value + ".aspx\">" + title + "</a>";
}
}
// To not add the row if HideField is enabled.
if (!sectionTableRow.HideField)
{
tableRows.Add(sectionTableRow);
}
}
return tableRows;
}
return
null;
}
/// <summary>
/// Gets the property value from the object by the selected fieldName
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="obj">The object.</param>
/// <returns>The property value from the object by the selected fieldName</returns>
private static string GetPropertyValue(string fieldName, object obj)
{
if (!string.IsNullOrEmpty(fieldName))
{
if (obj is Order)
{
IMappingRule<Order> rule = Context.Entity.Resolve<IMappingRule<Order>>("OrderMappingRule");
rule.MappingObject = (Order)obj;
obj = rule;
}
// If obj is of type Item, then retrieve fieldname.
if (obj is Item)
{
var item = (Item)obj;
return BusinessCatalogUtil.GetTitleFromReferencedItemOrValue(item[fieldName]);
}
EntityHelper entityHelper = Context.Entity.Resolve<EntityHelper>();
IDictionary<string, object> fieldsCollection = entityHelper.GetPropertiesValues(obj);
if (fieldsCollection.Count > 0)
{
string value = fieldsCollection.FirstOrDefault(p => p.Key.EndsWith(fieldName)).Value as string;
if (DateUtil.IsIsoDate(value))
{
DateTime date = DateUtil.IsoDateToDateTime(value);
return DateUtil.FormatShortDateTime(date, Sitecore.Context.Culture);
}
if (!string.IsNullOrEmpty(value) && ID.IsID(value))
{
Item valueItem = Sitecore.Context.Database.GetItem(value) ?? Sitecore.Context.ContentDatabase.GetItem(value);
if (valueItem != null)
{
value = valueItem.Name;
}
}
return value;
}
// Else retrieve from Property
if (obj != null)
{
PropertyInfo[] propertyInfos = obj.GetType().GetProperties();
foreach (PropertyInfo info in propertyInfos)
{
if (info.Name.Equals(fieldName))
{
object o = info.GetValue(obj, null);
string value = o + string.Empty;
return BusinessCatalogUtil.GetTitleFromReferencedItemOrValue(value);
}
}
}
}
return string.Empty;
}
/// <summary>
/// Gets the name of the template field.
/// </summary>
/// <param name="fieldId">The field id.</param>
/// <returns>The name of the template field.</returns>
private static string GetTemplateFieldName(string fieldId)
{
if (string.IsNullOrEmpty(fieldId))
{
return string.Empty;
}
if (!ID.IsID(fieldId))
{
return fieldId;
}
ID id = new ID(fieldId);
Item item = Sitecore.Context.Database.GetItem(id);
if (item != null)
{
var templateFieldItem = (TemplateFieldItem)item;
string name = templateFieldItem.Name;
return name;
}
return string.Empty;
}
/// <summary>
/// Gets the source object.
/// </summary>
/// <param name="fieldId">The field id.</param>
/// <param name="orderEntity">The order entity.</param>
/// <returns>The source object.</returns>
private static object GetSourceObject(string fieldId, object orderEntity)
{
if (!string.IsNullOrEmpty(fieldId))
{
if (!ID.IsID(fieldId))
{
return orderEntity;
}
var id = new ID(fieldId);
Item item = Sitecore.Context.Database.GetItem(id);
if (item != null)
{
var templateFieldItem = (TemplateFieldItem)item;
TemplateItem templateItem = templateFieldItem.Template;
if (templateItem.Name.Equals("Order"))
{
return orderEntity;
}
if (templateItem.Name.Equals("Company Master Data"))
{
BusinessCatalogSettings businessCatalogSettings = Context.Entity.GetConfiguration<BusinessCatalogSettings>();
return Sitecore.Context.Database.GetItem(businessCatalogSettings.CompanyMasterDataLink);
}
}
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//#define XSLT2
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.Xsl.Xslt
{
using StringConcat = System.Xml.Xsl.Runtime.StringConcat;
// a) Forward only, one pass.
// b) You should call MoveToFirstChildren on nonempty element node. (or may be skip)
internal class XsltInput : IErrorHelper
{
#if DEBUG
private const int InitRecordsSize = 1;
#else
private const int InitRecordsSize = 1 + 21;
#endif
private XmlReader _reader;
private IXmlLineInfo _readerLineInfo;
private bool _topLevelReader;
private CompilerScopeManager<VarPar> _scopeManager;
private KeywordsTable _atoms;
private Compiler _compiler;
private bool _reatomize;
// Cached properties. MoveTo* functions set them.
private XmlNodeType _nodeType;
private Record[] _records = new Record[InitRecordsSize];
private int _currentRecord;
private bool _isEmptyElement;
private int _lastTextNode;
private int _numAttributes;
private ContextInfo _ctxInfo;
private bool _attributesRead;
public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms)
{
Debug.Assert(reader != null);
Debug.Assert(atoms != null);
EnsureExpandEntities(reader);
IXmlLineInfo xmlLineInfo = reader as IXmlLineInfo;
_atoms = atoms;
_reader = reader;
_reatomize = reader.NameTable != atoms.NameTable;
_readerLineInfo = (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null;
_topLevelReader = reader.ReadState == ReadState.Initial;
_scopeManager = new CompilerScopeManager<VarPar>(atoms);
_compiler = compiler;
_nodeType = XmlNodeType.Document;
}
// Cached properties
public XmlNodeType NodeType { get { return _nodeType == XmlNodeType.Element && 0 < _currentRecord ? XmlNodeType.Attribute : _nodeType; } }
public string LocalName { get { return _records[_currentRecord].localName; } }
public string NamespaceUri { get { return _records[_currentRecord].nsUri; } }
public string Prefix { get { return _records[_currentRecord].prefix; } }
public string Value { get { return _records[_currentRecord].value; } }
public string BaseUri { get { return _records[_currentRecord].baseUri; } }
public string QualifiedName { get { return _records[_currentRecord].QualifiedName; } }
public bool IsEmptyElement { get { return _isEmptyElement; } }
public string Uri { get { return _records[_currentRecord].baseUri; } }
public Location Start { get { return _records[_currentRecord].start; } }
public Location End { get { return _records[_currentRecord].end; } }
private static void EnsureExpandEntities(XmlReader reader)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null && tr.EntityHandling != EntityHandling.ExpandEntities)
{
Debug.Assert(tr.Settings == null, "XmlReader created with XmlReader.Create should always expand entities.");
tr.EntityHandling = EntityHandling.ExpandEntities;
}
}
private void ExtendRecordBuffer(int position)
{
if (_records.Length <= position)
{
int newSize = _records.Length * 2;
if (newSize <= position)
{
newSize = position + 1;
}
Record[] tmp = new Record[newSize];
Array.Copy(_records, tmp, _records.Length);
_records = tmp;
}
}
public bool FindStylesheetElement()
{
if (!_topLevelReader)
{
if (_reader.ReadState != ReadState.Interactive)
{
return false;
}
}
// The stylesheet may be an embedded stylesheet. If this is the case the reader will be in Interactive state and should be
// positioned on xsl:stylesheet element (or any preceding whitespace) but there also can be namespaces defined on one
// of the ancestor nodes. These namespace definitions have to be copied to the xsl:stylesheet element scope. Otherwise it
// will not be possible to resolve them later and loading the stylesheet will end up with throwing an exception.
IDictionary<string, string> namespacesInScope = null;
if (_reader.ReadState == ReadState.Interactive)
{
// This may be an embedded stylesheet - store namespaces in scope
IXmlNamespaceResolver nsResolver = _reader as IXmlNamespaceResolver;
if (nsResolver != null)
{
namespacesInScope = nsResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
}
}
while (MoveToNextSibling() && _nodeType == XmlNodeType.Whitespace) ;
// An Element node was reached. Potentially this is xsl:stylesheet instruction.
if (_nodeType == XmlNodeType.Element)
{
// If namespacesInScope is not null then the stylesheet being read is an embedded stylesheet that can have namespaces
// defined outside of xsl:stylesheet instruction. In this case the namespace definitions collected above have to be added
// to the element scope.
if (namespacesInScope != null)
{
foreach (KeyValuePair<string, string> prefixNamespacePair in namespacesInScope)
{
// The namespace could be redefined on the element we just read. If this is the case scopeManager already has
// namespace definition for this prefix and the old definition must not be added to the scope.
if (_scopeManager.LookupNamespace(prefixNamespacePair.Key) == null)
{
string nsAtomizedValue = _atoms.NameTable.Add(prefixNamespacePair.Value);
_scopeManager.AddNsDeclaration(prefixNamespacePair.Key, nsAtomizedValue);
_ctxInfo.AddNamespace(prefixNamespacePair.Key, nsAtomizedValue);
}
}
}
// return true to indicate that we reached XmlNodeType.Element node - potentially xsl:stylesheet element.
return true;
}
// return false to indicate that we did not reach XmlNodeType.Element node so it is not a valid stylesheet.
return false;
}
public void Finish()
{
_scopeManager.CheckEmpty();
if (_topLevelReader)
{
while (_reader.ReadState == ReadState.Interactive)
{
_reader.Skip();
}
}
}
private void FillupRecord(ref Record rec)
{
rec.localName = _reader.LocalName;
rec.nsUri = _reader.NamespaceURI;
rec.prefix = _reader.Prefix;
rec.value = _reader.Value;
rec.baseUri = _reader.BaseURI;
if (_reatomize)
{
rec.localName = _atoms.NameTable.Add(rec.localName);
rec.nsUri = _atoms.NameTable.Add(rec.nsUri);
rec.prefix = _atoms.NameTable.Add(rec.prefix);
}
if (_readerLineInfo != null)
{
rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType));
}
}
private void SetRecordEnd(ref Record rec)
{
if (_readerLineInfo != null)
{
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType));
if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.start))
{
rec.end = new Location(rec.start.Line, int.MaxValue);
}
}
}
private void FillupTextRecord(ref Record rec)
{
Debug.Assert(
_reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace ||
_reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.CDATA
);
rec.localName = string.Empty;
rec.nsUri = string.Empty;
rec.prefix = string.Empty;
rec.value = _reader.Value;
rec.baseUri = _reader.BaseURI;
if (_readerLineInfo != null)
{
bool isCDATA = (_reader.NodeType == XmlNodeType.CDATA);
int line = _readerLineInfo.LineNumber;
int pos = _readerLineInfo.LinePosition;
rec.start = new Location(line, pos - (isCDATA ? 9 : 0));
char prevChar = ' ';
foreach (char ch in rec.value)
{
switch (ch)
{
case '\n':
if (prevChar != '\r')
{
goto case '\r';
}
break;
case '\r':
line++;
pos = 1;
break;
default:
pos++;
break;
}
prevChar = ch;
}
rec.end = new Location(line, pos + (isCDATA ? 3 : 0));
}
}
private void FillupCharacterEntityRecord(ref Record rec)
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
string local = _reader.LocalName;
Debug.Assert(local[0] == '#' || local == "lt" || local == "gt" || local == "quot" || local == "apos");
rec.localName = string.Empty;
rec.nsUri = string.Empty;
rec.prefix = string.Empty;
rec.baseUri = _reader.BaseURI;
if (_readerLineInfo != null)
{
rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - 1);
}
_reader.ResolveEntity();
_reader.Read();
Debug.Assert(_reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace);
rec.value = _reader.Value;
_reader.Read();
Debug.Assert(_reader.NodeType == XmlNodeType.EndEntity);
if (_readerLineInfo != null)
{
int line = _readerLineInfo.LineNumber;
int pos = _readerLineInfo.LinePosition;
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + 1);
}
}
private StringConcat _strConcat = new StringConcat();
// returns false if attribute is actualy namespace
private bool ReadAttribute(ref Record rec)
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute, "reader.NodeType == XmlNodeType.Attribute");
FillupRecord(ref rec);
if (Ref.Equal(rec.prefix, _atoms.Xmlns))
{ // xmlns:foo="NS_FOO"
string atomizedValue = _atoms.NameTable.Add(_reader.Value);
if (!Ref.Equal(rec.localName, _atoms.Xml))
{
_scopeManager.AddNsDeclaration(rec.localName, atomizedValue);
_ctxInfo.AddNamespace(rec.localName, atomizedValue);
}
return false;
}
else if (rec.prefix.Length == 0 && Ref.Equal(rec.localName, _atoms.Xmlns))
{ // xmlns="NS_FOO"
string atomizedValue = _atoms.NameTable.Add(_reader.Value);
_scopeManager.AddNsDeclaration(string.Empty, atomizedValue);
_ctxInfo.AddNamespace(string.Empty, atomizedValue);
return false;
}
/* Read Attribute Value */
{
if (!_reader.ReadAttributeValue())
{
// XmlTextReader never returns false from first call to ReadAttributeValue()
rec.value = string.Empty;
SetRecordEnd(ref rec);
return true;
}
if (_readerLineInfo != null)
{
int correction = (_reader.NodeType == XmlNodeType.EntityReference) ? -2 : -1;
rec.valueStart = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction);
if (_reader.BaseURI != rec.baseUri || rec.valueStart.LessOrEqual(rec.start))
{
int nameLength = ((rec.prefix.Length != 0) ? rec.prefix.Length + 1 : 0) + rec.localName.Length;
rec.end = new Location(rec.start.Line, rec.start.Pos + nameLength + 1);
}
}
string lastText = string.Empty;
_strConcat.Clear();
do
{
switch (_reader.NodeType)
{
case XmlNodeType.EntityReference:
_reader.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
Debug.Assert(_reader.NodeType == XmlNodeType.Text, "Unexpected node type inside attribute value");
lastText = _reader.Value;
_strConcat.Concat(lastText);
break;
}
} while (_reader.ReadAttributeValue());
rec.value = _strConcat.GetResult();
if (_readerLineInfo != null)
{
Debug.Assert(_reader.NodeType != XmlNodeType.EntityReference);
int correction = ((_reader.NodeType == XmlNodeType.EndEntity) ? 1 : lastText.Length) + 1;
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction);
if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.valueStart))
{
rec.end = new Location(rec.start.Line, int.MaxValue);
}
}
}
return true;
}
// --------------------
public bool MoveToFirstChild()
{
Debug.Assert(_nodeType == XmlNodeType.Element, "To call MoveToFirstChild() XsltInut should be positioned on an Element.");
if (IsEmptyElement)
{
return false;
}
return ReadNextSibling();
}
public bool MoveToNextSibling()
{
Debug.Assert(_nodeType != XmlNodeType.Element || IsEmptyElement, "On non-empty elements we should call MoveToFirstChild()");
if (_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement)
{
_scopeManager.ExitScope();
}
return ReadNextSibling();
}
public void SkipNode()
{
if (_nodeType == XmlNodeType.Element && MoveToFirstChild())
{
do
{
SkipNode();
} while (MoveToNextSibling());
}
}
private int ReadTextNodes()
{
bool textPreserveWS = _reader.XmlSpace == XmlSpace.Preserve;
bool textIsWhite = true;
int curTextNode = 0;
do
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
// XLinq reports WS nodes as Text so we need to analyze them here
case XmlNodeType.CDATA:
if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_reader.Value))
{
textIsWhite = false;
}
goto case XmlNodeType.SignificantWhitespace;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
ExtendRecordBuffer(curTextNode);
FillupTextRecord(ref _records[curTextNode]);
_reader.Read();
curTextNode++;
break;
case XmlNodeType.EntityReference:
string local = _reader.LocalName;
if (local.Length > 0 && (
local[0] == '#' ||
local == "lt" || local == "gt" || local == "quot" || local == "apos"
))
{
// Special treatment for character and built-in entities
ExtendRecordBuffer(curTextNode);
FillupCharacterEntityRecord(ref _records[curTextNode]);
if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_records[curTextNode].value))
{
textIsWhite = false;
}
curTextNode++;
}
else
{
_reader.ResolveEntity();
_reader.Read();
}
break;
case XmlNodeType.EndEntity:
_reader.Read();
break;
default:
_nodeType = (
!textIsWhite ? XmlNodeType.Text :
textPreserveWS ? XmlNodeType.SignificantWhitespace :
/*default: */ XmlNodeType.Whitespace
);
return curTextNode;
}
} while (true);
}
private bool ReadNextSibling()
{
if (_currentRecord < _lastTextNode)
{
Debug.Assert(_nodeType == XmlNodeType.Text || _nodeType == XmlNodeType.Whitespace || _nodeType == XmlNodeType.SignificantWhitespace);
_currentRecord++;
if (_currentRecord == _lastTextNode)
{
_lastTextNode = 0; // we are done with text nodes. Reset this counter
}
return true;
}
_currentRecord = 0;
while (!_reader.EOF)
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.EntityReference:
int numTextNodes = ReadTextNodes();
if (numTextNodes == 0)
{
// Most likely this was Entity that starts from non-text node
continue;
}
_lastTextNode = numTextNodes - 1;
return true;
case XmlNodeType.Element:
_scopeManager.EnterScope();
_numAttributes = ReadElement();
return true;
case XmlNodeType.EndElement:
_nodeType = XmlNodeType.EndElement;
_isEmptyElement = false;
FillupRecord(ref _records[0]);
_reader.Read();
SetRecordEnd(ref _records[0]);
return false;
default:
_reader.Read();
break;
}
}
return false;
}
private int ReadElement()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
_attributesRead = false;
FillupRecord(ref _records[0]);
_nodeType = XmlNodeType.Element;
_isEmptyElement = _reader.IsEmptyElement;
_ctxInfo = new ContextInfo(this);
int record = 1;
if (_reader.MoveToFirstAttribute())
{
do
{
ExtendRecordBuffer(record);
if (ReadAttribute(ref _records[record]))
{
record++;
}
} while (_reader.MoveToNextAttribute());
_reader.MoveToElement();
}
_reader.Read();
SetRecordEnd(ref _records[0]);
_ctxInfo.lineInfo = BuildLineInfo();
_attributes = null;
return record - 1;
}
public void MoveToElement()
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToElement() we should be positioned on Element or Attribute");
_currentRecord = 0;
}
private bool MoveToAttributeBase(int attNum)
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute");
if (0 < attNum && attNum <= _numAttributes)
{
_currentRecord = attNum;
return true;
}
else
{
_currentRecord = 0;
return false;
}
}
public bool MoveToLiteralAttribute(int attNum)
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute");
if (0 < attNum && attNum <= _numAttributes)
{
_currentRecord = attNum;
return true;
}
else
{
_currentRecord = 0;
return false;
}
}
public bool MoveToXsltAttribute(int attNum, string attName)
{
Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error.");
_currentRecord = _xsltAttributeNumber[attNum];
return _currentRecord != 0;
}
public bool IsRequiredAttribute(int attNum)
{
return (_attributes[attNum].flags & (_compiler.Version == 2 ? XsltLoader.V2Req : XsltLoader.V1Req)) != 0;
}
public bool AttributeExists(int attNum, string attName)
{
Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error.");
return _xsltAttributeNumber[attNum] != 0;
}
public struct DelayedQName
{
private string _prefix;
private string _localName;
public DelayedQName(ref Record rec)
{
_prefix = rec.prefix;
_localName = rec.localName;
}
public static implicit operator string (DelayedQName qn)
{
return qn._prefix.Length == 0 ? qn._localName : (qn._prefix + ':' + qn._localName);
}
}
public DelayedQName ElementName
{
get
{
Debug.Assert(_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement, "Input is positioned on element or attribute");
return new DelayedQName(ref _records[0]);
}
}
// -------------------- Keywords testing --------------------
public bool IsNs(string ns) { return Ref.Equal(ns, NamespaceUri); }
public bool IsKeyword(string kwd) { return Ref.Equal(kwd, LocalName); }
public bool IsXsltNamespace() { return IsNs(_atoms.UriXsl); }
public bool IsNullNamespace() { return IsNs(string.Empty); }
public bool IsXsltKeyword(string kwd) { return IsKeyword(kwd) && IsXsltNamespace(); }
// -------------------- Scope Management --------------------
// See private class InputScopeManager bellow.
// InputScopeManager handles some flags and values with respect of scope level where they as defined.
// To parse XSLT style sheet we need the folloing values:
// BackwardCompatibility -- this flag is set when compiler.version==2 && xsl:version<2.
// ForwardCompatibility -- this flag is set when compiler.version==2 && xsl:version>1 or compiler.version==1 && xsl:version!=1
// CanHaveApplyImports -- we allow xsl:apply-templates instruction to apear in any template with match!=null, but not inside xsl:for-each
// so it can't be inside global variable and has initial value = false
// ExtentionNamespace -- is defined by extension-element-prefixes attribute on LRE or xsl:stylesheet
public bool CanHaveApplyImports
{
get { return _scopeManager.CanHaveApplyImports; }
set { _scopeManager.CanHaveApplyImports = value; }
}
public bool IsExtensionNamespace(string uri)
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.IsExNamespace(uri);
}
public bool ForwardCompatibility
{
get
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.ForwardCompatibility;
}
}
public bool BackwardCompatibility
{
get
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.BackwardCompatibility;
}
}
public XslVersion XslVersion
{
get { return _scopeManager.ForwardCompatibility ? XslVersion.ForwardsCompatible : XslVersion.Current; }
}
private void SetVersion(int attVersion)
{
MoveToLiteralAttribute(attVersion);
Debug.Assert(IsKeyword(_atoms.Version));
double version = XPathConvert.StringToDouble(Value);
if (double.IsNaN(version))
{
ReportError(/*[XT0110]*/SR.Xslt_InvalidAttrValue, _atoms.Version, Value);
#if XSLT2
version = 2.0;
#else
version = 1.0;
#endif
}
SetVersion(version);
}
private void SetVersion(double version)
{
if (_compiler.Version == 0)
{
#if XSLT2
compiler.Version = version < 2.0 ? 1 : 2;
#else
_compiler.Version = 1;
#endif
}
if (_compiler.Version == 1)
{
_scopeManager.BackwardCompatibility = false;
_scopeManager.ForwardCompatibility = (version != 1.0);
}
else
{
_scopeManager.BackwardCompatibility = version < 2;
_scopeManager.ForwardCompatibility = 2 < version;
}
}
// --------------- GetAttributes(...) -------------------------
// All Xslt Instructions allows fixed set of attributes in null-ns, no in XSLT-ns and any in other ns.
// In ForwardCompatibility mode we should ignore any of this problems.
// We not use these functions for parseing LiteralResultElement and xsl:stylesheet
public struct XsltAttribute
{
public string name;
public int flags;
public XsltAttribute(string name, int flags)
{
this.name = name;
this.flags = flags;
}
}
private XsltAttribute[] _attributes = null;
// Mapping of attribute names as they ordered in 'attributes' array
// to there's numbers in actual stylesheet as they ordered in 'records' array
private int[] _xsltAttributeNumber = new int[21];
public ContextInfo GetAttributes()
{
return GetAttributes(Array.Empty<XsltAttribute>());
}
public ContextInfo GetAttributes(XsltAttribute[] attributes)
{
Debug.Assert(NodeType == XmlNodeType.Element);
Debug.Assert(attributes.Length <= _xsltAttributeNumber.Length);
_attributes = attributes;
// temp hack to fix value? = new AttValue(records[values[?]].value);
_records[0].value = null;
// Standard Attributes:
int attExtension = 0;
int attExclude = 0;
int attNamespace = 0;
int attCollation = 0;
int attUseWhen = 0;
bool isXslOutput = IsXsltNamespace() && IsKeyword(_atoms.Output);
bool SS = IsXsltNamespace() && (IsKeyword(_atoms.Stylesheet) || IsKeyword(_atoms.Transform));
bool V2 = _compiler.Version == 2;
for (int i = 0; i < attributes.Length; i++)
{
_xsltAttributeNumber[i] = 0;
}
_compiler.EnterForwardsCompatible();
if (SS || V2 && !isXslOutput)
{
for (int i = 1; MoveToAttributeBase(i); i++)
{
if (IsNullNamespace() && IsKeyword(_atoms.Version))
{
SetVersion(i);
break;
}
}
}
if (_compiler.Version == 0)
{
Debug.Assert(SS, "First we parse xsl:stylesheet element");
#if XSLT2
SetVersion(2.0);
#else
SetVersion(1.0);
#endif
}
V2 = _compiler.Version == 2;
int OptOrReq = V2 ? XsltLoader.V2Opt | XsltLoader.V2Req : XsltLoader.V1Opt | XsltLoader.V1Req;
for (int attNum = 1; MoveToAttributeBase(attNum); attNum++)
{
if (IsNullNamespace())
{
string localName = LocalName;
int kwd;
for (kwd = 0; kwd < attributes.Length; kwd++)
{
if (Ref.Equal(localName, attributes[kwd].name) && (attributes[kwd].flags & OptOrReq) != 0)
{
_xsltAttributeNumber[kwd] = attNum;
break;
}
}
if (kwd == attributes.Length)
{
if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes) && (SS || V2)) { attExclude = attNum; }
else
if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes) && (SS || V2)) { attExtension = attNum; }
else
if (Ref.Equal(localName, _atoms.XPathDefaultNamespace) && (V2)) { attNamespace = attNum; }
else
if (Ref.Equal(localName, _atoms.DefaultCollation) && (V2)) { attCollation = attNum; }
else
if (Ref.Equal(localName, _atoms.UseWhen) && (V2)) { attUseWhen = attNum; }
else
{
ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName);
}
}
}
else if (IsXsltNamespace())
{
ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName);
}
else
{
// Ignore the attribute.
// An element from the XSLT namespace may have any attribute not from the XSLT namespace,
// provided that the expanded-name of the attribute has a non-null namespace URI.
// For example, it may be 'xml:space'.
}
}
_attributesRead = true;
// Ignore invalid attributes if forwards-compatible behavior is enabled. Note that invalid
// attributes may encounter before ForwardCompatibility flag is set to true. For example,
// <xsl:stylesheet unknown="foo" version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>
_compiler.ExitForwardsCompatible(ForwardCompatibility);
InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/ true);
InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/ false);
SetXPathDefaultNamespace(attNamespace);
SetDefaultCollation(attCollation);
if (attUseWhen != 0)
{
ReportNYI(_atoms.UseWhen);
}
MoveToElement();
// Report missing mandatory attributes
for (int i = 0; i < attributes.Length; i++)
{
if (_xsltAttributeNumber[i] == 0)
{
int flags = attributes[i].flags;
if (
_compiler.Version == 2 && (flags & XsltLoader.V2Req) != 0 ||
_compiler.Version == 1 && (flags & XsltLoader.V1Req) != 0 && (!ForwardCompatibility || (flags & XsltLoader.V2Req) != 0)
)
{
ReportError(/*[XT_001]*/SR.Xslt_MissingAttribute, attributes[i].name);
}
}
}
return _ctxInfo;
}
public ContextInfo GetLiteralAttributes(bool asStylesheet)
{
Debug.Assert(NodeType == XmlNodeType.Element);
// Standard Attributes:
int attVersion = 0;
int attExtension = 0;
int attExclude = 0;
int attNamespace = 0;
int attCollation = 0;
int attUseWhen = 0;
for (int i = 1; MoveToLiteralAttribute(i); i++)
{
if (IsXsltNamespace())
{
string localName = LocalName;
if (Ref.Equal(localName, _atoms.Version)) { attVersion = i; }
else
if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes)) { attExtension = i; }
else
if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes)) { attExclude = i; }
else
if (Ref.Equal(localName, _atoms.XPathDefaultNamespace)) { attNamespace = i; }
else
if (Ref.Equal(localName, _atoms.DefaultCollation)) { attCollation = i; }
else
if (Ref.Equal(localName, _atoms.UseWhen)) { attUseWhen = i; }
}
}
_attributesRead = true;
this.MoveToElement();
if (attVersion != 0)
{
// Enable forwards-compatible behavior if version attribute is not "1.0"
SetVersion(attVersion);
}
else
{
if (asStylesheet)
{
ReportError(Ref.Equal(NamespaceUri, _atoms.UriWdXsl) && Ref.Equal(LocalName, _atoms.Stylesheet) ?
/*[XT_025]*/SR.Xslt_WdXslNamespace : /*[XT0150]*/SR.Xslt_WrongStylesheetElement
);
#if XSLT2
SetVersion(2.0);
#else
SetVersion(1.0);
#endif
}
}
// Parse xsl:extension-element-prefixes attribute (now that forwards-compatible mode is known)
InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/true);
if (!IsExtensionNamespace(_records[0].nsUri))
{
// Parse other attributes (now that it's known this is a literal result element)
if (_compiler.Version == 2)
{
SetXPathDefaultNamespace(attNamespace);
SetDefaultCollation(attCollation);
if (attUseWhen != 0)
{
ReportNYI(_atoms.UseWhen);
}
}
InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/false);
}
return _ctxInfo;
}
// Get just the 'version' attribute of an unknown XSLT instruction. All other attributes
// are ignored since we do not want to report an error on each of them.
public void GetVersionAttribute()
{
Debug.Assert(NodeType == XmlNodeType.Element && IsXsltNamespace());
bool V2 = _compiler.Version == 2;
if (V2)
{
for (int i = 1; MoveToAttributeBase(i); i++)
{
if (IsNullNamespace() && IsKeyword(_atoms.Version))
{
SetVersion(i);
break;
}
}
}
_attributesRead = true;
}
private void InsertExNamespaces(int attExPrefixes, ContextInfo ctxInfo, bool extensions)
{
// List of Extension namespaces are maintaned by XsltInput's ScopeManager and is used by IsExtensionNamespace() in XsltLoader.LoadLiteralResultElement()
// Both Extension and Exclusion namespaces will not be coppied by LiteralResultElement. Logic of copping namespaces are in QilGenerator.CompileLiteralElement().
// At this time we will have different scope manager and need preserve all required information from load time to compile time.
// Each XslNode contains list of NsDecls (nsList) wich stores prefix+namespaces pairs for each namespace decls as well as exclusion namespaces.
// In addition it also contains Exclusion namespace. They are represented as (null+namespace). Special case is Exlusion "#all" represented as (null+null).
//and Exclusion namespace
if (MoveToLiteralAttribute(attExPrefixes))
{
Debug.Assert(extensions ? IsKeyword(_atoms.ExtensionElementPrefixes) : IsKeyword(_atoms.ExcludeResultPrefixes));
string value = Value;
if (value.Length != 0)
{
if (!extensions && _compiler.Version != 1 && value == "#all")
{
ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, /*nsUri:*/null); // null, null means Exlusion #all
}
else
{
_compiler.EnterForwardsCompatible();
string[] list = XmlConvert.SplitString(value);
for (int idx = 0; idx < list.Length; idx++)
{
if (list[idx] == "#default")
{
list[idx] = this.LookupXmlNamespace(string.Empty);
if (list[idx].Length == 0 && _compiler.Version != 1 && !BackwardCompatibility)
{
ReportError(/*[XTSE0809]*/SR.Xslt_ExcludeDefault);
}
}
else
{
list[idx] = this.LookupXmlNamespace(list[idx]);
}
}
if (!_compiler.ExitForwardsCompatible(this.ForwardCompatibility))
{
// There were errors in the list, ignore the whole list
return;
}
for (int idx = 0; idx < list.Length; idx++)
{
if (list[idx] != null)
{
ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, list[idx]); // null means that this Exlusion NS
if (extensions)
{
_scopeManager.AddExNamespace(list[idx]); // At Load time we need to know Extencion namespaces to ignore such literal elements.
}
}
}
}
}
}
}
private void SetXPathDefaultNamespace(int attNamespace)
{
if (MoveToLiteralAttribute(attNamespace))
{
Debug.Assert(IsKeyword(_atoms.XPathDefaultNamespace));
if (Value.Length != 0)
{
ReportNYI(_atoms.XPathDefaultNamespace);
}
}
}
private void SetDefaultCollation(int attCollation)
{
if (MoveToLiteralAttribute(attCollation))
{
Debug.Assert(IsKeyword(_atoms.DefaultCollation));
string[] list = XmlConvert.SplitString(Value);
int col;
for (col = 0; col < list.Length; col++)
{
if (System.Xml.Xsl.Runtime.XmlCollation.Create(list[col], /*throw:*/false) != null)
{
break;
}
}
if (col == list.Length)
{
ReportErrorFC(/*[XTSE0125]*/SR.Xslt_CollationSyntax);
}
else
{
if (list[col] != XmlReservedNs.NsCollCodePoint)
{
ReportNYI(_atoms.DefaultCollation);
}
}
}
}
// ----------------------- ISourceLineInfo -----------------------
private static int PositionAdjustment(XmlNodeType nt)
{
switch (nt)
{
case XmlNodeType.Element:
return 1; // "<"
case XmlNodeType.CDATA:
return 9; // "<![CDATA["
case XmlNodeType.ProcessingInstruction:
return 2; // "<?"
case XmlNodeType.Comment:
return 4; // "<!--"
case XmlNodeType.EndElement:
return 2; // "</"
case XmlNodeType.EntityReference:
return 1; // "&"
default:
return 0;
}
}
public ISourceLineInfo BuildLineInfo()
{
return new SourceLineInfo(Uri, Start, End);
}
public ISourceLineInfo BuildNameLineInfo()
{
if (_readerLineInfo == null)
{
return BuildLineInfo();
}
// LocalName is checked against null since it is used to calculate QualifiedName used in turn to
// calculate end position.
// LocalName (and other cached properties) can be null only if nothing has been read from the reader.
// This happens for instance when a reader which has already been closed or a reader positioned
// on the very last node of the document is passed to the ctor.
if (LocalName == null)
{
// Fill up the current record to set all the properties used below.
FillupRecord(ref _records[_currentRecord]);
}
Location start = Start;
int line = start.Line;
int pos = start.Pos + PositionAdjustment(NodeType);
return new SourceLineInfo(Uri, new Location(line, pos), new Location(line, pos + QualifiedName.Length));
}
public ISourceLineInfo BuildReaderLineInfo()
{
Location loc;
if (_readerLineInfo != null)
loc = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition);
else
loc = new Location(0, 0);
return new SourceLineInfo(_reader.BaseURI, loc, loc);
}
// Resolve prefix, return null and report an error if not found
public string LookupXmlNamespace(string prefix)
{
Debug.Assert(prefix != null);
string nsUri = _scopeManager.LookupNamespace(prefix);
if (nsUri != null)
{
Debug.Assert(Ref.Equal(_atoms.NameTable.Get(nsUri), nsUri), "Namespaces must be atomized");
return nsUri;
}
if (prefix.Length == 0)
{
return string.Empty;
}
ReportError(/*[XT0280]*/SR.Xslt_InvalidPrefix, prefix);
return null;
}
// ---------------------- Error Handling ----------------------
public void ReportError(string res, params string[] args)
{
_compiler.ReportError(BuildNameLineInfo(), res, args);
}
public void ReportWarning(string res, params string[] args)
{
_compiler.ReportWarning(BuildNameLineInfo(), res, args);
}
public void ReportErrorFC(string res, params string[] args)
{
if (!ForwardCompatibility)
{
_compiler.ReportError(BuildNameLineInfo(), res, args);
}
}
private void ReportNYI(string arg)
{
ReportErrorFC(SR.Xslt_NotYetImplemented, arg);
}
// -------------------------------- ContextInfo ------------------------------------
internal class ContextInfo
{
public NsDecl nsList;
public ISourceLineInfo lineInfo; // Line info for whole start tag
public ISourceLineInfo elemNameLi; // Line info for element name
public ISourceLineInfo endTagLi; // Line info for end tag or '/>'
private int _elemNameLength;
// Create ContextInfo based on existing line info (used during AST rewriting)
internal ContextInfo(ISourceLineInfo lineinfo)
{
this.elemNameLi = lineinfo;
this.endTagLi = lineinfo;
this.lineInfo = lineinfo;
}
public ContextInfo(XsltInput input)
{
_elemNameLength = input.QualifiedName.Length;
}
public void AddNamespace(string prefix, string nsUri)
{
nsList = new NsDecl(nsList, prefix, nsUri);
}
public void SaveExtendedLineInfo(XsltInput input)
{
if (lineInfo.Start.Line == 0)
{
elemNameLi = endTagLi = null;
return;
}
elemNameLi = new SourceLineInfo(
lineInfo.Uri,
lineInfo.Start.Line, lineInfo.Start.Pos + 1, // "<"
lineInfo.Start.Line, lineInfo.Start.Pos + 1 + _elemNameLength
);
if (!input.IsEmptyElement)
{
Debug.Assert(input.NodeType == XmlNodeType.EndElement);
endTagLi = input.BuildLineInfo();
}
else
{
Debug.Assert(input.NodeType == XmlNodeType.Element || input.NodeType == XmlNodeType.Attribute);
endTagLi = new EmptyElementEndTag(lineInfo);
}
}
// We need this wrapper class because elementTagLi is not yet calculated
internal class EmptyElementEndTag : ISourceLineInfo
{
private ISourceLineInfo _elementTagLi;
public EmptyElementEndTag(ISourceLineInfo elementTagLi)
{
_elementTagLi = elementTagLi;
}
public string Uri { get { return _elementTagLi.Uri; } }
public bool IsNoSource { get { return _elementTagLi.IsNoSource; } }
public Location Start { get { return new Location(_elementTagLi.End.Line, _elementTagLi.End.Pos - 2); } }
public Location End { get { return _elementTagLi.End; } }
}
}
internal struct Record
{
public string localName;
public string nsUri;
public string prefix;
public string value;
public string baseUri;
public Location start;
public Location valueStart;
public Location end;
public string QualifiedName { get { return prefix.Length == 0 ? localName : string.Concat(prefix, ":", localName); } }
}
}
}
| |
/*
* Copyright 2005 OpenXRI Foundation
* Subsequently ported and altered by Andrew Arnott
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace DotNetXri.Client.Xml {
//using java.io.ByteArrayInputStream;
//using java.io.InputStream;
//using java.io.Serializable;
//using java.net.UriFormatException;
//using java.text.ParseException;
//using java.util.ArrayList;
//using java.util.Hashtable;
//using java.util.IEnumerator;
//using java.util.List;
//using java.util.ArrayList;
//using org.apache.xerces.dom.XmlDocument;
//using org.apache.xerces.parsers.DOMParser;
//using org.apache.xml.security.exceptions.XMLSecurityException;
//using org.apache.xml.security.keys.KeyInfo;
//using org.openxri.XRIParseException;
//using org.openxri.util.DOMUtils;
//using org.openxri.util.PrioritizedList;
//using org.w3c.dom.XmlDocument;
//using org.w3c.dom.XmlElement;
//using org.w3c.dom.Node;
//using org.xml.sax.InputSource;
using System;
using System.Collections;
using DotNetXri.Loggers;
using System.Xml;
using System.Text;
using DotNetXri.Syntax;
/**
* This class describes the Service XML element used for XRI Authority
* resolution.
*
* @author =chetan
* @author =wil
* @author =peacekeeper
*/
public class Service : Cloneable, Serializable {
private static ILog soLog = Logger.Create(typeof(Service));
private ProviderID providerID;
private ArrayList localIDs;
private ArrayList types;
private ArrayList paths;
private ArrayList mediaTypes;
private int? priority;
private KeyInfo keyInfo;
private ArrayList uris;
private PrioritizedList prioritizedURIs;
private ArrayList redirects;
private PrioritizedList prioritizedRedirects = null;
private ArrayList refs;
private PrioritizedList prioritizedRefs = null;
private Hashtable otherChildrenVectorMap = new Hashtable();
/**
* Contructs an empty Service element
*/
public Service() {
reset();
}
/**
* This method constructs the obj from DOM. It does not keep a
* copy of the DOM around. Whitespace information is lost in this process.
*/
public Service(XmlElement oElem) //throws UriFormatException
{
fromDOM(oElem);
}
/**
* Resets the internal state of this obj
*/
public void reset() {
providerID = null;
localIDs = new ArrayList();
types = new ArrayList();
paths = new ArrayList();
mediaTypes = new ArrayList();
priority = null;
keyInfo = null;
uris = new ArrayList();
prioritizedURIs = null;
redirects = new ArrayList();
prioritizedRedirects = null;
refs = new ArrayList();
prioritizedRefs = null;
otherChildrenVectorMap = new Hashtable();
}
/**
* This method populates the obj from DOM. It does not keep a
* copy of the DOM around. Whitespace information is lost in this processs.
*/
public void fromDOM(XmlElement oElem) //throws UriFormatException
{
reset();
string val = oElem.GetAttribute(Tags.ATTR_PRIORITY);
if (val != null && val.Length > 0) {
setPriority(val);
}
for (
XmlElement oChild = (XmlElement)oElem.FirstChild; oChild != null;
oChild = (XmlElement)oChild.NextSibling) {
// pre-grab the name and text value
string sChildName = oChild.LocalName;
if (sChildName == null) sChildName = oChild.getNodeName();
if (sChildName.Equals(Tags.TAG_TYPE)) {
// TODO: validate XRI/IRI/Uri (must be in Uri-normal form)
types.Add(SEPType.fromXML(oChild));
} else if (sChildName.Equals(Tags.TAG_PROVIDERID)) {
ProviderID p = new ProviderID();
p.fromXML(oChild);
this.providerID = p;
} else if (sChildName.Equals(Tags.TAG_PATH)) {
paths.Add(SEPPath.fromXML(oChild));
} else if (sChildName.Equals(Tags.TAG_MEDIATYPE)) {
mediaTypes.Add(SEPMediaType.fromXML(oChild));
} else if (sChildName.Equals(Tags.TAG_URI)) {
addURI(SEPUri.fromXML(oChild));
} else if (sChildName.Equals(Tags.TAG_REF)) {
addRef(new Ref(oChild));
} else if (sChildName.Equals(Tags.TAG_REDIRECT)) {
addRedirect(new Redirect(oChild));
} else if (sChildName.Equals(Tags.TAG_LOCALID)) {
addLocalID(new LocalID(oChild));
} else if (
(oChild.NamespaceURI != null) &&
oChild.NamespaceURI.Equals(Tags.NS_XMLDSIG) &&
(oChild.LocalName != null) &&
oChild.LocalName.Equals(Tags.TAG_KEYINFO)) {
try {
keyInfo = new KeyInfo(oChild, "");
} catch (XMLSecurityException oEx) {
soLog.Warn("Error constructing KeyInfo.", oEx);
}
} else {
ArrayList oVector =
(ArrayList)otherChildrenVectorMap[sChildName];
if (oVector == null) {
oVector = new ArrayList();
otherChildrenVectorMap[sChildName] = oVector;
}
// Instead of Storing just the Child Value, store a clone of the complete
// Node that if we support multiple child elements and also custom NameSpaces
oVector.Add(oChild.CloneNode(true));
}
}
}
/**
* Returns the media type element value
* @deprecated
*/
public string getMediaType() {
soLog.Warn("getMediaType - deprecated.");
SEPMediaType mtype = getMediaTypeAt(0);
return (mtype != null) ? mtype.getValue() : null;
}
/**
* Returns the number of media types in this service
*/
public int getNumMediaTypes() {
return (mediaTypes == null) ? 0 : mediaTypes.Count;
}
/**
* Returns the media type at the given index.
*/
public SEPMediaType getMediaTypeAt(int n) {
if (this.mediaTypes != null) return (SEPMediaType)mediaTypes[n];
return null;
}
/**
* Sets the media type element value
* @deprecated
*/
public void setMediaType(string sVal) {
soLog.Warn("setMediaType - deprecated.");
SEPMediaType mediaType = new SEPMediaType(sVal, null, null);
mediaTypes.Add(mediaType);
}
/**
* Adds a media type to this Service
*/
public void addMediaType(string sVal) {
addMediaType(sVal, null, null);
}
/**
* Adds a media type to this Service with attributes
*/
public void addMediaType(string sVal, string match, bool? select) {
SEPMediaType mediaType = new SEPMediaType(sVal, match, select);
mediaTypes.Add(mediaType);
}
/**
* Returns the type element value
* @deprecated
*/
public string getType() {
soLog.Warn("getType is deprecated.");
SEPType type = getTypeAt(0);
return (type != null) ? type.getValue() : null;
}
/**
* Returns the number of types in this service
*/
public int getNumTypes() {
return (types == null) ? 0 : types.Count;
}
/**
* Returns the type at the given index.
*/
public SEPType getTypeAt(int n) {
if (this.types != null)
return (SEPType)types[n];
return null;
}
/**
* Sets the type element value
* @deprecated
*/
public void setType(string sVal) {
soLog.Warn("setType is deprecated.");
types.Add(new SEPType(sVal, null, null));
}
/**
* Adds a type to this Service
*/
public void addType(string sVal) {
addType(sVal, null, null);
}
/**
* Adds a type to this Service with attributes
*/
public void addType(string sVal, string match, bool? select) {
types.Add(new SEPType(sVal, match, select));
}
/**
* Returns true if the given type is equivalent to the type of this service.
* TODO - this should probably compare the normalized type rather than
* performing a straight string comparison. Also, there may be multiple
* types associated with a service.
* @deprecated
*/
public bool matchType(string sVal) {
for (int i = 0; i < getNumTypes(); i++) {
SEPType type = (SEPType)getTypeAt(i);
if (type.match(sVal)) return true;
}
return false;
}
/**
* Returns the number of URIs
*/
public int getNumURIs() {
return (uris == null) ? 0 : uris.Count;
}
/**
* Returns the first Uri
* @deprecated
*/
public SEPUri getURI() {
soLog.Warn("getURI is deprecated.");
return getURIAt(0);
}
/**
* Returns the Uri at the given index
*/
public SEPUri getURIAt(int n) {
return (n < getNumURIs()) ? (SEPUri)uris[n] : null;
}
/**
* Returns the first Uri for the given scheme
*/
public SEPUri getURIForScheme(string sScheme) {
if (sScheme == null) return null;
for (int i = 0; i < getNumURIs(); i++) {
// just return the first Uri that matches the
// requested scheme
SEPUri oURI = (SEPUri)getURIAt(i);
if (oURI != null && oURI.getURI() != null &&
oURI.getURI().Scheme.Equals(sScheme, StringComparison.OrdinalIgnoreCase))
return oURI;
}
return null;
}
/**
* Returns the a vector of URIs
*/
public ArrayList getURIs() {
return uris;
}
/**
* Returns the URIs in sorted in priority order
* @return
*/
public ArrayList getPrioritizedURIs() {
if (prioritizedURIs == null)
return new ArrayList();
return prioritizedURIs.getList();
}
/**
* Adds a Uri to the service
*/
public void addURI(string sURI) {
addURI(sURI, null, null);
}
/**
* Adds a Uri to the service with attributes
*/
public void addURI(string sURI, int? priority, string append) {
try {
SEPUri uri = new SEPUri(sURI, priority, append);
addURI(uri);
} catch (Exception e) {
throw new XRIParseException("BadURI", e);
}
}
/**
* Adds an SEPUri obj to the list of URIs
* @param uri
*/
public void addURI(SEPUri uri) {
if (prioritizedURIs == null) {
prioritizedURIs = new PrioritizedList();
}
uris.Add(uri);
int? priority = uri.getPriority();
prioritizedURIs.addObject((priority == null) ? PrioritizedList.PRIORITY_NULL : priority.ToString(), uri);
}
/**
* Get a Servie Path
*/
public SEPPath getPathAt(int n) {
return (n < getNumPaths()) ? (SEPPath)paths[n] : null;
}
/**
* Adds a Uri to the service
*/
public void addPath(string sPath) {
addPath(sPath, null, null);
}
/**
* Adds a Uri to the service with attributes
*/
public void addPath(string sPath, string match, bool? select) {
try {
paths.Add(new SEPPath(sPath, match, select));
} catch (Exception e) {
throw new XRIParseException("BadPath", e);
}
}
/**
* Returns the number of URIs
*/
public int getNumPaths() {
return (paths == null) ? 0 : paths.Count;
}
/**
* Returns the authority id element value
*/
public string getProviderId() {
return (providerID != null) ? providerID.getValue() : null;
}
/**
* Sets the authority id element value
*/
public void setProviderId(string val) {
providerID = new ProviderID(val);
}
/**
* Sets the key info element
*/
public void setKeyInfo(KeyInfo oKeyInfo) {
keyInfo = oKeyInfo;
}
/**
* Returns the key info element
*/
public KeyInfo getKeyInfo() {
return keyInfo;
}
/**
* Stores simple elements in the Service by Tag
*
* Here we are converting the string obj that is being passed into XML
* XmlElement before storing it into otherChildrenVectorMap ArrayList. The reason
* we are doing this is, we need to preserve NameSpaces, and also support a scenario
* where a Child XmlElement under Service XmlElement, can have Sub Elements. With this
* it will preserve all the Text Nodes under the Sub XmlElement.
*
* @param sTag - The tag name. Needs to be the Fully Qualified Name of the XML XmlElement.
*
* For Example "usrns1:info1" or "info1" (If not using NameSpaces)
*
* @param sTagValue - The tag values. Needs to be valid XML string like --
*
* "<usrns1:info1 xmlns:usrns1=\"xri://$user1*schema/localinfo\" >Newton</usrns1:info1>"
* @return -- Boolean - -True if the string could be Successfully Parsed and Stored, Else it will return false
*
*/
public bool setOtherTagValues(string sTag, string sTagValue) {
string xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sTagValue;
bool returnValue = false;
try {
XmlDocument oDOMDoc = new XmlDocument();
oDOMDoc.LoadXml(xmlStr);
XmlElement oElement = oDOMDoc.DocumentElement;
ArrayList oVector = (ArrayList)otherChildrenVectorMap[sTag];
if (oVector == null) {
oVector = new ArrayList();
otherChildrenVectorMap[sTag] = oVector;
}
oVector.Add(oElement.CloneNode(true));
returnValue = true;
} catch (Exception exp) {
soLog.Error(string.Empty, exp);
returnValue = false;
}
return returnValue;
}
/**
* Returns unspecified simple elements in the Service by Tag
* @param sTag - The tag name to get values for
* @return a vector of text values whose element tag names match sTag
*/
public ArrayList getOtherTagValues(string sTag) {
return (ArrayList)otherChildrenVectorMap[sTag];
}
public void setExtension(string extension) {//throws UriFormatException, ParseException {
string xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xrd xmlns=\"xri://$xrd*($v*2.0)\"><Service>" +
extension
+ "</Service></xrd>";
Service tempService = XRD.parseXRD(xmlStr, false).getServiceAt(0);
this.otherChildrenVectorMap = tempService.otherChildrenVectorMap;
}
public string getExtension() {
StringBuilder extension = new StringBuilder();
IEnumerator oCustomTags = otherChildrenVectorMap.Keys.GetEnumerator();
while (oCustomTags.MoveNext()) {
string sTag = (string)oCustomTags.Current;
ArrayList oValues = (ArrayList)otherChildrenVectorMap[sTag];
for (int i = 0; i < oValues.Count; i++) {
XmlNode oChild = (XmlNode)oValues[i];
extension.Append(DOMUtils.ToString((XmlElement)oChild, true, true));
}
}
return extension.ToString();
}
/**
* This method will make DOM using the specified document. If any DOM state
* has been stored with the obj, it will not be used in this method.
* This method generates a reference-free copy of new DOM.
*
* @param oDoc - The document to use for generating DOM
*/
public XmlNode toDOM(XmlDocument oDoc) {
return toDOM(oDoc, false);
}
/**
* This method will make DOM using the specified document. If any DOM state
* has been stored with the obj, it will not be used in this method.
* This method generates a reference-free copy of new DOM.
*
* @param doc - The document to use for generating DOM
* @param wantFiltered - If true, the URIs will be sorted according to priority
*/
public XmlNode toDOM(XmlDocument doc, bool wantFiltered) {
XmlElement elem =
//name space tag is not required any more
doc.createElementNS(Tags.NS_XRD_V2, Tags.TAG_SERVICE);
if (getPriority() != null) {
elem.SetAttribute(Tags.ATTR_PRIORITY, getPriority().ToString());
}
if (providerID != null && providerID.getValue() != null) {
elem.AppendChild(this.providerID.toXML(doc));
}
for (int i = 0; i < getNumTypes(); i++) {
SEPElement type = (SEPElement)getTypeAt(i);
elem.AppendChild(type.toXML(doc, Tags.TAG_TYPE));
}
for (int i = 0; i < getNumPaths(); i++) {
SEPElement path = (SEPElement)getPathAt(i);
elem.AppendChild(path.toXML(doc, Tags.TAG_PATH));
}
for (int i = 0; i < getNumMediaTypes(); i++) {
SEPElement mtype = (SEPElement)getMediaTypeAt(i);
elem.AppendChild(mtype.toXML(doc, Tags.TAG_MEDIATYPE));
}
if (wantFiltered) {
ArrayList uris = getPrioritizedURIs();
for (int i = 0; i < uris.Count; i++) {
SEPUri u = (SEPUri)uris[i];
elem.AppendChild(u.toXML(doc, Tags.TAG_URI));
}
} else {
for (int i = 0; i < getNumURIs(); i++) {
SEPUri uri = getURIAt(i);
elem.AppendChild(uri.toXML(doc, Tags.TAG_URI));
}
}
for (int i = 0; i < getNumRedirects(); i++) {
Redirect redir = getRedirectAt(i);
elem.AppendChild(redir.toXML(doc, Tags.TAG_REDIRECT));
}
for (int i = 0; i < getNumRefs(); i++) {
Ref _ref = getRefAt(i);
elem.AppendChild(_ref.toXML(doc, Tags.TAG_REF));
}
for (int i = 0; i < getNumLocalIDs(); i++) {
XmlElement localID = (XmlElement)getLocalIDAt(i).toXML(doc);
elem.AppendChild(localID);
}
if (getKeyInfo() != null) {
XmlNode oChild = doc.importNode(getKeyInfo().getElement(), true);
elem.AppendChild(oChild);
}
// this does not preserve the order and only works for text elements
// TBD: Add namespace support for these
IEnumerator oCustomTags = otherChildrenVectorMap.Keys.GetEnumerator();
while (oCustomTags.MoveNext()) {
string sTag = (string)oCustomTags.Current;
ArrayList oValues = (ArrayList)otherChildrenVectorMap[sTag];
for (int i = 0; i < oValues.Count; i++) {
// Importing the Child Node into New XmlDocument and also adding it to the
// Service XmlElement as a Child Node
XmlNode oChild = (XmlNode)oValues[i];
XmlNode oChild2 = doc.ImportNode(oChild, true);
elem.AppendChild(oChild2);
}
}
return elem;
}
/**
* Returns formatted obj. Do not use if signature needs to be preserved.
*/
public override string ToString() {
return dump();
}
/**
* Returns obj as a formatted XML string.
* @param sTab - The characters to prepend before each new line
*/
public string dump() {
XmlDocument doc = new XmlDocument();
XmlNode elm = this.toDOM(doc);
doc.AppendChild(elm);
return DOMUtils.ToString(doc);
}
/**
* @return Returns the priority.
*/
public int? getPriority() {
return priority;
}
/**
* @param priority The priority to set.
*/
public void setPriority(int? priority) {
this.priority = priority;
}
/**
* @param priority The priority to set.
*/
public void setPriority(string priority) {
this.priority = priority != null ? (int?)int.Parse(priority) : null;
}
/**
* @return Returns the mediaTypes.
*/
public ArrayList getMediaTypes() {
return mediaTypes;
}
/**
* @return Returns the otherChildrenVectorMap.
*/
public Hashtable getOtherChildrenVectorMap() {
return otherChildrenVectorMap;
}
/**
* @return Returns the paths.
*/
public ArrayList getPaths() {
return paths;
}
/**
* @return Returns the types.
*/
public ArrayList getTypes() {
return types;
}
public void addType(SEPType type) {
if (type == null) return;
types.Add(type);
}
public void addMediaType(SEPMediaType mtype) {
if (mtype == null) return;
mediaTypes.Add(mtype);
}
public void addPath(SEPPath path) {
if (path == null) return;
paths.Add(path);
}
/**
* @param prioritizedURIs The prioritizedURIs to set.
*/
public void setPrioritizedURIs(PrioritizedList prioritizedURIs) {
this.prioritizedURIs = prioritizedURIs;
}
public Object clone() {//throws CloneNotSupportedException{
Service srvc = new Service();
/* for efficiency purpose didn't clone all the elements */
srvc.keyInfo = keyInfo;
srvc.otherChildrenVectorMap = this.otherChildrenVectorMap;
srvc.prioritizedURIs = this.prioritizedURIs;
srvc.priority = this.priority;
srvc.providerID = this.providerID;
srvc.refs = this.refs;
srvc.prioritizedRefs = this.prioritizedRefs;
srvc.redirects = this.redirects;
srvc.prioritizedRedirects = this.prioritizedRedirects;
srvc.localIDs = this.localIDs;
srvc.paths = srvc.mediaTypes = srvc.types = srvc.uris = null;
/* cloned types, mediatypes, path & uris cloned */
ArrayList elements = null;
if (types != null) {
elements = new ArrayList();
for (int i = 0; i < types.Count; i++) {
SEPElement element = (SEPElement)types[i];
elements.Add(element.clone());
}
srvc.types = elements;
}
if (mediaTypes != null) {
elements = new ArrayList();
for (int i = 0; i < mediaTypes.Count; i++) {
SEPElement element = (SEPElement)mediaTypes[i];
elements.Add(element.clone());
}
srvc.mediaTypes = elements;
}
if (paths != null) {
elements = new ArrayList();
for (int i = 0; i < paths.Count; i++) {
SEPElement element = (SEPElement)paths[i];
elements.Add(element.clone());
}
srvc.paths = elements;
}
if (uris != null) {
elements = new ArrayList();
for (int i = 0; i < uris.Count; i++) {
SEPUri element = (SEPUri)uris[i];
elements.Add(element.clone());
}
srvc.uris = elements;
}
return srvc;
}
/**
* @param uris The uris to set.
*/
public void setURIs(ArrayList uris) {
this.uris = uris;
}
/**
* @param mediaTypes The mediaTypes to set.
*/
public void setMediaTypes(ArrayList mediaTypes) {
this.mediaTypes = mediaTypes;
}
/**
* @param paths The paths to set.
*/
public void setPaths(ArrayList paths) {
this.paths = paths;
}
/**
* @param types The types to set.
*/
public void setTypes(ArrayList types) {
this.types = types;
}
/**
* @return Returns a copy of the collection of Refs in the order as it appears in the original XRD
*/
public ArrayList getRefs() {
return (ArrayList)refs.clone();
}
public Ref getRefAt(int n) {
return (Ref)refs[n];
}
public int getNumRefs() {
return refs.Count;
}
public void addRef(Ref _ref) {
if (prioritizedRefs == null)
prioritizedRefs = new PrioritizedList();
int? priority = _ref.getPriority();
refs.Add(_ref);
prioritizedRefs.addObject((priority == null) ? "null" : priority.ToString(), _ref);
}
public ArrayList getPrioritizedRefs() {
return prioritizedRefs.getList();
}
/**
* @return Returns a copy of the collection of Redirects in the order as it appears in the original XRD
*/
public ArrayList getRedirects() {
return (ArrayList)redirects.clone();
}
public Redirect getRedirectAt(int n) {
return (Redirect)redirects[n];
}
public int getNumRedirects() {
return redirects.Count;
}
public void addRedirect(Redirect redirect) {
if (prioritizedRedirects == null)
prioritizedRedirects = new PrioritizedList();
int? priority = redirect.getPriority();
redirects.Add(redirect);
prioritizedRedirects.addObject((priority == null) ? "null" : priority.ToString(), redirect);
}
public ArrayList getPrioritizedRedirects() {
return prioritizedRedirects.getList();
}
public int getNumLocalIDs() {
return localIDs.Count;
}
public LocalID getLocalIDAt(int n) {
return (LocalID)localIDs[n];
}
public void addLocalID(LocalID localId) {
localIDs.Add(localId);
}
public bool Equals(Object o) {
if (!(o is Service)) return (false);
Service other = (Service)o;
if (other == null) return (false);
if (other == this) return (true);
if (this.providerID == null && other.providerID != null) return (false);
if (this.providerID != null && !(this.providerID.Equals(other.providerID))) return (false);
if (this.priority == null && other.priority != null) return (false);
if (this.priority != null && !(this.priority.Equals(other.priority))) return (false);
if (this.types == null && other.types != null) return (false);
if (this.types != null && !(this.types.Equals(other.types))) return (false);
if (this.paths == null && other.paths != null) return (false);
if (this.paths != null && !(this.paths.Equals(other.paths))) return (false);
if (this.mediaTypes == null && other.mediaTypes != null) return (false);
if (this.mediaTypes != null && !(this.mediaTypes.Equals(other.mediaTypes))) return (false);
if (this.uris == null && other.uris != null) return (false);
if (this.uris != null && !(this.uris.Equals(other.uris))) return (false);
if (this.otherChildrenVectorMap == null && other.otherChildrenVectorMap != null) return (false);
if (this.otherChildrenVectorMap != null && !(this.otherChildrenVectorMap.Equals(other.otherChildrenVectorMap))) return (false);
if (this.prioritizedURIs == null && other.prioritizedURIs != null) return (false);
if (this.prioritizedURIs != null && !(this.prioritizedURIs.Equals(other.prioritizedURIs))) return (false);
// TODO: should we compare the KeyInfo too ?
return (true);
}
}
}
| |
/*
* 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 NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using SimpleFSDirectory = Lucene.Net.Store.SimpleFSDirectory;
using _TestHelper = Lucene.Net.Store._TestHelper;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Index
{
/// <summary> </summary>
/// <version> $Id: TestCompoundFile.java 780770 2009-06-01 18:34:10Z uschindler $
/// </version>
[TestFixture]
public class TestCompoundFile:LuceneTestCase
{
/// <summary>Main for running test case by itself. </summary>
[STAThread]
public static void Main(System.String[] args)
{
// TestRunner.run(new TestSuite(typeof(TestCompoundFile))); // {{Aroush-2.9}} how is this done in NUnit?
// TestRunner.run (new TestCompoundFile("testSingleFile"));
// TestRunner.run (new TestCompoundFile("testTwoFiles"));
// TestRunner.run (new TestCompoundFile("testRandomFiles"));
// TestRunner.run (new TestCompoundFile("testClonedStreamsClosing"));
// TestRunner.run (new TestCompoundFile("testReadAfterClose"));
// TestRunner.run (new TestCompoundFile("testRandomAccess"));
// TestRunner.run (new TestCompoundFile("testRandomAccessClones"));
// TestRunner.run (new TestCompoundFile("testFileNotFound"));
// TestRunner.run (new TestCompoundFile("testReadPastEOF"));
// TestRunner.run (new TestCompoundFile("testIWCreate"));
}
private Directory dir;
[SetUp]
public override void SetUp()
{
base.SetUp();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", ""), "testIndex"));
_TestUtil.RmDir(file);
// use a simple FSDir here, to be sure to have SimpleFSInputs
dir = new SimpleFSDirectory(file, null);
}
[TearDown]
public override void TearDown()
{
dir.Close();
base.TearDown();
}
/// <summary>Creates a file of the specified size with random data. </summary>
private void CreateRandomFile(Directory dir, System.String name, int size)
{
IndexOutput os = dir.CreateOutput(name);
for (int i = 0; i < size; i++)
{
byte b = (byte) ((new System.Random().NextDouble()) * 256);
os.WriteByte(b);
}
os.Close();
}
/// <summary>Creates a file of the specified size with sequential data. The first
/// byte is written as the start byte provided. All subsequent bytes are
/// computed as start + offset where offset is the number of the byte.
/// </summary>
private void CreateSequenceFile(Directory dir, System.String name, byte start, int size)
{
IndexOutput os = dir.CreateOutput(name);
for (int i = 0; i < size; i++)
{
os.WriteByte(start);
start++;
}
os.Close();
}
private void AssertSameStreams(System.String msg, IndexInput expected, IndexInput test)
{
Assert.IsNotNull(expected, msg + " null expected");
Assert.IsNotNull(test, msg + " null test");
Assert.AreEqual(expected.Length(), test.Length(), msg + " length");
Assert.AreEqual(expected.GetFilePointer(), test.GetFilePointer(), msg + " position");
byte[] expectedBuffer = new byte[512];
byte[] testBuffer = new byte[expectedBuffer.Length];
long remainder = expected.Length() - expected.GetFilePointer();
while (remainder > 0)
{
int readLen = (int) System.Math.Min(remainder, expectedBuffer.Length);
expected.ReadBytes(expectedBuffer, 0, readLen);
test.ReadBytes(testBuffer, 0, readLen);
AssertEqualArrays(msg + ", remainder " + remainder, expectedBuffer, testBuffer, 0, readLen);
remainder -= readLen;
}
}
private void AssertSameStreams(System.String msg, IndexInput expected, IndexInput actual, long seekTo)
{
if (seekTo >= 0 && seekTo < expected.Length())
{
expected.Seek(seekTo);
actual.Seek(seekTo);
AssertSameStreams(msg + ", seek(mid)", expected, actual);
}
}
private void AssertSameSeekBehavior(System.String msg, IndexInput expected, IndexInput actual)
{
// seek to 0
long point = 0;
AssertSameStreams(msg + ", seek(0)", expected, actual, point);
// seek to middle
point = expected.Length() / 2L;
AssertSameStreams(msg + ", seek(mid)", expected, actual, point);
// seek to end - 2
point = expected.Length() - 2;
AssertSameStreams(msg + ", seek(end-2)", expected, actual, point);
// seek to end - 1
point = expected.Length() - 1;
AssertSameStreams(msg + ", seek(end-1)", expected, actual, point);
// seek to the end
point = expected.Length();
AssertSameStreams(msg + ", seek(end)", expected, actual, point);
// seek past end
point = expected.Length() + 1;
AssertSameStreams(msg + ", seek(end+1)", expected, actual, point);
}
private void AssertEqualArrays(System.String msg, byte[] expected, byte[] test, int start, int len)
{
Assert.IsNotNull(expected, msg + " null expected");
Assert.IsNotNull(test, msg + " null test");
for (int i = start; i < len; i++)
{
Assert.AreEqual(expected[i], test[i], msg + " " + i);
}
}
// ===========================================================
// Tests of the basic CompoundFile functionality
// ===========================================================
/// <summary>This test creates compound file based on a single file.
/// Files of different sizes are tested: 0, 1, 10, 100 bytes.
/// </summary>
[Test]
public virtual void TestSingleFile()
{
int[] data = new int[]{0, 1, 10, 100};
for (int i = 0; i < data.Length; i++)
{
System.String name = "t" + data[i];
CreateSequenceFile(dir, name, (byte) 0, data[i]);
CompoundFileWriter csw = new CompoundFileWriter(dir, name + ".cfs");
csw.AddFile(name);
csw.Close();
CompoundFileReader csr = new CompoundFileReader(dir, name + ".cfs");
IndexInput expected = dir.OpenInput(name);
IndexInput actual = csr.OpenInput(name);
AssertSameStreams(name, expected, actual);
AssertSameSeekBehavior(name, expected, actual);
expected.Close();
actual.Close();
csr.Close();
}
}
/// <summary>This test creates compound file based on two files.
///
/// </summary>
[Test]
public virtual void TestTwoFiles()
{
CreateSequenceFile(dir, "d1", (byte) 0, 15);
CreateSequenceFile(dir, "d2", (byte) 0, 114);
CompoundFileWriter csw = new CompoundFileWriter(dir, "d.csf");
csw.AddFile("d1");
csw.AddFile("d2");
csw.Close();
CompoundFileReader csr = new CompoundFileReader(dir, "d.csf");
IndexInput expected = dir.OpenInput("d1");
IndexInput actual = csr.OpenInput("d1");
AssertSameStreams("d1", expected, actual);
AssertSameSeekBehavior("d1", expected, actual);
expected.Close();
actual.Close();
expected = dir.OpenInput("d2");
actual = csr.OpenInput("d2");
AssertSameStreams("d2", expected, actual);
AssertSameSeekBehavior("d2", expected, actual);
expected.Close();
actual.Close();
csr.Close();
}
/// <summary>This test creates a compound file based on a large number of files of
/// various length. The file content is generated randomly. The sizes range
/// from 0 to 1Mb. Some of the sizes are selected to test the buffering
/// logic in the file reading code. For this the chunk variable is set to
/// the length of the buffer used internally by the compound file logic.
/// </summary>
[Test]
public virtual void TestRandomFiles()
{
// Setup the test segment
System.String segment = "test";
int chunk = 1024; // internal buffer size used by the stream
CreateRandomFile(dir, segment + ".zero", 0);
CreateRandomFile(dir, segment + ".one", 1);
CreateRandomFile(dir, segment + ".ten", 10);
CreateRandomFile(dir, segment + ".hundred", 100);
CreateRandomFile(dir, segment + ".big1", chunk);
CreateRandomFile(dir, segment + ".big2", chunk - 1);
CreateRandomFile(dir, segment + ".big3", chunk + 1);
CreateRandomFile(dir, segment + ".big4", 3 * chunk);
CreateRandomFile(dir, segment + ".big5", 3 * chunk - 1);
CreateRandomFile(dir, segment + ".big6", 3 * chunk + 1);
CreateRandomFile(dir, segment + ".big7", 1000 * chunk);
// Setup extraneous files
CreateRandomFile(dir, "onetwothree", 100);
CreateRandomFile(dir, segment + ".notIn", 50);
CreateRandomFile(dir, segment + ".notIn2", 51);
// Now test
CompoundFileWriter csw = new CompoundFileWriter(dir, "test.cfs");
System.String[] data = new System.String[]{".zero", ".one", ".ten", ".hundred", ".big1", ".big2", ".big3", ".big4", ".big5", ".big6", ".big7"};
for (int i = 0; i < data.Length; i++)
{
csw.AddFile(segment + data[i]);
}
csw.Close();
CompoundFileReader csr = new CompoundFileReader(dir, "test.cfs");
for (int i = 0; i < data.Length; i++)
{
IndexInput check = dir.OpenInput(segment + data[i]);
IndexInput test = csr.OpenInput(segment + data[i]);
AssertSameStreams(data[i], check, test);
AssertSameSeekBehavior(data[i], check, test);
test.Close();
check.Close();
}
csr.Close();
}
/// <summary>Setup a larger compound file with a number of components, each of
/// which is a sequential file (so that we can easily tell that we are
/// reading in the right byte). The methods sets up 20 files - f0 to f19,
/// the size of each file is 1000 bytes.
/// </summary>
private void SetUp_2()
{
CompoundFileWriter cw = new CompoundFileWriter(dir, "f.comp");
for (int i = 0; i < 20; i++)
{
CreateSequenceFile(dir, "f" + i, (byte) 0, 2000);
cw.AddFile("f" + i);
}
cw.Close();
}
[Test]
public virtual void TestReadAfterClose()
{
Demo_FSIndexInputBug(dir, "test");
}
private void Demo_FSIndexInputBug(Directory fsdir, System.String file)
{
// Setup the test file - we need more than 1024 bytes
IndexOutput os = fsdir.CreateOutput(file);
for (int i = 0; i < 2000; i++)
{
os.WriteByte((byte) i);
}
os.Close();
IndexInput in_Renamed = fsdir.OpenInput(file);
// This read primes the buffer in IndexInput
byte b = in_Renamed.ReadByte();
// Close the file
in_Renamed.Close();
// ERROR: this call should fail, but succeeds because the buffer
// is still filled
b = in_Renamed.ReadByte();
// ERROR: this call should fail, but succeeds for some reason as well
in_Renamed.Seek(1099);
try
{
// OK: this call correctly fails. We are now past the 1024 internal
// buffer, so an actual IO is attempted, which fails
b = in_Renamed.ReadByte();
Assert.Fail("expected readByte() to throw exception");
}
catch (System.Exception e)
{
// expected exception
}
}
internal static bool IsCSIndexInput(IndexInput is_Renamed)
{
return is_Renamed is CompoundFileReader.CSIndexInput;
}
internal static bool IsCSIndexInputOpen(IndexInput is_Renamed)
{
if (IsCSIndexInput(is_Renamed))
{
CompoundFileReader.CSIndexInput cis = (CompoundFileReader.CSIndexInput) is_Renamed;
return _TestHelper.IsSimpleFSIndexInputOpen(cis.base_Renamed_ForNUnit);
}
else
{
return false;
}
}
[Test]
public virtual void TestClonedStreamsClosing()
{
SetUp_2();
CompoundFileReader cr = new CompoundFileReader(dir, "f.comp");
// basic clone
IndexInput expected = dir.OpenInput("f11");
// this test only works for FSIndexInput
Assert.IsTrue(_TestHelper.IsSimpleFSIndexInput(expected));
Assert.IsTrue(_TestHelper.IsSimpleFSIndexInputOpen(expected));
IndexInput one = cr.OpenInput("f11");
Assert.IsTrue(IsCSIndexInputOpen(one));
IndexInput two = (IndexInput) one.Clone();
Assert.IsTrue(IsCSIndexInputOpen(two));
AssertSameStreams("basic clone one", expected, one);
expected.Seek(0);
AssertSameStreams("basic clone two", expected, two);
// Now close the first stream
one.Close();
Assert.IsTrue(IsCSIndexInputOpen(one), "Only close when cr is closed");
// The following should really fail since we couldn't expect to
// access a file once close has been called on it (regardless of
// buffering and/or clone magic)
expected.Seek(0);
two.Seek(0);
AssertSameStreams("basic clone two/2", expected, two);
// Now close the compound reader
cr.Close();
Assert.IsFalse(IsCSIndexInputOpen(one), "Now closed one");
Assert.IsFalse(IsCSIndexInputOpen(two), "Now closed two");
// The following may also fail since the compound stream is closed
expected.Seek(0);
two.Seek(0);
//assertSameStreams("basic clone two/3", expected, two);
// Now close the second clone
two.Close();
expected.Seek(0);
two.Seek(0);
//assertSameStreams("basic clone two/4", expected, two);
expected.Close();
}
/// <summary>This test opens two files from a compound stream and verifies that
/// their file positions are independent of each other.
/// </summary>
[Test]
public virtual void TestRandomAccess()
{
SetUp_2();
CompoundFileReader cr = new CompoundFileReader(dir, "f.comp");
// Open two files
IndexInput e1 = dir.OpenInput("f11");
IndexInput e2 = dir.OpenInput("f3");
IndexInput a1 = cr.OpenInput("f11");
IndexInput a2 = dir.OpenInput("f3");
// Seek the first pair
e1.Seek(100);
a1.Seek(100);
Assert.AreEqual(100, e1.GetFilePointer());
Assert.AreEqual(100, a1.GetFilePointer());
byte be1 = e1.ReadByte();
byte ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now seek the second pair
e2.Seek(1027);
a2.Seek(1027);
Assert.AreEqual(1027, e2.GetFilePointer());
Assert.AreEqual(1027, a2.GetFilePointer());
byte be2 = e2.ReadByte();
byte ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Now make sure the first one didn't move
Assert.AreEqual(101, e1.GetFilePointer());
Assert.AreEqual(101, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now more the first one again, past the buffer length
e1.Seek(1910);
a1.Seek(1910);
Assert.AreEqual(1910, e1.GetFilePointer());
Assert.AreEqual(1910, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now make sure the second set didn't move
Assert.AreEqual(1028, e2.GetFilePointer());
Assert.AreEqual(1028, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Move the second set back, again cross the buffer size
e2.Seek(17);
a2.Seek(17);
Assert.AreEqual(17, e2.GetFilePointer());
Assert.AreEqual(17, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Finally, make sure the first set didn't move
// Now make sure the first one didn't move
Assert.AreEqual(1911, e1.GetFilePointer());
Assert.AreEqual(1911, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
e1.Close();
e2.Close();
a1.Close();
a2.Close();
cr.Close();
}
/// <summary>This test opens two files from a compound stream and verifies that
/// their file positions are independent of each other.
/// </summary>
[Test]
public virtual void TestRandomAccessClones()
{
SetUp_2();
CompoundFileReader cr = new CompoundFileReader(dir, "f.comp");
// Open two files
IndexInput e1 = cr.OpenInput("f11");
IndexInput e2 = cr.OpenInput("f3");
IndexInput a1 = (IndexInput) e1.Clone();
IndexInput a2 = (IndexInput) e2.Clone();
// Seek the first pair
e1.Seek(100);
a1.Seek(100);
Assert.AreEqual(100, e1.GetFilePointer());
Assert.AreEqual(100, a1.GetFilePointer());
byte be1 = e1.ReadByte();
byte ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now seek the second pair
e2.Seek(1027);
a2.Seek(1027);
Assert.AreEqual(1027, e2.GetFilePointer());
Assert.AreEqual(1027, a2.GetFilePointer());
byte be2 = e2.ReadByte();
byte ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Now make sure the first one didn't move
Assert.AreEqual(101, e1.GetFilePointer());
Assert.AreEqual(101, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now more the first one again, past the buffer length
e1.Seek(1910);
a1.Seek(1910);
Assert.AreEqual(1910, e1.GetFilePointer());
Assert.AreEqual(1910, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now make sure the second set didn't move
Assert.AreEqual(1028, e2.GetFilePointer());
Assert.AreEqual(1028, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Move the second set back, again cross the buffer size
e2.Seek(17);
a2.Seek(17);
Assert.AreEqual(17, e2.GetFilePointer());
Assert.AreEqual(17, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Finally, make sure the first set didn't move
// Now make sure the first one didn't move
Assert.AreEqual(1911, e1.GetFilePointer());
Assert.AreEqual(1911, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
e1.Close();
e2.Close();
a1.Close();
a2.Close();
cr.Close();
}
[Test]
public virtual void TestFileNotFound()
{
SetUp_2();
CompoundFileReader cr = new CompoundFileReader(dir, "f.comp");
// Open two files
try
{
IndexInput e1 = cr.OpenInput("bogus");
Assert.Fail("File not found");
}
catch (System.IO.IOException e)
{
/* success */
//System.out.println("SUCCESS: File Not Found: " + e);
}
cr.Close();
}
[Test]
public virtual void TestReadPastEOF()
{
SetUp_2();
CompoundFileReader cr = new CompoundFileReader(dir, "f.comp");
IndexInput is_Renamed = cr.OpenInput("f2");
is_Renamed.Seek(is_Renamed.Length() - 10);
byte[] b = new byte[100];
is_Renamed.ReadBytes(b, 0, 10);
try
{
byte test = is_Renamed.ReadByte();
Assert.Fail("Single byte read past end of file");
}
catch (System.IO.IOException e)
{
/* success */
//System.out.println("SUCCESS: single byte read past end of file: " + e);
}
is_Renamed.Seek(is_Renamed.Length() - 10);
try
{
is_Renamed.ReadBytes(b, 0, 50);
Assert.Fail("Block read past end of file");
}
catch (System.IO.IOException e)
{
/* success */
//System.out.println("SUCCESS: block read past end of file: " + e);
}
is_Renamed.Close();
cr.Close();
}
/// <summary>This test that writes larger than the size of the buffer output
/// will correctly increment the file pointer.
/// </summary>
[Test]
public virtual void TestLargeWrites()
{
IndexOutput os = dir.CreateOutput("testBufferStart.txt");
byte[] largeBuf = new byte[2048];
for (int i = 0; i < largeBuf.Length; i++)
{
largeBuf[i] = (byte) ((new System.Random().NextDouble()) * 256);
}
long currentPos = os.GetFilePointer();
os.WriteBytes(largeBuf, largeBuf.Length);
try
{
Assert.AreEqual(currentPos + largeBuf.Length, os.GetFilePointer());
}
finally
{
os.Close();
}
}
}
}
| |
using Drawing = DocumentFormat.OpenXml.Drawing;
using Presentation = DocumentFormat.OpenXml.Presentation;
using Charts = DocumentFormat.OpenXml.Drawing.Charts;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using Data = System.Data;
using System.Linq;
using DocumentFormat.OpenXml;
using Signum.Entities.UserQueries;
using Signum.Entities.Chart;
using Signum.Engine.UserQueries;
using Signum.Entities.UserAssets;
using Signum.Entities.DynamicQuery;
using Signum.Engine.Chart;
using Signum.Entities;
using DocumentFormat.OpenXml.Packaging;
using System.Globalization;
using System.Reflection;
using Signum.Engine.Templating;
using Signum.Entities.Word;
using System.Threading;
using Signum.Engine.Basics;
namespace Signum.Engine.Word
{
public static class TableBinder
{
internal static void ValidateTables(OpenXmlPart part, WordTemplateEntity template, List<TemplateError> errors)
{
var graphicFrames = part.RootElement.Descendants().Where(a => a.LocalName == "graphicFrame").ToList();
foreach (var item in graphicFrames)
{
var nonVisualProps = item.Descendants().SingleOrDefaultEx(a => a.LocalName == "cNvPr");
var title = GetTitle(nonVisualProps);
if (title != null)
{
var prefix = title.TryBefore(":");
if (prefix != null)
{
var provider = WordTemplateLogic.ToDataTableProviders.TryGetC(prefix);
if (provider == null)
errors.Add(new TemplateError(false, "No DataTableProvider '{0}' found (Possibilieties {1})".FormatWith(prefix, WordTemplateLogic.ToDataTableProviders.Keys.CommaOr())));
else
{
var error = provider.Validate(title.After(":"), template);
if (error != null)
errors.Add(new TemplateError(false, error));
}
}
}
}
}
internal static void ProcessTables(OpenXmlPart part, WordTemplateParameters parameters)
{
var graphicFrames = part.RootElement.Descendants().Where(a => a.LocalName == "graphicFrame").ToList();
foreach (var item in graphicFrames)
{
var nonVisualProps = item.Descendants().SingleEx(a => a.LocalName == "cNvPr");
var title = GetTitle(nonVisualProps);
Data.DataTable? dataTable = title != null ? GetDataTable(parameters, title) : null;
if (dataTable != null)
{
var chartRef = item.Descendants<Charts.ChartReference>().SingleOrDefaultEx();
if (chartRef != null)
{
OpenXmlPart chartPart = part.GetPartById(chartRef.Id.Value);
var chart = chartPart.RootElement.Descendants<Charts.Chart>().SingleEx();
ReplaceChart(chart, dataTable);
}
else
{
var table = item.Descendants<Drawing.Table>().SingleOrDefaultEx();
if (table != null)
{
ReplaceTable(table, dataTable);
}
}
}
}
}
static string? GetTitle(OpenXmlElement? nonVisualProps)
{
if (nonVisualProps is Drawing.NonVisualDrawingProperties draw)
return draw.Title?.Value;
if (nonVisualProps is Presentation.NonVisualDrawingProperties pres)
return pres.Title?.Value;
throw new NotImplementedException("Imposible to get the Title from " + nonVisualProps?.GetType().FullName);
}
static void SynchronizeNodes<N, T>(List<N> nodes, List<T> data, Action<N, T, int, bool> apply)
where N : OpenXmlElement
{
for (int i = 0; i < data.Count; i++)
{
if (i < nodes.Count)
{
apply(nodes[i], data[i], i, false);
}
else
{
var last = nodes[nodes.Count - 1];
var clone = (N)last.CloneNode(true);
last.Parent.InsertAfter(clone, last);
apply(clone, data[i], i, true);
}
}
for (int i = data.Count; i < nodes.Count; i++)
{
nodes[i].Remove();
}
}
private static void ReplaceTable(Drawing.Table table, Data.DataTable dataTable)
{
var tableGrid = table.Descendants<Drawing.TableGrid>().SingleEx();
SynchronizeNodes(
tableGrid.Descendants<Drawing.GridColumn>().ToList(),
dataTable.Columns.Cast<Data.DataColumn>().ToList(),
(gc, dc, i, isCloned) => { });
var rows = table.Descendants<Drawing.TableRow>().ToList();
SynchronizeNodes(
rows.FirstEx().Descendants<Drawing.TableCell>().ToList(),
dataTable.Columns.Cast<Data.DataColumn>().ToList(),
(gc, dc, i, isCloned) =>
{
var text = gc.Descendants<Drawing.Text>().SingleOrDefaultEx();
if (text != null)
text.Text = dc.Caption ?? dc.ColumnName;
});
SynchronizeNodes(
rows.Skip(1).ToList(),
dataTable.Rows.Cast<Data.DataRow>().ToList(),
(tr, dr, j, isCloned) =>
{
SynchronizeNodes(
tr.Descendants<Drawing.TableCell>().ToList(),
dataTable.Columns.Cast<Data.DataColumn>().Select(dc => dr[dc]).ToList(),
(gc, val, i, isCloned2) => { gc.Descendants<Drawing.Text>().SingleEx().Text = ToStringLocal(val); });
});
}
public static void ReplaceChart(Charts.Chart chart, Data.DataTable table)
{
var plotArea = chart.Descendants<Charts.PlotArea>().SingleEx();
var series = plotArea.Descendants<OpenXmlCompositeElement>().Where(a => a.LocalName == "ser").ToList();
SynchronizeNodes(series, table.Rows.Cast<Data.DataRow>().ToList(),
(ser, row, i, isCloned) =>
{
if (isCloned)
ser.Descendants<Drawing.SchemeColor>().ToList().ForEach(f => f.Remove());
BindSerie(ser, row, i);
});
}
private static void BindSerie(OpenXmlCompositeElement serie, Data.DataRow dataRow, int index)
{
serie.Descendants<Charts.Formula>().ToList().ForEach(f => f.Remove());
serie.GetFirstChild<Charts.Index>().Val = new UInt32Value((uint)index);
serie.GetFirstChild<Charts.Order>().Val = new UInt32Value((uint)index);
var setTxt = serie.Descendants<Charts.SeriesText>().SingleEx();
setTxt.StringReference.Descendants<Charts.NumericValue>().SingleEx().Text = dataRow[0]?.ToString();
{
var cat = serie.Descendants<Charts.CategoryAxisData>().SingleEx();
cat.Descendants<Charts.PointCount>().SingleEx().Val = new UInt32Value((uint)dataRow.Table.Columns.Count - 1);
var catValues = cat.Descendants<Charts.StringPoint>().ToList();
SynchronizeNodes(catValues, dataRow.Table.Columns.Cast<Data.DataColumn>().Skip(1).ToList(),
(sp, col, i, isCloned) =>
{
sp.Index = new UInt32Value((uint)i);
sp.Descendants<Charts.NumericValue>().Single().Text = col.ColumnName;
});
}
{
var vals = serie.Descendants<Charts.Values>().SingleEx();
vals.Descendants<Charts.PointCount>().SingleEx().Val = new UInt32Value((uint)dataRow.Table.Columns.Count - 1);
var valsValues = vals.Descendants<Charts.NumericPoint>().ToList();
SynchronizeNodes(valsValues, dataRow.ItemArray.Skip(1).ToList(),
(sp, val, i, isCloned) =>
{
sp.Index = new UInt32Value((uint)i);
sp.Descendants<Charts.NumericValue>().Single().Text = ToStringLocal(val);
});
}
}
private static string? ToStringLocal(object val)
{
return val == null ? null :
(val is IFormattable) ? ((IFormattable)val).ToString(null, CultureInfo.InvariantCulture) :
val.ToString();
}
private static Data.DataTable? GetDataTable(WordTemplateParameters parameters, string title)
{
var key = title.TryBefore(":");
if (key == null)
return null;
var provider = WordTemplateLogic.ToDataTableProviders.GetOrThrow(key);
var table = provider.GetDataTable(title.After(":"), new WordTemplateLogic.WordContext(parameters.Template, (Entity?)parameters.Entity, parameters.Model));
return table;
}
}
public class ModelDataTableProvider : IWordDataTableProvider
{
public Data.DataTable GetDataTable(string suffix, WordTemplateLogic.WordContext ctx)
{
MethodInfo mi = GetMethod(ctx.Template, suffix);
object? result;
try
{
result = mi.Invoke(ctx.Model, null);
}
catch (TargetInvocationException e)
{
e.InnerException!.PreserveStackTrace();
throw e.InnerException!;
}
if (!(result is Data.DataTable dt))
throw new InvalidOperationException($"Method '{suffix}' on '{ctx.Model!.GetType().Name}' did not return a DataTable");
return dt;
}
private static MethodInfo GetMethod(WordTemplateEntity template, string method)
{
if (template.Model == null)
throw new InvalidOperationException($"No WordModel found in template '{template}' to call '{method}'");
var type = template.Model.ToType();
var mi = type.GetMethod(method);
if (mi == null)
throw new InvalidOperationException($"No Method with name '{method}' found in type '{type.Name}'");
return mi;
}
public string? Validate(string suffix, WordTemplateEntity template)
{
try
{
GetMethod(template, suffix);
return null;
}
catch (Exception e)
{
return e.Message;
}
}
}
public class UserQueryDataTableProvider : IWordDataTableProvider
{
public Data.DataTable GetDataTable(string suffix, WordTemplateLogic.WordContext context)
{
var userQuery = Database.Query<UserQueryEntity>().SingleOrDefault(a => a.Guid == Guid.Parse(suffix));
using (CurrentEntityConverter.SetCurrentEntity(context.Entity))
{
var request = UserQueryLogic.ToQueryRequest(userQuery);
ResultTable resultTable = QueryLogic.Queries.ExecuteQuery(request);
var dataTable = resultTable.ToDataTable();
return dataTable;
}
}
public string? Validate(string suffix, WordTemplateEntity template)
{
if (!Guid.TryParse(suffix, out Guid guid))
return "Impossible to convert '{0}' in a GUID for a UserQuery".FormatWith(suffix);
if (!Database.Query<UserQueryEntity>().Any(a => a.Guid == guid))
return "No UserQuery with GUID={0} found".FormatWith(guid);
return null;
}
}
public class UserChartDataTableProvider : IWordDataTableProvider
{
public Data.DataTable GetDataTable(string suffix, WordTemplateLogic.WordContext context)
{
return GetDataTable(suffix, context.Entity!);
}
public Data.DataTable GetDataTable(string suffix, Entity entity)
{
var userChart = Database.Query<UserChartEntity>().SingleOrDefault(a => a.Guid == Guid.Parse(suffix));
using (CurrentEntityConverter.SetCurrentEntity(entity))
{
var chartRequest = UserChartLogic.ToChartRequest(userChart);
ResultTable result = ChartLogic.ExecuteChartAsync(chartRequest, CancellationToken.None).Result;
var tokens = chartRequest.Columns.Select(a => a.Token).NotNull().ToList();
//TODO: Too specific. Will be better if controlled by some parameters.
if (chartRequest.HasAggregates() && tokens.Count(a => !(a.Token is AggregateToken)) == 2 && tokens.Count(a => a.Token is AggregateToken) == 1)
{
var firstKeyIndex = tokens.FindIndex(a => !(a.Token is AggregateToken));
var secondKeyIndex = tokens.FindIndex(firstKeyIndex + 1, a => !(a.Token is AggregateToken));
var valueIndex = tokens.FindIndex(a => a.Token is AggregateToken);
return result.ToDataTablePivot(secondKeyIndex, firstKeyIndex, valueIndex);
}
else
return result.ToDataTable();
}
}
public string? Validate(string suffix, WordTemplateEntity template)
{
if (!Guid.TryParse(suffix, out Guid guid))
return "Impossible to convert '{0}' in a GUID for a UserChart".FormatWith(suffix);
if (!Database.Query<UserChartEntity>().Any(a => a.Guid == guid))
return "No UserChart with GUID={0} found".FormatWith(guid);
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class EqualInstruction : Instruction
{
// Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double;
private static Instruction s_referenceLiftedToNull, s_booleanLiftedToNull, s_SByteLiftedToNull, s_int16LiftedToNull, s_charLiftedToNull, s_int32LiftedToNull, s_int64LiftedToNull, s_byteLiftedToNull, s_UInt16LiftedToNull, s_UInt32LiftedToNull, s_UInt64LiftedToNull, s_singleLiftedToNull, s_doubleLiftedToNull;
public override int ConsumedStack { get { return 2; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "Equal"; }
}
private EqualInstruction()
{
}
internal sealed class EqualBoolean : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) == ((Boolean)right)));
}
return +1;
}
}
internal sealed class EqualSByte : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) == ((SByte)right)));
}
return +1;
}
}
internal sealed class EqualInt16 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) == ((Int16)right)));
}
return +1;
}
}
internal sealed class EqualChar : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) == ((Char)right)));
}
return +1;
}
}
internal sealed class EqualInt32 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) == ((Int32)right)));
}
return +1;
}
}
internal sealed class EqualInt64 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) == ((Int64)right)));
}
return +1;
}
}
internal sealed class EqualByte : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) == ((Byte)right)));
}
return +1;
}
}
internal sealed class EqualUInt16 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) == ((UInt16)right)));
}
return +1;
}
}
internal sealed class EqualUInt32 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) == ((UInt32)right)));
}
return +1;
}
}
internal sealed class EqualUInt64 : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) == ((UInt64)right)));
}
return +1;
}
}
internal sealed class EqualSingle : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) == ((Single)right)));
}
return +1;
}
}
internal sealed class EqualDouble : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null));
}
else if (right == null)
{
frame.Push(ScriptingRuntimeHelpers.False);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) == ((Double)right)));
}
return +1;
}
}
internal sealed class EqualReference : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() == frame.Pop()));
return +1;
}
}
internal sealed class EqualBooleanLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) == ((Boolean)right)));
}
return +1;
}
}
internal sealed class EqualSByteLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) == ((SByte)right)));
}
return +1;
}
}
internal sealed class EqualInt16LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) == ((Int16)right)));
}
return +1;
}
}
internal sealed class EqualCharLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) == ((Char)right)));
}
return +1;
}
}
internal sealed class EqualInt32LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) == ((Int32)right)));
}
return +1;
}
}
internal sealed class EqualInt64LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) == ((Int64)right)));
}
return +1;
}
}
internal sealed class EqualByteLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) == ((Byte)right)));
}
return +1;
}
}
internal sealed class EqualUInt16LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) == ((UInt16)right)));
}
return +1;
}
}
internal sealed class EqualUInt32LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) == ((UInt32)right)));
}
return +1;
}
}
internal sealed class EqualUInt64LiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) == ((UInt64)right)));
}
return +1;
}
}
internal sealed class EqualSingleLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) == ((Single)right)));
}
return +1;
}
}
internal sealed class EqualDoubleLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) == ((Double)right)));
}
return +1;
}
}
internal sealed class EqualReferenceLiftedToNull : EqualInstruction
{
public override int Run(InterpretedFrame frame)
{
var right = frame.Pop();
var left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push(ScriptingRuntimeHelpers.BooleanToObject(left == right));
}
return +1;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public static Instruction Create(Type type, bool liftedToNull)
{
// Boxed enums can be unboxed as their underlying types:
if (liftedToNull)
{
switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type)))
{
case TypeCode.Boolean: return s_booleanLiftedToNull ?? (s_booleanLiftedToNull = new EqualBooleanLiftedToNull());
case TypeCode.SByte: return s_SByteLiftedToNull ?? (s_SByteLiftedToNull = new EqualSByteLiftedToNull());
case TypeCode.Byte: return s_byteLiftedToNull ?? (s_byteLiftedToNull = new EqualByteLiftedToNull());
case TypeCode.Char: return s_charLiftedToNull ?? (s_charLiftedToNull = new EqualCharLiftedToNull());
case TypeCode.Int16: return s_int16LiftedToNull ?? (s_int16LiftedToNull = new EqualInt16LiftedToNull());
case TypeCode.Int32: return s_int32LiftedToNull ?? (s_int32LiftedToNull = new EqualInt32LiftedToNull());
case TypeCode.Int64: return s_int64LiftedToNull ?? (s_int64LiftedToNull = new EqualInt64LiftedToNull());
case TypeCode.UInt16: return s_UInt16LiftedToNull ?? (s_UInt16LiftedToNull = new EqualUInt16LiftedToNull());
case TypeCode.UInt32: return s_UInt32LiftedToNull ?? (s_UInt32LiftedToNull = new EqualUInt32LiftedToNull());
case TypeCode.UInt64: return s_UInt64LiftedToNull ?? (s_UInt64LiftedToNull = new EqualUInt64LiftedToNull());
case TypeCode.Single: return s_singleLiftedToNull ?? (s_singleLiftedToNull = new EqualSingleLiftedToNull());
case TypeCode.Double: return s_doubleLiftedToNull ?? (s_doubleLiftedToNull = new EqualDoubleLiftedToNull());
case TypeCode.String:
case TypeCode.Object:
if (!type.GetTypeInfo().IsValueType)
{
return s_referenceLiftedToNull ?? (s_referenceLiftedToNull = new EqualReferenceLiftedToNull());
}
// TODO: Nullable<T>
throw Error.ExpressionNotSupportedForNullableType("Equal", type);
default:
throw Error.ExpressionNotSupportedForType("Equal", type);
}
}
else
{
switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type)))
{
case TypeCode.Boolean: return s_boolean ?? (s_boolean = new EqualBoolean());
case TypeCode.SByte: return s_SByte ?? (s_SByte = new EqualSByte());
case TypeCode.Byte: return s_byte ?? (s_byte = new EqualByte());
case TypeCode.Char: return s_char ?? (s_char = new EqualChar());
case TypeCode.Int16: return s_int16 ?? (s_int16 = new EqualInt16());
case TypeCode.Int32: return s_int32 ?? (s_int32 = new EqualInt32());
case TypeCode.Int64: return s_int64 ?? (s_int64 = new EqualInt64());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new EqualUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new EqualUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new EqualUInt64());
case TypeCode.Single: return s_single ?? (s_single = new EqualSingle());
case TypeCode.Double: return s_double ?? (s_double = new EqualDouble());
case TypeCode.String:
case TypeCode.Object:
if (!type.GetTypeInfo().IsValueType)
{
return s_reference ?? (s_reference = new EqualReference());
}
// TODO: Nullable<T>
throw Error.ExpressionNotSupportedForNullableType("Equal", type);
default:
throw Error.ExpressionNotSupportedForType("Equal", type);
}
}
}
public override string ToString()
{
return "Equal()";
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GenericLocalizeTagHelperTests.cs">
// Copyright (c) Kim Nordmo. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <author>Kim Nordmo</author>
//-----------------------------------------------------------------------
#pragma warning disable CA1707 // Identifiers should not contain underscores
namespace Localization.AspNetCore.TagHelpers.Tests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
public class GenericLocalizeTagHelperTests
{
public static IEnumerable<object[]> LocalizeNewLinesTestData
{
get
{
var text = "This is\r\nThe\nUnormalized Text\r\n";
yield return new object[] { text, text.Trim(), NewLineHandling.None, true, false };
var expectedText = text.Replace("\r\n", "\n", StringComparison.OrdinalIgnoreCase).Replace("\n", Environment.NewLine, StringComparison.OrdinalIgnoreCase);
yield return new object[] { text, expectedText.Trim(), NewLineHandling.Auto, true, false };
expectedText = text.Replace("\n", "\r\n", StringComparison.OrdinalIgnoreCase).Replace("\r\r", "\r", StringComparison.OrdinalIgnoreCase);
yield return new object[] { text, expectedText.Trim(), NewLineHandling.Windows, true, false };
expectedText = text.Replace("\r", "", StringComparison.OrdinalIgnoreCase);
yield return new object[] { text, expectedText.Trim(), NewLineHandling.Unix, true, false };
text = " This\r\n Will\r\nAlways\r\n Trimmed \r\nDown ";
expectedText = "This\r\nWill\r\nAlways\r\nTrimmed\r\nDown";
yield return new object[] { text, expectedText.Trim(), NewLineHandling.Windows, true, false };
yield return new object[]{"This will transform\nNew Lines \r\n But not trim\n whitespace ",
"This will transform\nNew Lines \n But not trim\n whitespace ", NewLineHandling.Unix, false, false };
yield return new object[]{"\r\n \r\n This should trim everything before and after \r\n \n \r\n",
"This should trim everything before and after", NewLineHandling.Auto, false, true };
}
}
public static IEnumerable<object[]> LocalizeTestData
{
get
{
var encoder = HtmlEncoder.Default;
yield return new object[] { "p", "This will be localized", "This is the localized text", true, false, "<p>This is the localized text</p>" };
var text = "This the the <small>localized</small> text with <strong>html</strong>";
yield return new object[] { "p", "This wi be localized", text, true, false, $"<p>{encoder.Encode(text)}</p>" };
yield return new object[] { "span", "This", text, true, true, $"<span>{text}</span>" };
yield return new object[] { "div", "Localize", $" {text} ", false, false, $"<div> {encoder.Encode(text)} </div>" };
yield return new object[] { "div", "Localize", $" {text} ", false, true, $"<div> {text} </div>" };
yield return new object[] { "div", " Localize ", $"{text}", true, false, $"<div>{encoder.Encode(text)}</div>" };
yield return new object[] { "div", " Localize ", $"{text}", true, true, $"<div>{text}</div>" };
}
}
public static IEnumerable<object[]> LocalizeTestDataWithParameters
{
get
{
var encoder = HtmlEncoder.Default;
yield return new object[] { "p", "This will be {0}", "This is the {0} text", true, false, new[] { "Localized" }, "<p>This is the Localized text</p>" };
var text = "This the the <small>{0}</small> {1} with <strong>html</strong>";
var parameters = new[] { "Localized", "text" };
yield return new object[] { "p", "This wi be localized", text, true, false, parameters, $"<p>{encoder.Encode(string.Format(CultureInfo.InvariantCulture, text, parameters))}</p>" };
yield return new object[] { "span", "This", text, true, true, parameters, $"<span>{string.Format(CultureInfo.InvariantCulture, text, parameters)}</span>" };
yield return new object[] { "div", "Localize", $" {text} ", false, false, parameters, $"<div> {encoder.Encode(string.Format(CultureInfo.InvariantCulture, text, parameters))} </div>" };
yield return new object[] { "div", "Localize", $" {text} ", false, true, parameters, $"<div> {string.Format(CultureInfo.InvariantCulture, text, parameters)} </div>" };
yield return new object[] { "div", " Localize ", $"{text}", true, false, parameters, $"<div>{encoder.Encode(string.Format(CultureInfo.InvariantCulture, text, parameters))}</div>" };
yield return new object[] { "div", " Localize ", $"{text}", true, true, parameters, $"<div>{string.Format(CultureInfo.InvariantCulture, text, parameters)}</div>" };
}
}
[Fact]
public void Constructor_ThrowsArgumentNullExceptionOnHostingEnvironmentIsNull()
{
Assert.Throws<ArgumentNullException>(() => new GenericLocalizeTagHelper(TestHelper.CreateFactoryMock(false).Object, null, null));
}
[Fact]
public void Constructor_ThrowsArgumentNullExceptionOnHtmlLocalizerFactoryIsNull()
{
var hostMock =
#if NETCOREAPP3_0
new Mock<IWebHostEnvironment>();
#else
new Mock<IHostingEnvironment>();
#endif
Assert.Throws<ArgumentNullException>(() => new GenericLocalizeTagHelper(null, hostMock.Object, null));
}
[Fact]
public void Init_AddsNewParameterListToExistingStack()
{
var tagHelper = CreateTagHelper();
var tagContext = TestHelper.CreateTagContext();
tagHelper.Init(tagContext);
tagHelper.Init(tagContext);
Assert.Contains(tagContext.Items, (contextItems) => (Type)contextItems.Key == typeof(GenericLocalizeTagHelper));
var item = tagContext.Items[typeof(GenericLocalizeTagHelper)];
Assert.NotNull(item);
Assert.IsType<Stack<List<object>>>(item);
Assert.Equal(2, ((Stack<List<object>>)item).Count);
}
[Fact]
public void Init_CreatesANewParameterStack()
{
var tagHelper = CreateTagHelper();
var tagContext = TestHelper.CreateTagContext();
tagHelper.Init(tagContext);
Assert.Contains(tagContext.Items, (contextItem) => (Type)contextItem.Key == typeof(GenericLocalizeTagHelper));
var item = tagContext.Items[typeof(GenericLocalizeTagHelper)];
Assert.NotNull(item);
var stackList = Assert.IsType<Stack<List<object>>>(item);
Assert.Single(stackList);
}
[Theory]
[InlineData("TestApplication", "Views/Home/Index.cshtml", "Views/Home/Index.cshtml", "TestApplication.Views.Home.Index")]
[InlineData("TestApplication", "/Views/Home/Index.cshtml", "/Views/Home/Index.cshtml", "TestApplication.Views.Home.Index")]
[InlineData("TestApplication", "\\Views\\Home\\Index.cshtml", "\\Views\\Home\\Index.cshtml", "TestApplication.Views.Home.Index")]
[InlineData("TestApplication.Web", "Views/Home/Index.cshtml", "Views/Home/Index.cshtml", "TestApplication.Web.Views.Home.Index")]
[InlineData("TestApplication", "Views/Home/Index.cshtml", "Views/Shared/_Layout.cshtml", "TestApplication.Views.Shared._Layout")]
[InlineData("TestApplication", "Views/Home/Index.cshtml", "Views/Shared/_MyPartial.cshtml", "TestApplication.Views.Shared._MyPartial")]
[InlineData("TestApplication", "Views/Home/Index.cshtml", "Views/Home/_HomePartial.cshtml", "TestApplication.Views.Home._HomePartial")]
[InlineData("TestApplication", "Views/Home/Index.cshtml", null, "TestApplication.Views.Home.Index")]
[InlineData("TestApplication", "Views/Home/Index.txt", null, "TestApplication.Views.Home.Index")]
[InlineData("TestApplication", "Views/Home/Index.cshtml", "", "TestApplication.Views.Home.Index")]
[InlineData("TestApplication", "Views/Home/Index.txt", "", "TestApplication.Views.Home.Index")]
public void Init_CreatesHtmlLocalizerFromViewContext(string appName, string viewPath, string executionPath, string expectedBaseName)
{
var hostingEnvironment =
#if NETCOREAPP3_0
new Mock<IWebHostEnvironment>();
#else
new Mock<IHostingEnvironment>();
#endif
hostingEnvironment.Setup(a => a.ApplicationName).Returns(appName);
var factoryMock = TestHelper.CreateFactoryMock(true);
var view = new Mock<IView>();
view.Setup(v => v.Path).Returns(viewPath);
var viewContext = new ViewContext
{
ExecutingFilePath = executionPath,
View = view.Object
};
var tagHelper = new GenericLocalizeTagHelper(factoryMock.Object, hostingEnvironment.Object, null)
{
ViewContext = viewContext
};
var context = TestHelper.CreateTagContext();
tagHelper.Init(context);
factoryMock.Verify(x => x.Create(expectedBaseName, appName), Times.Once());
}
[Theory]
[InlineData("MyCustomName")]
[InlineData("MyBase.Name")]
public void Init_CreatesHtmlLocalizerWithUserSpecifiedName(string name)
{
var factory = TestHelper.CreateFactoryMock(true);
var helper = CreateTagHelper(factory.Object);
var context = TestHelper.CreateTagContext();
helper.Name = name;
helper.Init(context);
factory.Verify(x => x.Create(name, TestHelper.ApplicationName), Times.Once());
}
[Theory]
[InlineData(typeof(GenericLocalizeTagHelper))]
[InlineData(typeof(TestHelper))]
[InlineData(typeof(ParamTagHelperTests))]
public void Init_CreatesHtmlLocalizerWithUserSpecifiedType(Type type)
{
var factory = TestHelper.CreateFactoryMock(true);
var helper = CreateTagHelper(factory.Object);
var context = TestHelper.CreateTagContext();
helper.Type = type;
helper.Init(context);
factory.Verify(x => x.Create(type), Times.Once());
}
[Fact]
public void Init_NeverCallsHtmlLocalizerFactoryIfHtmlLocalizerIsNotNull()
{
var factoryMock = new Mock<IHtmlLocalizerFactory>();
var tagHelper = TestHelper.CreateTagHelper<GenericLocalizeTagHelper>(factoryMock.Object);
tagHelper.Localizer = new Mock<IHtmlLocalizer>().Object;
var tagContext = TestHelper.CreateTagContext();
tagHelper.Init(tagContext);
factoryMock.Verify(f => f.Create(It.IsAny<Type>()), Times.Never);
factoryMock.Verify(f => f.Create(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Fact]
public void Init_CachesIHtmlLocalizerInstances()
{
var localizerMock = new Mock<IHtmlLocalizer>();
var factoryMock = new Mock<IHtmlLocalizerFactory>();
factoryMock.Setup(m => m.Create(It.IsAny<string>(), It.IsAny<string>())).Returns(localizerMock.Object);
var tagHelper = TestHelper.CreateTagHelper<GenericLocalizeTagHelper>(factoryMock.Object);
var tagContext = TestHelper.CreateTagContext();
tagHelper.Init(tagContext);
tagHelper.Init(tagContext);
factoryMock.Verify(f => f.Create(It.IsAny<Type>()), Times.Never);
factoryMock.Verify(f => f.Create(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Fact]
public void Init_CreatesNewIHtmlLocalizerForEachView()
{
var localizerMock = new Mock<IHtmlLocalizer>();
var factoryMock = new Mock<IHtmlLocalizerFactory>();
factoryMock.Setup(m => m.Create(It.IsAny<string>(), It.IsAny<string>())).Returns(localizerMock.Object);
var tagHelper = TestHelper.CreateTagHelper<GenericLocalizeTagHelper>(factoryMock.Object);
var tagContext = TestHelper.CreateTagContext();
tagHelper.ViewContext.ExecutingFilePath = "View1";
tagHelper.Init(tagContext);
tagHelper.Init(tagContext);
tagHelper.Localizer = null;
tagHelper.ViewContext.ExecutingFilePath = "View2";
tagHelper.Init(tagContext);
tagHelper.Init(tagContext);
factoryMock.Verify(f => f.Create(It.IsAny<Type>()), Times.Never);
factoryMock.Verify(f => f.Create(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(2));
}
[Fact]
public void Init_SkipsCreatingParameterStackIfInheritedClassSetsSupportsParametersToFalse()
{
var tagHelper = TestHelper.CreateTagHelper<NoParametersSupported>(null);
var tagContext = TestHelper.CreateTagContext();
tagHelper.Init(tagContext);
Assert.DoesNotContain(tagContext.Items, (item) => (Type)item.Key == typeof(GenericLocalizeTagHelper));
}
[Theory]
[MemberData(nameof(LocalizeNewLinesTestData))]
public async Task ProcessAsync_CanHandleNewLineNormalization(string text, string expectedText, NewLineHandling handling, bool trimEachLine, bool trimWhitespace)
{
var localizer = TestHelper.CreateLocalizerMock(false);
SetupLocalizer(localizer, expectedText, expectedText, false);
var factory = TestHelper.CreateFactoryMock(localizer.Object);
var helper = CreateTagHelper(factory.Object);
helper.TrimWhitespace = trimWhitespace;
helper.IsHtml = false;
helper.NewLineHandling = handling;
helper.TrimEachLine = trimEachLine;
await TestHelper.GenerateHtmlAsync(helper, "span", text).ConfigureAwait(false);
localizer.Verify(x => x.GetString(expectedText), Times.Once);
}
[Theory]
[MemberData(nameof(LocalizeTestData))]
public async Task ProcessAsync_CanLocalizeText(string tagName, string text, string expectedText, bool trim, bool isHtml, string expected)
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
var textToLocalize = trim ? text.Trim() : text;
var localizer = TestHelper.CreateLocalizerMock(false);
SetupLocalizer(localizer, textToLocalize, expectedText, isHtml);
var factory = TestHelper.CreateFactoryMock(localizer.Object);
var helper = CreateTagHelper(factory.Object);
helper.TrimWhitespace = trim;
helper.IsHtml = isHtml;
var output = await TestHelper.GenerateHtmlAsync(helper, tagName, text).ConfigureAwait(false);
if (isHtml)
{
localizer.Verify(x => x[textToLocalize], Times.Once);
}
else
{
localizer.Verify(x => x.GetString(textToLocalize), Times.Once);
}
Assert.Equal(expected, output);
}
[Theory]
[MemberData(nameof(LocalizeTestDataWithParameters))]
public async Task ProcessAsync_CanLocalizeTextWithParameters(string tagName, string text, string expectedText, bool trim, bool isHtml, object[] parameters, string expected)
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
var textToLocalize = trim ? text.Trim() : text;
var localizer = TestHelper.CreateLocalizerMock(false);
SetupLocalizerWithParameters(localizer, textToLocalize, expectedText, isHtml);
var factory = TestHelper.CreateFactoryMock(localizer.Object);
var helper = CreateTagHelper(factory.Object);
helper.TrimWhitespace = trim;
helper.IsHtml = isHtml;
var context = TestHelper.CreateTagContext();
helper.Init(context);
var stack = (Stack<List<object>>)context.Items[typeof(GenericLocalizeTagHelper)];
var list = stack.Peek();
foreach (var parameter in parameters)
{
list.Add(parameter);
}
var output = TestHelper.CreateTagOutput(tagName, text);
var htmlOutput = await TestHelper.GenerateHtmlAsync(helper, context, output).ConfigureAwait(false);
if (isHtml)
{
localizer.Verify(x => x[textToLocalize, parameters], Times.Once);
}
else
{
localizer.Verify(x => x.GetString(textToLocalize, parameters), Times.Once);
}
Assert.Equal(expected, htmlOutput);
}
[Fact]
public async Task ProcessAsync_DoesNotHtmlEncodeWhenGloballyDisabled()
{
const string expected = "<a href=\"https://google.com\">Hello</a>";
var localizer = TestHelper.CreateLocalizerMock(false);
SetupLocalizer(localizer, expected, expected, true);
var factory = TestHelper.CreateFactoryMock(localizer.Object);
var hostingEnvMock =
#if NETCOREAPP3_0
new Mock<IWebHostEnvironment>();
#else
new Mock<IHostingEnvironment>();
#endif
hostingEnvMock.SetupGet(x => x.ApplicationName).Returns(TestHelper.ApplicationName);
var options = Options.Create(new LocalizeTagHelperOptions { HtmlEncodeByDefault = false, NewLineHandling = NewLineHandling.None, TrimWhitespace = false });
var helper = new GenericLocalizeTagHelper(factory.Object, hostingEnvMock.Object, options)
{
ViewContext = TestHelper.CreateViewContext()
};
var result = await TestHelper.GenerateHtmlAsync(helper, "p", expected).ConfigureAwait(false);
localizer.Verify(x => x[expected], Times.Once());
Assert.Equal("<p>" + expected + "</p>", result);
}
protected static GenericLocalizeTagHelper CreateTagHelper()
{
return CreateTagHelper(null);
}
protected static GenericLocalizeTagHelper CreateTagHelper(IHtmlLocalizerFactory factory)
{
return TestHelper.CreateTagHelper<GenericLocalizeTagHelper>(factory);
}
private void SetupLocalizer(Mock<IHtmlLocalizer> localizer, string textToLocalize, string expectedText, bool isHtml)
{
if (isHtml)
{
localizer.Setup(x => x[textToLocalize]).Returns<string>(s => new LocalizedHtmlString(s, expectedText, s == expectedText));
}
else
{
localizer.Setup(x => x.GetString(textToLocalize)).Returns<string>(s => new LocalizedString(s, expectedText, s == expectedText));
}
}
private void SetupLocalizerWithParameters(Mock<IHtmlLocalizer> localizer, string textToLocalize, string expectedText, bool isHtml)
{
if (isHtml)
{
localizer.Setup(x => x[textToLocalize, It.IsAny<object[]>()]).Returns<string, object[]>((s, o) => new LocalizedHtmlString(s, string.Format(CultureInfo.InvariantCulture, expectedText, o), s == expectedText));
}
else
{
localizer.Setup(x => x.GetString(textToLocalize, It.IsAny<object[]>())).Returns<string, object[]>((s, o) => new LocalizedString(s, string.Format(CultureInfo.InvariantCulture, expectedText, o), s == expectedText));
}
}
#pragma warning disable CA1812 // Avoid uninstantiated internal classes
private class NoParametersSupported : GenericLocalizeTagHelper
#pragma warning restore CA1812 // Avoid uninstantiated internal classes
{
#if NETCOREAPP3_0
public NoParametersSupported(IHtmlLocalizerFactory localizerFactory, IWebHostEnvironment hostingEnvironment, IOptions<LocalizeTagHelperOptions> options)
#else
public NoParametersSupported(IHtmlLocalizerFactory localizerFactory, IHostingEnvironment hostingEnvironment, IOptions<LocalizeTagHelperOptions> options)
#endif
: base(localizerFactory, hostingEnvironment, options)
{
}
protected override bool SupportsParameters => false;
}
}
}
| |
using Bridge.Html5;
using Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
namespace Bridge.ClientTest.Collections.Native
{
[Category(Constants.MODULE_TYPEDARRAYS)]
[TestFixture(TestNameFormat = "DataViewTests - {0}")]
public class DataViewTests
{
private DataView GetView(byte[] content)
{
var result = new Uint8Array(content.Length);
for (int i = 0; i < content.Length; i++)
result[i] = content[i];
return new DataView(result.Buffer);
}
[Test]
public void TypePropertiesAreCorrect()
{
if (!Utilities.BrowserHelper.IsPhantomJs())
{
Assert.AreEqual("DataView", typeof(DataView).FullName, "FullName");
}
else
{
Assert.AreEqual("DataViewConstructor", typeof(DataView).FullName, "FullName");
}
var interfaces = typeof(DataView).GetInterfaces();
Assert.AreEqual(0, interfaces.Length, "Interface count should be empty");
}
[Test]
public void ArrayBufferOnlyConstructorWorks()
{
var b = new Uint8Array(new byte[] { 2, 3, 5 }).Buffer;
var view = new DataView(b);
Assert.True((object)view is DataView, "Should be DataView");
Assert.AreEqual(3, view.GetInt8(1), "StartIndex should be correct");
}
[Test]
public void ArrayBufferAndByteOffsetConstructorWorks()
{
var b = new Uint8Array(new byte[] { 2, 3, 5 }).Buffer;
var view = new DataView(b, 1);
Assert.True((object)view is DataView, "Should be DataView");
Assert.AreEqual(5, view.GetInt8(1), "StartIndex should be correct");
}
[Test]
public void ArrayBufferAndByteOffsetAndByteLengthConstructorWorks()
{
var b = new Uint8Array(new byte[] { 2, 3, 5, 7, 2, 0 }).Buffer;
var view = new DataView(b, 1, 3);
Assert.True((object)view is DataView, "Should be DataView");
Assert.AreEqual(5, view.GetInt8(1), "StartIndex should be correct");
Assert.Throws(() => view.GetInt8(4), "Length should be correct");
}
[Test]
public void GetInt8Works()
{
var b = GetView(new byte[] { 3, 0xfd });
Assert.AreEqual(3, b.GetInt8(0), "0");
Assert.AreEqual(-3, b.GetInt8(1), "1");
}
[Test]
public void GetUint8Works()
{
var b = GetView(new byte[] { 3, 0xfd });
Assert.AreEqual(3, b.GetUint8(0), "0");
Assert.AreEqual(0xfd, b.GetUint8(1), "1");
}
[Test]
public void GetInt16Works()
{
var b = GetView(new byte[] { 3, 0xfd, 3, 4, 0xfd, 3 });
Assert.AreEqual(-765, b.GetInt16(0, true), "0, true");
Assert.AreEqual(1027, b.GetInt16(2, true), "2, true");
Assert.AreEqual(1021, b.GetInt16(4, true), "4, true");
Assert.AreEqual(1021, b.GetInt16(0, false), "0, false");
Assert.AreEqual(772, b.GetInt16(2, false), "2, false");
Assert.AreEqual(-765, b.GetInt16(4, false), "4, false");
Assert.AreEqual(1021, b.GetInt16(0), "0, default");
Assert.AreEqual(772, b.GetInt16(2), "2, default");
Assert.AreEqual(-765, b.GetInt16(4), "4, default");
}
[Test]
public void GetUint16Works()
{
var b = GetView(new byte[] { 3, 0xfd, 3, 4, 0xfd, 3 });
Assert.AreEqual(64771, b.GetUint16(0, true), "0, true");
Assert.AreEqual(1027, b.GetUint16(2, true), "2, true");
Assert.AreEqual(1021, b.GetUint16(4, true), "4, true");
Assert.AreEqual(1021, b.GetUint16(0, false), "0, false");
Assert.AreEqual(772, b.GetUint16(2, false), "2, false");
Assert.AreEqual(64771, b.GetUint16(4, false), "4, false");
Assert.AreEqual(1021, b.GetUint16(0), "0, default");
Assert.AreEqual(772, b.GetUint16(2), "2, default");
Assert.AreEqual(64771, b.GetUint16(4), "4, default");
}
[Test]
public void GetInt32Works()
{
var b = GetView(new byte[] { 3, 0, 0, 0xfd, 3, 0, 0, 4, 0xfd, 0, 0, 3 });
Assert.AreEqual(-50331645, b.GetInt32(0, true), "0, true");
Assert.AreEqual(67108867, b.GetInt32(4, true), "4, true");
Assert.AreEqual(50331901, b.GetInt32(8, true), "8, true");
Assert.AreEqual(50331901, b.GetInt32(0, false), "0, false");
Assert.AreEqual(50331652, b.GetInt32(4, false), "4, false");
Assert.AreEqual(-50331645, b.GetInt32(8, false), "8, false");
Assert.AreEqual(50331901, b.GetInt32(0), "0, default");
Assert.AreEqual(50331652, b.GetInt32(4), "4, default");
Assert.AreEqual(-50331645, b.GetInt32(8), "8, default");
}
[Test]
public void GetUint32Works()
{
var b = GetView(new byte[] { 3, 0, 0, 0xfd, 3, 0, 0, 4, 0xfd, 0, 0, 3 });
Assert.AreEqual(4244635651, b.GetUint32(0, true), "0, true");
Assert.AreEqual(67108867, b.GetUint32(4, true), "4, true");
Assert.AreEqual(50331901, b.GetUint32(8, true), "8, true");
Assert.AreEqual(50331901, b.GetUint32(0, false), "0, false");
Assert.AreEqual(50331652, b.GetUint32(4, false), "4, false");
Assert.AreEqual(4244635651, b.GetUint32(8, false), "8, false");
Assert.AreEqual(50331901, b.GetUint32(0), "0, default");
Assert.AreEqual(50331652, b.GetUint32(4), "4, default");
Assert.AreEqual(4244635651, b.GetUint32(8), "8, default");
}
[Test]
public void GetFloat32Works()
{
var b = GetView(new byte[] { 255, 255, 255, 255, 0, 0, 192, 63, 63, 192, 0, 0 });
Assert.AreEqual(1.5, b.GetFloat32(4, true), "4, true");
Assert.AreEqual(1.5, b.GetFloat32(8, false), "8, false");
Assert.AreEqual(1.5, b.GetFloat32(8), "8, default");
}
[Test]
public void GetFloat64Works()
{
var b = GetView(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 248, 63, 63, 248, 0, 0, 0, 0, 0, 0 });
Assert.AreEqual(1.5, b.GetFloat64(8, true), "8, true");
Assert.AreEqual(1.5, b.GetFloat64(16, false), "16, false");
Assert.AreEqual(1.5, b.GetFloat64(16), "16, default");
}
private void SetTest(Action<DataView> populator, byte[] expected)
{
var b = new ArrayBuffer(expected.Length);
var v = new DataView(b);
populator(v);
var actual = new List<byte>();
var ub = new Uint8Array(b);
for (int i = 0; i < ub.Length; i++)
{
actual.Add(ub[i]);
}
Assert.AreEqual(expected, actual.ToArray());
}
[Test]
public void SetInt8Works()
{
SetTest(v =>
{
v.SetInt8(1, 14);
v.SetInt8(2, -14);
}, new byte[] { 0, 14, 242 });
}
[Test]
public void SetUint8Works()
{
SetTest(v =>
{
v.SetUint8(1, 14);
v.SetUint8(2, 242);
}, new byte[] { 0, 14, 242 });
}
[Test]
public void SetInt16Works()
{
SetTest(v =>
{
v.SetInt16(2, -4, false);
v.SetInt16(4, -4, true);
v.SetInt16(6, -4);
v.SetInt16(8, 14, false);
v.SetInt16(10, 14, true);
v.SetInt16(12, 14);
}, new byte[] { 0, 0, 255, 252, 252, 255, 255, 252, 0, 14, 14, 0, 0, 14, 0 });
}
[Test]
public void SetUint16Works()
{
SetTest(v =>
{
v.SetUint16(2, 35875, false);
v.SetUint16(4, 35875, true);
v.SetUint16(6, 35875);
v.SetUint16(8, 14, false);
v.SetUint16(10, 14, true);
v.SetUint16(12, 14);
}, new byte[] { 0, 0, 140, 35, 35, 140, 140, 35, 0, 14, 14, 0, 0, 14, 0 });
}
[Test]
public void SetInt32Works()
{
SetTest(v =>
{
v.SetInt32(4, -4, false);
v.SetInt32(8, -4, true);
v.SetInt32(12, -4);
v.SetInt32(16, 14, false);
v.SetInt32(20, 14, true);
v.SetInt32(24, 14);
}, new byte[] { 0, 0, 0, 0, 255, 255, 255, 252, 252, 255, 255, 255, 255, 255, 255, 252, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 14, 0, 0 });
}
[Test]
public void SetUint32Works()
{
SetTest(v =>
{
v.SetUint32(4, 3487568527, false);
v.SetUint32(8, 3487568527, true);
v.SetUint32(12, 3487568527);
v.SetUint32(16, 14, false);
v.SetUint32(20, 14, true);
v.SetUint32(24, 14);
}, new byte[] { 0, 0, 0, 0, 207, 224, 18, 143, 143, 18, 224, 207, 207, 224, 18, 143, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 14, 0, 0 });
}
[Test]
public void SetFloat32Works()
{
SetTest(v =>
{
v.SetFloat32(4, 1.5f, false);
v.SetFloat32(8, 1.5f, true);
v.SetFloat32(12, 1.5f);
}, new byte[] { 0, 0, 0, 0, 63, 192, 0, 0, 0, 0, 192, 63, 63, 192, 0, 0 });
}
[Test]
public void SetFloat64Works()
{
SetTest(v =>
{
v.SetFloat64(8, 1.5, false);
v.SetFloat64(16, 1.5, true);
v.SetFloat64(24, 1.5);
}, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 63, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 63, 63, 248, 0, 0, 0, 0, 0, 0 });
}
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Quartz.Impl.Matchers;
using Quartz.Logging;
using Quartz.Spi;
namespace Quartz.Plugin.History
{
/// <summary>
/// Logs a history of all job executions (and execution vetoes) via common
/// logging.
/// </summary>
/// <remarks>
/// <para>
/// The logged message is customizable by setting one of the following message
/// properties to a string that conforms to the syntax of <see cref="string.Format(string,object)"/>.
/// </para>
/// <para>
/// JobToBeFiredMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Trigger's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}"</i>
/// </para>
/// <para>
/// JobSuccessMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Trigger's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// <tr>
/// <td>8</td>
/// <td>Object</td>
/// <td>The string value (toString() having been called) of the result (if any)
/// that the Job set on the JobExecutionContext, with on it. "NULL" if no
/// result was set.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} execution complete at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}"</i>
/// </para>
/// <para>
/// JobFailedMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Trigger's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// <tr>
/// <td>8</td>
/// <td>String</td>
/// <td>The message from the thrown JobExecution Exception.
/// </td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} execution failed at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}"</i>
/// </para>
/// <para>
/// JobWasVetoedMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Job's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Job's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The current time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>String</td>
/// <td>The Trigger's name.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>String</td>
/// <td>The Trigger's group.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// </table>
/// The default message text is <i>"Job {1}.{0} was vetoed. It was to be fired
/// (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}"</i>
/// </para>
/// </remarks>
/// <author>Marko Lahma (.NET)</author>
public class LoggingJobHistoryPlugin : ISchedulerPlugin, IJobListener
{
/// <summary>
/// Logger instance to use. Defaults to common logging.
/// </summary>
private ILog Log { get; set; } = LogProvider.GetLogger(typeof(LoggingJobHistoryPlugin));
/// <summary>
/// Get or sets the message that is logged when a Job successfully completes its
/// execution.
/// </summary>
public virtual string JobSuccessMessage { get; set; } = "Job {1}.{0} execution complete at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}";
/// <summary>
/// Get or sets the message that is logged when a Job fails its
/// execution.
/// </summary>
public virtual string JobFailedMessage { get; set; } = "Job {1}.{0} execution failed at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}";
/// <summary>
/// Gets or sets the message that is logged when a Job is about to Execute.
/// </summary>
public virtual string JobToBeFiredMessage { get; set; } = "Job {1}.{0} fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}";
/// <summary>
/// Gets or sets the message that is logged when a Job execution is vetoed by a
/// trigger listener.
/// </summary>
public virtual string JobWasVetoedMessage { get; set; } = "Job {1}.{0} was vetoed. It was to be fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}";
/// <summary>
/// Get the name of the <see cref="IJobListener" />.
/// </summary>
/// <value></value>
public virtual string Name { get; set; } = "Logging Job History Plugin";
/// <summary>
/// Called during creation of the <see cref="IScheduler" /> in order to give
/// the <see cref="ISchedulerPlugin" /> a chance to Initialize.
/// </summary>
public virtual Task Initialize(
string pluginName,
IScheduler scheduler,
CancellationToken cancellationToken = default)
{
Name = pluginName;
scheduler.ListenerManager.AddJobListener(this, EverythingMatcher<JobKey>.AllJobs());
return Task.CompletedTask;
}
/// <summary>
/// Called when the associated <see cref="IScheduler" /> is started, in order
/// to let the plug-in know it can now make calls into the scheduler if it
/// needs to.
/// </summary>
public virtual Task Start(CancellationToken cancellationToken = default)
{
// do nothing...
return Task.CompletedTask;
}
/// <summary>
/// Called in order to inform the <see cref="ISchedulerPlugin" /> that it
/// should free up all of it's resources because the scheduler is shutting
/// down.
/// </summary>
public virtual Task Shutdown(CancellationToken cancellationToken = default)
{
// nothing to do...
return Task.CompletedTask;
}
/// <summary>
/// Called by the <see cref="IScheduler"/> when a <see cref="IJobDetail"/> is
/// about to be executed (an associated <see cref="ITrigger"/> has occurred).
/// <para>
/// This method will not be invoked if the execution of the Job was vetoed by a
/// <see cref="ITriggerListener"/>.
/// </para>
/// </summary>
/// <seealso cref="JobExecutionVetoed"/>
public virtual Task JobToBeExecuted(
IJobExecutionContext context,
CancellationToken cancellationToken = default)
{
if (!IsInfoEnabled)
{
return Task.CompletedTask;
}
ITrigger trigger = context.Trigger;
object?[] args =
{
context.JobDetail.Key.Name,
context.JobDetail.Key.Group,
SystemTime.UtcNow(),
trigger.Key.Name,
trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(),
trigger.GetNextFireTimeUtc(),
context.RefireCount
};
WriteInfo(string.Format(CultureInfo.InvariantCulture, JobToBeFiredMessage, args));
return Task.CompletedTask;
}
/// <summary>
/// Called by the <see cref="IScheduler" /> after a <see cref="IJobDetail" />
/// has been executed, and be for the associated <see cref="ITrigger" />'s
/// <see cref="IOperableTrigger.Triggered" /> method has been called.
/// </summary>
public virtual Task JobWasExecuted(IJobExecutionContext context,
JobExecutionException? jobException,
CancellationToken cancellationToken = default)
{
ITrigger trigger = context.Trigger;
object?[] args;
if (jobException != null)
{
if (!IsWarnEnabled)
{
return Task.CompletedTask;
}
string errMsg = jobException.Message;
args = new object?[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, errMsg
};
WriteWarning(string.Format(CultureInfo.InvariantCulture, JobFailedMessage, args), jobException);
}
else
{
if (!IsInfoEnabled)
{
return Task.CompletedTask;
}
var result = Convert.ToString(context.Result, CultureInfo.InvariantCulture);
args = new object?[]
{
context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, result
};
WriteInfo(string.Format(CultureInfo.InvariantCulture, JobSuccessMessage, args));
}
return Task.CompletedTask;
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="IJobDetail" />
/// was about to be executed (an associated <see cref="ITrigger" />
/// has occurred), but a <see cref="ITriggerListener" /> vetoed it's
/// execution.
/// </summary>
/// <seealso cref="JobToBeExecuted"/>
public virtual Task JobExecutionVetoed(
IJobExecutionContext context,
CancellationToken cancellationToken = default)
{
if (!IsInfoEnabled)
{
return Task.CompletedTask;
}
ITrigger trigger = context.Trigger;
object?[] args =
{
context.JobDetail.Key.Name,
context.JobDetail.Key.Group,
SystemTime.UtcNow(),
trigger.Key.Name,
trigger.Key.Group,
trigger.GetPreviousFireTimeUtc(),
trigger.GetNextFireTimeUtc(),
context.RefireCount
};
WriteInfo(string.Format(CultureInfo.InvariantCulture, JobWasVetoedMessage, args));
return Task.CompletedTask;
}
protected virtual bool IsInfoEnabled => Log.IsInfoEnabled();
protected virtual void WriteInfo(string message)
{
Log.Info(message);
}
protected virtual bool IsWarnEnabled => Log.IsWarnEnabled();
protected virtual void WriteWarning(string message, Exception ex)
{
Log.WarnException(message, ex);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Bmz.Framework.Application.Features;
using Bmz.Framework.Auditing;
using Bmz.Framework.Authorization;
using Bmz.Framework.Collections.Extensions;
using Bmz.Framework.Configuration;
using Bmz.Framework.Domain.Uow;
using Bmz.Framework.Events.Bus;
using Bmz.Framework.Events.Bus.Exceptions;
using Bmz.Framework.Localization;
using Bmz.Framework.Localization.Sources;
using Bmz.Framework.Logging;
using Bmz.Framework.Reflection;
using Bmz.Framework.Runtime.Session;
using Bmz.Framework.Timing;
using Bmz.Framework.Web.Models;
using Bmz.Framework.Web.Mvc.Controllers.Results;
using Bmz.Framework.Web.Mvc.Models;
using Castle.Core.Logging;
namespace Bmz.Framework.Web.Mvc.Controllers
{
/// <summary>
/// Base class for all MVC Controllers in Bmz system.
/// </summary>
public abstract class BmzController : Controller
{
/// <summary>
/// Gets current session information.
/// </summary>
public IBmzSession BmzSession { get; set; }
/// <summary>
/// Gets the event bus.
/// </summary>
public IEventBus EventBus { get; set; }
/// <summary>
/// Reference to the permission manager.
/// </summary>
public IPermissionManager PermissionManager { get; set; }
/// <summary>
/// Reference to the setting manager.
/// </summary>
public ISettingManager SettingManager { get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IPermissionChecker PermissionChecker { protected get; set; }
/// <summary>
/// Reference to the feature manager.
/// </summary>
public IFeatureManager FeatureManager { protected get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IFeatureChecker FeatureChecker { protected get; set; }
/// <summary>
/// Reference to the localization manager.
/// </summary>
public ILocalizationManager LocalizationManager { protected get; set; }
/// <summary>
/// Gets/sets name of the localization source that is used in this application service.
/// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods.
/// </summary>
protected string LocalizationSourceName { get; set; }
/// <summary>
/// Gets localization source.
/// It's valid if <see cref="LocalizationSourceName"/> is set.
/// </summary>
protected ILocalizationSource LocalizationSource
{
get
{
if (LocalizationSourceName == null)
{
throw new BmzException("Must set LocalizationSourceName before, in order to get LocalizationSource");
}
if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName)
{
_localizationSource = LocalizationManager.GetSource(LocalizationSourceName);
}
return _localizationSource;
}
}
private ILocalizationSource _localizationSource;
/// <summary>
/// Reference to the logger to write logs.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets current session information.
/// </summary>
[Obsolete("Use BmzSession property instead. CurrentSession will be removed in future releases.")]
protected IBmzSession CurrentSession { get { return BmzSession; } }
/// <summary>
/// Reference to <see cref="IUnitOfWorkManager"/>.
/// </summary>
public IUnitOfWorkManager UnitOfWorkManager
{
get
{
if (_unitOfWorkManager == null)
{
throw new BmzException("Must set UnitOfWorkManager before use it.");
}
return _unitOfWorkManager;
}
set { _unitOfWorkManager = value; }
}
private IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Gets current unit of work.
/// </summary>
protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } }
public IAuditingConfiguration AuditingConfiguration { get; set; }
public IAuditInfoProvider AuditInfoProvider { get; set; }
public IAuditingStore AuditingStore { get; set; }
/// <summary>
/// This object is used to measure an action execute duration.
/// </summary>
private Stopwatch _actionStopwatch;
private AuditInfo _auditInfo;
/// <summary>
/// MethodInfo for currently executing action.
/// </summary>
private MethodInfo _currentMethodInfo;
/// <summary>
/// WrapResultAttribute for currently executing action.
/// </summary>
private WrapResultAttribute _wrapResultAttribute;
/// <summary>
/// Ignored types for serialization on audit logging.
/// </summary>
protected static List<Type> IgnoredTypesForSerializationOnAuditLogging { get; private set; }
static BmzController()
{
IgnoredTypesForSerializationOnAuditLogging = new List<Type>
{
typeof (HttpPostedFileBase),
typeof (IEnumerable<HttpPostedFileBase>)
};
}
/// <summary>
/// Constructor.
/// </summary>
protected BmzController()
{
BmzSession = NullBmzSession.Instance;
Logger = NullLogger.Instance;
LocalizationManager = NullLocalizationManager.Instance;
PermissionChecker = NullPermissionChecker.Instance;
AuditingStore = SimpleLogAuditingStore.Instance;
EventBus = NullEventBus.Instance;
}
/// <summary>
/// Gets localized string for given key name and current language.
/// </summary>
/// <param name="name">Key name</param>
/// <returns>Localized string</returns>
protected virtual string L(string name)
{
return LocalizationSource.GetString(name);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, params object[] args)
{
return LocalizationSource.GetString(name, args);
}
/// <summary>
/// Gets localized string for given key name and specified culture information.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture)
{
return LocalizationSource.GetString(name, culture);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, CultureInfo culture, params object[] args)
{
return LocalizationSource.GetString(name, culture, args);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected Task<bool> IsGrantedAsync(string permissionName)
{
return PermissionChecker.IsGrantedAsync(permissionName);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected bool IsGranted(string permissionName)
{
return PermissionChecker.IsGranted(permissionName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual Task<bool> IsEnabledAsync(string featureName)
{
return FeatureChecker.IsEnabledAsync(featureName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual bool IsEnabled(string featureName)
{
return FeatureChecker.IsEnabled(featureName);
}
/// <summary>
/// Json the specified data, contentType, contentEncoding and behavior.
/// </summary>
/// <param name="data">Data.</param>
/// <param name="contentType">Content type.</param>
/// <param name="contentEncoding">Content encoding.</param>
/// <param name="behavior">Behavior.</param>
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess)
{
return base.Json(data, contentType, contentEncoding, behavior);
}
if (data == null)
{
data = new AjaxResponse();
}
else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>)))
{
data = new AjaxResponse(data);
}
return new BmzJsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
#region OnActionExecuting / OnActionExecuted
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
SetCurrentMethodInfoAndWrapResultAttribute(filterContext);
HandleAuditingBeforeAction(filterContext);
base.OnActionExecuting(filterContext);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
HandleAuditingAfterAction(filterContext);
}
private void SetCurrentMethodInfoAndWrapResultAttribute(ActionExecutingContext filterContext)
{
_currentMethodInfo = ActionDescriptorHelper.GetMethodInfo(filterContext.ActionDescriptor);
_wrapResultAttribute =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrNull<WrapResultAttribute>(_currentMethodInfo) ??
WrapResultAttribute.Default;
}
#endregion
#region Exception handling
protected override void OnException(ExceptionContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
//If exception handled before, do nothing.
//If this is child action, exception should be handled by main action.
if (context.ExceptionHandled || context.IsChildAction)
{
base.OnException(context);
return;
}
//Log exception
if (_wrapResultAttribute.LogError)
{
LogHelper.LogException(Logger, context.Exception);
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (!context.HttpContext.IsCustomErrorEnabled)
{
base.OnException(context);
return;
}
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, context.Exception).GetHttpCode() != 500)
{
base.OnException(context);
return;
}
//Check WrapResultAttribute
if (!_wrapResultAttribute.WrapOnError)
{
base.OnException(context);
return;
}
//We handled the exception!
context.ExceptionHandled = true;
//Return a special error response to the client.
context.HttpContext.Response.Clear();
context.Result = IsJsonResult()
? GenerateJsonExceptionResult(context)
: GenerateNonJsonExceptionResult(context);
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
context.HttpContext.Response.TrySkipIisCustomErrors = true;
//Trigger an event, so we can register it.
EventBus.Trigger(this, new BmzHandledExceptionData(context.Exception));
}
protected virtual bool IsJsonResult()
{
return typeof(JsonResult).IsAssignableFrom(_currentMethodInfo.ReturnType) ||
typeof(Task<JsonResult>).IsAssignableFrom(_currentMethodInfo.ReturnType);
}
protected virtual ActionResult GenerateJsonExceptionResult(ExceptionContext context)
{
context.HttpContext.Items.Add("IgnoreJsonRequestBehaviorDenyGet", "true");
context.HttpContext.Response.StatusCode = 200; //TODO: Consider to return 500
return new BmzJsonResult(
new MvcAjaxResponse(
ErrorInfoBuilder.Instance.BuildForException(context.Exception),
context.Exception is BmzAuthorizationException
)
);
}
protected virtual ActionResult GenerateNonJsonExceptionResult(ExceptionContext context)
{
context.HttpContext.Response.StatusCode = 500;
return new ViewResult
{
ViewName = "Error",
MasterName = string.Empty,
ViewData = new ViewDataDictionary<ErrorViewModel>(new ErrorViewModel(context.Exception)),
TempData = context.Controller.TempData
};
}
#endregion
#region Auditing
private void HandleAuditingBeforeAction(ActionExecutingContext filterContext)
{
if (!ShouldSaveAudit(filterContext))
{
_auditInfo = null;
return;
}
_actionStopwatch = Stopwatch.StartNew();
_auditInfo = new AuditInfo
{
TenantId = BmzSession.TenantId,
UserId = BmzSession.UserId,
ImpersonatorUserId = BmzSession.ImpersonatorUserId,
ImpersonatorTenantId = BmzSession.ImpersonatorTenantId,
ServiceName = _currentMethodInfo.DeclaringType != null
? _currentMethodInfo.DeclaringType.FullName
: filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
MethodName = _currentMethodInfo.Name,
Parameters = ConvertArgumentsToJson(filterContext.ActionParameters),
ExecutionTime = Clock.Now
};
}
private void HandleAuditingAfterAction(ActionExecutedContext filterContext)
{
if (_auditInfo == null || _actionStopwatch == null)
{
return;
}
_actionStopwatch.Stop();
_auditInfo.ExecutionDuration = Convert.ToInt32(_actionStopwatch.Elapsed.TotalMilliseconds);
_auditInfo.Exception = filterContext.Exception;
if (AuditInfoProvider != null)
{
AuditInfoProvider.Fill(_auditInfo);
}
AuditingStore.Save(_auditInfo);
}
private bool ShouldSaveAudit(ActionExecutingContext filterContext)
{
if (AuditingConfiguration == null)
{
return false;
}
if (!AuditingConfiguration.MvcControllers.IsEnabled)
{
return false;
}
if (filterContext.IsChildAction && !AuditingConfiguration.MvcControllers.IsEnabledForChildActions)
{
return false;
}
return AuditingHelper.ShouldSaveAudit(
_currentMethodInfo,
AuditingConfiguration,
BmzSession,
true
);
}
private string ConvertArgumentsToJson(IDictionary<string, object> arguments)
{
try
{
if (arguments.IsNullOrEmpty())
{
return "{}";
}
var dictionary = new Dictionary<string, object>();
foreach (var argument in arguments)
{
if (argument.Value != null && IgnoredTypesForSerializationOnAuditLogging.Any(t => t.IsInstanceOfType(argument.Value)))
{
dictionary[argument.Key] = null;
}
else
{
dictionary[argument.Key] = argument.Value;
}
}
return AuditingHelper.Serialize(dictionary);
}
catch (Exception ex)
{
Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName);
Logger.Warn(ex.ToString(), ex);
return "{}";
}
}
#endregion
}
}
| |
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Hosting;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private readonly ILogger log;
private Action<Message> rerouteHandler;
internal Func<Message, bool> ShouldDrop;
// ReSharper disable NotAccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore NotAccessedField.Local
internal IOutboundMessageQueue OutboundQueue { get; set; }
internal IInboundMessageQueue InboundQueue { get; set; }
internal SocketManager SocketManager;
private readonly SerializationManager serializationManager;
private readonly MessageFactory messageFactory;
private readonly ILoggerFactory loggerFactory;
private readonly ExecutorService executorService;
internal bool IsBlockingApplicationMessages { get; private set; }
public bool IsProxying { get { return Gateway != null; } }
public bool TryDeliverToProxy(Message msg)
{
return msg.TargetGrain.IsClient && Gateway != null && Gateway.TryDeliverToProxy(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public MessageCenter(
ILocalSiloDetails siloDetails,
IOptions<EndpointOptions> endpointOptions,
IOptions<SiloMessagingOptions> messagingOptions,
IOptions<NetworkingOptions> networkingOptions,
SerializationManager serializationManager,
MessageFactory messageFactory,
Factory<MessageCenter, Gateway> gatewayFactory,
ExecutorService executorService,
ILoggerFactory loggerFactory)
{
this.loggerFactory = loggerFactory;
this.log = loggerFactory.CreateLogger<MessageCenter>();
this.serializationManager = serializationManager;
this.messageFactory = messageFactory;
this.executorService = executorService;
this.MyAddress = siloDetails.SiloAddress;
this.Initialize(endpointOptions, messagingOptions, networkingOptions);
if (siloDetails.GatewayAddress != null)
{
Gateway = gatewayFactory(this);
}
}
private void Initialize(IOptions<EndpointOptions> endpointOptions, IOptions<SiloMessagingOptions> messagingOptions, IOptions<NetworkingOptions> networkingOptions)
{
if(log.IsEnabled(LogLevel.Trace)) log.Trace("Starting initialization.");
SocketManager = new SocketManager(networkingOptions, this.loggerFactory);
var listeningEndpoint = endpointOptions.Value.GetListeningSiloEndpoint();
ima = new IncomingMessageAcceptor(this, listeningEndpoint, SocketDirection.SiloToSilo, this.messageFactory, this.serializationManager, this.executorService, this.loggerFactory);
InboundQueue = new InboundMessageQueue(this.loggerFactory);
OutboundQueue = new OutboundMessageQueue(this, messagingOptions, this.serializationManager, this.executorService, this.loggerFactory);
sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength);
receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength);
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Completed initialization.");
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway(ClientObserverRegistrar clientRegistrar)
{
if (Gateway != null)
Gateway.Start(clientRegistrar);
}
public void PrepareToStop()
{
}
public void Stop()
{
IsBlockingApplicationMessages = true;
try
{
ima.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc);
}
StopAcceptingClientMessages();
try
{
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
try
{
SocketManager.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsEnabled(LogLevel.Debug)) log.Debug("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
ima.SniffIncomingMessage = value;
}
}
public Func<SiloAddress, bool> SiloDeadOracle { get; set; }
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableId.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
}
else
{
if (msg.SendingSilo == null)
msg.SendingSilo = MyAddress;
OutboundQueue.SendMessage(msg);
}
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (string.IsNullOrEmpty(reason)) reason = string.Format("Rejection from silo {0} - Unknown reason.", MyAddress);
Message error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
InboundQueue.PostMessage(error);
}
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
return InboundQueue.WaitMessage(type);
}
public void Dispose()
{
if (ima != null)
{
ima.Dispose();
ima = null;
}
InboundQueue?.Dispose();
OutboundQueue?.Dispose();
GC.SuppressFinalize(this);
}
public int SendQueueLength { get { return OutboundQueue.Count; } }
public int ReceiveQueueLength { get { return InboundQueue.Count; } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsEnabled(LogLevel.Debug)) log.Debug("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace ByteFX.Data.MySqlClient
{
/// <summary>
/// Summary description for Packet.
/// </summary>
internal class Packet : MemoryStream
{
Encoding encoding;
byte sequence;
int completeLen;
public static int NULL_LEN=-1;
private int shortLen = 2;
private int intLen = 3;
private int longLen = 4;
private bool longInts = false;
public Packet(bool longInts) : base()
{
LongInts = longInts;
}
public Packet(byte[] bytes, bool longInts) : base(bytes.Length)
{
this.Write( bytes, 0, bytes.Length );
Position = 0;
LongInts = longInts;
}
public bool LongInts
{
get { return longInts; }
set
{
longInts = value;
if (longInts)
{
intLen = 4;
longLen = 8;
}
}
}
public int CompleteLength
{
get { return completeLen; }
set { completeLen = value; }
}
public byte Sequence
{
get { return sequence; }
set { sequence = value; }
}
public Encoding Encoding
{
set { encoding = value; }
get { return encoding; }
}
public void Clear()
{
Position = 0;
this.SetLength(0);
}
public byte this[int index]
{
get
{
long pos = Position;
Position = index;
byte b = (byte)ReadByte();
Position = pos;
return b;
}
}
public new int Length
{
get { return (int)base.Length; }
}
public bool IsLastPacket()
{
return (Length == 1 && this[0] == 0xfe);
}
public void Append( Packet p )
{
long oldPos = Position;
Position = Length;
this.Write( p.GetBuffer(), 0, p.Length );
Position = oldPos;
}
public Packet ReadPacket()
{
if (! HasMoreData) return null;
int len = this.ReadInteger(3);
byte seq = (byte)this.ReadByte();
byte[] buf = new byte[ len ];
this.Read( buf, 0, len );
Packet p = new Packet( buf, LongInts );
p.Sequence = seq;
p.Encoding = this.Encoding;
return p;
}
public int ReadNBytes()
{
byte c = (byte)ReadByte();
if (c < 1 || c > 4) throw new MySqlException("Unexpected byte count received");
return ReadInteger((int)c);
}
public string ReadLenString()
{
long len = ReadLenInteger();
byte[] buffer = new Byte[len];
Read(buffer, 0, (int)len);
return encoding.GetString( buffer, 0, (int)len);
}
/// <summary>
/// WriteInteger
/// </summary>
/// <param name="v"></param>
/// <param name="numbytes"></param>
public void WriteInteger( int v, int numbytes )
{
int val = v;
if (numbytes < 1 || numbytes > 4)
throw new ArgumentOutOfRangeException("Wrong byte count for WriteInteger");
for (int x=0; x < numbytes; x++)
{
WriteByte( (byte)(val&0xff) );
val >>= 8;
}
}
/// <summary>
///
/// </summary>
/// <param name="numbytes"></param>
/// <returns></returns>
public int ReadInteger(int numbytes)
{
int val = 0;
int raise = 1;
for (int x=0; x < numbytes; x++)
{
int b = ReadByte();
val += (b*raise);
raise *= 256;
}
return val;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public long ReadLenInteger()
{
byte c = (byte)ReadByte();
switch(c)
{
case 251 : return NULL_LEN;
case 252 : return ReadInteger(shortLen);
case 253 : return ReadInteger(intLen);
case 254 : return ReadInteger(longLen);
default : return c;
}
}
public bool HasMoreData
{
get { return Position < Length; }
}
#region String Functions
public string ReadString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while ( HasMoreData )
{
byte b = (byte)ReadByte();
if (b == 0) break;
sb.Append( Convert.ToChar( b ));
}
return sb.ToString();
}
public void WriteString(string v, Encoding encoding)
{
WriteStringNoNull(v, encoding);
WriteByte(0);
}
public void WriteStringNoNull(string v, Encoding encoding)
{
byte[] bytes = encoding.GetBytes(v);
Write(bytes, 0, bytes.Length);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.NodeJS.Templates;
using Newtonsoft.Json;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.NodeJS.Model
{
public class MethodJs : Method
{
public MethodJs()
{
// methods that have no group name get the client name as their name
Group.OnGet += groupName =>
{
return groupName.IsNullOrEmpty() ? CodeModel?.Name.Value : groupName;
};
OptionsParameterTemplateModel = (ParameterJs)New<Parameter>(new
{
Name = "options",
SerializedName = "options",
IsRequired = false,
Documentation = "Optional Parameters.",
Location = ParameterLocation.None,
ModelType = New<CompositeType>(new
{
Name = "options",
SerializedName = "options",
Documentation = "Optional Parameters."
})
});
OptionsParameterModelType.Add(New<Core.Model.Property>(new
{
IsReadOnly = false,
Name = "customHeaders",
IsRequired = false,
Documentation = "Headers that will be added to the request",
ModelType = New<PrimaryType>(KnownPrimaryType.Object),
SerializedName = "customHeaders"
}));
}
public override void Remove(Parameter item)
{
base.Remove(item);
// find a Property in OptionsParameterModelType with the same name and remove it.
OptionsParameterModelType.Remove(prop => prop.Name == item.Name);
}
public enum MethodFlavor
{
Callback,
Promise,
HttpOperationResponse
}
public enum Language
{
JavaScript,
TypeScript
}
public override Parameter Add(Parameter item)
{
var parameter = base.Add(item) as ParameterJs;
if (parameter.IsLocal && !parameter.IsRequired)
{
OptionsParameterModelType.Add(New<Core.Model.Property>(new
{
IsReadOnly = false,
Name = parameter.Name,
IsRequired = parameter.IsRequired,
DefaultValue = parameter.DefaultValue,
Documentation = parameter.Documentation,
ModelType = parameter.ModelType,
SerializedName = parameter.SerializedName,
Constraints = parameter.Constraints,
// optionalProperty.Constraints.AddRange(parameter.Constraints);
Extensions = parameter.Extensions // optionalProperty.Extensions.AddRange(parameter.Extensions);
}));
}
return parameter;
}
[JsonIgnore]
private CompositeType OptionsParameterModelType => ((CompositeType)OptionsParameterTemplateModel.ModelType);
[JsonIgnore]
public IEnumerable<ParameterJs> ParameterTemplateModels => Parameters.Cast<ParameterJs>();
[JsonIgnore]
public ParameterJs OptionsParameterTemplateModel { get; }
/// <summary>
/// Get the predicate to determine of the http operation status code indicates success
/// </summary>
public string FailureStatusCodePredicate
{
get
{
if (Responses.Any())
{
List<string> predicates = new List<string>();
foreach (var responseStatus in Responses.Keys)
{
predicates.Add(string.Format(CultureInfo.InvariantCulture,
"statusCode !== {0}", GetStatusCodeReference(responseStatus)));
}
return string.Join(" && ", predicates);
}
return "statusCode < 200 || statusCode >= 300";
}
}
/// <summary>
/// Generate the method parameter declarations for a method
/// </summary>
public string MethodParameterDeclaration
{
get
{
List<string> declarations = new List<string>();
foreach (var parameter in LocalParametersWithOptions)
{
declarations.Add(parameter.Name);
}
var declaration = string.Join(", ", declarations);
return declaration;
}
}
/// <summary>
/// Generate the method parameter declarations for a method, using TypeScript declaration syntax
/// <param name="includeOptions">whether the ServiceClientOptions parameter should be included</param>
/// <param name="isOptionsOptional">whether the ServiceClientOptions parameter should be optional</param>
/// </summary>
public string MethodParameterDeclarationTS(bool includeOptions, bool isOptionsOptional = true)
{
StringBuilder declarations = new StringBuilder();
bool first = true;
IEnumerable<ParameterJs> requiredParameters = LocalParameters.Where(p => p.IsRequired);
foreach (var parameter in requiredParameters)
{
if (!first)
declarations.Append(", ");
declarations.Append(parameter.Name);
declarations.Append(": ");
// For date/datetime parameters, use a union type to reflect that they can be passed as a JS Date or a string.
var type = parameter.ModelType;
if (type.IsPrimaryType(KnownPrimaryType.Date) || type.IsPrimaryType(KnownPrimaryType.DateTime))
declarations.Append("Date|string");
else declarations.Append(type.TSType(false));
first = false;
}
if (includeOptions)
{
if (!first)
declarations.Append(", ");
if (isOptionsOptional)
{
declarations.Append("options?: { ");
}
else
{
declarations.Append("options: { ");
}
var optionalParameters = ((CompositeType)OptionsParameterTemplateModel.ModelType).Properties.OrderBy(each => each.Name == "customHeaders" ? 1 : 0).ToArray();
for (int i = 0; i < optionalParameters.Length; i++)
{
if (i != 0)
{
declarations.Append(", ");
}
declarations.Append(optionalParameters[i].Name);
declarations.Append("? : ");
if (optionalParameters[i].Name.EqualsIgnoreCase("customHeaders"))
{
declarations.Append("{ [headerName: string]: string; }");
}
else
{
declarations.Append(optionalParameters[i].ModelType.TSType(false));
}
}
declarations.Append(" }");
}
return declarations.ToString();
}
/// <summary>
/// Generate the method parameter declarations with callback or optionalCallback for a method
/// <param name="isCallbackOptional">If true, the method signature has an optional callback, otherwise the callback is required.</param>
/// </summary>
public string MethodParameterDeclarationWithCallback(bool isCallbackOptional = false)
{
var parameters = MethodParameterDeclaration;
if (isCallbackOptional)
{
parameters += ", optionalCallback";
}
else
{
parameters += ", callback";
}
return parameters;
}
/// <summary>
/// Generate the method parameter declarations with callback for a method, using TypeScript method syntax
/// <param name="includeOptions">whether the ServiceClientOptions parameter should be included</param>
/// <param name="includeCallback">If true, the method signature will have a callback, otherwise the callback will not be present.</param>
/// </summary>
public string MethodParameterDeclarationWithCallbackTS(bool includeOptions, bool includeCallback = true)
{
//var parameters = MethodParameterDeclarationTS(includeOptions);
StringBuilder parameters = new StringBuilder();
if (!includeCallback)
{
//Promise scenario no callback and options is optional
parameters.Append(MethodParameterDeclarationTS(includeOptions));
}
else
{
//callback scenario
if (includeOptions)
{
//with options as required parameter
parameters.Append(MethodParameterDeclarationTS(includeOptions, isOptionsOptional: false));
}
else
{
//with options as optional parameter
parameters.Append(MethodParameterDeclarationTS(includeOptions: false));
}
}
if (includeCallback)
{
if (parameters.Length > 0)
{
parameters.Append(", ");
}
parameters.Append("callback: ServiceCallback<" + ReturnTypeTSString + ">");
}
return parameters.ToString();
}
/// <summary>
/// Get the parameters that are actually method parameters in the order they appear in the method signature
/// exclude global parameters and constants.
/// </summary>
internal IEnumerable<ParameterJs> LocalParameters
{
get
{
return ParameterTemplateModels.Where(
p => p != null && !p.IsClientProperty && !string.IsNullOrWhiteSpace(p.Name) && !p.IsConstant)
.OrderBy(item => !item.IsRequired);
}
}
/// <summary>
/// Get the parameters that are actually method parameters in the order they appear in the method signature
/// exclude global parameters. All the optional parameters are pushed into the second last "options" parameter.
/// </summary>
[JsonIgnore]
public IEnumerable<ParameterJs> LocalParametersWithOptions
{
get
{
List<ParameterJs> requiredParamsWithOptionsList = LocalParameters.Where(p => p.IsRequired).ToList();
requiredParamsWithOptionsList.Add(OptionsParameterTemplateModel);
return requiredParamsWithOptionsList as IEnumerable<ParameterJs>;
}
}
/// <summary>
/// Returns list of parameters and their properties in (alphabetical order) that needs to be documented over a method.
/// This property does simple tree traversal using stack and hashtable for already visited complex types.
/// </summary>
[JsonIgnore]
public IEnumerable<ParameterJs> DocumentationParameters
{
get
{
var traversalStack = new Stack<ParameterJs>();
var visitedHash = new HashSet<string>();
var retValue = new Stack<ParameterJs>();
foreach (var param in LocalParametersWithOptions)
{
traversalStack.Push(param);
}
while (traversalStack.Count() != 0)
{
var param = traversalStack.Pop();
if (!(param.ModelType is CompositeType))
{
retValue.Push(param);
}
if (param.ModelType is CompositeType)
{
if (!visitedHash.Contains(param.ModelType.Name))
{
traversalStack.Push(param);
foreach (var property in param.ComposedProperties.OrderBy(each => each.Name == "customHeaders" ? 1 : 0)) //.OrderBy( each => each.Name.Else("")))
{
if (property.IsReadOnly || property.IsConstant)
{
continue;
}
var propertyParameter = New<Parameter>() as ParameterJs;
propertyParameter.ModelType = property.ModelType;
propertyParameter.IsRequired = property.IsRequired;
propertyParameter.Name.FixedValue = param.Name + "." + property.Name;
string documentationString = string.Join(" ", (new[] { property.Summary, property.Documentation }).Where(s => !string.IsNullOrEmpty(s)));
propertyParameter.Documentation = documentationString;
traversalStack.Push(propertyParameter);
}
visitedHash.Add(param.ModelType.Name);
}
else
{
retValue.Push(param);
}
}
}
return retValue.ToList();
}
}
public static string ConstructParameterDocumentation(string documentation)
{
var builder = new IndentedStringBuilder(" ");
return builder.AppendLine(documentation)
.AppendLine(" * ").ToString();
}
/// <summary>
/// Get the type name for the method's return type
/// </summary>
[JsonIgnore]
public string ReturnTypeString
{
get
{
if (ReturnType.Body != null)
{
return ReturnType.Body.Name;
}
else
{
return "null";
}
}
}
/// <summary>
/// Get the type name for the method's return type for TS
/// </summary>
[JsonIgnore]
public string ReturnTypeTSString
{
get
{
if (ReturnType.Body != null)
{
return ReturnType.Body.TSType(false);
}
else
{
return "void";
}
}
}
/// <summary>
/// The Deserialization Error handling code block that provides a useful Error
/// message when exceptions occur in deserialization along with the request
/// and response object
/// </summary>
[JsonIgnore]
public string DeserializationError
{
get
{
var builder = new IndentedStringBuilder(" ");
var errorVariable = this.GetUniqueName("deserializationError");
return builder.AppendLine("let {0} = new Error(`Error ${{error}} occurred in " +
"deserializing the responseBody - ${{responseBody}}`);", errorVariable)
.AppendLine("{0}.request = msRest.stripRequest(httpRequest);", errorVariable)
.AppendLine("{0}.response = msRest.stripResponse(response);", errorVariable)
.AppendLine("return callback({0});", errorVariable).ToString();
}
}
public string PopulateErrorCodeAndMessage()
{
var builder = new IndentedStringBuilder(" ");
if (DefaultResponse.Body != null && DefaultResponse.Body.Name.RawValue.EqualsIgnoreCase("CloudError"))
{
builder.AppendLine("if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;")
.AppendLine("if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;")
.AppendLine("if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;");
}
else
{
builder.AppendLine("let internalError = null;")
.AppendLine("if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;")
.AppendLine("error.code = internalError ? internalError.code : parsedErrorResponse.code;")
.AppendLine("error.message = internalError ? internalError.message : parsedErrorResponse.message;");
}
return builder.ToString();
}
/// <summary>
/// Provides the parameter name in the correct jsdoc notation depending on
/// whether it is required or optional
/// </summary>
/// <param name="parameter">Parameter to be documented</param>
/// <returns>Parameter name in the correct jsdoc notation</returns>
public static string GetParameterDocumentationName(Parameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
if (parameter.IsRequired)
{
return parameter.Name;
}
else
{
return string.Format(CultureInfo.InvariantCulture, "[{0}]", parameter.Name);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
public static string GetParameterDocumentationType(Parameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
string typeName = "object";
if (parameter.ModelType is PrimaryTypeJs)
{
typeName = parameter.ModelType.Name;
}
else if (parameter.ModelType is Core.Model.SequenceType)
{
typeName = "array";
}
else if (parameter.ModelType is EnumType)
{
typeName = "string";
}
return typeName.ToLowerInvariant();
}
public string GetDeserializationString(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
{
var builder = new IndentedStringBuilder(" ");
if (type is CompositeType)
{
builder.AppendLine("let resultMapper = new client.models['{0}']().mapper();", type.Name);
}
else
{
builder.AppendLine("let resultMapper = {{{0}}};", type.ConstructMapper(responseVariable, null, false, false));
}
builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
return builder.ToString();
}
[JsonIgnore]
public string ValidationString
{
get
{
var builder = new IndentedStringBuilder(" ");
foreach (var parameter in ParameterTemplateModels.Where(p => !p.IsConstant))
{
if ((HttpMethod == HttpMethod.Patch && parameter.ModelType is CompositeType))
{
if (parameter.IsRequired)
{
builder.AppendLine("if ({0} === null || {0} === undefined) {{", parameter.Name)
.Indent()
.AppendLine("throw new Error('{0} cannot be null or undefined.');", parameter.Name)
.Outdent()
.AppendLine("}");
}
}
else
{
builder.AppendLine(parameter.ModelType.ValidateType(this, parameter.Name, parameter.IsRequired));
if (parameter.Constraints != null && parameter.Constraints.Count > 0 && parameter.Location != ParameterLocation.Body)
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", parameter.Name).Indent();
builder = parameter.ModelType.AppendConstraintValidations(parameter.Name, parameter.Constraints, builder);
builder.Outdent().AppendLine("}");
}
}
}
return builder.ToString();
}
}
public string DeserializeResponse(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var builder = new IndentedStringBuilder(" ");
builder.AppendLine("let {0} = null;", responseVariable)
.AppendLine("try {")
.Indent()
.AppendLine("{0} = JSON.parse(responseBody);", responseVariable)
.AppendLine("{0} = JSON.parse(responseBody);", valueReference);
var deserializeBody = GetDeserializationString(type, valueReference, responseVariable);
if (!string.IsNullOrWhiteSpace(deserializeBody))
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable)
.Indent()
.AppendLine(deserializeBody)
.Outdent()
.AppendLine("}");
}
builder.Outdent()
.AppendLine("} catch (error) {")
.Indent()
.AppendLine(DeserializationError)
.Outdent()
.AppendLine("}");
return builder.ToString();
}
/// <summary>
/// Get the method's request body (or null if there is no request body)
/// </summary>
public ParameterJs RequestBody => Body as ParameterJs;
/// <summary>
/// Generate a reference to the ServiceClient
/// </summary>
[JsonIgnore]
public string ClientReference => MethodGroup.IsCodeModelMethodGroup ? "this" : "this.client";
public static string GetStatusCodeReference(HttpStatusCode code)
{
return string.Format(CultureInfo.InvariantCulture, "{0}", (int)code);
}
/// <summary>
/// Generate code to build the URL from a url expression and method parameters
/// </summary>
/// <param name="variableName">The variable to store the url in.</param>
/// <returns></returns>
public virtual string BuildUrl(string variableName)
{
var builder = new IndentedStringBuilder(" ");
BuildPathParameters(variableName, builder);
if (HasQueryParameters())
{
BuildQueryParameterArray(builder);
AddQueryParametersToUrl(variableName, builder);
}
return builder.ToString();
}
/// <summary>
/// Generate code to construct the query string from an array of query parameter strings containing 'key=value'
/// </summary>
/// <param name="variableName">The variable reference for the url</param>
/// <param name="builder">The string builder for url construction</param>
private void AddQueryParametersToUrl(string variableName, IndentedStringBuilder builder)
{
builder.AppendLine("if (queryParameters.length > 0) {")
.Indent();
if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"])
{
builder.AppendLine("{0} += ({0}.indexOf('?') !== -1 ? '&' : '?') + queryParameters.join('&');", variableName);
}
else
{
builder.AppendLine("{0} += '?' + queryParameters.join('&');", variableName);
}
builder.Outdent().AppendLine("}");
}
/// <summary>
/// Detremines whether the Uri will have any query string
/// </summary>
/// <returns>True if a query string is possible given the method parameters, otherwise false</returns>
protected virtual bool HasQueryParameters()
{
return LogicalParameters.Any(p => p.Location == ParameterLocation.Query);
}
/// <summary>
/// Genrate code to build an array of query parameter strings in a variable named 'queryParameters'. The
/// array should contain one string element for each query parameter of the form 'key=value'
/// </summary>
/// <param name="builder">The stringbuilder for url construction</param>
protected virtual void BuildQueryParameterArray(IndentedStringBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.AppendLine("let queryParameters = [];");
foreach (var queryParameter in LogicalParameters
.Where(p => p.Location == ParameterLocation.Query))
{
var queryAddFormat = "queryParameters.push('{0}=' + encodeURIComponent({1}));";
if (queryParameter.SkipUrlEncoding())
{
queryAddFormat = "queryParameters.push('{0}=' + {1});";
}
if (!queryParameter.IsRequired)
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", queryParameter.Name)
.Indent()
.AppendLine(queryAddFormat,
queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue()).Outdent()
.AppendLine("}");
}
else
{
builder.AppendLine(queryAddFormat,
queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue());
}
}
}
/// <summary>
/// Generate code to replace path parameters in the url template with the appropriate values
/// </summary>
/// <param name="variableName">The variable name for the url to be constructed</param>
/// <param name="builder">The string builder for url construction</param>
protected virtual void BuildPathParameters(string variableName, IndentedStringBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path))
{
var pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', encodeURIComponent({2}));";
if (pathParameter.SkipUrlEncoding())
{
pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});";
}
builder.AppendLine(pathReplaceFormat, variableName, pathParameter.SerializedName,
pathParameter.ModelType.ToString(pathParameter.Name));
}
}
/// <summary>
/// Gets the expression for default header setting.
/// </summary>
public virtual string SetDefaultHeaders
{
get
{
return string.Empty;
}
}
[JsonIgnore]
public string ConstructRequestBodyMapper
{
get
{
var builder = new IndentedStringBuilder(" ");
if (RequestBody.ModelType is CompositeType)
{
builder.AppendLine("let requestModelMapper = new client.models['{0}']().mapper();", RequestBody.ModelType.Name);
}
else
{
builder.AppendLine("let requestModelMapper = {{{0}}};",
RequestBody.ModelType.ConstructMapper(RequestBody.SerializedName, RequestBody, false, false));
}
return builder.ToString();
}
}
[JsonIgnore]
public virtual string InitializeResult
{
get
{
return string.Empty;
}
}
[JsonIgnore]
public string ReturnTypeInfo
{
get
{
string result = null;
if (ReturnType.Body is EnumType)
{
var returnBodyType = ReturnType.Body as EnumType;
if (!returnBodyType.ModelAsString)
{
string enumValues = "";
for (var i = 0; i < returnBodyType.Values.Count; i++)
{
if (i == returnBodyType.Values.Count - 1)
{
enumValues += returnBodyType.Values[i].SerializedName;
}
else
{
enumValues += returnBodyType.Values[i].SerializedName + ", ";
}
}
result = string.Format(CultureInfo.InvariantCulture,
"Possible values for result are - {0}.", enumValues);
}
}
else if (ReturnType.Body is CompositeType)
{
result = string.Format(CultureInfo.InvariantCulture,
"See {{@link {0}}} for more information.", ReturnTypeString);
}
return result;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
[JsonIgnore]
public string DocumentReturnTypeString
{
get
{
string typeName = "object";
IModelType returnBodyType = ReturnType.Body;
if (returnBodyType == null)
{
typeName = "null";
}
else if (returnBodyType is PrimaryTypeJs)
{
typeName = returnBodyType.Name;
}
else if (returnBodyType is Core.Model.SequenceType)
{
typeName = "array";
}
else if (returnBodyType is EnumType)
{
typeName = "string";
}
return typeName.ToLowerInvariant();
}
}
/// <summary>
/// Generates input mapping code block.
/// </summary>
/// <returns></returns>
public virtual string BuildInputMappings()
{
var builder = new IndentedStringBuilder(" ");
if (InputParameterTransformation.Count > 0)
{
if (AreWeFlatteningParameters())
{
return BuildFlattenParameterMappings();
}
else
{
return BuildGroupedParameterMappings();
}
}
return builder.ToString();
}
public virtual bool AreWeFlatteningParameters()
{
bool result = true;
foreach (var transformation in InputParameterTransformation)
{
var compositeOutputParameter = transformation.OutputParameter.ModelType as CompositeType;
if (compositeOutputParameter == null)
{
result = false;
break;
}
else
{
foreach (var poperty in compositeOutputParameter.ComposedProperties.Select(p => p.Name))
{
if (!transformation.ParameterMappings.Select(m => m.InputParameter.Name).Contains(poperty))
{
result = false;
break;
}
}
if (!result) break;
}
}
return result;
}
public virtual string BuildFlattenParameterMappings()
{
var builder = new IndentedStringBuilder(" ");
foreach (var transformation in InputParameterTransformation)
{
builder.AppendLine("let {0};",
transformation.OutputParameter.Name);
builder.AppendLine("if ({0}) {{", BuildNullCheckExpression(transformation))
.Indent();
if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
transformation.OutputParameter.ModelType is CompositeType)
{
builder.AppendLine("{0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
foreach (var mapping in transformation.ParameterMappings)
{
builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter));
}
builder.Outdent()
.AppendLine("}");
}
return builder.ToString();
}
public virtual string BuildGroupedParameterMappings()
{
var builder = new IndentedStringBuilder(" ");
if (InputParameterTransformation.Count > 0)
{
// Declare all the output paramaters outside the try block
foreach (var transformation in InputParameterTransformation)
{
if (transformation.OutputParameter.ModelType is CompositeType &&
transformation.OutputParameter.IsRequired)
{
builder.AppendLine("let {0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
else
{
builder.AppendLine("let {0};", transformation.OutputParameter.Name);
}
}
builder.AppendLine("try {").Indent();
foreach (var transformation in InputParameterTransformation)
{
builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation))
.AppendLine("{").Indent();
var outputParameter = transformation.OutputParameter;
bool noCompositeTypeInitialized = true;
if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
transformation.OutputParameter.ModelType is CompositeType)
{
//required outputParameter is initialized at the time of declaration
if (!transformation.OutputParameter.IsRequired)
{
builder.AppendLine("{0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
noCompositeTypeInitialized = false;
}
foreach (var mapping in transformation.ParameterMappings)
{
builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter));
if (noCompositeTypeInitialized)
{
// If composite type is initialized based on the above logic then it should not be validated.
builder.AppendLine(outputParameter.ModelType.ValidateType(this, outputParameter.Name, outputParameter.IsRequired));
}
}
builder.Outdent()
.AppendLine("}");
}
builder.Outdent()
.AppendLine("} catch (error) {")
.Indent()
.AppendLine("return callback(error);")
.Outdent()
.AppendLine("}");
}
return builder.ToString();
}
private static string BuildNullCheckExpression(ParameterTransformation transformation)
{
if (transformation == null)
{
throw new ArgumentNullException(nameof(transformation));
}
if (transformation.ParameterMappings.Count == 1)
{
return string.Format(CultureInfo.InvariantCulture,
"{0} !== null && {0} !== undefined",
transformation.ParameterMappings[0].InputParameter.Name);
}
else
{
return string.Join(" || ",
transformation.ParameterMappings.Select(m =>
string.Format(CultureInfo.InvariantCulture,
"({0} !== null && {0} !== undefined)", m.InputParameter.Name)));
}
}
public string BuildOptionalMappings()
{
IEnumerable<Core.Model.Property> optionalParameters =
((CompositeType)OptionsParameterTemplateModel.ModelType)
.Properties.Where(p => p.Name != "customHeaders");
var builder = new IndentedStringBuilder(" ");
foreach (var optionalParam in optionalParameters)
{
string defaultValue = "undefined";
if (!string.IsNullOrWhiteSpace(optionalParam.DefaultValue))
{
defaultValue = optionalParam.DefaultValue;
}
builder.AppendLine("let {0} = ({1} && {1}.{2} !== undefined) ? {1}.{2} : {3};",
optionalParam.Name, OptionsParameterTemplateModel.Name, optionalParam.Name, defaultValue);
}
return builder.ToString();
}
/// <summary>
/// Generates documentation for every method on the client.
/// </summary>
/// <param name="flavor">Describes the flavor of the method (Callback based, promise based,
/// raw httpOperationResponse based) to be documented.</param>
/// <param name = "language" > Describes the language in which the method needs to be documented (Javascript (default), TypeScript).</param>
/// <returns></returns>
public string GenerateMethodDocumentation(MethodFlavor flavor, Language language = Language.JavaScript)
{
var template = new Core.Template<Object>();
var builder = new IndentedStringBuilder(" ");
builder.AppendLine("/**");
if (!String.IsNullOrEmpty(Summary))
{
builder.AppendLine(template.WrapComment(" * ", "@summary " + Summary)).AppendLine(" *");
}
if (!String.IsNullOrEmpty(Description))
{
builder.AppendLine(template.WrapComment(" * ", Description)).AppendLine(" *");
}
foreach (var parameter in DocumentationParameters)
{
var paramDoc = $"@param {{{GetParameterDocumentationType(parameter)}}} {GetParameterDocumentationName(parameter)} {parameter.Documentation}";
builder.AppendLine(ConstructParameterDocumentation(template.WrapComment(" * ", paramDoc)));
}
if (flavor == MethodFlavor.HttpOperationResponse)
{
var errorType = (language == Language.JavaScript) ? "Error" : "Error|ServiceError";
builder.AppendLine(" * @returns {Promise} A promise is returned").AppendLine(" *")
.AppendLine(" * @resolve {{HttpOperationResponse<{0}>}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {{{0}}} - The error object.", errorType);
}
else
{
if (language == Language.JavaScript)
{
if (flavor == MethodFlavor.Callback)
{
builder.AppendLine(template.WrapComment(" * ", " @param {function} callback - The callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {function} callback(err, result, request, response)")).AppendLine(" *");
}
else if (flavor == MethodFlavor.Promise)
{
builder.AppendLine(template.WrapComment(" * ", " @param {function} [optionalCallback] - The optional callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {function|Promise} If a callback was passed as the last parameter " +
"then it returns the callback else returns a Promise.")).AppendLine(" *")
.AppendLine(" * {Promise} A promise is returned").AppendLine(" *")
.AppendLine(" * @resolve {{{0}}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {Error} - The error object.").AppendLine(" *")
.AppendLine(template.WrapComment(" * ", "{function} optionalCallback(err, result, request, response)")).AppendLine(" *");
}
builder.AppendLine(" * {Error} err - The Error object if an error occurred, null otherwise.").AppendLine(" *")
.AppendLine(" * {{{0}}} [result] - The deserialized result object if an error did not occur.", DocumentReturnTypeString)
.AppendLine(template.WrapComment(" * ", ReturnTypeInfo)).AppendLine(" *")
.AppendLine(" * {object} [request] - The HTTP Request object if an error did not occur.").AppendLine(" *")
.AppendLine(" * {stream} [response] - The HTTP Response stream if an error did not occur.");
}
else
{
if (flavor == MethodFlavor.Callback)
{
builder.AppendLine(template.WrapComment(" * ", " @param {ServiceCallback} callback - The callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {ServiceCallback} callback(err, result, request, response)")).AppendLine(" *");
}
else if (flavor == MethodFlavor.Promise)
{
builder.AppendLine(template.WrapComment(" * ", " @param {ServiceCallback} [optionalCallback] - The optional callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {ServiceCallback|Promise} If a callback was passed as the last parameter " +
"then it returns the callback else returns a Promise.")).AppendLine(" *")
.AppendLine(" * {Promise} A promise is returned.").AppendLine(" *")
.AppendLine(" * @resolve {{{0}}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {Error|ServiceError} - The error object.").AppendLine(" *")
.AppendLine(template.WrapComment(" * ", "{ServiceCallback} optionalCallback(err, result, request, response)")).AppendLine(" *");
}
builder.AppendLine(" * {Error|ServiceError} err - The Error object if an error occurred, null otherwise.").AppendLine(" *")
.AppendLine(" * {{{0}}} [result] - The deserialized result object if an error did not occur.", ReturnTypeString)
.AppendLine(template.WrapComment(" * ", ReturnTypeInfo)).AppendLine(" *")
.AppendLine(" * {WebResource} [request] - The HTTP Request object if an error did not occur.").AppendLine(" *")
.AppendLine(" * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.");
}
}
builder.AppendLine(" */");
return builder.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
namespace RefactorThis.GraphDiff.Internal.Graph
{
internal class GraphNode
{
#region Fields, Properties Constructors
public GraphNode Parent { get; private set; }
public Stack<GraphNode> Members { get; private set; }
public bool? AllowDelete { get; set; }
protected readonly PropertyInfo Accessor;
protected string IncludeString
{
get
{
var ownIncludeString = Accessor != null ? Accessor.Name : null;
return Parent != null && Parent.IncludeString != null
? Parent.IncludeString + "." + ownIncludeString
: ownIncludeString;
}
}
public GraphNode()
{
Members = new Stack<GraphNode>();
}
protected GraphNode(GraphNode parent, PropertyInfo accessor)
{
Accessor = accessor;
Members = new Stack<GraphNode>();
Parent = parent;
}
#endregion
// overridden by different implementations
public virtual void Update<T>(DbContext context, T persisted, T updating) where T : class, new()
{
UpdateValuesWithConcurrencyCheck(context, updating, persisted);
// Foreach branch perform recursive update
foreach (var member in Members)
{
member.Update(context, persisted, updating);
}
}
protected T GetValue<T>(object instance)
{
return (T)Accessor.GetValue(instance, null);
}
protected void SetValue(object instance, object value)
{
Accessor.SetValue(instance, value, null);
}
protected static EntityKey CreateEntityKey(IObjectContextAdapter context, object entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
return context.ObjectContext.CreateEntityKey(context.GetEntitySetName(entity.GetType()), entity);
}
internal void GetIncludeStrings(DbContext context, List<string> includeStrings)
{
var ownIncludeString = IncludeString;
if (!string.IsNullOrEmpty(ownIncludeString))
{
includeStrings.Add(ownIncludeString);
}
includeStrings.AddRange(GetRequiredNavigationPropertyIncludes(context));
foreach (var member in Members)
{
member.GetIncludeStrings(context, includeStrings);
}
}
protected virtual IEnumerable<string> GetRequiredNavigationPropertyIncludes(DbContext context)
{
return new string[0];
}
protected static IEnumerable<string> GetRequiredNavigationPropertyIncludes(DbContext context, Type entityType, string ownIncludeString)
{
return context.GetRequiredNavigationPropertiesForType(entityType)
.Select(navigationProperty => ownIncludeString + "." + navigationProperty.Name);
}
protected static void AttachCyclicNavigationProperty(IObjectContextAdapter context, object parent, object child)
{
if (parent == null || child == null) return;
var parentType = ObjectContext.GetObjectType(parent.GetType());
var childType = ObjectContext.GetObjectType(child.GetType());
var navigationProperties = context.GetNavigationPropertiesForType(childType);
var parentNavigationProperty = navigationProperties
.Where(navigation => navigation.TypeUsage.EdmType.Name == parentType.Name)
.Select(navigation => childType.GetProperty(navigation.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
.FirstOrDefault();
if (parentNavigationProperty != null)
parentNavigationProperty.SetValue(child, parent, null);
}
protected static void UpdateValuesWithConcurrencyCheck<T>(DbContext context, T from, T to) where T : class
{
if (context.Entry(to).State != EntityState.Added)
{
EnsureConcurrency(context, from, to);
}
context.Entry(to).CurrentValues.SetValues(from);
}
protected static object AttachAndReloadAssociatedEntity(DbContext context, object entity)
{
var localCopy = FindLocalByKey(context, entity);
if (localCopy != null) return localCopy;
if (context.Entry(entity).State == EntityState.Detached)
{
var entityType = ObjectContext.GetObjectType(entity.GetType());
var instance = CreateEmptyEntityWithKey(context, entity);
context.Set(entityType).Attach(instance);
context.Entry(instance).Reload();
AttachRequiredNavigationProperties(context, entity, instance);
return instance;
}
if (GraphDiffConfiguration.ReloadAssociatedEntitiesWhenAttached)
{
context.Entry(entity).Reload();
}
return entity;
}
private static object FindLocalByKey(DbContext context, object entity)
{
var eType = ObjectContext.GetObjectType(entity.GetType());
return context.Set(eType).Local.OfType<object>().FirstOrDefault(local => IsKeyIdentical(context, local, entity));
}
protected static void AttachRequiredNavigationProperties(DbContext context, object updating, object persisted)
{
var entityType = ObjectContext.GetObjectType(updating.GetType());
foreach (var navigationProperty in context.GetRequiredNavigationPropertiesForType(updating.GetType()))
{
var navigationPropertyInfo = entityType.GetProperty(navigationProperty.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var associatedEntity = navigationPropertyInfo.GetValue(updating, null);
if (associatedEntity != null)
{
associatedEntity = FindEntityByKey(context, associatedEntity);
}
navigationPropertyInfo.SetValue(persisted, associatedEntity, null);
}
}
private static object FindEntityByKey(DbContext context, object associatedEntity)
{
var associatedEntityType = ObjectContext.GetObjectType(associatedEntity.GetType());
var keyFields = context.GetPrimaryKeyFieldsFor(associatedEntityType);
var keys = keyFields.Select(key => key.GetValue(associatedEntity, null)).ToArray();
return context.Set(associatedEntityType).Find(keys);
}
protected static object CreateEmptyEntityWithKey(IObjectContextAdapter context, object entity)
{
var instance = Activator.CreateInstance(entity.GetType());
CopyPrimaryKeyFields(context, entity, instance);
return instance;
}
private static void CopyPrimaryKeyFields(IObjectContextAdapter context, object from, object to)
{
var keyProperties = context.GetPrimaryKeyFieldsFor(from.GetType()).ToList();
foreach (var keyProperty in keyProperties)
keyProperty.SetValue(to, keyProperty.GetValue(from, null), null);
}
protected static bool IsKeyIdentical(DbContext context, object newValue, object dbValue)
{
if (newValue == null || dbValue == null) return false;
return CreateEntityKey(context, newValue) == CreateEntityKey(context, dbValue);
}
private static void EnsureConcurrency<T>(IObjectContextAdapter db, T entity1, T entity2)
{
// get concurrency properties of T
var entityType = ObjectContext.GetObjectType(entity1.GetType());
var metadata = db.ObjectContext.MetadataWorkspace;
var objType = metadata.GetEntityTypeByType(entityType);
// need internal string, code smells bad.. any better way to do this?
var cTypeName = (string)objType.GetType()
.GetProperty("CSpaceTypeName", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(objType, null);
var conceptualType = metadata.GetItems<EntityType>(DataSpace.CSpace).Single(p => p.FullName == cTypeName);
var concurrencyProperties = conceptualType.Members
.Where(member => member.TypeUsage.Facets.Any(facet => facet.Name == "ConcurrencyMode" && (ConcurrencyMode)facet.Value == ConcurrencyMode.Fixed))
.Select(member => entityType.GetProperty(member.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
.ToList();
// Check if concurrency properties are equal
// TODO EF should do this automatically should it not?
foreach (var concurrencyProp in concurrencyProperties)
{
// if is byte[] use array comparison, else equals().
var type = concurrencyProp.PropertyType;
var obj1 = concurrencyProp.GetValue(entity1, null);
var obj2 = concurrencyProp.GetValue(entity2, null);
if (
(obj1 == null || obj2 == null) ||
(type == typeof (byte[]) && !((byte[]) obj1).SequenceEqual((byte[]) obj2)) ||
(type != typeof (byte[]) && !obj1.Equals(obj2))
)
{
throw new DbUpdateConcurrencyException(String.Format("{0} failed optimistic concurrency", concurrencyProp.Name));
}
}
}
}
}
| |
using System;
using System.Data.Entity.Migrations;
namespace MOE.Common.Migrations
{
public partial class DataAggregation : DbMigration
{
public override void Up()
{
//Historical Configuration Migration
DropForeignKey("dbo.ActionLogs", "SignalId", "dbo.Signals");
DropForeignKey("dbo.ApproachRouteDetail", "ApproachID", "dbo.Approaches");
DropForeignKey("dbo.SPMWatchDogErrorEvents", "SignalID", "dbo.Signals");
DropForeignKey("dbo.MetricComments", "SignalID", "dbo.Signals");
DropForeignKey("dbo.Approaches", "SignalID", "dbo.Signals");
DropIndex("dbo.ActionLogs", new[] { "SignalID" });
DropIndex("dbo.MetricComments", new[] { "SignalID" });
DropIndex("dbo.Approaches", new[] { "SignalID" });
DropIndex("dbo.ApproachRouteDetail", new[] { "ApproachID" });
DropIndex("dbo.Detectors", "IX_DetectorIDUnique");
DropIndex("dbo.SPMWatchDogErrorEvents", new[] { "SignalID" });
DropPrimaryKey("Signals", "PK_dbo.Signals");
//}
CreateTable(
"dbo.VersionActions",
c => new
{
ID = c.Int(false),
Description = c.String()
})
.PrimaryKey(t => t.ID);
Sql("Insert into VersionActions(ID, Description) values (1, 'New')");
Sql("Insert into VersionActions(ID, Description) values (2, 'Edit')");
Sql("Insert into VersionActions(ID, Description) values (3, 'Delete')");
Sql("Insert into VersionActions(ID, Description) values (4, 'New Version')");
Sql("Insert into VersionActions(ID, Description) values (10, 'Initial')");
AddColumn("dbo.MetricComments", "VersionID", c => c.Int(nullable: false));
AddColumn("dbo.Signals", "VersionID", c => c.Int(nullable: false, identity: true));
AddColumn("dbo.Signals", "VersionActionId", c => c.Int(nullable: false, defaultValue:10));
AddColumn("dbo.Signals", "Note", c => c.String(nullable: false, defaultValue: "Initial"));
AddColumn("dbo.Signals", "Start", c => c.DateTime(nullable: false ));
AddColumn("dbo.Approaches", "VersionID", c => c.Int(nullable: false));
AlterColumn("dbo.ActionLogs", "SignalID", c => c.String(nullable: false));
AlterColumn("dbo.MetricComments", "SignalID", c => c.String());
AlterColumn("dbo.Approaches", "SignalID", c => c.String());
AlterColumn("dbo.SPMWatchDogErrorEvents", "SignalID", c => c.String(nullable: false));
AddPrimaryKey("dbo.Signals", "VersionID");
CreateIndex("dbo.MetricComments", "VersionID");
CreateIndex("dbo.Signals", "VersionActionId");
CreateIndex("dbo.Approaches", "VersionID");
//AddForeignKey("dbo.Signals", "VersionActionId", "dbo.VersionActions", "ID", cascadeDelete: true);
//AddForeignKey("dbo.MetricComments", "VersionID", "dbo.Signals", "VersionID", cascadeDelete: true);
//AddForeignKey("dbo.Approaches", "VersionID", "dbo.Signals", "VersionID", cascadeDelete: true);
DropColumn("dbo.ApproachRouteDetail", "ApproachOrder");
DropColumn("dbo.ApproachRouteDetail", "ApproachID");
DropTable("dbo.SignalWithDetections");
//This only exists on UDOT Database
//DropTable("dbo.ApproachRoute");
DropTable("dbo.ApproachRouteDetail");
//Original Data Aggregation Migration
CreateTable(
"dbo.ApproachCycleAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
ApproachId = c.Int(false),
RedTime = c.Double(false),
YellowTime = c.Double(false),
GreenTime = c.Double(false),
TotalCycles = c.Int(false),
PedActuations = c.Int(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Approaches", t => t.ApproachId, false)
.Index(t => t.ApproachId);
CreateTable(
"dbo.ApproachPcdAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
ApproachId = c.Int(false),
ArrivalsOnGreen = c.Int(false),
ArrivalsOnRed = c.Int(false),
ArrivalsOnYellow = c.Int(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Approaches", t => t.ApproachId, false)
.Index(t => t.ApproachId);
CreateTable(
"dbo.ApproachSpeedAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
ApproachId = c.Int(false),
SummedSpeed = c.Double(false),
SpeedVolume = c.Double(false),
Speed85Th = c.Double(false),
Speed15Th = c.Double(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Approaches", t => t.ApproachId, false)
.Index(t => t.ApproachId);
CreateTable(
"dbo.ApproachSplitFailAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
ApproachId = c.Int(false),
SplitFailures = c.Int(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Approaches", t => t.ApproachId, false)
.Index(t => t.ApproachId);
CreateTable(
"dbo.ApproachYellowRedActivationAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
ApproachId = c.Int(false),
SevereRedLightViolations = c.Int(false),
TotalRedLightViolations = c.Int(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Approaches", t => t.ApproachId, false)
.Index(t => t.ApproachId);
CreateTable(
"dbo.DetectorAggregations",
c => new
{
Id = c.Int(false, true),
BinStartTime = c.DateTime(false),
DetectorId = c.String(false, 10),
Volume = c.Int(false)
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Detectors", t => t.Id)
.Index(t => t.Id);
CreateTable(
"dbo.PreemptionAggregations",
c => new
{
ID = c.Int(false, true),
BinStartTime = c.DateTime(false),
SignalID = c.String(false, 10),
PreemptNumber = c.Int(false),
PreemptRequests = c.Int(false),
PreemptServices = c.Int(false),
Signal_VersionID = c.Int()
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Signals", t => t.Signal_VersionID)
.Index(t => t.Signal_VersionID);
CreateTable(
"dbo.PriorityAggregations",
c => new
{
ID = c.Int(false, true),
BinStartTime = c.DateTime(false),
SignalID = c.String(false, 10),
PriorityNumber = c.Int(false),
TotalCycles = c.Int(false),
PriorityRequests = c.Int(false),
PriorityServiceEarlyGreen = c.Int(false),
PriorityServiceExtendedGreen = c.Int(false),
Signal_VersionID = c.Int()
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Signals", t => t.Signal_VersionID)
.Index(t => t.Signal_VersionID);
CreateTable(
"dbo.SignalAggregations",
c => new
{
ID = c.Int(false, true),
BinStartTime = c.DateTime(false),
VersionlID = c.Int(false),
TotalCycles = c.Int(false),
AddCyclesInTransition = c.Int(false),
SubtractCyclesInTransition = c.Int(false),
DwellCyclesInTransition = c.Int(false)
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Signals", t => t.VersionlID, false)
.Index(t => t.VersionlID);
DropTable("dbo.Archived_Metrics");
}
public override void Down()
{
CreateTable(
"dbo.Archived_Metrics",
c => new
{
Timestamp = c.DateTime(false),
DetectorID = c.String(false, 50, unicode: false),
BinSize = c.Int(false),
Volume = c.Int(),
speed = c.Int(),
delay = c.Int(),
AoR = c.Int(),
SpeedHits = c.Int(),
BinGreenTime = c.Int()
})
.PrimaryKey(t => new {t.Timestamp, t.DetectorID, t.BinSize});
DropForeignKey("dbo.SignalAggregations", "VersionlID", "dbo.Signals");
DropForeignKey("dbo.PriorityAggregations", "Signal_VersionID", "dbo.Signals");
DropForeignKey("dbo.PreemptionAggregations", "Signal_VersionID", "dbo.Signals");
DropForeignKey("dbo.DetectorAggregations", "Id", "dbo.Detectors");
DropForeignKey("dbo.ApproachYellowRedActivationAggregations", "ApproachId", "dbo.Approaches");
DropForeignKey("dbo.ApproachSplitFailAggregations", "ApproachId", "dbo.Approaches");
DropForeignKey("dbo.ApproachSpeedAggregations", "ApproachId", "dbo.Approaches");
DropForeignKey("dbo.ApproachPcdAggregations", "ApproachId", "dbo.Approaches");
DropForeignKey("dbo.ApproachCycleAggregations", "ApproachId", "dbo.Approaches");
DropIndex("dbo.SignalAggregations", new[] {"VersionlID"});
DropIndex("dbo.PriorityAggregations", new[] {"Signal_VersionID"});
DropIndex("dbo.PreemptionAggregations", new[] {"Signal_VersionID"});
DropIndex("dbo.DetectorAggregations", new[] {"Id"});
DropIndex("dbo.ApproachYellowRedActivationAggregations", new[] {"ApproachId"});
DropIndex("dbo.ApproachSplitFailAggregations", new[] {"ApproachId"});
DropIndex("dbo.ApproachSpeedAggregations", new[] {"ApproachId"});
DropIndex("dbo.ApproachPcdAggregations", new[] {"ApproachId"});
DropIndex("dbo.ApproachCycleAggregations", new[] {"ApproachId"});
DropTable("dbo.SignalAggregations");
DropTable("dbo.PriorityAggregations");
DropTable("dbo.PreemptionAggregations");
DropTable("dbo.DetectorAggregations");
DropTable("dbo.ApproachYellowRedActivationAggregations");
DropTable("dbo.ApproachSplitFailAggregations");
DropTable("dbo.ApproachSpeedAggregations");
DropTable("dbo.ApproachPcdAggregations");
DropTable("dbo.ApproachCycleAggregations");
//Historical Configuration Migration
CreateTable(
"dbo.SignalWithDetections",
c => new
{
SignalID = c.String(false, 10),
DetectionTypeID = c.Int(false),
PrimaryName = c.String(),
Secondary_Name = c.String(),
Latitude = c.String(),
Longitude = c.String(),
Region = c.String()
})
.PrimaryKey(t => new {t.SignalID, t.DetectionTypeID});
AddColumn("dbo.ApproachRouteDetail", "ApproachID", c => c.Int(false));
AddColumn("dbo.ApproachRouteDetail", "ApproachOrder", c => c.Int(false));
DropForeignKey("dbo.Approaches", "VersionID", "dbo.Signals");
DropForeignKey("dbo.MetricComments", "VersionID", "dbo.Signals");
DropForeignKey("dbo.Signals", "VersionActionId", "dbo.VersionActions");
DropForeignKey("dbo.ApproachRouteDetail", "DirectionType2_DirectionTypeID", "dbo.DirectionTypes");
DropForeignKey("dbo.ApproachRouteDetail", "DirectionType1_DirectionTypeID", "dbo.DirectionTypes");
DropIndex("dbo.Approaches", new[] { "VersionID" });
DropIndex("dbo.Signals", new[] { "VersionActionId" });
DropIndex("dbo.MetricComments", new[] { "VersionID" });
DropIndex("dbo.ApproachRouteDetail", new[] { "DirectionType2_DirectionTypeID" });
DropIndex("dbo.ApproachRouteDetail", new[] { "DirectionType1_DirectionTypeID" });
AlterColumn("dbo.SPMWatchDogErrorEvents", "SignalID", c => c.String(nullable: false, maxLength: 10));
AlterColumn("dbo.Approaches", "SignalID", c => c.String(nullable: false, maxLength: 10));
AlterColumn("dbo.MetricComments", "SignalID", c => c.String(nullable: false, maxLength: 10));
AlterColumn("dbo.ActionLogs", "SignalID", c => c.String(nullable: false, maxLength: 10));
DropColumn("dbo.Approaches", "VersionID");
DropColumn("dbo.Signals", "Start");
DropColumn("dbo.Signals", "Note");
DropColumn("dbo.Signals", "VersionActionId");
DropColumn("dbo.Signals", "VersionID");
DropColumn("dbo.MetricComments", "VersionID");
DropTable("dbo.VersionActions");
AddPrimaryKey("dbo.Signals", "SignalID");
CreateIndex("dbo.SPMWatchDogErrorEvents", "SignalID");
CreateIndex("dbo.Detectors", "DetectorID", unique: true, name: "IX_DetectorIDUnique");
CreateIndex("dbo.ApproachRouteDetail", "ApproachID");
CreateIndex("dbo.Approaches", "SignalID");
CreateIndex("dbo.MetricComments", "SignalID");
CreateIndex("dbo.ActionLogs", "SignalID");
AddForeignKey("dbo.Approaches", "SignalID", "dbo.Signals", "SignalID", cascadeDelete: true);
AddForeignKey("dbo.MetricComments", "SignalID", "dbo.Signals", "SignalID", cascadeDelete: true);
AddForeignKey("dbo.SPMWatchDogErrorEvents", "SignalID", "dbo.Signals", "SignalID", cascadeDelete: true);
AddForeignKey("dbo.ApproachRouteDetail", "ApproachID", "dbo.Approaches", "ApproachID", cascadeDelete: true);
AddForeignKey("dbo.ActionLogs", "SignalID", "dbo.Signals", "SignalID");
}
}
}
//DropForeignKey("dbo.SPMWatchDogErrorEvents", "SignalID", "dbo.Signals");
//DropForeignKey("dbo.MetricComments", "SignalID", "dbo.Signals");
//DropForeignKey("dbo.Approaches", "SignalID", "dbo.Signals");
//DropIndex("dbo.ActionLogs", new[] {"SignalID"});
//DropIndex("dbo.MetricComments", new[] {"SignalID"});
//DropIndex("dbo.Approaches", new[] {"SignalID"});
//DropIndex("dbo.ApproachRouteDetail", new[] {"ApproachID"});
//DropIndex("dbo.SPMWatchDogErrorEvents", new[] {"SignalID"});
//DropPrimaryKey("dbo.Signals");
////try
////{
//// DropPrimaryKey("dbo.Signals", "PK_Signals");
////}
////catch (Exception e)
////{
//// DropPrimaryKey("dbo.Signals", "PK_dbo._Signals");
////}
////finally
////{
//Sql("Insert into VersionActions(ID, Description) values (10, 'Initial')");
//AddColumn("dbo.MetricComments", "VersionID", c => c.Int(false));
//AddColumn("dbo.Signals", "VersionID", c => c.Int(false, true));
//AddColumn("dbo.Signals", "VersionActionId", c => c.Int(false, defaultValue: 10));
//AddColumn("dbo.Signals", "Note", c => c.String(false, defaultValue: "Initial"));
//AddColumn("dbo.Signals", "Start", c => c.DateTime(false));
//AddColumn("dbo.Approaches", "VersionID", c => c.Int(false));
//AlterColumn("dbo.ActionLogs", "SignalID", c => c.String(false));
//AlterColumn("dbo.MetricComments", "SignalID", c => c.String());
//AlterColumn("dbo.Approaches", "SignalID", c => c.String());
//AlterColumn("dbo.SPMWatchDogErrorEvents", "SignalID", c => c.String(false));
//DropIndex("dbo.Approaches", new[] {"VersionID"});
//DropIndex("dbo.Signals", new[] {"VersionActionId"});
//DropIndex("dbo.MetricComments", new[] {"VersionID"});
//DropIndex("dbo.ApproachRouteDetail", new[] {"DirectionType2_DirectionTypeID"});
//DropIndex("dbo.ApproachRouteDetail", new[] {"DirectionType1_DirectionTypeID"});
//AlterColumn("dbo.SPMWatchDogErrorEvents", "SignalID", c => c.String(false, 10));
//AlterColumn("dbo.Approaches", "SignalID", c => c.String(false, 10));
//AlterColumn("dbo.MetricComments", "SignalID", c => c.String(false, 10));
//AlterColumn("dbo.ActionLogs", "SignalID", c => c.String(false, 10));
//AddPrimaryKey("dbo.Signals", "SignalID");
//CreateIndex("dbo.SPMWatchDogErrorEvents", "SignalID");
//CreateIndex("dbo.Detectors", "DetectorID", true, "IX_DetectorIDUnique");
//CreateIndex("dbo.Approaches", "SignalID");
//CreateIndex("dbo.MetricComments", "SignalID");
//CreateIndex("dbo.ActionLogs", "SignalID");
//AddForeignKey("dbo.Approaches", "SignalID", "dbo.Signals", "SignalID", true);
//AddForeignKey("dbo.MetricComments", "SignalID", "dbo.Signals", "SignalID", true);
//AddForeignKey("dbo.SPMWatchDogErrorEvents", "SignalID", "dbo.Signals", "SignalID", true);
//AddForeignKey("dbo.ApproachRouteDetail", "ApproachID", "dbo.Approaches", "ApproachID", true);
//AddForeignKey("dbo.ActionLogs", "SignalID", "dbo.Signals", "SignalID");
| |
// 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.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
namespace System.Data.SqlClient
{
sealed internal class SqlStream : Stream
{
private SqlDataReader _reader; // reader we will stream off
private int _columnOrdinal;
private long _bytesCol;
private int _bom;
private byte[] _bufferedData;
private bool _processAllRows;
private bool _advanceReader;
private bool _readFirstRow = false;
private bool _endOfColumn = false;
internal SqlStream(SqlDataReader reader, bool addByteOrderMark, bool processAllRows) :
this(0, reader, addByteOrderMark, processAllRows, true)
{
}
internal SqlStream(int columnOrdinal, SqlDataReader reader, bool addByteOrderMark, bool processAllRows, bool advanceReader)
{
_columnOrdinal = columnOrdinal;
_reader = reader;
_bom = addByteOrderMark ? 0xfeff : 0;
_processAllRows = processAllRows;
_advanceReader = advanceReader;
}
override public bool CanRead
{
get
{
return true;
}
}
override public bool CanSeek
{
get
{
return false;
}
}
override public bool CanWrite
{
get
{
return false;
}
}
override public long Length
{
get
{
throw ADP.NotSupported();
}
}
override public long Position
{
get
{
throw ADP.NotSupported();
}
set
{
throw ADP.NotSupported();
}
}
override protected void Dispose(bool disposing)
{
try
{
if (disposing && _advanceReader && _reader != null && !_reader.IsClosed)
{
_reader.Close();
}
_reader = null;
}
finally
{
base.Dispose(disposing);
}
}
override public void Flush()
{
throw ADP.NotSupported();
}
override public int Read(byte[] buffer, int offset, int count)
{
int intCount = 0;
int cBufferedData = 0;
if ((null == _reader))
{
throw ADP.StreamClosed();
}
if (null == buffer)
{
throw ADP.ArgumentNull(nameof(buffer));
}
if ((offset < 0) || (count < 0))
{
throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? nameof(offset) : nameof(count)));
}
if (buffer.Length - offset < count)
{
throw ADP.ArgumentOutOfRange(nameof(count));
}
// Need to find out if we should add byte order mark or not.
// We need to add this if we are getting ntext xml, not if we are getting binary xml
// Binary Xml always begins with the bytes 0xDF and 0xFF
// If we aren't getting these, then we are getting unicode xml
if (_bom > 0)
{
// Read and buffer the first two bytes
_bufferedData = new byte[2];
cBufferedData = ReadBytes(_bufferedData, 0, 2);
// Check to se if we should add the byte order mark
if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF)))
{
_bom = 0;
}
while (count > 0)
{
if (_bom > 0)
{
buffer[offset] = (byte)_bom;
_bom >>= 8;
offset++;
count--;
intCount++;
}
else
{
break;
}
}
}
if (cBufferedData > 0)
{
while (count > 0)
{
buffer[offset++] = _bufferedData[0];
intCount++;
count--;
if ((cBufferedData > 1) && (count > 0))
{
buffer[offset++] = _bufferedData[1];
intCount++;
count--;
break;
}
}
_bufferedData = null;
}
intCount += ReadBytes(buffer, offset, count);
return intCount;
}
private static bool AdvanceToNextRow(SqlDataReader reader)
{
Debug.Assert(reader != null && !reader.IsClosed);
// this method skips empty result sets
do
{
if (reader.Read())
{
return true;
}
} while (reader.NextResult());
// no more rows
return false;
}
private int ReadBytes(byte[] buffer, int offset, int count)
{
bool gotData = true;
int intCount = 0;
int cb = 0;
if (_reader.IsClosed || _endOfColumn)
{
return 0;
}
try
{
while (count > 0)
{
// if no bytes were read, get the next row
if (_advanceReader && (0 == _bytesCol))
{
gotData = false;
if (_readFirstRow && !_processAllRows)
{
// for XML column, stop processing after the first row
// no op here - reader is closed after the end of this loop
}
else if (AdvanceToNextRow(_reader))
{
_readFirstRow = true;
if (_reader.IsDBNull(_columnOrdinal))
{
// Handle row with DBNULL as empty data
// for XML column, processing is stopped on the next loop since _readFirstRow is true
continue;
}
// the value is not null, read it
gotData = true;
}
// else AdvanceToNextRow has returned false - no more rows or result sets remained, stop processing
}
if (gotData)
{
cb = (int)_reader.GetBytesInternal(_columnOrdinal, _bytesCol, buffer, offset, count);
if (cb < count)
{
_bytesCol = 0;
gotData = false;
if (!_advanceReader)
{
_endOfColumn = true;
}
}
else
{
Debug.Assert(cb == count);
_bytesCol += cb;
}
// we are guaranteed that cb is < Int32.Max since we always pass in count which is of type Int32 to
// our getbytes interface
count -= (int)cb;
offset += (int)cb;
intCount += (int)cb;
}
else
{
break; // no more data available, we are done
}
}
if (!gotData && _advanceReader)
{
_reader.Close(); // Need to close the reader if we are done reading
}
}
catch (Exception e)
{
if (_advanceReader && ADP.IsCatchableExceptionType(e))
{
_reader.Close();
}
throw;
}
return intCount;
}
internal XmlReader ToXmlReader(bool async = false)
{
return SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(this, closeInput: true, async: async);
}
override public long Seek(long offset, SeekOrigin origin)
{
throw ADP.NotSupported();
}
override public void SetLength(long value)
{
throw ADP.NotSupported();
}
override public void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
}
// XmlTextReader does not read all the bytes off the network buffers, so we have to cache it here in the random access
// case. This causes double buffering and is a perf hit, but this is not the high perf way for accessing this type of data.
// In the case of sequential access, we do not have to do any buffering since the XmlTextReader we return can become
// invalid as soon as we move off the current column.
sealed internal class SqlCachedStream : Stream
{
private int _currentPosition; // Position within the current array byte
private int _currentArrayIndex; // Index into the _cachedBytes List
private List<byte[]> _cachedBytes;
private long _totalLength;
// Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
internal SqlCachedStream(SqlCachedBuffer sqlBuf)
{
_cachedBytes = sqlBuf.CachedBytes;
}
override public bool CanRead
{
get
{
return true;
}
}
override public bool CanSeek
{
get
{
return true;
}
}
override public bool CanWrite
{
get
{
return false;
}
}
override public long Length
{
get
{
return TotalLength;
}
}
override public long Position
{
get
{
long pos = 0;
if (_currentArrayIndex > 0)
{
for (int ii = 0; ii < _currentArrayIndex; ii++)
{
pos += _cachedBytes[ii].Length;
}
}
pos += _currentPosition;
return pos;
}
set
{
if (null == _cachedBytes)
{
throw ADP.StreamClosed(ADP.ParameterSetPosition);
}
SetInternalPosition(value, ADP.ParameterSetPosition);
}
}
override protected void Dispose(bool disposing)
{
try
{
if (disposing && _cachedBytes != null)
_cachedBytes.Clear();
_cachedBytes = null;
_currentPosition = 0;
_currentArrayIndex = 0;
_totalLength = 0;
}
finally
{
base.Dispose(disposing);
}
}
override public void Flush()
{
throw ADP.NotSupported();
}
override public int Read(byte[] buffer, int offset, int count)
{
int cb;
int intCount = 0;
if (null == _cachedBytes)
{
throw ADP.StreamClosed();
}
if (null == buffer)
{
throw ADP.ArgumentNull(nameof(buffer));
}
if ((offset < 0) || (count < 0))
{
throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? nameof(offset) : nameof(count)));
}
if (buffer.Length - offset < count)
{
throw ADP.ArgumentOutOfRange(nameof(count));
}
if (_cachedBytes.Count <= _currentArrayIndex)
{
return 0; // Everything is read!
}
while (count > 0)
{
if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition)
{
_currentArrayIndex++; // We are done reading this chunk, go to next
if (_cachedBytes.Count > _currentArrayIndex)
{
_currentPosition = 0;
}
else
{
break;
}
}
cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition;
if (cb > count)
cb = count;
Buffer.BlockCopy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb);
_currentPosition += cb;
count -= (int)cb;
offset += (int)cb;
intCount += (int)cb;
}
return intCount;
}
override public long Seek(long offset, SeekOrigin origin)
{
long pos = 0;
if (null == _cachedBytes)
{
throw ADP.StreamClosed();
}
switch (origin)
{
case SeekOrigin.Begin:
SetInternalPosition(offset, nameof(offset));
break;
case SeekOrigin.Current:
pos = offset + Position;
SetInternalPosition(pos, nameof(offset));
break;
case SeekOrigin.End:
pos = TotalLength + offset;
SetInternalPosition(pos, nameof(offset));
break;
default:
throw ADP.InvalidSeekOrigin(nameof(offset));
}
return pos;
}
override public void SetLength(long value)
{
throw ADP.NotSupported();
}
override public void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
private void SetInternalPosition(long lPos, string argumentName)
{
long pos = lPos;
if (pos < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
for (int ii = 0; ii < _cachedBytes.Count; ii++)
{
if (pos > _cachedBytes[ii].Length)
{
pos -= _cachedBytes[ii].Length;
}
else
{
_currentArrayIndex = ii;
_currentPosition = (int)pos;
return;
}
}
if (pos > 0)
throw new ArgumentOutOfRangeException(argumentName);
}
private long TotalLength
{
get
{
if ((_totalLength == 0) && (_cachedBytes != null))
{
long pos = 0;
for (int ii = 0; ii < _cachedBytes.Count; ii++)
{
pos += _cachedBytes[ii].Length;
}
_totalLength = pos;
}
return _totalLength;
}
}
}
sealed internal class SqlStreamingXml
{
private int _columnOrdinal;
private SqlDataReader _reader;
private XmlReader _xmlReader;
private XmlWriter _xmlWriter;
private StringWriter _strWriter;
private long _charsRemoved;
public SqlStreamingXml(int i, SqlDataReader reader)
{
_columnOrdinal = i;
_reader = reader;
}
public void Close()
{
((IDisposable)_xmlWriter).Dispose();
((IDisposable)_xmlReader).Dispose();
_reader = null;
_xmlReader = null;
_xmlWriter = null;
_strWriter = null;
}
public int ColumnOrdinal
{
get
{
return _columnOrdinal;
}
}
public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length)
{
if (_xmlReader == null)
{
SqlStream sqlStream = new SqlStream(_columnOrdinal, _reader, true /* addByteOrderMark */, false /* processAllRows*/, false /*advanceReader*/);
_xmlReader = sqlStream.ToXmlReader();
_strWriter = new StringWriter((System.IFormatProvider)null);
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.CloseOutput = true; // close the memory stream when done
writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
_xmlWriter = XmlWriter.Create(_strWriter, writerSettings);
}
int charsToSkip = 0;
int cnt = 0;
if (dataIndex < _charsRemoved)
{
throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, nameof(GetChars));
}
else if (dataIndex > _charsRemoved)
{
charsToSkip = (int)(dataIndex - _charsRemoved);
}
// If buffer parameter is null, we have to return -1 since there is no way for us to know the
// total size up front without reading and converting the XML.
if (buffer == null)
{
return (long)(-1);
}
StringBuilder strBldr = _strWriter.GetStringBuilder();
while (!_xmlReader.EOF)
{
if (strBldr.Length >= (length + charsToSkip))
{
break;
}
// Can't call _xmlWriter.WriteNode here, since it reads all of the data in before returning the first char.
// Do own implementation of WriteNode instead that reads just enough data to return the required number of chars
//_xmlWriter.WriteNode(_xmlReader, true);
// _xmlWriter.Flush();
WriteXmlElement();
if (charsToSkip > 0)
{
// Aggressively remove the characters we want to skip to avoid growing StringBuilder size too much
cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
strBldr.Remove(0, cnt);
charsToSkip -= cnt;
_charsRemoved += (long)cnt;
}
}
if (charsToSkip > 0)
{
cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
strBldr.Remove(0, cnt);
charsToSkip -= cnt;
_charsRemoved += (long)cnt;
}
if (strBldr.Length == 0)
{
return 0;
}
// At this point charsToSkip must be 0
Debug.Assert(charsToSkip == 0);
cnt = strBldr.Length < length ? strBldr.Length : length;
for (int i = 0; i < cnt; i++)
{
buffer[bufferIndex + i] = strBldr[i];
}
// Remove the characters we have already returned
strBldr.Remove(0, cnt);
_charsRemoved += (long)cnt;
return (long)cnt;
}
// This method duplicates the work of XmlWriter.WriteNode except that it reads one element at a time
// instead of reading the entire node like XmlWriter.
private void WriteXmlElement()
{
if (_xmlReader.EOF)
return;
bool canReadChunk = _xmlReader.CanReadValueChunk;
char[] writeNodeBuffer = null;
// Constants
const int WriteNodeBufferSize = 1024;
_xmlReader.Read();
switch (_xmlReader.NodeType)
{
case XmlNodeType.Element:
_xmlWriter.WriteStartElement(_xmlReader.Prefix, _xmlReader.LocalName, _xmlReader.NamespaceURI);
_xmlWriter.WriteAttributes(_xmlReader, true);
if (_xmlReader.IsEmptyElement)
{
_xmlWriter.WriteEndElement();
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (writeNodeBuffer == null)
{
writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = _xmlReader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
_xmlWriter.WriteChars(writeNodeBuffer, 0, read);
}
}
else
{
_xmlWriter.WriteString(_xmlReader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_xmlWriter.WriteWhitespace(_xmlReader.Value);
break;
case XmlNodeType.CDATA:
_xmlWriter.WriteCData(_xmlReader.Value);
break;
case XmlNodeType.EntityReference:
_xmlWriter.WriteEntityRef(_xmlReader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
_xmlWriter.WriteProcessingInstruction(_xmlReader.Name, _xmlReader.Value);
break;
case XmlNodeType.DocumentType:
_xmlWriter.WriteDocType(_xmlReader.Name, _xmlReader.GetAttribute("PUBLIC"), _xmlReader.GetAttribute("SYSTEM"), _xmlReader.Value);
break;
case XmlNodeType.Comment:
_xmlWriter.WriteComment(_xmlReader.Value);
break;
case XmlNodeType.EndElement:
_xmlWriter.WriteFullEndElement();
break;
}
_xmlWriter.Flush();
}
}
}
| |
// <copyright file="ActivityHelperTest.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace OpenTelemetry.Instrumentation.AspNet.Tests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using OpenTelemetry.Context.Propagation;
using Xunit;
public class ActivityHelperTest : IDisposable
{
private const string TraceParentHeaderName = "traceparent";
private const string TraceStateHeaderName = "tracestate";
private const string BaggageHeaderName = "baggage";
private const string BaggageInHeader = "TestKey1=123,TestKey2=456,TestKey1=789";
private const string TestActivityName = "Activity.Test";
private readonly TextMapPropagator noopTextMapPropagator = new NoopTextMapPropagator();
private ActivityListener activitySourceListener;
public void Dispose()
{
this.activitySourceListener?.Dispose();
}
[Fact]
public void Has_Started_Returns_Correctly()
{
var context = HttpContextHelper.GetFakeHttpContext();
bool result = ActivityHelper.HasStarted(context, out Activity aspNetActivity);
Assert.False(result);
Assert.Null(aspNetActivity);
context.Items[ActivityHelper.ContextKey] = ActivityHelper.StartedButNotSampledObj;
result = ActivityHelper.HasStarted(context, out aspNetActivity);
Assert.True(result);
Assert.Null(aspNetActivity);
Activity activity = new Activity(TestActivityName);
context.Items[ActivityHelper.ContextKey] = new ActivityHelper.ContextHolder { Activity = activity };
result = ActivityHelper.HasStarted(context, out aspNetActivity);
Assert.True(result);
Assert.NotNull(aspNetActivity);
Assert.Equal(activity, aspNetActivity);
}
[Fact]
public async Task Can_Restore_Activity()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
rootActivity.AddTag("k1", "v1");
rootActivity.AddTag("k2", "v2");
Task testTask;
using (ExecutionContext.SuppressFlow())
{
testTask = Task.Run(() =>
{
Task.Yield();
Assert.Null(Activity.Current);
ActivityHelper.RestoreContextIfNeeded(context);
Assert.Same(Activity.Current, rootActivity);
});
}
await testTask.ConfigureAwait(false);
}
[Fact(Skip = "Temporarily disable until stable.")]
public async Task Can_Restore_Baggage()
{
this.EnableListener();
var requestHeaders = new Dictionary<string, string>
{
{ BaggageHeaderName, BaggageInHeader },
};
var context = HttpContextHelper.GetFakeHttpContext(headers: requestHeaders);
using var rootActivity = ActivityHelper.StartAspNetActivity(new CompositeTextMapPropagator(new TextMapPropagator[] { new TraceContextPropagator(), new BaggagePropagator() }), context, null);
rootActivity.AddTag("k1", "v1");
rootActivity.AddTag("k2", "v2");
Task testTask;
using (ExecutionContext.SuppressFlow())
{
testTask = Task.Run(() =>
{
Task.Yield();
Assert.Null(Activity.Current);
Assert.Equal(0, Baggage.Current.Count);
ActivityHelper.RestoreContextIfNeeded(context);
Assert.Same(Activity.Current, rootActivity);
Assert.Empty(rootActivity.Baggage);
Assert.Equal(2, Baggage.Current.Count);
Assert.Equal("789", Baggage.Current.GetBaggage("TestKey1"));
Assert.Equal("456", Baggage.Current.GetBaggage("TestKey2"));
});
}
await testTask.ConfigureAwait(false);
}
[Fact]
public void Can_Stop_Lost_Activity()
{
this.EnableListener(a =>
{
Assert.NotNull(Activity.Current);
Assert.Equal(Activity.Current, a);
Assert.Equal(TelemetryHttpModule.AspNetActivityName, Activity.Current.OperationName);
});
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
rootActivity.AddTag("k1", "v1");
rootActivity.AddTag("k2", "v2");
Activity.Current = null;
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.True(rootActivity.Duration != TimeSpan.Zero);
Assert.Null(Activity.Current);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Do_Not_Restore_Activity_When_There_Is_No_Activity_In_Context()
{
this.EnableListener();
ActivityHelper.RestoreContextIfNeeded(HttpContextHelper.GetFakeHttpContext());
Assert.Null(Activity.Current);
}
[Fact]
public void Do_Not_Restore_Activity_When_It_Is_Not_Lost()
{
this.EnableListener();
var root = new Activity("root").Start();
var context = HttpContextHelper.GetFakeHttpContext();
context.Items[ActivityHelper.ContextKey] = new ActivityHelper.ContextHolder { Activity = root };
ActivityHelper.RestoreContextIfNeeded(context);
Assert.Equal(root, Activity.Current);
}
[Fact]
public void Can_Stop_Activity_Without_AspNetListener_Enabled()
{
var context = HttpContextHelper.GetFakeHttpContext();
var rootActivity = new Activity(TestActivityName);
rootActivity.Start();
context.Items[ActivityHelper.ContextKey] = new ActivityHelper.ContextHolder { Activity = rootActivity };
Thread.Sleep(100);
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.True(rootActivity.Duration != TimeSpan.Zero);
Assert.Null(rootActivity.Parent);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Can_Stop_Activity_With_AspNetListener_Enabled()
{
var context = HttpContextHelper.GetFakeHttpContext();
var rootActivity = new Activity(TestActivityName);
rootActivity.Start();
context.Items[ActivityHelper.ContextKey] = new ActivityHelper.ContextHolder { Activity = rootActivity };
Thread.Sleep(100);
this.EnableListener();
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.True(rootActivity.Duration != TimeSpan.Zero);
Assert.Null(rootActivity.Parent);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Can_Stop_Root_Activity_With_All_Children()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
var child = new Activity("child").Start();
new Activity("grandchild").Start();
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.True(rootActivity.Duration != TimeSpan.Zero);
Assert.True(child.Duration == TimeSpan.Zero);
Assert.Null(rootActivity.Parent);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Can_Stop_Root_While_Child_Is_Current()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
var child = new Activity("child").Start();
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.True(child.Duration == TimeSpan.Zero);
Assert.NotNull(Activity.Current);
Assert.Equal(Activity.Current, child);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public async Task Can_Stop_Root_Activity_If_It_Is_Broken()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var root = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
new Activity("child").Start();
for (int i = 0; i < 2; i++)
{
await Task.Run(() =>
{
// when we enter this method, Current is 'child' activity
Activity.Current.Stop();
// here Current is 'parent', but only in this execution context
});
}
// when we return back here, in the 'parent' execution context
// Current is still 'child' activity - changes in child context (inside Task.Run)
// do not affect 'parent' context in which Task.Run is called.
// But 'child' Activity is stopped, thus consequent calls to Stop will
// not update Current
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, root, context, null);
Assert.True(root.Duration != TimeSpan.Zero);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
Assert.Null(Activity.Current);
}
[Fact]
public void Stop_Root_Activity_With_129_Nesting_Depth()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var root = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
for (int i = 0; i < 129; i++)
{
new Activity("child" + i).Start();
}
// can stop any activity regardless of the stack depth
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, root, context, null);
Assert.True(root.Duration != TimeSpan.Zero);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
Assert.NotNull(Activity.Current);
}
[Fact]
public void Should_Not_Create_RootActivity_If_AspNetListener_Not_Enabled()
{
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
Assert.Null(rootActivity);
Assert.Equal(ActivityHelper.StartedButNotSampledObj, context.Items[ActivityHelper.ContextKey]);
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Should_Not_Create_RootActivity_If_AspNetActivity_Not_Enabled()
{
var context = HttpContextHelper.GetFakeHttpContext();
this.EnableListener(onSample: (context) => ActivitySamplingResult.None);
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
Assert.Null(rootActivity);
Assert.Equal(ActivityHelper.StartedButNotSampledObj, context.Items[ActivityHelper.ContextKey]);
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.Null(context.Items[ActivityHelper.ContextKey]);
}
[Fact]
public void Can_Create_RootActivity_From_W3C_Traceparent()
{
this.EnableListener();
var requestHeaders = new Dictionary<string, string>
{
{ TraceParentHeaderName, "00-0123456789abcdef0123456789abcdef-0123456789abcdef-00" },
};
var context = HttpContextHelper.GetFakeHttpContext(headers: requestHeaders);
using var rootActivity = ActivityHelper.StartAspNetActivity(new TraceContextPropagator(), context, null);
Assert.NotNull(rootActivity);
Assert.Equal(ActivityIdFormat.W3C, rootActivity.IdFormat);
Assert.Equal("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00", rootActivity.ParentId);
Assert.Equal("0123456789abcdef0123456789abcdef", rootActivity.TraceId.ToHexString());
Assert.Equal("0123456789abcdef", rootActivity.ParentSpanId.ToHexString());
Assert.True(rootActivity.Recorded); // note: We're not using a parent-based sampler in this test so the recorded flag of traceparent is ignored.
Assert.Null(rootActivity.TraceStateString);
Assert.Empty(rootActivity.Baggage);
Assert.Equal(0, Baggage.Current.Count);
}
[Fact]
public void Can_Create_RootActivityWithTraceState_From_W3C_TraceContext()
{
this.EnableListener();
var requestHeaders = new Dictionary<string, string>
{
{ TraceParentHeaderName, "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01" },
{ TraceStateHeaderName, "ts1=v1,ts2=v2" },
};
var context = HttpContextHelper.GetFakeHttpContext(headers: requestHeaders);
using var rootActivity = ActivityHelper.StartAspNetActivity(new TraceContextPropagator(), context, null);
Assert.NotNull(rootActivity);
Assert.Equal(ActivityIdFormat.W3C, rootActivity.IdFormat);
Assert.Equal("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01", rootActivity.ParentId);
Assert.Equal("0123456789abcdef0123456789abcdef", rootActivity.TraceId.ToHexString());
Assert.Equal("0123456789abcdef", rootActivity.ParentSpanId.ToHexString());
Assert.True(rootActivity.Recorded);
Assert.Equal("ts1=v1,ts2=v2", rootActivity.TraceStateString);
Assert.Empty(rootActivity.Baggage);
Assert.Equal(0, Baggage.Current.Count);
}
[Fact]
public void Can_Create_RootActivity_From_W3C_Traceparent_With_Baggage()
{
this.EnableListener();
var requestHeaders = new Dictionary<string, string>
{
{ TraceParentHeaderName, "00-0123456789abcdef0123456789abcdef-0123456789abcdef-00" },
{ BaggageHeaderName, BaggageInHeader },
};
var context = HttpContextHelper.GetFakeHttpContext(headers: requestHeaders);
using var rootActivity = ActivityHelper.StartAspNetActivity(new CompositeTextMapPropagator(new TextMapPropagator[] { new TraceContextPropagator(), new BaggagePropagator() }), context, null);
Assert.NotNull(rootActivity);
Assert.Equal(ActivityIdFormat.W3C, rootActivity.IdFormat);
Assert.Equal("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00", rootActivity.ParentId);
Assert.Equal("0123456789abcdef0123456789abcdef", rootActivity.TraceId.ToHexString());
Assert.Equal("0123456789abcdef", rootActivity.ParentSpanId.ToHexString());
Assert.True(rootActivity.Recorded); // note: We're not using a parent-based sampler in this test so the recorded flag of traceparent is ignored.
Assert.Null(rootActivity.TraceStateString);
Assert.Empty(rootActivity.Baggage);
Assert.Equal(2, Baggage.Current.Count);
Assert.Equal("789", Baggage.Current.GetBaggage("TestKey1"));
Assert.Equal("456", Baggage.Current.GetBaggage("TestKey2"));
ActivityHelper.StopAspNetActivity(this.noopTextMapPropagator, rootActivity, context, null);
Assert.Equal(0, Baggage.Current.Count);
}
[Fact]
public void Can_Create_RootActivity_And_Start_Activity()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
Assert.NotNull(rootActivity);
Assert.True(!string.IsNullOrEmpty(rootActivity.Id));
}
[Fact]
public void Can_Create_RootActivity_And_Saved_In_HttContext()
{
this.EnableListener();
var context = HttpContextHelper.GetFakeHttpContext();
using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null);
Assert.NotNull(rootActivity);
Assert.Same(rootActivity, ((ActivityHelper.ContextHolder)context.Items[ActivityHelper.ContextKey])?.Activity);
}
[Fact]
public void Fire_Exception_Events()
{
int callbacksFired = 0;
var context = HttpContextHelper.GetFakeHttpContext();
Activity activity = new Activity(TestActivityName);
ActivityHelper.WriteActivityException(activity, context, new InvalidOperationException(), (a, c, e) => { callbacksFired++; });
ActivityHelper.WriteActivityException(null, context, new InvalidOperationException(), (a, c, e) => { callbacksFired++; });
// Callback should fire only for non-null activity
Assert.Equal(1, callbacksFired);
}
private void EnableListener(Action<Activity> onStarted = null, Action<Activity> onStopped = null, Func<ActivityContext, ActivitySamplingResult> onSample = null)
{
Debug.Assert(this.activitySourceListener == null, "Cannot attach multiple listeners in tests.");
this.activitySourceListener = new ActivityListener
{
ShouldListenTo = (activitySource) => activitySource.Name == TelemetryHttpModule.AspNetSourceName,
ActivityStarted = (a) => onStarted?.Invoke(a),
ActivityStopped = (a) => onStopped?.Invoke(a),
Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
{
if (onSample != null)
{
return onSample(options.Parent);
}
return ActivitySamplingResult.AllDataAndRecorded;
},
};
ActivitySource.AddActivityListener(this.activitySourceListener);
}
private class TestHttpRequest : HttpRequestBase
{
private readonly NameValueCollection headers = new NameValueCollection();
public override NameValueCollection Headers => this.headers;
public override UnvalidatedRequestValuesBase Unvalidated => new TestUnvalidatedRequestValues(this.headers);
}
private class TestUnvalidatedRequestValues : UnvalidatedRequestValuesBase
{
public TestUnvalidatedRequestValues(NameValueCollection headers)
{
this.Headers = headers;
}
public override NameValueCollection Headers { get; }
}
private class TestHttpResponse : HttpResponseBase
{
}
private class TestHttpServerUtility : HttpServerUtilityBase
{
private readonly HttpContextBase context;
public TestHttpServerUtility(HttpContextBase context)
{
this.context = context;
}
public override Exception GetLastError()
{
return this.context.Error;
}
}
private class TestHttpContext : HttpContextBase
{
private readonly Hashtable items;
public TestHttpContext(Exception error = null)
{
this.Server = new TestHttpServerUtility(this);
this.items = new Hashtable();
this.Error = error;
}
public override HttpRequestBase Request { get; } = new TestHttpRequest();
/// <inheritdoc />
public override IDictionary Items => this.items;
public override Exception Error { get; }
public override HttpServerUtilityBase Server { get; }
}
private class NoopTextMapPropagator : TextMapPropagator
{
private static readonly PropagationContext DefaultPropagationContext = default;
public override ISet<string> Fields => null;
public override PropagationContext Extract<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter)
{
return DefaultPropagationContext;
}
public override void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter)
{
}
}
}
}
| |
using System;
using System.Windows.Forms;
using OpenZWaveDotNet;
//using zVirtualScenesAPI;
//using zVirtualScenesCommon;
//using zVirtualScenesCommon.Util;
//using zvsModel; <-- causing the SQL LITE ERRORS
namespace OpenZWavePlugin.Forms
{
public partial class ControllerCommandDlg : Form
{
static private ZWManager m_manager;
static private ControllerCommandDlg _controllercommanddlg;
static private UInt32 _homeid;
static private ManagedControllerStateChangedHandler m_controllerStateChangedHandler = new ManagedControllerStateChangedHandler(MyControllerStateChangedHandler);
static private ZWControllerCommand _zwcontrollercommand;
static private Byte _nodeid;
public ControllerCommandDlg(ZWManager _manager, UInt32 homeId, ZWControllerCommand _op, Byte nodeId)
{
m_manager = _manager;
_homeid = homeId;
_zwcontrollercommand = _op;
_nodeid = nodeId;
_controllercommanddlg = this;
InitializeComponent();
switch (_zwcontrollercommand)
{
case ZWControllerCommand.AddDevice:
{
Text = " - Add Device";
label1.Text = "Press the program button on the Z-Wave device to add it to the network.\nFor security reasons, the PC Z-Wave Controller must be close to the device being added.";
break;
}
case ZWControllerCommand.CreateNewPrimary:
{
Text = " - Create New Primary Controller";
label1.Text = "Put the target controller into receive configuration mode.\nThe PC Z-Wave Controller must be within 2m of the controller that is being made the primary.";
break;
}
case ZWControllerCommand.ReceiveConfiguration:
{
Text = " - Receive Configuration";
label1.Text = "Transfering the network configuration\nfrom another controller.\n\nPlease bring the other controller within 2m of the PC controller and set it to send its network configuration.";
break;
}
case ZWControllerCommand.RemoveDevice:
{
Text = " - Remove Device";
label1.Text = "Press the program button on the Z-Wave device to remove it from the network.\nFor security reasons, the PC Z-Wave Controller must be close to the device being removed.";
break;
}
case ZWControllerCommand.TransferPrimaryRole:
{
Text = " - Transfer Primary Role";
label1.Text = "Transfering the primary role\nto another controller.\n\nPlease bring the new controller within 2m of the PC controller and set it to receive the network configuration.";
break;
}
case ZWControllerCommand.HasNodeFailed:
{
ButtonCancel.Enabled = false;
Text = " - Has Node Failed";
label1.Text = "Testing whether the node has failed.\nThis command cannot be cancelled.";
break;
}
case ZWControllerCommand.RemoveFailedNode:
{
ButtonCancel.Enabled = false;
Text = " - Remove Failed Node";
label1.Text = "Removing the failed node from the controller's list.\nThis command cannot be cancelled.";
break;
}
case ZWControllerCommand.ReplaceFailedNode:
{
ButtonCancel.Enabled = false;
Text = " - Replacing Failed Node";
label1.Text = "Testing the failed node.\nThis command cannot be cancelled.";
break;
}
}
m_manager.OnControllerStateChanged += m_controllerStateChangedHandler;
if (!m_manager.BeginControllerCommand(_homeid, _zwcontrollercommand, false, _nodeid))
{
m_manager.OnControllerStateChanged -= m_controllerStateChangedHandler;
}
}
public static void MyControllerStateChangedHandler(ZWControllerState state)
{
// Handle the controller state notifications here.
bool complete = false;
String dlgText = "";
bool buttonEnabled = true;
switch (state)
{
case ZWControllerState.Waiting:
{
// Display a message to tell the user to press the include button on the controller
if (_zwcontrollercommand == ZWControllerCommand.ReplaceFailedNode)
{
dlgText = "Press the program button on the replacement Z-Wave device to add it to the network.\nFor security reasons, the PC Z-Wave Controller must be close to the device being added.\nThis command cannot be cancelled.";
}
break;
}
case ZWControllerState.InProgress:
{
// Tell the user that the controller has been found and the adding process is in progress.
//Logger.log.Info(_zwcontrollercommand.ToString() + " in progress...", "OPENZWAVE");
dlgText = "Please wait...";
buttonEnabled = false;
break;
}
case ZWControllerState.Completed:
{
// Tell the user that the controller has been successfully added.
// The command is now complete
//Logger.log.Info(_zwcontrollercommand.ToString() + " command complete.", "OPENZWAVE");
dlgText = "Command Completed OK.";
complete = true;
break;
}
case ZWControllerState.Failed:
{
// Tell the user that the controller addition process has failed.
// The command is now complete
//Logger.log.Info(_zwcontrollercommand.ToString() + " command failed.", "OPENZWAVE");
dlgText = "Command Failed.";
complete = true;
break;
}
case ZWControllerState.NodeOK:
{
//Logger.log.Info(_zwcontrollercommand.ToString() + " node has not failed.", "OPENZWAVE");
dlgText = "Node has not failed.";
complete = true;
break;
}
case ZWControllerState.NodeFailed:
{
// Logger.log.Info(_zwcontrollercommand.ToString() + " node has failed.", "OPENZWAVE");
dlgText = "Node has failed.";
complete = true;
break;
}
}
if (dlgText != "")
{
_controllercommanddlg.SetDialogText(dlgText);
}
_controllercommanddlg.SetButtonEnabled(buttonEnabled);
if (complete)
{
_controllercommanddlg.SetButtonText("OK");
// Remove the event handler
m_manager.OnControllerStateChanged -= m_controllerStateChangedHandler;
}
}
private void SetDialogText(String text)
{
if (_controllercommanddlg.InvokeRequired)
{
Invoke(new MethodInvoker(delegate() { SetDialogText(text); }));
}
else
{
_controllercommanddlg.label1.Text = text;
}
}
private void SetButtonText(String text)
{
if (_controllercommanddlg.InvokeRequired)
{
Invoke(new MethodInvoker(delegate() { SetButtonText(text); }));
}
else
{
_controllercommanddlg.ButtonCancel.Text = text;
}
}
private void SetButtonEnabled(bool enabled)
{
if (_controllercommanddlg.InvokeRequired)
{
Invoke(new MethodInvoker(delegate() { SetButtonEnabled(enabled); }));
}
else
{
_controllercommanddlg.ButtonCancel.Enabled = enabled;
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
if (ButtonCancel.Text != "OK")
{
// Remove the event handler
m_manager.OnControllerStateChanged -= m_controllerStateChangedHandler;
// Cancel the operation
if (m_manager.CancelControllerCommand(_homeid))
{
// Logger.log.Info(_zwcontrollercommand.ToString() + " cancelled by user.", "OPENZWAVE");
}
else
{
//Logger.log.Info("Failed to cancel " + _zwcontrollercommand.ToString() + ".", "OPENZWAVE");
}
}
// Close the dialog
Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using JuloUtil;
namespace TurtleIsland {
public class SmartController : Controller {
public bool debugEnabled = false;
public float speedDeviation = 0f;
public float angleDeviation = 0f;
public float thinkingTimeMean = 1.5f;
public float thinkingTimeDeviation = 1f;
public float walkingTime = 1.8f;
public float walkingTimeDeviation = 1f;
public float targetSpeedMinimum = 0.1f;
public float targetSpeedFactor = 0.02f;
public float targetAngleThreshold = 0.1f;
private TurtleIslandGame game;
private Character character;
private enum RobotState { THINKING, WALKING, THINKING2, AIMING, SHOTING, DONE }
private StateMachine<RobotState> machine;
private float currentTime;
private float targetAngle;
private int grenadeTime;
public override void initialize(TurtleIslandGame game, int difficulty) {
this.game = game;
machine = new StateMachine<RobotState>(RobotState.THINKING);
switch(difficulty) {
case TurtleIsland.Easy:
speedDeviation = 1.2f;
angleDeviation = 6f;
break;
case TurtleIsland.Medium:
speedDeviation = 0.6f;
angleDeviation = 3f;
break;
case TurtleIsland.Hard:
speedDeviation = 0.2f;
angleDeviation = 1f;
break;
case TurtleIsland.Maximum:
speedDeviation = 0f;
angleDeviation = 0f;
break;
default:
Debug.LogWarning("WARNING: difficulty greater than maximum");
speedDeviation = 0f;
angleDeviation = 0f;
break;
}
}
public override void play(Character character) {
this.character = character;
//status = TTPlayStatus.PREPARE;
think(1f);
}
public override void dischargeForced() {
//status = TTPlayStatus.DONE;
}
public override void step() {
if(machine.state == RobotState.THINKING) {
if(machine.isOver(currentTime)) {
tryToShot();
}
} else if(machine.state == RobotState.WALKING) {
if(machine.isOver(currentTime)) {
think(0.5f);
//tryToShot();
} else {
//game.walk(1f * (character.side ? 1f : -1f));
game.walk(1f * (character.orientation == Character.EAST ? 1f : -1f));
}
} else if(machine.state == RobotState.AIMING) {
// TODO check this
float current = character.getTargetWorldAngle();
if(Mathf.Abs(current - targetAngle) >= targetAngleThreshold) {
float targetSpeed = (targetAngle - current) * targetSpeedFactor;
if(Mathf.Abs(targetSpeed) < targetSpeedMinimum)
targetSpeed = targetSpeedMinimum * Mathf.Sign(targetSpeed);
if(character.orientation == Character.WEST) {
targetSpeed *= -1f;
}
game.moveTarget(targetSpeed);
} else {
machine.trigger(RobotState.SHOTING);
game.setWeaponValue(grenadeTime);
game.charge();
}
} else if(machine.state == RobotState.SHOTING) {
if(machine.triggerIfEllapsed(RobotState.DONE, currentTime)) {
game.discharge();
}
}
}
public override void setValue(int number) { } // nothing
public override void incrementValue() { } // nothing
public override void decrementValue() { } // nothing
public override void nextWeapon() { } // nothing
void think(float factor) {
float thinkTime;
if(factor >= 1f) {
thinkTime = JuloMath.randomFloat(thinkingTimeMean, thinkingTimeDeviation);
} else {
thinkTime = thinkingTimeMean * factor;
}
machine.trigger(RobotState.THINKING);
currentTime = thinkTime;
}
void tryToShot() {
List<Character> rivals = game.getRivals();
int numRivals = rivals.Count;
if(numRivals == 0) {
think(1f);
return;
}
TTShot shot = null;
//Vector2 pa = character.shotPoint.position;
Vector2 pa = character.transform.position;
int rivalIndex = JuloMath.randomInt(0, numRivals - 1);
for(int ft = 1; ft <= 3 && shot == null; ft++) {
for(int i = 0; i < numRivals && shot == null; i++) {
Character rival = rivals[(rivalIndex + i) % numRivals];
Vector2 pb = (Vector2) rival.transform.position;
if(Math.Abs(pa.x) > 2.2f && Math.Abs(pb.x) > 2.2f) {
pa.x += .15f * Mathf.Sign(pb.x - pa.x);
pb.x -= .15f * Mathf.Sign(pb.x - pa.x);
pb.y -= 0.15f;
}
shot = TTShot.getPerfectShotForTime(pa, pb, ft);
if(hitsSomeBarrier(shot)) {
shot = null;
}
}
}
if(shot == null) {
float remaining = game.getRemainingTime();
bool leftSide = Mathf.Sign(pa.x) < 0f;
if(remaining < walkingTime * 2) {
if(debugEnabled) Debug.Log("Tiro apurado");
shot = getTetaInterna(!leftSide, 3f, 5f);
} else if(Mathf.Abs(pa.x) < 1.8f) {
walk(leftSide); // caminar hacia afuera
} else if(Math.Abs(pa.x) > 6.5f) {
walk(!leftSide); // caminar hacia adentro
} else {
//Character rival = rivals[0];
int first = JuloMath.randomInt(3, 5);
//int second = (first - 2) % 3 + 3;
//int third = (second - 2) % 3 + 3;
shot = getTetaInterna(!leftSide, 2, first);
if(hitsSomeBarrier(shot)) {
Debug.Log("No se encontro nada");
/*shot = getTetaInterna(!leftSide, 2, second);
if(hitsSomeBarrier(shot)) {
shot = getTetaInterna(!leftSide, 2, third);
}*/
//if(debugEnabled)
//Debug.Log(hitsSomeBarrier(shot) ? "Yet hitting barrier" : "Tiro de descarte 2");
//} else {
//if(debugEnabled) Debug.Log("Tiro de descarte 1");
}
}
}
if(shot != null)
doShot(shot);
}
void walk(bool toLeft) {
game.walk(0.1f * (toLeft ? -1f : +1f));
currentTime = JuloMath.randomFloat(/*curve, */walkingTime, walkingTimeDeviation);
machine.trigger(RobotState.WALKING);
}
void doShot(TTShot shot) {
hitsSomeBarrier(shot/*, true*/);
bool charSide = (character.orientation == Character.EAST);
bool shotSide = shot.angle < 90f;
if(charSide != shotSide) {
game.walk(0.01f * (shotSide ? 1f : -1f));
}
shot.randomizeAngle(angleDeviation);
shot.randomizeSpeed(speedDeviation);
targetAngle = shot.angle;
currentTime = shot.speed / game.options.weaponSpeedFactor;
grenadeTime = (int)shot.fuse;
machine.trigger(RobotState.AIMING);
}
private TTShot getTetaInterna(bool left, float tetaTime, float explosionTime) {
GameObject[] caras = GameObject.FindGameObjectsWithTag("CaraInterna");
bool isFirst = caras[0].transform.position.x < 0 == left;
GameObject cara = isFirst ? caras[0] : caras[1];
Vector2 pa = character.shotPoint.position;
Vector2 pb = cara.transform.position;
TTShot ret = TTShot.getPerfectShotForTime(pa, pb, tetaTime);
ret.fuse = explosionTime;
return ret;
}
private static bool hitsSomeBarrier(TTShot shot/*, bool debugInfo = false*/) {
GameObject[] barrierObjs = GameObject.FindGameObjectsWithTag("Barrier");
foreach(GameObject barrier in barrierObjs) {
if(shot.under(barrier.transform.position/*, debugInfo*/)) {
return true;
}
}
return false;
}
}
}
| |
//
// TemplateContext.cs
//
// Author: najmeddine nouri
//
// Copyright (c) 2013 najmeddine nouri, amine gassem
//
// 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.
//
// Except as contained in this notice, the name(s) of the above copyright holders
// shall not be used in advertising or otherwise to promote the sale, use or other
// dealings in this Software without prior written authorization.
//
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using Badr.Net.Utils;
using Badr.Server.Utils;
using Badr.Server.Templates.Filters;
using Badr.Server.Templates.Rendering;
using System.Collections;
using Badr.Server.Templates.Parsing;
namespace Badr.Server.Templates
{
public sealed class TemplateContext: DynamicObject
{
public static TemplateContext Empty = new TemplateContext(true);
private readonly Dictionary<Scope, Dictionary<string, object>> _overrides;
private readonly Dictionary<string, object> _objects;
private readonly bool _alwaysEmpty = false;
private TemplateContext(bool isEmpty)
{
_alwaysEmpty = isEmpty;
if (!isEmpty)
{
_objects = new Dictionary<string, object>();
_overrides = new Dictionary<Scope, Dictionary<string, object>>();
}
}
public TemplateContext()
:this(false)
{
}
public object this[string objname]
{
get
{
if (!_alwaysEmpty && _objects.ContainsKey(objname))
return _objects[objname];
return null;
}
set
{
if (!_alwaysEmpty)
_objects[objname] = value;
}
}
public void Add(string objname, object obj)
{
if (!_alwaysEmpty)
_objects[objname] = obj;
}
public void Remove(string objname)
{
if (!_alwaysEmpty && _objects.ContainsKey(objname))
_objects.Remove(objname);
}
public bool Contains(string objname)
{
return !_alwaysEmpty && _objects.ContainsKey(objname);
}
public void Clear()
{
if (!_alwaysEmpty)
_objects.Clear();
}
#region overrides
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder == null)
{
result = null;
return false;
}
result = !_alwaysEmpty ? _objects[binder.Name]: null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (binder == null)
return false;
if (!_alwaysEmpty)
_objects[binder.Name] = value;
return true;
}
#endregion
#region protected internal
internal bool Contains(Scope scope, string objname)
{
return !_alwaysEmpty && _overrides.ContainsKey(scope) && _overrides[scope].ContainsKey(objname);
}
internal bool GetOverride (Scope scope, string objname, out object result)
{
if (_alwaysEmpty) {
result = null;
return false;
}
if (_overrides.ContainsKey (scope) && _overrides [scope].ContainsKey (objname))
result = _overrides [scope] [objname];
else if (scope.ParentScope != null)
return GetOverride (scope.ParentScope, objname, out result);
else if (_objects.ContainsKey (objname))
result = _objects [objname];
else {
result = null;
return false;
}
return true;
}
internal object this [Scope scope, TemplateVar variable, List<TemplateFilter> filters]
{
get {
object val = null;
if (variable != null && variable.StrValue != null)
{
if (variable.IsLiteralString)
val = variable.StrValue;
else
{
string varStr = variable.StrValue;
if (!string.IsNullOrWhiteSpace (varStr))
{
if (!GetOverride (scope, varStr, out val))
{
string[] varSplit = varStr.Split ('.');
if (GetOverride (scope, varSplit [0], out val))
{
if (val != null && varSplit.Length > 1)
val = ReadSubProperty (val, varSplit, 1);
} else
{
int i;
if (int.TryParse (variable.StrValue, out i))
val = i;
else
{
double d;
if (double.TryParse (variable.StrValue, out d))
val = d;
}
}
}
}
}
}
if (filters != null && filters.Count > 0)
{
int filtersCount = filters.Count;
KeyValuePair<string, object>[] resolvedFilters = new KeyValuePair<string, object>[filtersCount];
for (int i = 0; i < filtersCount; i++)
{
TemplateFilter currFilter = filters [i];
resolvedFilters [i] = new KeyValuePair<string, object> (currFilter.Name, this [scope, currFilter.Argument, null]);
}
return FilterManager.Filter (val, resolvedFilters);
} else
return val;
}
}
internal void PushOverride(Scope scope, string objName, object value)
{
if (_alwaysEmpty)
return;
if (!_overrides.ContainsKey(scope))
_overrides.Add(scope, new Dictionary<string, object>());
_overrides[scope][objName] = value;
}
internal void PopOverride(Scope scope, string objName)
{
if (_alwaysEmpty)
return;
if (_overrides.ContainsKey(scope))
_overrides[scope].Remove(objName);
}
internal object ReadSubProperty(object var, string[] varSplit, int subPropLevel)
{
if (_alwaysEmpty)
return null;
if (var != null && varSplit != null && varSplit.Length > subPropLevel)
{
string prop = varSplit[subPropLevel];
if (var is DynamicObject)
var = ((dynamic)var)[prop];
else if (var is IDictionary)
var = ((IDictionary)var)[prop];
else
{
PropertyInfo pi = var.GetType().GetProperty(prop, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (pi != null)
var = pi.GetValue(var, null);
else
var = null;
}
if (var != null)
{
if (subPropLevel == varSplit.Length - 1)
return var;
else
return ReadSubProperty(var, varSplit, subPropLevel + 1);
}
}
return null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Collections.Tests
{
public class Hashtable_CopyToTests
{
[Fact]
public void TestCopyToBasic()
{
Hashtable hash = null; // the hashtable object which will be used in the tests
object[] objArr = null; // the object array corresponding to arr
object[] objArr2 = null; // helper object array
object[,] objArrRMDim = null; // multi dimensional object array
// these are the keys and values which will be added to the hashtable in the tests
object[] keys = new object[] {
new object(),
"Hello" ,
"my array" ,
new DateTime(),
new SortedList(),
typeof( System.Environment ),
5
};
object[] values = new object[] {
"Somestring" ,
new object(),
new int [] { 1, 2, 3, 4, 5 },
new Hashtable(),
new Exception(),
new Hashtable_CopyToTests(),
null
};
//[]test normal conditions, array is large enough to hold all elements
// make new hashtable
hash = new Hashtable();
// put in values and keys
for (int i = 0; i < values.Length; i++)
{
hash.Add(keys[i], values[i]);
}
// now try getting out the values using CopyTo method
objArr = new object[values.Length + 2];
// put a sentinal in first position, and make sure it is not overriden
objArr[0] = "startstring";
// put a sentinal in last position, and make sure it is not overriden
objArr[values.Length + 1] = "endstring";
hash.Values.CopyTo((Array)objArr, 1);
// make sure sentinal character is still there
Assert.Equal("startstring", objArr[0]);
Assert.Equal("endstring", objArr[values.Length + 1]);
// check to make sure arr is filled up with the correct elements
objArr2 = new object[values.Length];
Array.Copy(objArr, 1, objArr2, 0, values.Length);
objArr = objArr2;
Assert.True(CompareArrays(objArr, values));
//[] This is the same test as before but now we are going to used Hashtable.CopyTo instead of Hasthabe.Values.CopyTo
// now try getting out the values using CopyTo method
objArr = new object[values.Length + 2];
// put a sentinal in first position, and make sure it is not overriden
objArr[0] = "startstring";
// put a sentinal in last position, and make sure it is not overriden
objArr[values.Length + 1] = "endstring";
hash.CopyTo((Array)objArr, 1);
// make sure sentinal character is still there
Assert.Equal("startstring", objArr[0]);
Assert.Equal("endstring", objArr[values.Length + 1]);
// check to make sure arr is filled up with the correct elements
BitArray bitArray = new BitArray(values.Length);
for (int i = 0; i < values.Length; i++)
{
DictionaryEntry entry = (DictionaryEntry)objArr[i + 1];
int valueIndex = Array.IndexOf(values, entry.Value);
int keyIndex = Array.IndexOf(keys, entry.Key);
Assert.NotEqual(-1, valueIndex);
Assert.NotEqual(-1, keyIndex);
Assert.Equal(valueIndex, keyIndex);
bitArray[i] = true;
}
for (int i = 0; i < ((ICollection)bitArray).Count; i++)
{
Assert.True(bitArray[i]);
}
//[] Parameter validation
//[] Null array
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(null, 0);
}
);
//[] Multidimentional array
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
objArrRMDim = new object[16, 16];
hash.CopyTo(objArrRMDim, 0);
}
);
//[] Array not large enough
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
for (int i = 0; i < 256; i++)
{
hash.Add(i.ToString(), i);
}
objArr = new object[hash.Count + 8];
hash.CopyTo(objArr, 9);
}
);
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, Int32.MaxValue);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, Int32.MinValue);
}
);
//[]copy should throw because of outofrange
Random random = new Random(-55);
for (int iii = 0; iii < 20; iii++)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable();
objArr = new object[0];
hash.CopyTo(objArr, random.Next(-1000, 0));
}
);
}
//[]test when array is to small to hold all values hashtable has more values then array can hold
hash = new Hashtable();
// put in values and keys
for (int i = 0; i < values.Length; i++)
{
hash.Add(keys[i], values[i]);
}
// now try getting out the values using CopyTo method into a small array
objArr = new object[values.Length - 1];
Assert.Throws<ArgumentException>(() =>
{
hash.Values.CopyTo((Array)objArr, 0);
}
);
//[]test when array is size 0
// now try getting out the values using CopyTo method into a 0 sized array
objArr = new object[0];
Assert.Throws<ArgumentException>(() =>
{
hash.Values.CopyTo((Array)objArr, 0);
}
);
//[]test when array is null
Assert.Throws<ArgumentNullException>(() =>
{
hash.Values.CopyTo(null, 0);
}
);
}
[Fact]
public void TestCopyToWithValidIndex()
{
//[]test when hashtable has no elements in it
var hash = new Hashtable();
// make an array of 100 size to hold elements
var objArr = new object[100];
hash.Values.CopyTo(objArr, 0);
objArr = new object[100];
hash.Values.CopyTo(objArr, 99);
objArr = new object[100];
// valid now
hash.Values.CopyTo(objArr, 100);
// make an array of 0 size to hold elements
objArr = new object[0];
hash.Values.CopyTo(objArr, 0);
int key = 123;
int val = 456;
hash.Add(key, val);
objArr = new object[100];
objArr[0] = 0;
hash.Values.CopyTo(objArr, 0);
Assert.Equal(val, objArr[0]);
hash.Values.CopyTo(objArr, 99);
Assert.Equal(val, objArr[99]);
}
[Fact]
public void TestCopyToWithInvalidIndex()
{
object[] objArr = null;
object[][] objArrMDim = null; // multi dimensional object array
object[,] objArrRMDim = null; // multi dimensional object array
//[]test when hashtable has no elements in it and index is out of range (negative)
var hash = new Hashtable();
// put no elements in hashtable
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
// make an array of 100 size to hold elements
objArr = new object[0];
hash.Values.CopyTo(objArr, -1);
}
);
//[]test when array is multi dimensional and array is large enough
hash = new Hashtable();
// put elements into hashtable
for (int i = 0; i < 100; i++)
{
hash.Add(i.ToString(), i.ToString());
}
Assert.Throws<InvalidCastException>(() =>
{
// make an array of 100 size to hold elements
objArrMDim = new object[100][];
for (int i = 0; i < 100; i++)
{
objArrMDim[i] = new object[i + 1];
}
hash.Values.CopyTo(objArrMDim, 0);
}
);
Assert.Throws<ArgumentException>(() =>
{
// make an array of 100 size to hold elements
objArrRMDim = new object[100, 100];
hash.Values.CopyTo(objArrRMDim, 0);
}
);
//[]test when array is multi dimensional and array is small
hash = new Hashtable();
// put elements into hashtable
for (int i = 0; i < 100; i++)
{
hash.Add(i.ToString(), i.ToString());
}
Assert.Throws<ArgumentException>(() =>
{
// make an array of 100 size to hold elements
objArrMDim = new object[99][];
for (int i = 0; i < 99; i++)
{
objArrMDim[i] = new object[i + 1];
}
hash.Values.CopyTo(objArrMDim, 0);
}
);
//[]test to see if CopyTo throws correct exception
hash = new Hashtable();
Assert.Throws<ArgumentException>(() =>
{
string[] str = new string[100];
// i will be calling CopyTo with the str array and index 101 it should throw an exception
// since the array index 101 is not valid
hash.Values.CopyTo(str, 101);
}
);
}
/////////////////////////// HELPER FUNCTIONS
// this is pretty slow algorithm but it works
// returns true if arr1 has the same elements as arr2
// arrays can have nulls in them, but arr1 and arr2 should not be null
public static bool CompareArrays(object[] arr1, object[] arr2)
{
if (arr1.Length != arr2.Length)
{
return false;
}
int i, j;
bool fPresent = false;
for (i = 0; i < arr1.Length; i++)
{
fPresent = false;
for (j = 0; j < arr2.Length && (fPresent == false); j++)
{
if ((arr1[i] == null && arr2[j] == null)
||
(arr1[i] != null && arr1[i].Equals(arr2[j])))
{
fPresent = true;
}
}
if (fPresent == false)
{
return false;
}
}
// now do the same thing but the other way around
for (i = 0; i < arr2.Length; i++)
{
fPresent = false;
for (j = 0; j < arr1.Length && (fPresent == false); j++)
{
if ((arr2[i] == null && arr1[j] == null) || (arr2[i] != null && arr2[i].Equals(arr1[j])))
{
fPresent = true;
}
}
if (fPresent == false)
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace pnp.api.contosoorders.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Security.Cryptography;
namespace Braintree
{
[Serializable]
public class CreditCardCustomerLocation : Enumeration
{
public static readonly CreditCardCustomerLocation US = new CreditCardCustomerLocation("us");
public static readonly CreditCardCustomerLocation INTERNATIONAL = new CreditCardCustomerLocation("international");
public static readonly CreditCardCustomerLocation UNRECOGNIZED = new CreditCardCustomerLocation("unrecognized");
public static readonly CreditCardCustomerLocation[] ALL = {US, INTERNATIONAL};
protected CreditCardCustomerLocation(String name) : base(name) {}
}
[Serializable]
public class CreditCardPrepaid : Enumeration
{
public static readonly CreditCardPrepaid YES = new CreditCardPrepaid("Yes");
public static readonly CreditCardPrepaid NO = new CreditCardPrepaid("No");
public static readonly CreditCardPrepaid UNKNOWN = new CreditCardPrepaid("Unknown");
public static readonly CreditCardPrepaid[] ALL = {YES, NO, UNKNOWN};
protected CreditCardPrepaid(String name) : base(name) {}
}
[Serializable]
public class CreditCardPayroll : Enumeration
{
public static readonly CreditCardPayroll YES = new CreditCardPayroll("Yes");
public static readonly CreditCardPayroll NO = new CreditCardPayroll("No");
public static readonly CreditCardPayroll UNKNOWN = new CreditCardPayroll("Unknown");
public static readonly CreditCardPayroll[] ALL = {YES, NO, UNKNOWN};
protected CreditCardPayroll(String name) : base(name) {}
}
[Serializable]
public class CreditCardDebit : Enumeration
{
public static readonly CreditCardDebit YES = new CreditCardDebit("Yes");
public static readonly CreditCardDebit NO = new CreditCardDebit("No");
public static readonly CreditCardDebit UNKNOWN = new CreditCardDebit("Unknown");
public static readonly CreditCardDebit[] ALL = {YES, NO, UNKNOWN};
protected CreditCardDebit(String name) : base(name) {}
}
[Serializable]
public class CreditCardCommercial : Enumeration
{
public static readonly CreditCardCommercial YES = new CreditCardCommercial("Yes");
public static readonly CreditCardCommercial NO = new CreditCardCommercial("No");
public static readonly CreditCardCommercial UNKNOWN = new CreditCardCommercial("Unknown");
public static readonly CreditCardCommercial[] ALL = {YES, NO, UNKNOWN};
protected CreditCardCommercial(String name) : base(name) {}
}
[Serializable]
public class CreditCardHealthcare : Enumeration
{
public static readonly CreditCardHealthcare YES = new CreditCardHealthcare("Yes");
public static readonly CreditCardHealthcare NO = new CreditCardHealthcare("No");
public static readonly CreditCardHealthcare UNKNOWN = new CreditCardHealthcare("Unknown");
public static readonly CreditCardHealthcare[] ALL = {YES, NO, UNKNOWN};
protected CreditCardHealthcare(String name) : base(name) {}
}
[Serializable]
public class CreditCardDurbinRegulated : Enumeration
{
public static readonly CreditCardDurbinRegulated YES = new CreditCardDurbinRegulated("Yes");
public static readonly CreditCardDurbinRegulated NO = new CreditCardDurbinRegulated("No");
public static readonly CreditCardDurbinRegulated UNKNOWN = new CreditCardDurbinRegulated("Unknown");
public static readonly CreditCardDurbinRegulated[] ALL = {YES, NO, UNKNOWN};
protected CreditCardDurbinRegulated(String name) : base(name) {}
}
[Serializable]
public class CreditCardCardType : Enumeration
{
public static readonly CreditCardCardType AMEX = new CreditCardCardType("American Express");
public static readonly CreditCardCardType CARTE_BLANCHE = new CreditCardCardType("Carte Blanche");
public static readonly CreditCardCardType CHINA_UNION_PAY = new CreditCardCardType("China UnionPay");
public static readonly CreditCardCardType DINERS_CLUB_INTERNATIONAL = new CreditCardCardType("Diners Club");
public static readonly CreditCardCardType DISCOVER = new CreditCardCardType("Discover");
public static readonly CreditCardCardType JCB = new CreditCardCardType("JCB");
public static readonly CreditCardCardType LASER = new CreditCardCardType("Laser");
public static readonly CreditCardCardType MAESTRO = new CreditCardCardType("Maestro");
public static readonly CreditCardCardType MASTER_CARD = new CreditCardCardType("MasterCard");
public static readonly CreditCardCardType SOLO = new CreditCardCardType("Solo");
public static readonly CreditCardCardType SWITCH = new CreditCardCardType("Switch");
public static readonly CreditCardCardType VISA = new CreditCardCardType("Visa");
public static readonly CreditCardCardType UNKNOWN = new CreditCardCardType("Unknown");
public static readonly CreditCardCardType UNRECOGNIZED = new CreditCardCardType("Unrecognized");
public static readonly CreditCardCardType[] ALL = {
AMEX, CARTE_BLANCHE, CHINA_UNION_PAY, DINERS_CLUB_INTERNATIONAL, DISCOVER,
JCB, LASER, MAESTRO, MASTER_CARD, SOLO, SWITCH, VISA, UNKNOWN
};
protected CreditCardCardType(String name) : base(name) {}
}
/// <summary>
/// A credit card returned by the Braintree Gateway
/// </summary>
/// <remarks>
/// A credit card can belong to:
/// <ul>
/// <li>a <see cref="Customer"/> as a stored credit card</li>
/// <li>a <see cref="Transaction"/> as the credit card used for the transaction</li>
/// </ul>
/// </remarks>
/// <example>
/// Credit Cards can be retrieved via the gateway using the associated credit card token:
/// <code>
/// CreditCard creditCard = gateway.CreditCard.Find("token");
/// </code>
/// For more information about Credit Cards, see <a href="http://www.braintreepayments.com/gateway/credit-card-api" target="_blank">http://www.braintreepaymentsolutions.com/gateway/credit-card-api</a><br />
/// For more information about Credit Card Verifications, see <a href="http://www.braintreepayments.com/gateway/credit-card-verification-api" target="_blank">http://www.braintreepaymentsolutions.com/gateway/credit-card-verification-api</a>
/// </example>
[Serializable]
public class CreditCard
{
public static readonly String CountryOfIssuanceUnknown = "Unknown";
public static readonly String IssuingBankUnknown = "Unknown";
public String Bin { get; protected set; }
public String CardholderName { get; protected set; }
public CreditCardCardType CardType { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public String CustomerId { get; protected set; }
public Boolean? IsDefault { get; protected set; }
public Boolean? IsExpired { get; protected set; }
public CreditCardCustomerLocation CustomerLocation { get; protected set; }
public String LastFour { get; protected set; }
public String UniqueNumberIdentifier { get; protected set; }
public Subscription[] Subscriptions { get; protected set; }
public String Token { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Address BillingAddress { get; protected set; }
public String ExpirationMonth { get; protected set; }
public String ExpirationYear { get; protected set; }
public CreditCardPrepaid Prepaid { get; protected set; }
public CreditCardPayroll Payroll { get; protected set; }
public CreditCardDebit Debit { get; protected set; }
public CreditCardCommercial Commercial { get; protected set; }
public CreditCardHealthcare Healthcare { get; protected set; }
public CreditCardDurbinRegulated DurbinRegulated { get; protected set; }
private String _CountryOfIssuance;
public String CountryOfIssuance
{
get
{
if (_CountryOfIssuance == "")
{
return CountryOfIssuanceUnknown;
}
else
{
return _CountryOfIssuance;
}
}
}
private String _IssuingBank;
public String IssuingBank
{
get
{
if (_IssuingBank == "")
{
return IssuingBankUnknown;
}
else
{
return _IssuingBank;
}
}
}
public String ExpirationDate
{
get
{
return ExpirationMonth + "/" + ExpirationYear;
}
protected set
{
ExpirationMonth = value.Split('/')[0];
ExpirationYear = value.Split('/')[1];
}
}
public String MaskedNumber
{
get
{
return String.Format("{0}******{1}", Bin, LastFour);
}
}
protected internal CreditCard(NodeWrapper node, BraintreeService service)
{
if (node == null) return;
Bin = node.GetString("bin");
CardholderName = node.GetString("cardholder-name");
CardType = (CreditCardCardType)CollectionUtil.Find(CreditCardCardType.ALL, node.GetString("card-type"), CreditCardCardType.UNRECOGNIZED);
CustomerId = node.GetString("customer-id");
IsDefault = node.GetBoolean("default");
ExpirationMonth = node.GetString("expiration-month");
ExpirationYear = node.GetString("expiration-year");
IsExpired = node.GetBoolean("expired");
CustomerLocation = (CreditCardCustomerLocation)CollectionUtil.Find(CreditCardCustomerLocation.ALL, node.GetString("customer-location"), CreditCardCustomerLocation.UNRECOGNIZED);
LastFour = node.GetString("last-4");
UniqueNumberIdentifier = node.GetString("unique-number-identifier");
Token = node.GetString("token");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
BillingAddress = new Address(node.GetNode("billing-address"));
Prepaid = (CreditCardPrepaid)CollectionUtil.Find(CreditCardPrepaid.ALL, node.GetString("prepaid"), CreditCardPrepaid.UNKNOWN);
Payroll = (CreditCardPayroll)CollectionUtil.Find(CreditCardPayroll.ALL, node.GetString("payroll"), CreditCardPayroll.UNKNOWN);
DurbinRegulated = (CreditCardDurbinRegulated)CollectionUtil.Find(CreditCardDurbinRegulated.ALL, node.GetString("durbin-regulated"), CreditCardDurbinRegulated.UNKNOWN);
Debit = (CreditCardDebit)CollectionUtil.Find(CreditCardDebit.ALL, node.GetString("debit"), CreditCardDebit.UNKNOWN);
Commercial = (CreditCardCommercial)CollectionUtil.Find(CreditCardCommercial.ALL, node.GetString("commercial"), CreditCardCommercial.UNKNOWN);
Healthcare = (CreditCardHealthcare)CollectionUtil.Find(CreditCardHealthcare.ALL, node.GetString("healthcare"), CreditCardHealthcare.UNKNOWN);
_CountryOfIssuance = node.GetString("country-of-issuance");
_IssuingBank = node.GetString("issuing-bank");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], service);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PostIncrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostIncrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostIncrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(IncrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PostIncrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(null, () => Expression.PostIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PostIncrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<long>.TestStatic = 2L;
Assert.Equal(
2L,
Expression.Lambda<Func<long>>(
Expression.PostIncrementAssign(
Expression.Property(null, typeof(TestPropertyClass<long>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(3L, TestPropertyClass<long>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(3, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostIncrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(3, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PostIncrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PostIncrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Forms.VisualStyles;
namespace inSyca.foundation.framework.application.windowsforms
{
/// <summary>
/// Represents a TabStrip control
/// </summary>
public class TabStrip : ToolStrip
{
private TabStripRenderer myRenderer = new TabStripRenderer();
protected TabStripButton mySelTab;
DesignerVerb insPage = null;
public TabStrip()
: base()
{
InitControl();
}
public TabStrip(params TabStripButton[] buttons)
: base(buttons)
{
InitControl();
}
protected void InitControl()
{
base.RenderMode = ToolStripRenderMode.ManagerRenderMode;
base.Renderer = myRenderer;
myRenderer.RenderMode = this.RenderStyle;
insPage = new DesignerVerb(Properties.Resources.ts_insert, new EventHandler(OnInsertPageClicked));
}
public override ISite Site
{
get
{
ISite site = base.Site;
if (site != null && site.DesignMode)
{
IContainer comp = site.Container;
if (comp != null)
{
IDesignerHost host = comp as IDesignerHost;
if (host != null)
{
IDesigner designer = host.GetDesigner(site.Component);
if (designer != null && !designer.Verbs.Contains(insPage))
designer.Verbs.Add(insPage);
}
}
}
return site;
}
set
{
base.Site = value;
}
}
protected void OnInsertPageClicked(object sender, EventArgs e)
{
ISite site = base.Site;
if (site != null && site.DesignMode)
{
IContainer container = site.Container;
if (container != null)
{
TabStripButton btn = new TabStripButton();
container.Add(btn);
btn.Text = btn.Name;
}
}
}
/// <summary>
/// Gets custom renderer for TabStrip. Set operation has no effect
/// </summary>
public new ToolStripRenderer Renderer
{
get { return myRenderer; }
set { base.Renderer = myRenderer; }
}
/// <summary>
/// Gets or sets layout style for TabStrip control
/// </summary>
public new ToolStripLayoutStyle LayoutStyle
{
get { return base.LayoutStyle; }
set
{
switch (value)
{
case ToolStripLayoutStyle.StackWithOverflow:
case ToolStripLayoutStyle.HorizontalStackWithOverflow:
case ToolStripLayoutStyle.VerticalStackWithOverflow:
base.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow;
break;
case ToolStripLayoutStyle.Table:
base.LayoutStyle = ToolStripLayoutStyle.Table;
break;
case ToolStripLayoutStyle.Flow:
base.LayoutStyle = ToolStripLayoutStyle.Flow;
break;
default:
base.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow;
break;
}
}
}
/// <summary>
///
/// </summary>
[Obsolete("Use RenderStyle instead")]
[Browsable(false)]
public new ToolStripRenderMode RenderMode
{
get { return base.RenderMode; }
set { RenderStyle = value; }
}
/// <summary>
/// Gets or sets render style for TabStrip, use it instead of
/// </summary>
[Category("Appearance")]
[Description("Gets or sets render style for TabStrip. You should use this property instead of RenderMode.")]
public ToolStripRenderMode RenderStyle
{
get { return myRenderer.RenderMode; }
set
{
myRenderer.RenderMode = value;
this.Invalidate();
}
}
protected override Padding DefaultPadding
{
get
{
return Padding.Empty;
}
}
[Browsable(false)]
public new Padding Padding
{
get { return DefaultPadding; }
set { }
}
/// <summary>
/// Gets or sets if control should use system visual styles for painting items
/// </summary>
[Category("Appearance")]
[Description("Specifies if TabStrip should use system visual styles for painting items")]
public bool UseVisualStyles
{
get { return myRenderer.UseVS; }
set
{
myRenderer.UseVS = value;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets if TabButtons should be drawn flipped
/// </summary>
[Category("Appearance")]
[Description("Specifies if TabButtons should be drawn flipped (for right- and bottom-aligned TabStrips)")]
public bool FlipButtons
{
get { return myRenderer.Mirrored; }
set
{
myRenderer.Mirrored = value;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets currently selected tab
/// </summary>
public TabStripButton SelectedTab
{
get { return mySelTab; }
set
{
if (value == null)
return;
if (mySelTab == value)
return;
if (value.Owner != this)
throw new ArgumentException("Cannot select TabButtons that do not belong to this TabStrip");
OnItemClicked(new ToolStripItemClickedEventArgs(value));
}
}
public event EventHandler<SelectedTabChangedEventArgs> SelectedTabChanged;
protected void OnTabSelected(TabStripButton tab)
{
this.Invalidate();
if (SelectedTabChanged != null)
SelectedTabChanged(this, new SelectedTabChangedEventArgs(tab));
}
protected override void OnItemAdded(ToolStripItemEventArgs e)
{
base.OnItemAdded(e);
if (e.Item is TabStripButton)
SelectedTab = (TabStripButton)e.Item;
}
protected override void OnItemClicked(ToolStripItemClickedEventArgs e)
{
TabStripButton clickedBtn = e.ClickedItem as TabStripButton;
if (clickedBtn != null)
{
this.SuspendLayout();
mySelTab = clickedBtn;
this.ResumeLayout();
OnTabSelected(clickedBtn);
}
base.OnItemClicked(e);
}
}
/// <summary>
/// Represents a renderer class for TabStrip control
/// </summary>
internal class TabStripRenderer : ToolStripRenderer
{
private const int selOffset = 2;
private ToolStripRenderer currentRenderer = null;
private ToolStripRenderMode renderMode = ToolStripRenderMode.Custom;
private bool mirrored = false;
private bool useVS = Application.RenderWithVisualStyles;
/// <summary>
/// Gets or sets render mode for this renderer
/// </summary>
public ToolStripRenderMode RenderMode
{
get { return renderMode; }
set
{
renderMode = value;
switch (renderMode)
{
case ToolStripRenderMode.Professional:
currentRenderer = new ToolStripProfessionalRenderer();
break;
case ToolStripRenderMode.System:
currentRenderer = new ToolStripSystemRenderer();
break;
default:
currentRenderer = null;
break;
}
}
}
/// <summary>
/// Gets or sets whether to mirror background
/// </summary>
/// <remarks>Use false for left and top positions, true for right and bottom</remarks>
public bool Mirrored
{
get { return mirrored; }
set { mirrored = value; }
}
/// <summary>
/// Returns if visual styles should be applied for drawing
/// </summary>
public bool UseVS
{
get { return useVS; }
set
{
if (value && !Application.RenderWithVisualStyles)
return;
useVS = value;
}
}
protected override void Initialize(ToolStrip ts)
{
base.Initialize(ts);
}
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
Color c = SystemColors.AppWorkspace;
if (UseVS)
{
VisualStyleRenderer rndr = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);
c = rndr.GetColor(ColorProperty.BorderColorHint);
}
using (Pen p = new Pen(c))
using (Pen p2 = new Pen(e.BackColor))
{
Rectangle r = e.ToolStrip.Bounds;
int x1 = (Mirrored) ? 0 : r.Width - 1 - e.ToolStrip.Padding.Horizontal;
int y1 = (Mirrored) ? 0 : r.Height - 1;
if (e.ToolStrip.Orientation == Orientation.Horizontal)
e.Graphics.DrawLine(p, 0, y1, r.Width, y1);
else
{
e.Graphics.DrawLine(p, x1, 0, x1, r.Height);
if (!Mirrored)
for (int i = x1 + 1; i < r.Width; i++)
e.Graphics.DrawLine(p2, i, 0, i, r.Height);
}
foreach (ToolStripItem x in e.ToolStrip.Items)
{
if (x.IsOnOverflow) continue;
TabStripButton btn = x as TabStripButton;
if (btn == null) continue;
Rectangle rc = btn.Bounds;
int x2 = (Mirrored) ? rc.Left : rc.Right;
int y2 = (Mirrored) ? rc.Top : rc.Bottom - 1;
int addXY = (Mirrored) ? 0 : 1;
if (e.ToolStrip.Orientation == Orientation.Horizontal)
{
e.Graphics.DrawLine(p, rc.Left, y2, rc.Right, y2);
if (btn.Checked) e.Graphics.DrawLine(p2, rc.Left + 2 - addXY, y2, rc.Right - 2 - addXY, y2);
}
else
{
e.Graphics.DrawLine(p, x2, rc.Top, x2, rc.Bottom);
if (btn.Checked) e.Graphics.DrawLine(p2, x2, rc.Top + 2 - addXY, x2, rc.Bottom - 2 - addXY);
}
}
}
}
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawToolStripBackground(e);
else
base.OnRenderToolStripBackground(e);
}
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
{
Graphics g = e.Graphics;
TabStrip tabs = e.ToolStrip as TabStrip;
TabStripButton tab = e.Item as TabStripButton;
if (tabs == null || tab == null)
{
if (currentRenderer != null)
currentRenderer.DrawButtonBackground(e);
else
base.OnRenderButtonBackground(e);
return;
}
bool selected = tab.Checked;
bool hovered = tab.Selected;
int top = 0;
int left = 0;
int width = tab.Bounds.Width - 1;
int height = tab.Bounds.Height - 1;
Rectangle drawBorder;
if (UseVS)
{
if (tabs.Orientation == Orientation.Horizontal)
{
if (!selected)
{
top = selOffset;
height -= (selOffset - 1);
}
else
top = 1;
drawBorder = new Rectangle(0, 0, width, height);
}
else
{
if (!selected)
{
left = selOffset;
width -= (selOffset - 1);
}
else
left = 1;
drawBorder = new Rectangle(0, 0, height, width);
}
using (Bitmap b = new Bitmap(drawBorder.Width, drawBorder.Height))
{
VisualStyleElement el = VisualStyleElement.Tab.TabItem.Normal;
if (selected)
el = VisualStyleElement.Tab.TabItem.Pressed;
if (hovered)
el = VisualStyleElement.Tab.TabItem.Hot;
if (!tab.Enabled)
el = VisualStyleElement.Tab.TabItem.Disabled;
if (!selected || hovered) drawBorder.Width++; else drawBorder.Height++;
using (Graphics gr = Graphics.FromImage(b))
{
VisualStyleRenderer rndr = new VisualStyleRenderer(el);
rndr.DrawBackground(gr, drawBorder);
if (tabs.Orientation == Orientation.Vertical)
{
if (Mirrored)
b.RotateFlip(RotateFlipType.Rotate270FlipXY);
else
b.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
else
{
if (Mirrored)
b.RotateFlip(RotateFlipType.RotateNoneFlipY);
}
if (Mirrored)
{
left = tab.Bounds.Width - b.Width - left;
top = tab.Bounds.Height - b.Height - top;
}
g.DrawImage(b, left, top);
}
}
}
else
{
if (tabs.Orientation == Orientation.Horizontal)
{
if (!selected)
{
top = selOffset;
height -= (selOffset - 1);
}
else
top = 1;
if (Mirrored)
{
left = 1;
top = 0;
}
else
top++;
width--;
}
else
{
if (!selected)
{
left = selOffset;
width--;
}
else
left = 1;
if (Mirrored)
{
left = 0;
top = 1;
}
}
height--;
drawBorder = new Rectangle(left, top, width, height);
using (GraphicsPath gp = new GraphicsPath())
{
if (Mirrored && tabs.Orientation == Orientation.Horizontal)
{
gp.AddLine(drawBorder.Left, drawBorder.Top, drawBorder.Left, drawBorder.Bottom - 2);
gp.AddArc(drawBorder.Left, drawBorder.Bottom - 3, 2, 2, 90, 90);
gp.AddLine(drawBorder.Left + 2, drawBorder.Bottom, drawBorder.Right - 2, drawBorder.Bottom);
gp.AddArc(drawBorder.Right - 2, drawBorder.Bottom - 3, 2, 2, 0, 90);
gp.AddLine(drawBorder.Right, drawBorder.Bottom - 2, drawBorder.Right, drawBorder.Top);
}
else if (!Mirrored && tabs.Orientation == Orientation.Horizontal)
{
gp.AddLine(drawBorder.Left, drawBorder.Bottom, drawBorder.Left, drawBorder.Top + 2);
gp.AddArc(drawBorder.Left, drawBorder.Top + 1, 2, 2, 180, 90);
gp.AddLine(drawBorder.Left + 2, drawBorder.Top, drawBorder.Right - 2, drawBorder.Top);
gp.AddArc(drawBorder.Right - 2, drawBorder.Top + 1, 2, 2, 270, 90);
gp.AddLine(drawBorder.Right, drawBorder.Top + 2, drawBorder.Right, drawBorder.Bottom);
}
else if (Mirrored && tabs.Orientation == Orientation.Vertical)
{
gp.AddLine(drawBorder.Left, drawBorder.Top, drawBorder.Right - 2, drawBorder.Top);
gp.AddArc(drawBorder.Right - 2, drawBorder.Top + 1, 2, 2, 270, 90);
gp.AddLine(drawBorder.Right, drawBorder.Top + 2, drawBorder.Right, drawBorder.Bottom - 2);
gp.AddArc(drawBorder.Right - 2, drawBorder.Bottom - 3, 2, 2, 0, 90);
gp.AddLine(drawBorder.Right - 2, drawBorder.Bottom, drawBorder.Left, drawBorder.Bottom);
}
else
{
gp.AddLine(drawBorder.Right, drawBorder.Top, drawBorder.Left + 2, drawBorder.Top);
gp.AddArc(drawBorder.Left, drawBorder.Top + 1, 2, 2, 180, 90);
gp.AddLine(drawBorder.Left, drawBorder.Top + 2, drawBorder.Left, drawBorder.Bottom - 2);
gp.AddArc(drawBorder.Left, drawBorder.Bottom - 3, 2, 2, 90, 90);
gp.AddLine(drawBorder.Left + 2, drawBorder.Bottom, drawBorder.Right, drawBorder.Bottom);
}
if (selected || hovered)
{
Color fill = (hovered) ? Color.WhiteSmoke : Color.White;
if (renderMode == ToolStripRenderMode.Professional)
{
fill = (hovered) ? ProfessionalColors.ButtonCheckedGradientBegin : ProfessionalColors.ButtonCheckedGradientEnd;
using (LinearGradientBrush br = new LinearGradientBrush(tab.ContentRectangle, fill, ProfessionalColors.ButtonCheckedGradientMiddle, LinearGradientMode.Vertical))
g.FillPath(br, gp);
}
else
using (SolidBrush br = new SolidBrush(fill))
g.FillPath(br, gp);
}
using (Pen p = new Pen((selected) ? ControlPaint.Dark(SystemColors.AppWorkspace) : SystemColors.AppWorkspace))
g.DrawPath(p, gp);
}
}
}
protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
{
Rectangle rc = e.ImageRectangle;
TabStripButton btn = e.Item as TabStripButton;
if (btn != null)
{
int delta = ((Mirrored) ? -1 : 1) * ((btn.Checked) ? 1 : selOffset);
if (e.ToolStrip.Orientation == Orientation.Horizontal)
rc.Offset((Mirrored) ? 2 : 1, delta + ((Mirrored) ? 1 : 0));
else
rc.Offset(delta + 2, 0);
}
ToolStripItemImageRenderEventArgs x =
new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, e.Image, rc);
if (currentRenderer != null)
currentRenderer.DrawItemImage(x);
else
base.OnRenderItemImage(x);
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
Rectangle rc = e.TextRectangle;
TabStripButton btn = e.Item as TabStripButton;
Color c = e.TextColor;
Font f = e.TextFont;
if (btn != null)
{
int delta = ((Mirrored) ? -1 : 1) * ((btn.Checked) ? 1 : selOffset);
if (e.ToolStrip.Orientation == Orientation.Horizontal)
rc.Offset((Mirrored) ? 2 : 1, delta + ((Mirrored) ? 1 : -1));
else
rc.Offset(delta + 2, 0);
if (btn.Selected)
c = btn.HotTextColor;
else if (btn.Checked)
c = btn.SelectedTextColor;
if (btn.Checked)
f = btn.SelectedFont;
}
ToolStripItemTextRenderEventArgs x =
new ToolStripItemTextRenderEventArgs(e.Graphics, e.Item, e.Text, rc, c, f, e.TextFormat);
x.TextDirection = e.TextDirection;
if (currentRenderer != null)
currentRenderer.DrawItemText(x);
else
base.OnRenderItemText(x);
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawArrow(e);
else
base.OnRenderArrow(e);
}
protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawDropDownButtonBackground(e);
else
base.OnRenderDropDownButtonBackground(e);
}
protected override void OnRenderGrip(ToolStripGripRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawGrip(e);
else
base.OnRenderGrip(e);
}
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawImageMargin(e);
else
base.OnRenderImageMargin(e);
}
protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawItemBackground(e);
else
base.OnRenderItemBackground(e);
}
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawItemCheck(e);
else
base.OnRenderItemCheck(e);
}
protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawLabelBackground(e);
else
base.OnRenderLabelBackground(e);
}
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawMenuItemBackground(e);
else
base.OnRenderMenuItemBackground(e);
}
protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawOverflowButtonBackground(e);
else
base.OnRenderOverflowButtonBackground(e);
}
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawSeparator(e);
else
base.OnRenderSeparator(e);
}
protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawSplitButton(e);
else
base.OnRenderSplitButtonBackground(e);
}
protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawStatusStripSizingGrip(e);
else
base.OnRenderStatusStripSizingGrip(e);
}
protected override void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawToolStripContentPanelBackground(e);
else
base.OnRenderToolStripContentPanelBackground(e);
}
protected override void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawToolStripPanelBackground(e);
else
base.OnRenderToolStripPanelBackground(e);
}
protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e)
{
if (currentRenderer != null)
currentRenderer.DrawToolStripStatusLabelBackground(e);
else
base.OnRenderToolStripStatusLabelBackground(e);
}
}
/// <summary>
/// Represents a TabButton for TabStrip control
/// </summary>
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)]
public class TabStripButton : ToolStripButton
{
public TabStripButton() : base() { InitButton(); }
public TabStripButton(Image image) : base(image) { InitButton(); }
public TabStripButton(string text) : base(text) { InitButton(); }
public TabStripButton(string text, Image image) : base(text, image) { InitButton(); }
public TabStripButton(string Text, Image Image, EventHandler Handler) : base(Text, Image, Handler) { InitButton(); }
public TabStripButton(string Text, Image Image, EventHandler Handler, string name) : base(Text, Image, Handler, name) { InitButton(); }
private void InitButton()
{
m_SelectedFont = this.Font;
}
public override Size GetPreferredSize(Size constrainingSize)
{
Size sz = base.GetPreferredSize(constrainingSize);
if (this.Owner != null && this.Owner.Orientation == Orientation.Vertical)
{
sz.Width += 3;
sz.Height += 10;
}
return sz;
}
protected override Padding DefaultMargin
{
get
{
return new Padding(0);
}
}
[Browsable(false)]
public new Padding Margin
{
get { return base.Margin; }
set { }
}
[Browsable(false)]
public new Padding Padding
{
get { return base.Padding; }
set { }
}
private Color m_HotTextColor = Control.DefaultForeColor;
[Category("Appearance")]
[Description("Text color when TabButton is highlighted")]
public Color HotTextColor
{
get { return m_HotTextColor; }
set { m_HotTextColor = value; }
}
private Color m_SelectedTextColor = Control.DefaultForeColor;
[Category("Appearance")]
[Description("Text color when TabButton is selected")]
public Color SelectedTextColor
{
get { return m_SelectedTextColor; }
set { m_SelectedTextColor = value; }
}
private Font m_SelectedFont;
[Category("Appearance")]
[Description("Font when TabButton is selected")]
public Font SelectedFont
{
get { return (m_SelectedFont == null) ? this.Font : m_SelectedFont; }
set { m_SelectedFont = value; }
}
[Browsable(false)]
[DefaultValue(false)]
public new bool Checked
{
get { return IsSelected; }
set { }
}
/// <summary>
/// Gets or sets if this TabButton is currently selected
/// </summary>
[Browsable(false)]
public bool IsSelected
{
get
{
TabStrip owner = Owner as TabStrip;
if (owner != null)
return (this == owner.SelectedTab);
return false;
}
set
{
if (value == false) return;
TabStrip owner = Owner as TabStrip;
if (owner == null) return;
owner.SelectedTab = this;
}
}
protected override void OnOwnerChanged(EventArgs e)
{
if (Owner != null && !(Owner is TabStrip))
throw new Exception("Cannot add TabStripButton to " + Owner.GetType().Name);
base.OnOwnerChanged(e);
}
}
public class SelectedTabChangedEventArgs : EventArgs
{
public readonly TabStripButton SelectedTab;
public SelectedTabChangedEventArgs(TabStripButton tab)
{
SelectedTab = tab;
}
}
}
| |
// Copyright (c) Ben A Adams. All rights reserved.
// Licensed under the Apache License, Version 2.0.
//
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestUtilities.Ben.Demystifier {
public static class StringBuilderExtensions {
public static StringBuilder AppendException(this StringBuilder stringBuilder, Exception exception) {
stringBuilder.Append(exception.Message);
if (exception.InnerException != null) {
stringBuilder
.Append(" ---> ")
.AppendException(exception.InnerException)
.AppendLine()
.Append(" --- End of inner exception stack trace ---");
}
var frames = new StackTrace(exception, true).GetFrames();
if (frames != null && frames.Length > 0) {
stringBuilder.AppendLine().AppendFrames(frames);
}
return stringBuilder;
}
public static StringBuilder AppendFrames(this StringBuilder stringBuilder, StackFrame[] frames) {
if (frames == null || frames.Length == 0) {
return stringBuilder;
}
for (var i = 0; i < frames.Length; i++) {
var frame = frames[i];
var method = frame.GetMethod();
// Always show last stackFrame
if (!ShowInStackTrace(method) && i != frames.Length - 1) {
continue;
}
if (i > 0) {
stringBuilder.AppendLine();
}
stringBuilder
.Append(" at ")
.AppendMethod(GetMethodDisplay(method));
var filePath = frame.GetFileName();
if (!string.IsNullOrEmpty(filePath) && Uri.TryCreate(filePath, UriKind.Absolute, out var uri)) {
try {
filePath = uri.IsFile ? Path.GetFullPath(filePath) : uri.ToString();
stringBuilder.Append(" in ").Append(filePath);
} catch (PathTooLongException) { } catch (SecurityException) { }
}
var lineNo = frame.GetFileLineNumber();
if (lineNo != 0) {
stringBuilder.Append(":line ");
stringBuilder.Append(lineNo);
}
}
return stringBuilder;
}
private static void AppendMethod(this StringBuilder builder, ResolvedMethod method) {
if (method.IsAsync) {
builder.Append("async ");
}
if (method.ReturnParameter.Type != null) {
builder
.AppendParameter(method.ReturnParameter)
.Append(" ");
}
var isSubMethodOrLambda = !string.IsNullOrEmpty(method.SubMethod) || method.IsLambda;
builder
.AppendMethodName(method.Name, method.DeclaringTypeName, isSubMethodOrLambda)
.Append(method.GenericArguments)
.AppendParameters(method.Parameters, method.MethodBase != null);
if (isSubMethodOrLambda) {
builder
.Append("+")
.Append(method.SubMethod)
.AppendParameters(method.SubMethodParameters, method.SubMethodBase != null);
if (method.IsLambda) {
builder.Append(" => { }");
if (method.Ordinal.HasValue){
builder.Append(" [");
builder.Append(method.Ordinal);
builder.Append("]");
}
}
}
}
public static StringBuilder AppendMethodName(this StringBuilder stringBuilder, string name, string declaringTypeName, bool isSubMethodOrLambda) {
if (!string.IsNullOrEmpty(declaringTypeName)) {
if (name == ".ctor") {
if (!isSubMethodOrLambda)
stringBuilder.Append("new ");
stringBuilder.Append(declaringTypeName);
} else if (name == ".cctor") {
stringBuilder
.Append("static ")
.Append(declaringTypeName);
} else {
stringBuilder
.Append(declaringTypeName)
.Append(".")
.Append(name);
}
} else {
stringBuilder.Append(name);
}
return stringBuilder;
}
private static void AppendParameters(this StringBuilder stringBuilder, List<ResolvedParameter> parameters, bool condition) {
stringBuilder.Append("(");
if (parameters != null) {
if (condition) {
stringBuilder.AppendParameters(parameters);
} else {
stringBuilder.Append("?");
}
}
stringBuilder.Append(")");
}
private static void AppendParameters(this StringBuilder stringBuilder, List<ResolvedParameter> parameters) {
var isFirst = true;
foreach (var param in parameters) {
if (isFirst) {
isFirst = false;
} else {
stringBuilder.Append(", ");
}
stringBuilder.AppendParameter(param);
}
}
private static StringBuilder AppendParameter(this StringBuilder stringBuilder, ResolvedParameter parameter) {
if (!string.IsNullOrEmpty(parameter.Prefix)) {
stringBuilder.Append(parameter.Prefix).Append(" ");
}
stringBuilder.Append(parameter.Type);
if (!string.IsNullOrEmpty(parameter.Name)) {
stringBuilder.Append(" ").Append(parameter.Name);
}
return stringBuilder;
}
private static bool ShowInStackTrace(MethodBase method) {
try {
var type = method.DeclaringType;
if (type == null) {
return true;
}
if (type == typeof(Task<>) && method.Name == "InnerInvoke") {
return false;
}
if (type == typeof(Task)) {
switch (method.Name) {
case "ExecuteWithThreadLocal":
case "Execute":
case "ExecutionContextCallback":
case "ExecuteEntry":
case "InnerInvoke":
return false;
}
}
if (type == typeof(ExecutionContext)) {
switch (method.Name) {
case "RunInternal":
case "Run":
return false;
}
}
// Don't show any methods marked with the StackTraceHiddenAttribute
// https://github.com/dotnet/coreclr/pull/14652
foreach (var attibute in method.GetCustomAttributesData()) {
// internal Attribute, match on name
if (attibute.AttributeType.Name == "StackTraceHiddenAttribute") {
return false;
}
}
foreach (var attibute in type.GetCustomAttributesData()) {
// internal Attribute, match on name
if (attibute.AttributeType.Name == "StackTraceHiddenAttribute") {
return false;
}
}
// Fallbacks for runtime pre-StackTraceHiddenAttribute
if (type == typeof(ExceptionDispatchInfo) && method.Name == nameof(ExceptionDispatchInfo)) {
return false;
}
if (type == typeof(TaskAwaiter) ||
type == typeof(TaskAwaiter<>) ||
type == typeof(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter) ||
type == typeof(ConfiguredTaskAwaitable<>.ConfiguredTaskAwaiter)) {
switch (method.Name) {
case "HandleNonSuccessAndDebuggerNotification":
case "ThrowForNonSuccess":
case "ValidateEnd":
case "GetResult":
return false;
}
} else if (type.FullName == "System.ThrowHelper") {
return false;
}
} catch {
// GetCustomAttributesData can throw
return true;
}
return true;
}
private static ResolvedMethod GetMethodDisplay(MethodBase originMethod) {
var methodDisplayInfo = new ResolvedMethod();
// Special case: no method available
if (originMethod == null) {
return methodDisplayInfo;
}
var method = originMethod;
methodDisplayInfo.SubMethodBase = method;
// Type name
var type = method.DeclaringType;
var subMethodName = method.Name;
var methodName = method.Name;
if (type != null && type.IsDefined(typeof(CompilerGeneratedAttribute)) &&
(typeof(IAsyncStateMachine).IsAssignableFrom(type) || typeof(IEnumerator).IsAssignableFrom(type))) {
methodDisplayInfo.IsAsync = typeof(IAsyncStateMachine).IsAssignableFrom(type);
// Convert StateMachine methods to correct overload +MoveNext()
if (!TryResolveStateMachineMethod(ref method, out type)) {
methodDisplayInfo.SubMethodBase = null;
subMethodName = null;
}
methodName = method.Name;
}
// Method name
methodDisplayInfo.MethodBase = method;
methodDisplayInfo.Name = methodName;
if (method.Name.IndexOf("<", StringComparison.Ordinal) >= 0) {
if (TryResolveGeneratedName(ref method, out type, out methodName, out subMethodName, out var kind, out var ordinal)) {
methodName = method.Name;
methodDisplayInfo.MethodBase = method;
methodDisplayInfo.Name = methodName;
methodDisplayInfo.Ordinal = ordinal;
} else {
methodDisplayInfo.MethodBase = null;
}
methodDisplayInfo.IsLambda = (kind == GeneratedNameKind.LambdaMethod);
if (methodDisplayInfo.IsLambda && type != null) {
if (methodName == ".cctor") {
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var field in fields) {
var value = field.GetValue(field);
if (value is Delegate d) {
if (ReferenceEquals(d.Method, originMethod) && d.Target.ToString() == originMethod.DeclaringType?.ToString()) {
methodDisplayInfo.Name = field.Name;
methodDisplayInfo.IsLambda = false;
method = originMethod;
break;
}
}
}
}
}
}
if (subMethodName != methodName) {
methodDisplayInfo.SubMethod = subMethodName;
}
// ResolveStateMachineMethod may have set declaringType to null
if (type != null) {
var declaringTypeName = TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: true);
methodDisplayInfo.DeclaringTypeName = declaringTypeName;
}
if (method is MethodInfo mi) {
var returnParameter = mi.ReturnParameter;
if (returnParameter != null) {
methodDisplayInfo.ReturnParameter = GetParameter(mi.ReturnParameter);
} else {
methodDisplayInfo.ReturnParameter = new ResolvedParameter(string.Empty
, TypeNameHelper.GetTypeDisplayName(mi.ReturnType, fullName: false, includeGenericParameterNames: true)
, mi.ReturnType
, string.Empty);
}
}
if (method.IsGenericMethod) {
var genericArguments = method.GetGenericArguments();
var genericArgumentsString = string.Join(", ", genericArguments
.Select(arg => TypeNameHelper.GetTypeDisplayName(arg, fullName: false, includeGenericParameterNames: true)));
methodDisplayInfo.GenericArguments += "<" + genericArgumentsString + ">";
methodDisplayInfo.ResolvedGenericArguments = genericArguments;
}
// Method parameters
var parameters = method.GetParameters();
if (parameters.Length > 0) {
var resolvedParameters = new List<ResolvedParameter>(parameters.Length);
for (var i = 0; i < parameters.Length; i++) {
resolvedParameters.Add(GetParameter(parameters[i]));
}
methodDisplayInfo.Parameters = resolvedParameters;
}
if (methodDisplayInfo.SubMethodBase == methodDisplayInfo.MethodBase) {
methodDisplayInfo.SubMethodBase = null;
} else if (methodDisplayInfo.SubMethodBase != null) {
parameters = methodDisplayInfo.SubMethodBase.GetParameters();
if (parameters.Length > 0) {
var parameterList = new List<ResolvedParameter>(parameters.Length);
foreach (var parameter in parameters) {
var param = GetParameter(parameter);
if (param.Name?.StartsWith("<") ?? true) {
continue;
}
parameterList.Add(param);
}
methodDisplayInfo.SubMethodParameters = parameterList;
}
}
return methodDisplayInfo;
}
private static bool TryResolveGeneratedName(ref MethodBase method
, out Type type
, out string methodName
, out string subMethodName
, out GeneratedNameKind kind
, out int? ordinal) {
kind = GeneratedNameKind.None;
type = method.DeclaringType;
subMethodName = null;
ordinal = null;
methodName = method.Name;
var generatedName = methodName;
if (!TryParseGeneratedName(generatedName, out kind, out var openBracketOffset, out var closeBracketOffset)) {
return false;
}
methodName = generatedName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
switch (kind) {
case GeneratedNameKind.LocalFunction: {
var localNameStart = generatedName.IndexOf((char)kind, closeBracketOffset + 1);
if (localNameStart < 0) break;
localNameStart += 3;
if (localNameStart < generatedName.Length) {
var localNameEnd = generatedName.IndexOf("|", localNameStart, StringComparison.Ordinal);
if (localNameEnd > 0) {
subMethodName = generatedName.Substring(localNameStart, localNameEnd - localNameStart);
}
}
break;
}
case GeneratedNameKind.LambdaMethod:
subMethodName = "";
break;
}
var dt = method.DeclaringType;
if (dt == null) {
return false;
}
var matchHint = GetMatchHint(kind, method);
var matchName = methodName;
var candidateMethods = dt.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(m => m.Name == matchName);
if (TryResolveSourceMethod(candidateMethods, kind, matchHint, ref method, ref type, out ordinal)) return true;
var candidateConstructors = dt.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(m => m.Name == matchName);
if (TryResolveSourceMethod(candidateConstructors, kind, matchHint, ref method, ref type, out ordinal)) return true;
const int MaxResolveDepth = 10;
for (var i = 0; i < MaxResolveDepth; i++) {
dt = dt.DeclaringType;
if (dt == null) {
return false;
}
candidateMethods = dt.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(m => m.Name == matchName);
if (TryResolveSourceMethod(candidateMethods, kind, matchHint, ref method, ref type, out ordinal)) return true;
candidateConstructors = dt.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(m => m.Name == matchName);
if (TryResolveSourceMethod(candidateConstructors, kind, matchHint, ref method, ref type, out ordinal)) return true;
if (methodName == ".cctor") {
candidateConstructors = dt.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly).Where(m => m.Name == matchName);
foreach (var cctor in candidateConstructors)
{
method = cctor;
type = dt;
return true;
}
}
}
return false;
}
private static bool TryResolveSourceMethod(IEnumerable<MethodBase> candidateMethods
, GeneratedNameKind kind
, string matchHint
, ref MethodBase method
, ref Type type
, out int? ordinal) {
ordinal = null;
foreach (var candidateMethod in candidateMethods) {
var methodBody = candidateMethod.GetMethodBody();
if (methodBody != null && kind == GeneratedNameKind.LambdaMethod) {
foreach (var v in methodBody.LocalVariables) {
if (v.LocalType == type) {
GetOrdinal(method, ref ordinal);
}
method = candidateMethod;
type = method.DeclaringType;
return true;
}
}
try {
var rawIL = methodBody?.GetILAsByteArray();
if (rawIL == null) {
continue;
}
var reader = new ILReader(rawIL);
while (reader.Read(candidateMethod)) {
if (reader.Operand is MethodBase mb) {
if (method == mb || (matchHint != null && method.Name.Contains(matchHint))) {
if (kind == GeneratedNameKind.LambdaMethod) {
GetOrdinal(method, ref ordinal);
}
method = candidateMethod;
type = method.DeclaringType;
return true;
}
}
}
} catch {
// https://github.com/benaadams/Ben.Demystifier/issues/32
// Skip methods where il can't be interpreted
}
}
return false;
}
private static void GetOrdinal(MethodBase method, ref int? ordinal) {
var lamdaStart = method.Name.IndexOf((char)GeneratedNameKind.LambdaMethod + "__", StringComparison.Ordinal) + 3;
if (lamdaStart > 3) {
var secondStart = method.Name.IndexOf("_", lamdaStart, StringComparison.Ordinal) + 1;
if (secondStart > 0) {
lamdaStart = secondStart;
}
if (!int.TryParse(method.Name.Substring(lamdaStart), out var foundOrdinal)) {
ordinal = null;
return;
}
ordinal = foundOrdinal;
var methods = method.DeclaringType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var startName = method.Name.Substring(0, lamdaStart);
var count = 0;
foreach (var m in methods) {
if (m.Name.Length > lamdaStart && m.Name.StartsWith(startName)) {
count++;
if (count > 1) {
break;
}
}
}
if (count <= 1) {
ordinal = null;
}
}
}
private static string GetMatchHint(GeneratedNameKind kind, MethodBase method) {
var methodName = method.Name;
switch (kind) {
case GeneratedNameKind.LocalFunction:
var start = methodName.IndexOf("|", StringComparison.Ordinal);
if (start < 1) return null;
var end = methodName.IndexOf("_", start, StringComparison.Ordinal) + 1;
if (end <= start) return null;
return methodName.Substring(start, end - start);
default:
return null;
}
}
// Parse the generated name. Returns true for names of the form
// [CS$]<[middle]>c[__[suffix]] where [CS$] is included for certain
// generated names, where [middle] and [__[suffix]] are optional,
// and where c is a single character in [1-9a-z]
// (csharp\LanguageAnalysis\LIB\SpecialName.cpp).
private static bool TryParseGeneratedName(string name, out GeneratedNameKind kind, out int openBracketOffset, out int closeBracketOffset) {
openBracketOffset = -1;
if (name.StartsWith("CS$<", StringComparison.Ordinal)) {
openBracketOffset = 3;
} else if (name.StartsWith("<", StringComparison.Ordinal)) {
openBracketOffset = 0;
}
if (openBracketOffset >= 0) {
closeBracketOffset = IndexOfBalancedParenthesis(name, openBracketOffset, '>');
if (closeBracketOffset >= 0 && closeBracketOffset + 1 < name.Length) {
int c = name[closeBracketOffset + 1];
// Note '0' is not special.
if ((c >= '1' && c <= '9') || (c >= 'a' && c <= 'z')) {
kind = (GeneratedNameKind)c;
return true;
}
}
}
kind = GeneratedNameKind.None;
openBracketOffset = -1;
closeBracketOffset = -1;
return false;
}
private static int IndexOfBalancedParenthesis(string str, int openingOffset, char closing) {
var opening = str[openingOffset];
var depth = 1;
for (var i = openingOffset + 1; i < str.Length; i++) {
var c = str[i];
if (c == opening) {
depth++;
} else if (c == closing) {
depth--;
if (depth == 0) {
return i;
}
}
}
return -1;
}
private static string GetPrefix(ParameterInfo parameter, Type parameterType) {
if (parameter.IsOut) {
return "out";
}
if (parameterType != null && parameterType.IsByRef) {
var attribs = parameter.GetCustomAttributes(inherit: false);
if (attribs?.Length > 0) {
foreach (var attrib in attribs) {
if (attrib is Attribute att && att.GetType().Namespace == "System.Runtime.CompilerServices" && att.GetType().Name == "IsReadOnlyAttribute") {
return "in";
}
}
}
return "ref";
}
return string.Empty;
}
private static ResolvedParameter GetParameter(ParameterInfo parameter) {
var parameterType = parameter.ParameterType;
var prefix = GetPrefix(parameter, parameterType);
var parameterTypeString = "?";
if (parameterType.IsGenericType) {
var customAttribs = parameter.GetCustomAttributes(inherit: false);
// We don't use System.ValueTuple yet
//if (customAttribs.Length > 0) {
// var tupleNames = customAttribs.OfType<TupleElementNamesAttribute>().FirstOrDefault()?.TransformNames;
// if (tupleNames?.Count > 0) {
// return GetValueTupleParameter(tupleNames, prefix, parameter.Name, parameterType);
// }
//}
}
if (parameterType.IsByRef) {
parameterType = parameterType.GetElementType();
}
parameterTypeString = TypeNameHelper.GetTypeDisplayName(parameterType, fullName: false, includeGenericParameterNames: true);
return new ResolvedParameter(parameter.Name, parameterTypeString, parameterType, prefix);
}
private static ResolvedParameter GetValueTupleParameter(List<string> tupleNames, string prefix, string name, Type parameterType) {
var sb = new StringBuilder();
sb.Append("(");
var args = parameterType.GetGenericArguments();
for (var i = 0; i < args.Length; i++) {
if (i > 0) {
sb.Append(", ");
}
sb.Append(TypeNameHelper.GetTypeDisplayName(args[i], fullName: false, includeGenericParameterNames: true));
if (i >= tupleNames.Count) {
continue;
}
var argName = tupleNames[i];
if (argName == null) {
continue;
}
sb.Append(" ");
sb.Append(argName);
}
sb.Append(")");
return new ResolvedParameter(name, sb.ToString(), parameterType, prefix);
}
private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type declaringType) {
Debug.Assert(method != null);
Debug.Assert(method.DeclaringType != null);
declaringType = method.DeclaringType;
var parentType = declaringType.DeclaringType;
if (parentType == null) {
return false;
}
var methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (var candidateMethod in methods) {
var attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>();
foreach (var asma in attributes) {
if (asma.StateMachineType == declaringType) {
method = candidateMethod;
declaringType = candidateMethod.DeclaringType;
// Mark the iterator as changed; so it gets the + annotation of the original method
// async statemachines resolve directly to their builder methods so aren't marked as changed
return asma is IteratorStateMachineAttribute;
}
}
}
return false;
}
private enum GeneratedNameKind {
None = 0,
// Used by EE:
ThisProxyField = '4',
HoistedLocalField = '5',
DisplayClassLocalOrField = '8',
LambdaMethod = 'b',
LambdaDisplayClass = 'c',
StateMachineType = 'd',
LocalFunction = 'g', // note collision with Deprecated_InitializerLocal, however this one is only used for method names
// Used by EnC:
AwaiterField = 'u',
HoistedSynthesizedLocalField = 's',
// Currently not parsed:
StateMachineStateField = '1',
IteratorCurrentBackingField = '2',
StateMachineParameterProxyField = '3',
ReusableHoistedLocalField = '7',
LambdaCacheField = '9',
FixedBufferField = 'e',
AnonymousType = 'f',
TransparentIdentifier = 'h',
AnonymousTypeField = 'i',
AutoPropertyBackingField = 'k',
IteratorCurrentThreadIdField = 'l',
IteratorFinallyMethod = 'm',
BaseMethodWrapper = 'n',
AsyncBuilderField = 't',
DynamicCallSiteContainerType = 'o',
DynamicCallSiteField = 'p'
}
private struct ResolvedMethod {
public MethodBase MethodBase { get; set; }
public string DeclaringTypeName { get; set; }
public bool IsAsync { get; set; }
public bool IsLambda { get; set; }
public ResolvedParameter ReturnParameter { get; set; }
public string Name { get; set; }
public int? Ordinal { get; set; }
public string GenericArguments { get; set; }
public Type[] ResolvedGenericArguments { get; set; }
public MethodBase SubMethodBase { get; set; }
public string SubMethod { get; set; }
public List<ResolvedParameter> Parameters { get; set; }
public List<ResolvedParameter> SubMethodParameters { get; set; }
}
private struct ResolvedParameter {
public string Name { get; }
public string Type { get; }
public Type ResolvedType { get; }
public string Prefix { get; }
public ResolvedParameter(string name, string type, Type resolvedType, string prefix) {
Name = name;
Type = type;
ResolvedType = resolvedType;
Prefix = prefix;
}
}
}
}
| |
//
// Copyright (c) 2004-2017 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.Common
{
using JetBrains.Annotations;
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using Internal;
using Time;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
using ConfigurationManager = System.Configuration.ConfigurationManager;
using System.Diagnostics;
#endif
/// <summary>
/// NLog internal logger.
///
/// Writes to file, console or custom textwriter (see <see cref="InternalLogger.LogWriter"/>)
/// </summary>
/// <remarks>
/// Don't use <see cref="ExceptionHelper.MustBeRethrown"/> as that can lead to recursive calls - stackoverflows
/// </remarks>
public static partial class InternalLogger
{
private static readonly object LockObject = new object();
private static string _logFile;
/// <summary>
/// Initializes static members of the InternalLogger class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static InternalLogger()
{
Reset();
}
/// <summary>
/// Set the config of the InternalLogger with defaults and config.
/// </summary>
public static void Reset()
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false);
LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false);
LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Info);
LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty);
LogToTrace = GetSetting("nlog.internalLogToTrace", "NLOG_INTERNAL_LOG_TO_TRACE", false);
IncludeTimestamp = GetSetting("nlog.internalLogIncludeTimestamp", "NLOG_INTERNAL_INCLUDE_TIMESTAMP", true);
Info("NLog internal logger initialized.");
#else
LogLevel = LogLevel.Info;
LogToConsole = false;
LogToConsoleError = false;
LogFile = string.Empty;
IncludeTimestamp = true;
#endif
ExceptionThrowWhenWriting = false;
LogWriter = null;
}
/// <summary>
/// Gets or sets the minimal internal log level.
/// </summary>
/// <example>If set to <see cref="NLog.LogLevel.Info"/>, then messages of the levels <see cref="NLog.LogLevel.Info"/>, <see cref="NLog.LogLevel.Error"/> and <see cref="NLog.LogLevel.Fatal"/> will be written.</example>
public static LogLevel LogLevel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console output stream.
/// </summary>
/// <remarks>Your application must be a console application.</remarks>
public static bool LogToConsole { get; set; }
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console error stream.
/// </summary>
/// <remarks>Your application must be a console application.</remarks>
public static bool LogToConsoleError { get; set; }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the <see cref="System.Diagnostics.Trace"/>.
/// </summary>
public static bool LogToTrace { get; set; }
#endif
/// <summary>
/// Gets or sets the file path of the internal log file.
/// </summary>
/// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks>
public static string LogFile
{
get
{
return _logFile;
}
set
{
_logFile = value;
#if !SILVERLIGHT
if (!string.IsNullOrEmpty(_logFile))
{
CreateDirectoriesIfNeeded(_logFile);
}
#endif
}
}
/// <summary>
/// Gets or sets the text writer that will receive internal logs.
/// </summary>
public static TextWriter LogWriter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether timestamp should be included in internal log output.
/// </summary>
public static bool IncludeTimestamp { get; set; }
/// <summary>
/// Is there an <see cref="Exception"/> thrown when writing the message?
/// </summary>
internal static bool ExceptionThrowWhenWriting { get; private set; }
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Log(LogLevel level, [Localizable(false)] string message, params object[] args)
{
Write(null, level, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Log message.</param>
public static void Log(LogLevel level, [Localizable(false)] string message)
{
Write(null, level, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="messageFunc">Function that returns the log message.</param>
public static void Log(LogLevel level, [Localizable(false)] Func<string> messageFunc)
{
if (level >= LogLevel)
{
Write(null, level, messageFunc(), null);
}
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="messageFunc">Function that returns the log message.</param>
[StringFormatMethod("message")]
public static void Log(Exception ex, LogLevel level, [Localizable(false)] Func<string> messageFunc)
{
if (level >= LogLevel)
{
Write(ex, level, messageFunc(), null);
}
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message, params object[] args)
{
Write(ex, level, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="message">Log message.</param>
public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message)
{
Write(ex, level, message, null);
}
/// <summary>
/// Write to internallogger.
/// </summary>
/// <param name="ex">optional exception to be logged.</param>
/// <param name="level">level</param>
/// <param name="message">message</param>
/// <param name="args">optional args for <paramref name="message"/></param>
private static void Write([CanBeNull]Exception ex, LogLevel level, string message, [CanBeNull]object[] args)
{
if (IsSeriousException(ex))
{
//no logging!
return;
}
if (!LoggingEnabled(level))
{
return;
}
try
{
var formattedMessage = message;
if (args != null)
{
formattedMessage = string.Format(CultureInfo.InvariantCulture, message, args);
}
var builder = new StringBuilder(message.Length + 32);
if (IncludeTimestamp)
{
builder.Append(TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture));
builder.Append(" ");
}
builder.Append(level);
builder.Append(" ");
builder.Append(formattedMessage);
if (ex != null)
{
ex.MarkAsLoggedToInternalLogger();
builder.Append(" Exception: ");
builder.Append(ex);
}
var msg = builder.ToString();
// log to file
var logFile = LogFile;
if (!string.IsNullOrEmpty(logFile))
{
lock (LockObject)
{
using (var textWriter = File.AppendText(logFile))
{
textWriter.WriteLine(msg);
}
}
}
// log to LogWriter
var writer = LogWriter;
if (writer != null)
{
lock (LockObject)
{
writer.WriteLine(msg);
}
}
// log to console
if (LogToConsole)
{
lock (LockObject)
{
Console.WriteLine(msg);
}
}
// log to console error
if (LogToConsoleError)
{
lock (LockObject)
{
Console.Error.WriteLine(msg);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
WriteToTrace(msg);
#endif
}
catch (Exception exception)
{
ExceptionThrowWhenWriting = true;
// no log looping.
// we have no place to log the message to so we ignore it
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
/// <summary>
/// Determine if logging should be avoided because of exception type.
/// </summary>
/// <param name="exception">The exception to check.</param>
/// <returns><c>true</c> if logging should be avoided; otherwise, <c>false</c>.</returns>
private static bool IsSeriousException(Exception exception)
{
return exception != null && exception.MustBeRethrownImmediately();
}
/// <summary>
/// Determine if logging is enabled.
/// </summary>
/// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param>
/// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns>
private static bool LoggingEnabled(LogLevel logLevel)
{
if (logLevel == LogLevel.Off || logLevel < LogLevel)
{
return false;
}
return !string.IsNullOrEmpty(LogFile) ||
LogToConsole ||
LogToConsoleError ||
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
LogToTrace ||
#endif
LogWriter != null;
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Write internal messages to the <see cref="System.Diagnostics.Trace"/>.
/// </summary>
/// <param name="message">A message to write.</param>
/// <remarks>
/// Works when property <see cref="LogToTrace"/> set to true.
/// The <see cref="System.Diagnostics.Trace"/> is used in Debug and Relese configuration.
/// The <see cref="System.Diagnostics.Debug"/> works only in Debug configuration and this is reason why is replaced by <see cref="System.Diagnostics.Trace"/>.
/// in DEBUG
/// </remarks>
private static void WriteToTrace(string message)
{
if (!LogToTrace)
{
return;
}
System.Diagnostics.Trace.WriteLine(message, "NLog");
}
#endif
/// <summary>
/// Logs the assembly version and file version of the given Assembly.
/// </summary>
/// <param name="assembly">The assembly to log.</param>
public static void LogAssemblyVersion(Assembly assembly)
{
try
{
#if SILVERLIGHT || __IOS__ || __ANDROID__ || NETSTANDARD
Info(assembly.FullName);
#else
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
Info("{0}. File version: {1}. Product version: {2}.",
assembly.FullName,
fileVersionInfo.FileVersion,
fileVersionInfo.ProductVersion);
#endif
}
catch (Exception ex)
{
Error(ex, "Error logging version of assembly {0}.", assembly.FullName);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
private static string GetSettingString(string configName, string envName)
{
string settingValue = ConfigurationManager.AppSettings[configName];
if (settingValue == null)
{
try
{
settingValue = Environment.GetEnvironmentVariable(envName);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
return settingValue;
}
private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return LogLevel.FromString(value);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
return defaultValue;
}
}
private static T GetSetting<T>(string configName, string envName, T defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
return defaultValue;
}
}
#endif
#if !SILVERLIGHT
private static void CreateDirectoriesIfNeeded(string filename)
{
try
{
if (InternalLogger.LogLevel == NLog.LogLevel.Off)
{
return;
}
string parentDirectory = Path.GetDirectoryName(filename);
if (!string.IsNullOrEmpty(parentDirectory))
{
Directory.CreateDirectory(parentDirectory);
}
}
catch (Exception exception)
{
Error(exception, "Cannot create needed directories to '{0}'.", filename);
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
#endif
}
}
| |
namespace NuGet.Test {
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NuGet.Test.Mocks;
[TestClass]
public class PackageManagerTest {
[TestMethod]
public void CtorThrowsIfDependenciesAreNull() {
// Act & Assert
ExceptionAssert.ThrowsArgNull(() => new PackageManager(null, new DefaultPackagePathResolver("foo"), new MockProjectSystem(), new MockPackageRepository()), "sourceRepository");
ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), null, new MockProjectSystem(), new MockPackageRepository()), "pathResolver");
ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), null, new MockPackageRepository()), "fileSystem");
ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), new MockProjectSystem(), null), "localRepository");
}
[TestMethod]
public void InstallingPackageWithUnknownDependencyAndIgnoreDepencenciesInstallsPackageWithoutDependencies() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageC);
// Act
packageManager.InstallPackage("A", version: null, ignoreDependencies: true);
// Assert
Assert.IsTrue(localRepository.Exists(packageA));
Assert.IsFalse(localRepository.Exists(packageC));
}
[TestMethod]
public void UninstallingUnknownPackageThrows() {
// Arrange
PackageManager packageManager = CreatePackageManager();
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UninstallPackage("foo"), "Unable to find package 'foo'.");
}
[TestMethod]
public void UninstallingUnknownNullOrEmptyPackageIdThrows() {
// Arrange
PackageManager packageManager = CreatePackageManager();
// Act & Assert
ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage((string)null), "packageId");
ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage(String.Empty), "packageId");
}
[TestMethod]
public void UninstallingPackageWithNoDependents() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
var package = PackageUtility.CreatePackage("foo", "1.2.33");
localRepository.AddPackage(package);
// Act
packageManager.UninstallPackage("foo");
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(package));
}
[TestMethod]
public void InstallingUnknownPackageThrows() {
// Arrange
PackageManager packageManager = CreatePackageManager();
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.InstallPackage("unknown"),
"Unable to find package 'unknown'.");
}
[TestMethod]
public void InstallPackageNullOrEmptyPackageIdThrows() {
// Arrange
PackageManager packageManager = CreatePackageManager();
// Act & Assert
ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage((string)null), "packageId");
ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage(String.Empty), "packageId");
}
[TestMethod]
public void InstallPackageAddsAllFilesToFileSystem() {
// Arrange
var projectSystem = new MockProjectSystem();
var sourceRepository = new MockPackageRepository();
var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem);
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
new[] { "contentFile", @"sub\contentFile" },
new[] { @"lib\reference.dll" },
new[] { @"readme.txt" });
sourceRepository.AddPackage(packageA);
// Act
packageManager.InstallPackage("A");
// Assert
Assert.AreEqual(0, projectSystem.References.Count);
Assert.AreEqual(5, projectSystem.Paths.Count);
Assert.IsTrue(projectSystem.FileExists(@"A.1.0\content\contentFile"));
Assert.IsTrue(projectSystem.FileExists(@"A.1.0\content\sub\contentFile"));
Assert.IsTrue(projectSystem.FileExists(@"A.1.0\lib\reference.dll"));
Assert.IsTrue(projectSystem.FileExists(@"A.1.0\tools\readme.txt"));
Assert.IsTrue(projectSystem.FileExists(@"A.1.0\A.1.0.nupkg"));
}
[TestMethod]
public void UnInstallingPackageUninstallsPackageButNotDependencies() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
// Act
packageManager.UninstallPackage("A");
// Assert
Assert.IsFalse(localRepository.Exists(packageA));
Assert.IsTrue(localRepository.Exists(packageB));
}
[TestMethod]
public void ReInstallingPackageAfterUninstallingDependencyShouldReinstallAllDependencies() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C")
});
var packageC = PackageUtility.CreatePackage("C", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
// Act
packageManager.InstallPackage("A");
// Assert
Assert.IsTrue(localRepository.Exists(packageA));
Assert.IsTrue(localRepository.Exists(packageB));
Assert.IsTrue(localRepository.Exists(packageC));
}
[TestMethod]
public void InstallPackageThrowsExceptionPackageIsNotInstalled() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new Mock<IProjectSystem>();
projectSystem.Setup(m => m.AddFile(@"A.1.0\content\file", It.IsAny<Stream>())).Throws<UnauthorizedAccessException>();
projectSystem.Setup(m => m.Root).Returns("FakeRoot");
PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem.Object), projectSystem.Object, localRepository);
IPackage packageA = PackageUtility.CreatePackage("A", "1.0", new[] { "file" });
sourceRepository.AddPackage(packageA);
// Act
ExceptionAssert.Throws<UnauthorizedAccessException>(() => packageManager.InstallPackage("A"));
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(packageA));
}
[TestMethod]
public void UpdatePackageUninstallsPackageAndInstallsNewPackage() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage A10 = PackageUtility.CreatePackage("A", "1.0");
IPackage A20 = PackageUtility.CreatePackage("A", "2.0");
localRepository.Add(A10);
sourceRepository.Add(A20);
// Act
packageManager.UpdatePackage("A", updateDependencies: true);
// Assert
Assert.IsFalse(localRepository.Exists("A", new Version("1.0")));
Assert.IsTrue(localRepository.Exists("A", new Version("2.0")));
}
[TestMethod]
public void UpdatePackageThrowsIfPackageNotInstalled() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage A20 = PackageUtility.CreatePackage("A", "2.0");
sourceRepository.Add(A20);
// Act
ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UpdatePackage("A", updateDependencies: true), "Unable to find package 'A'.");
}
[TestMethod]
public void UpdatePackageDoesNothingIfNoUpdatesAvailable() {
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository);
IPackage A10 = PackageUtility.CreatePackage("A", "1.0");
localRepository.Add(A10);
// Act
packageManager.UpdatePackage("A", updateDependencies: true);
// Assert
Assert.IsTrue(localRepository.Exists("A", new Version("1.0")));
}
private PackageManager CreatePackageManager() {
var projectSystem = new MockProjectSystem();
return new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver(projectSystem), projectSystem);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Contracts.Foxtrot.Driver
{
internal class FoxtrotOptions : OptionParsing
{
[OptionDescription("Automatically load out-of-band contracts.", ShortForm = "autoRef")]
public bool automaticallyLookForOOBs = true;
[OptionDescription("Silently do nothing if the input assembly has already been rewritten.")]
public bool allowRewritten = false;
[OptionDescription("Causes the debugger to be invoked.", ShortForm = "break")]
public bool breakIntoDebugger = false;
[OptionDescription("Out-of-band contract assemblies.")]
public List<string> contracts = null;
[OptionDescription("Use debug information.")]
public bool debug = true;
[OptionDescription("produce non-zero return code when warnings are found")]
public bool failOnWarnings = false;
[OptionDescription("Hide rewritten contract methods from debugger.")]
public bool hideFromDebugger = true;
[OptionDescription("Full paths to candidate dlls to load for resolution.")]
public List<string> resolvedPaths =
null;
[OptionDescription("Additional paths to search for referenced assemblies.")]
public List<string> libpaths = null;
[OptionDescription("Instrumentation level: 0=no contracts, 1=ReleaseRequires, 2=Requires, 3=Ensures, 4=Invariants. (Each increase includes the previous)")]
public int level = 4; // default: all contracts
[OptionDescription("Contract recursion level at which to stop evaluating contracts")]
public int recursionGuard= 4;
[OptionDescription("Throw ContractException on contract failure", ShortForm = "throw")]
public bool throwOnFailure = false;
[OptionDescription("Remove all contracts except those visible from outside assembly", ShortForm = "publicSurface")]
public bool publicSurfaceOnly = false; // default everywhere
[OptionDescription("Instrument call sites with requires checks where necessary", ShortForm = "csr")]
public bool callSiteRequires = false;
[OptionDescription("Output path for the rewritten assembly.", ShortForm = "out")]
public string output = "same";
[OptionDescription("Write PDB file. Cannot be specified unless /debug is also specified")]
public bool writePDBFile = true;
[OptionDescription("Copy original files (using .original extension)", ShortForm = "originalFiles")]
public bool keepOriginalFiles = false;
[OptionDescription("Don't actually use the rewriter, but pass the assembly through CCI.")]
public bool passthrough = false;
[OptionDescription("Rewrites the given assembly to insert runtime contract checks.")]
public bool rewrite = true;
[OptionDescription("Alternative methods to use for checking contracts at runtime. Syntax: /rw:<assembly>,<class name> or /rw:<assembly>,<namespace name>,<class name>.", ShortForm = "rw")]
public string rewriterMethods = null;
[OptionDescription("Preserve short branches in the rewritten assembly.")]
public bool shortBranches = false;
[OptionDescription("Extract the source text for the contracts. (Requires /debug.)")]
public bool extractSourceText = true;
[OptionDescription("Path to alternate core library (and set of framework assemblies).", ShortForm = "platform")]
public string targetplatform = "";
[OptionDescription("Target .NET framework")]
public string framework = "";
[OptionDescription("Print out extra information.")]
public int verbose = 0;
[OptionDescription("Don't throw up assert listener boxes.")]
public bool nobox = false;
[OptionDescription("Don't print version.")]
public bool nologo = false;
[OptionDescription("Verify the output of rewriting and fail if it verified before but not after.")]
public bool verify = true;
[OptionDescription("Set warning level (0-4)")]
public uint warn = 1;
[OptionDescription("Dll/Exe name containing shared contract class")]
public string contractLibrary = null;
[OptionDescription("Assembly to process is F#")]
public bool fSharp = false;
public enum AssemblyMode
{
standard,
legacy
}
[OptionDescription("Set to legacy if assembly uses if-then-throw parameter validation")]
public AssemblyMode assemblyMode = AssemblyMode.legacy;
[OptionDescription("Write repro.bat for debugging")]
public bool repro = false;
[OptionDescription("Inherit invariants across assemblies", ShortForm = "ii")]
public bool inheritInvariants = true;
[OptionDescription("Skip contracts containing quantifiers", ShortForm = "sq")]
public bool skipQuantifiers =
false;
[OptionDescription("Assembly to process.")]
public string assembly = null;
[OptionDescription("Add interface wrappers to hold inherited contracts when a method used for interface implementation is inherited but does not implement the interface method", ShortForm = "iw")]
public bool addInterfaceWrappersWhenNeeded = true;
[OptionDescription("Use global assembly cache")]
public bool useGAC = true;
[OptionDescription("Suppress warnings")]
public List<int> nowarn = new List<int>();
[OptionDescription("Don't abort due to metadata errors")]
public bool ignoreMetadataErrors = false;
private void HACK_FORCLOUSOT()
{
// set the fields to avoid the warning from clousot
automaticallyLookForOOBs = true;
allowRewritten = false;
breakIntoDebugger = false;
contracts = null;
debug = true;
failOnWarnings = false;
hideFromDebugger = true;
resolvedPaths = null;
libpaths = null;
level = 4;
recursionGuard = 4;
throwOnFailure = false;
publicSurfaceOnly = false;
callSiteRequires = false;
output = "same";
writePDBFile = true;
keepOriginalFiles = false;
passthrough = false;
rewrite = true;
rewriterMethods = null;
shortBranches = false;
extractSourceText = true;
targetplatform = "";
framework = "";
verbose = 0;
nobox = false;
nologo = false;
verify = true;
warn = 1;
contractLibrary = null;
fSharp = false;
assemblyMode = AssemblyMode.legacy;
repro = false;
inheritInvariants = true;
skipQuantifiers = false;
assembly = null;
addInterfaceWrappersWhenNeeded = true;
useGAC = true;
nowarn = new List<int>();
ignoreMetadataErrors = false;
}
private int ErrorCount;
internal int GetErrorCount()
{
return this.ErrorCount;
}
internal void EmitError(System.CodeDom.Compiler.CompilerError error)
{
Contract.Requires(error != null);
if (!error.IsWarning || this.failOnWarnings)
{
ErrorCount++;
}
if (ShouldEmitErrorWarning(error))
{
if (error.IsWarning && this.failOnWarnings)
error.IsWarning = false;
Console.WriteLine(error.ToString());
}
}
private bool ShouldEmitErrorWarning(System.CodeDom.Compiler.CompilerError error)
{
Contract.Requires(error != null);
if (!error.IsWarning || this.failOnWarnings) return true;
if (warn <= 0) return false;
var eName = error.ErrorNumber;
if (eName != null && eName.StartsWith("CC") && eName.Length >= 3)
{
int num;
if (Int32.TryParse(eName.Substring(2), out num))
{
if (nowarn.Contains(num)) return false;
}
}
return true;
}
public bool IsLegacyModeAssembly
{
get { return this.assemblyMode == AssemblyMode.legacy; }
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Runtime.InteropServices;
namespace Facebook.Yoga
{
internal static class Native
{
#if (UNITY_IOS && !UNITY_EDITOR) || __IOS__
private const string DllName = "__Internal";
#else
private const string DllName = "yoga";
#endif
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGInteropSetLogger(
[MarshalAs(UnmanagedType.FunctionPtr)] YogaLogger logger);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YGNodeHandle YGNodeNew();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YGNodeHandle YGNodeNewWithConfig(YGConfigHandle config);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeFree(IntPtr node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeReset(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YGConfigHandle YGConfigGetDefault();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YGConfigHandle YGConfigNew();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigFree(IntPtr node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int YGConfigGetInstanceCount();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigSetExperimentalFeatureEnabled(
YGConfigHandle config,
YogaExperimentalFeature feature,
bool enabled);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern bool YGConfigIsExperimentalFeatureEnabled(
YGConfigHandle config,
YogaExperimentalFeature feature);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigSetUseWebDefaults(
YGConfigHandle config,
bool useWebDefaults);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern bool YGConfigGetUseWebDefaults(YGConfigHandle config);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigSetUseLegacyStretchBehaviour(
YGConfigHandle config,
bool useLegacyStretchBehavior);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern bool YGConfigGetUseLegacyStretchBehaviour(YGConfigHandle config);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigSetPointScaleFactor(
YGConfigHandle config,
float pixelsInPoint);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeInsertChild(
YGNodeHandle node,
YGNodeHandle child,
uint index);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeRemoveChild(YGNodeHandle node, YGNodeHandle child);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetIsReferenceBaseline(
YGNodeHandle node,
bool isReferenceBaseline);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern bool YGNodeIsReferenceBaseline(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeCalculateLayout(
YGNodeHandle node,
float availableWidth,
float availableHeight,
YogaDirection parentDirection);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeMarkDirty(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool YGNodeIsDirty(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodePrint(YGNodeHandle node, YogaPrintOptions options);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeCopyStyle(YGNodeHandle dstNode, YGNodeHandle srcNode);
#region YG_NODE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetMeasureFunc(
YGNodeHandle node,
[MarshalAs(UnmanagedType.FunctionPtr)] YogaMeasureFunc measureFunc);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetBaselineFunc(
YGNodeHandle node,
[MarshalAs(UnmanagedType.FunctionPtr)] YogaBaselineFunc baselineFunc);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetHasNewLayout(
YGNodeHandle node,
[MarshalAs(UnmanagedType.I1)] bool hasNewLayout);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool YGNodeGetHasNewLayout(YGNodeHandle node);
#endregion
#region YG_NODE_STYLE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetDirection(YGNodeHandle node, YogaDirection direction);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDirection YGNodeStyleGetDirection(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexDirection(YGNodeHandle node, YogaFlexDirection flexDirection);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaFlexDirection YGNodeStyleGetFlexDirection(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetJustifyContent(YGNodeHandle node, YogaJustify justifyContent);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaJustify YGNodeStyleGetJustifyContent(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignContent(YGNodeHandle node, YogaAlign alignContent);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignContent(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignItems(YGNodeHandle node, YogaAlign alignItems);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignItems(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignSelf(YGNodeHandle node, YogaAlign alignSelf);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignSelf(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPositionType(YGNodeHandle node, YogaPositionType positionType);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaPositionType YGNodeStyleGetPositionType(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexWrap(YGNodeHandle node, YogaWrap flexWrap);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaWrap YGNodeStyleGetFlexWrap(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetOverflow(YGNodeHandle node, YogaOverflow flexWrap);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaOverflow YGNodeStyleGetOverflow(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetDisplay(YGNodeHandle node, YogaDisplay display);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDisplay YGNodeStyleGetDisplay(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlex(YGNodeHandle node, float flex);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexGrow(YGNodeHandle node, float flexGrow);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetFlexGrow(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexShrink(YGNodeHandle node, float flexShrink);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetFlexShrink(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasis(YGNodeHandle node, float flexBasis);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasisPercent(YGNodeHandle node, float flexBasis);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasisAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetFlexBasis(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidth(YGNodeHandle node, float width);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidthPercent(YGNodeHandle node, float width);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidthAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeight(YGNodeHandle node, float height);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeightPercent(YGNodeHandle node, float height);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeightAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinWidth(YGNodeHandle node, float minWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinWidthPercent(YGNodeHandle node, float minWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMinWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinHeight(YGNodeHandle node, float minHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinHeightPercent(YGNodeHandle node, float minHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMinHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxWidth(YGNodeHandle node, float maxWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxWidthPercent(YGNodeHandle node, float maxWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMaxWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxHeight(YGNodeHandle node, float maxHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxHeightPercent(YGNodeHandle node, float maxHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMaxHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAspectRatio(YGNodeHandle node, float aspectRatio);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetAspectRatio(YGNodeHandle node);
#endregion
#region YG_NODE_STYLE_EDGE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPosition(YGNodeHandle node, YogaEdge edge, float position);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPositionPercent(YGNodeHandle node, YogaEdge edge, float position);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetPosition(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMargin(YGNodeHandle node, YogaEdge edge, float margin);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMarginPercent(YGNodeHandle node, YogaEdge edge, float margin);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMarginAuto(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMargin(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPadding(YGNodeHandle node, YogaEdge edge, float padding);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPaddingPercent(YGNodeHandle node, YogaEdge edge, float padding);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetPadding(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetBorder(YGNodeHandle node, YogaEdge edge, float border);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetBorder(YGNodeHandle node, YogaEdge edge);
#endregion
#region YG_NODE_LAYOUT_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetLeft(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetTop(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetRight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetBottom(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetMargin(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetPadding(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDirection YGNodeLayoutGetDirection(YGNodeHandle node);
#endregion
#region Context
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr YGNodeGetContext(IntPtr node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetContext(IntPtr node, IntPtr managed);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr YGConfigGetContext(IntPtr config);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGConfigSetContext(IntPtr config, IntPtr managed);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using bv.winclient.BasePanel;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using EIDSS.Reports.BaseControls.Filters;
using EIDSS.Reports.BaseControls.Keeper;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.OperationContext;
using EIDSS.Reports.Parameterized.Filters;
using EIDSS.Reports.Parameterized.Human.AJ.Reports;
using bv.common.win;
using bv.model.BLToolkit;
using bv.winclient.Layout;
using eidss.model.Reports.AZ;
namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
public partial class ExternalComparativeReportKeeper : BaseReportKeeper
{
private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ExternalComparativeReportKeeper));
private readonly ComponentResourceManager m_BaseResources = new ComponentResourceManager(typeof(BaseComparativeReportKeeper));
private List<ItemWrapper> m_MonthCollection;
public ExternalComparativeReportKeeper()
: base(new Dictionary<string, string>())
{
InitializeComponent();
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
SetMandatory();
Year2SpinEdit.Value = DateTime.Now.Year;
Year1SpinEdit.Value = DateTime.Now.Year - 1;
BindLookup(StartMonthLookUp, MonthCollection, EndYearLabel.Text);
BindLookup(EndMonthLookUp, MonthCollection, EndMonthLabel.Text);
StartMonthLookUp.EditValue = MonthCollection[0];
EndMonthLookUp.EditValue = MonthCollection[DateTime.Now.Month - 1];
}
m_HasLoad = true;
}
#region Properties
[Browsable(false)]
protected int Year1Param
{
get { return (int) Year1SpinEdit.Value; }
}
[Browsable(false)]
protected int Year2Param
{
get { return (int) Year2SpinEdit.Value; }
}
[Browsable(false)]
protected int? StartMonthParam
{
get
{
return (StartMonthLookUp.EditValue == null)
? (int?) null
: ((ItemWrapper) StartMonthLookUp.EditValue).Number;
}
}
[Browsable(false)]
protected int? EndMonthParam
{
get
{
return (EndMonthLookUp.EditValue == null)
? (int?) null
: ((ItemWrapper) EndMonthLookUp.EditValue).Number;
}
}
protected List<ItemWrapper> MonthCollection
{
get { return m_MonthCollection ?? (m_MonthCollection = BaseDateKeeper.CreateMonthCollection()); }
}
#endregion
protected override BaseReport GenerateReport(DbManagerProxy manager)
{
if (ContextKeeper.ContainsContext(ContextValue.ReportFirstLoading))
{
FiltersHelper.SetDefaultFiltes(manager, ContextKeeper, region1Filter, rayon1Filter);
}
long? firstRegionID = region1Filter.RegionId > 0 ? (long?) region1Filter.RegionId : null;
long? firstRayonID = rayon1Filter.RayonId > 0 ? (long?) rayon1Filter.RayonId : null;
var report = new ExternalComparativeReport();
var model = new ExternalComparativeSurrogateModel(CurrentCulture.ShortName,
firstRegionID, firstRayonID,
Year1Param, Year2Param,
StartMonthParam, EndMonthParam
, UseArchive
);
report.SetParameters(manager, model);
return report;
}
protected override void ApplyResources()
{
try
{
IsResourceLoading = true;
m_HasLoad = false;
base.ApplyResources();
m_Resources.ApplyResources(StartMonthLookUp, "StartMonthLookUp");
m_Resources.ApplyResources(EndMonthLookUp, "EndMonthLookUp");
m_Resources.ApplyResources(StartYearLabel, "StartYearLabel");
m_Resources.ApplyResources(EndYearLabel, "EndYearLabel");
m_BaseResources.ApplyResources(StartMonthLabel, "StartMonthLabel");
m_BaseResources.ApplyResources(EndMonthLabel, "EndMonthLabel");
ApplyLookupResources(StartMonthLookUp, MonthCollection, StartMonthParam, EndYearLabel.Text);
ApplyLookupResources(EndMonthLookUp, MonthCollection, EndMonthParam, EndMonthLabel.Text);
// Note: do not load resources for spinEdit because it reset it's value
//m_Resources.ApplyResources(spinEdit, "spinEdit");
region1Filter.DefineBinding();
rayon1Filter.DefineBinding();
}
finally
{
m_HasLoad = true;
IsResourceLoading = false;
}
}
public void SetMandatory()
{
LayoutCorrector.SetStyleController(Year1SpinEdit, LayoutCorrector.MandatoryStyleController);
LayoutCorrector.SetStyleController(Year2SpinEdit, LayoutCorrector.MandatoryStyleController);
}
private void seYear1_EditValueChanged(object sender, EventArgs e)
{
CorrectYearRange();
ReloadReportIfFormLoaded(Year1SpinEdit);
}
private void seYear2_EditValueChanged(object sender, EventArgs e)
{
CorrectYearRange();
ReloadReportIfFormLoaded(Year2SpinEdit);
}
private void CorrectYearRange()
{
if (Year2Param <= Year1Param)
{
if (!ContextKeeper.ContainsContext(ContextValue.ReportFilterLoading))
{
if (!BaseFormManager.IsReportsServiceRunning && !BaseFormManager.IsAvrServiceRunning)
{
ErrorForm.ShowWarning("msgComparativeReportCorrectYear", "Year 1 shall be greater than Year 2");
}
}
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
Year1SpinEdit.EditValue = Year2Param - 1;
}
}
}
private void region1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
FiltersHelper.RegionFilterValueChanged(this, region1Filter, rayon1Filter, e);
}
}
private void rayon1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
{
if (ContextKeeper.ContainsContext(ContextValue.ReportFilterResetting))
{
return;
}
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
{
FiltersHelper.RayonFilterValueChanged(this, region1Filter, rayon1Filter, e);
}
}
private void MonthLookUp_ButtonClick(object sender, ButtonPressedEventArgs e)
{
if (e.Button.Kind == ButtonPredefines.Delete && sender is LookUpEdit)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
StartMonthLookUp.EditValue = null;
EndMonthLookUp.EditValue = null;
}
ReloadReportIfFormLoaded((LookUpEdit) sender);
}
}
private void StartMonthLookUp_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
ReloadReportIfFormLoaded(StartMonthLookUp);
}
private void EndMonthLookUp_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
ReloadReportIfFormLoaded(EndMonthLookUp);
}
private void CorrectMonthRange()
{
if ((EndMonthLookUp.EditValue != null) && (StartMonthLookUp.EditValue != null))
{
var startMonth = ((ItemWrapper) (StartMonthLookUp.EditValue));
var endMonth = ((ItemWrapper) (EndMonthLookUp.EditValue));
if (endMonth.Number < startMonth.Number)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
EndMonthLookUp.EditValue = StartMonthLookUp.EditValue;
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.