context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Songhay.Models; using System; using System.Collections.Generic; using System.Linq; namespace Songhay.Extensions { /// <summary> /// Extensions of <see cref="JObject"/> /// </summary> public static class JObjectExtensions { /// <summary> /// Displays the top properties of <see cref="JObject"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> public static string DisplayTopProperties(this JObject jObject) { var properties = jObject? .Properties() .Select(p => p.Name); return ((properties != null) && properties.Any()) ? properties.Aggregate((a, name) => string.Concat(a, Environment.NewLine, name)) : string.Empty; } /// <summary> /// Ensures the specified <see cref="JObject"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <returns></returns> /// <exception cref="NullReferenceException">The expected {nameof(JObject)} is not here.</exception> public static JObject Ensure(this JObject jObject) { if (jObject == null) { throw new NullReferenceException($"The expected {nameof(JObject)} is not here."); } return jObject; } /// <summary> /// Converts to <c>TDomainData</c> from <see cref="JObject" />. /// </summary> /// <typeparam name="TInterface">The type of the interface.</typeparam> /// <typeparam name="TDomainData">The type of the domain data.</typeparam> /// <param name="jObject">The <see cref="JObject" />.</param> /// <returns></returns> public static TDomainData FromJObject<TInterface, TDomainData>(this JObject jObject) where TDomainData : class where TInterface : class { return jObject.FromJObject<TInterface, TDomainData>(settings: null); } /// <summary> /// Converts to <c>TDomainData</c> from <see cref="JObject" />. /// </summary> /// <typeparam name="TInterface">The type of the interface.</typeparam> /// <typeparam name="TDomainData">The type of the domain data.</typeparam> /// <param name="jObject">The <see cref="JObject" /> in the shape of <c>TInterface</c>.</param> /// <param name="settings">The <see cref="JsonSerializerSettings" />.</param> /// <returns></returns> /// <remarks> /// The default <see cref="JsonSerializerSettings" /> /// from <see cref="IContractResolverExtensions.ToJsonSerializerSettings(Newtonsoft.Json.Serialization.IContractResolver)" /> /// assumes <c>TDomainData</c> derives from an Interface. /// </remarks> public static TDomainData FromJObject<TInterface, TDomainData>(this JObject jObject, JsonSerializerSettings settings) where TDomainData : class where TInterface : class { if (jObject == null) return null; if (settings == null) settings = new InterfaceContractResolver<TInterface>().ToJsonSerializerSettings(); var domainData = jObject.ToObject<TDomainData>(JsonSerializer.Create(settings)); return domainData; } /// <summary> /// Gets the <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="dictionaryPropertyName">Name of the dictionary property.</param> /// <returns></returns> public static Dictionary<string, string> GetDictionary(this JObject jObject, string dictionaryPropertyName) { return jObject.GetDictionary(dictionaryPropertyName, throwException: true); } /// <summary> /// Gets the <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="dictionaryPropertyName">Name of the dictionary property.</param> /// <param name="throwException">when set to <c>true</c> then [throw exception].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">dictionaryPropertyName;The expected Dictionary Property Name is not here.</exception> /// <exception cref="System.FormatException"></exception> public static Dictionary<string, string> GetDictionary(this JObject jObject, string dictionaryPropertyName, bool throwException) { var token = jObject.GetJToken(dictionaryPropertyName, throwException); JObject jO = null; if (token.HasValues) jO = (JObject)token; else if (throwException) throw new FormatException($"The expected property name `{dictionaryPropertyName}` is not here."); var data = jO.ToObject<Dictionary<string, string>>(); return data; } /// <summary> /// Gets the <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <returns></returns> public static Dictionary<string, string[]> GetDictionary(this JObject jObject) { return jObject.GetDictionary(throwException: true); } /// <summary> /// Gets the <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="throwException">when set to <c>true</c> then [throw exception].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">jObject;The expected JObject is not here.</exception> public static Dictionary<string, string[]> GetDictionary(this JObject jObject, bool throwException) { if (throwException) jObject.Ensure(); if ((jObject == null) && !throwException) return null; var data = jObject.ToObject<Dictionary<string, string[]>>(); return data; } /// <summary> /// Gets the <see cref="JArray" /> or will throw <see cref="FormatException"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="arrayPropertyName">Name of the array property.</param> /// <returns></returns> public static JArray GetJArray(this JObject jObject, string arrayPropertyName) { return jObject.GetJArray(arrayPropertyName, throwException: true); } /// <summary> /// Gets the <see cref="JArray" />. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="arrayPropertyName">Name of the array property.</param> /// <param name="throwException">when set to <c>true</c> then throw <see cref="FormatException"/>.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">arrayPropertyName;The expected JArray Property Name is not here.</exception> /// <exception cref="FormatException"> /// </exception> public static JArray GetJArray(this JObject jObject, string arrayPropertyName, bool throwException) { var token = jObject.GetJToken(arrayPropertyName, throwException); if (token == null) return null; JArray jsonArray = null; if (token.HasValues) jsonArray = (JArray)token; else if (throwException) throw new FormatException($"The expected array `{arrayPropertyName}` is not here."); return jsonArray; } /// <summary> /// Gets the <see cref="JObject"/> by the specified property name. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <returns></returns> public static JObject GetJObject(this JObject jObject, string objectPropertyName) { return jObject.GetJObject(objectPropertyName, throwException: true); } /// <summary> /// Gets the <see cref="JObject"/> by the specified property name. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <param name="throwException">when set to <c>true</c> then throw exception.</param> /// <returns></returns> public static JObject GetJObject(this JObject jObject, string objectPropertyName, bool throwException) { return jObject.GetValue<JObject>(objectPropertyName, throwException); } /// <summary> /// Gets the <see cref="JToken"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <param name="throwException">when set to <c>true</c> then throw exception.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// jObject;The expected JObject is not here. /// or /// objectPropertyName;The expected property name is not here. /// </exception> /// <exception cref="System.FormatException"></exception> public static JToken GetJToken(this JObject jObject, string objectPropertyName, bool throwException) { return jObject.GetValue<JToken>(objectPropertyName, throwException); } /// <summary> /// Gets the <see cref="JToken" /> from <see cref="JArray" /> or will throw <see cref="FormatException"/>. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="arrayPropertyName">Name of the array property.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <param name="arrayIndex">Index of the array.</param> /// <returns></returns> public static JToken GetJTokenFromJArray(this JObject jObject, string arrayPropertyName, string objectPropertyName, int arrayIndex) { return jObject.GetJTokenFromJArray(arrayPropertyName, objectPropertyName, arrayIndex, throwException: true); } /// <summary> /// Gets the <see cref="JToken" /> from <see cref="JArray" />. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="arrayPropertyName">Name of the array property.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <param name="arrayIndex">Index of the array.</param> /// <param name="throwException">when set to <c>true</c> then throw <see cref="FormatException"/>.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">objectPropertyName;The expected JObject Property Name is not here.</exception> public static JToken GetJTokenFromJArray(this JObject jObject, string arrayPropertyName, string objectPropertyName, int arrayIndex, bool throwException) { var jsonArray = jObject.GetJArray(arrayPropertyName, throwException); if (jsonArray == null) return null; var jsonToken = jsonArray.ElementAtOrDefault(arrayIndex); if (jsonToken == default(JToken)) { var errorMessage = $"The expected JToken in the JArray at index {arrayIndex} is not here."; if (throwException) throw new NullReferenceException(errorMessage); else return null; } var jO = jsonToken as JObject; if (jsonToken == null) { var errorMessage = "The expected JObject of the JToken is not here."; if (throwException) throw new NullReferenceException(errorMessage); else return null; } jsonToken = jO.GetJToken(objectPropertyName, throwException); return jsonToken; } /// <summary> /// Get the value by property name /// from the specified <see cref="JObject"/>. /// </summary> /// <typeparam name="TValue">type of returned value</typeparam> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the <see cref="JObject" /> property.</param> /// <returns></returns> public static TValue GetValue<TValue>(this JObject jObject, string objectPropertyName) { return jObject.GetValue<TValue>(objectPropertyName, throwException: true); } /// <summary> /// Get the value by property name /// from the specified <see cref="JObject"/>. /// </summary> /// <typeparam name="TValue">type of returned value</typeparam> /// <param name="jObject"></param> /// <param name="objectPropertyName"></param> /// <param name="throwException">when set to <c>true</c> then throw exception.</param> /// <returns></returns> public static TValue GetValue<TValue>(this JObject jObject, string objectPropertyName, bool throwException) { if (string.IsNullOrWhiteSpace(objectPropertyName)) throw new ArgumentNullException(nameof(objectPropertyName)); if (throwException) jObject.Ensure(); if ((jObject == null) && !throwException) return default(TValue); var jToken = jObject[objectPropertyName]; if ((jToken == null) && throwException) throw new NullReferenceException($"The expected {nameof(JToken)} of `{objectPropertyName}` is not here."); return jToken.GetValue<TValue>(throwException); } /// <summary> /// Returns <c>true</c> when <see cref="JObject.Properties"/> /// has a <see cref="JProperty"/> with the specified name. /// </summary> /// <param name="jObject"></param> /// <param name="objectPropertyName"></param> /// <returns></returns> public static bool HasProperty(this JObject jObject, string objectPropertyName) { if (string.IsNullOrWhiteSpace(objectPropertyName)) throw new ArgumentNullException(nameof(objectPropertyName)); if (jObject == null) return false; return jObject.Properties().Any(i => i.Name.EqualsInvariant(objectPropertyName)); } /// <summary> /// Parses the <see cref="JObject"/> /// serialized as a string /// at the specified property name. /// /// It will throw any exceptions. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the object property.</param> /// <returns></returns> public static JObject ParseJObject(this JObject jObject, string objectPropertyName) { return jObject.ParseJObject(objectPropertyName, throwException: true); } /// <summary> /// Parses the <see cref="JObject"/> /// serialized as a string /// at the specified property name. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the object property.</param> /// <param name="throwException">when <c>true</c> throw any exceptions; otherwise, return <c>null</c>.</param> /// <returns></returns> public static JObject ParseJObject(this JObject jObject, string objectPropertyName, bool throwException) { var json = jObject.GetValue<string>(objectPropertyName, throwException); JObject jO = null; try { jO = JObject.Parse(json); } catch (Exception) { if (throwException) throw; } return jO; } /// <summary> /// Ensures the <see cref="JObject"/> has the specified property. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the object property.</param> public static JObject WithProperty(this JObject jObject, string objectPropertyName) { return jObject.WithProperty(objectPropertyName, throwException: true); } /// <summary> /// Ensures the <see cref="JObject"/> has the specified property. /// </summary> /// <param name="jObject">The <see cref="JObject"/>.</param> /// <param name="objectPropertyName">Name of the object property.</param> /// <param name="throwException">if set to <c>true</c> [throw exception].</param> public static JObject WithProperty(this JObject jObject, string objectPropertyName, bool throwException) { if (string.IsNullOrWhiteSpace(objectPropertyName)) throw new ArgumentNullException(nameof(objectPropertyName)); if (throwException && !jObject.HasProperty(objectPropertyName)) { jObject.Ensure(); var msg = $@" The expected property name `{objectPropertyName}` is not here. Actual properties: {jObject.DisplayTopProperties()} ".Trim(); throw new FormatException(msg); } return jObject; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertInt161() { var test = new InsertScalarTest__InsertInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertInt161 { private struct TestStruct { public Vector128<Int16> _fld; public Int16 _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); testStruct._scalarFldData = (short)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertInt161 testClass) { var result = Sse2.Insert(_fld, _scalarFldData, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Int16 _scalarClsData = (short)2; private static Vector128<Int16> _clsVar; private Vector128<Int16> _fld; private Int16 _scalarFldData = (short)2; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static InsertScalarTest__InsertInt161() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public InsertScalarTest__InsertInt161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse2.Insert( Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (short)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Int16 localData = (short)2; Int16* ptr = &localData; var result = Sse2.Insert( Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Int16 localData = (short)2; Int16* ptr = &localData; var result = Sse2.Insert( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (short)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), (short)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), (short)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Insert( _clsVar, _scalarClsData, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); Int16 localData = (short)2; var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr); var result = Sse2.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); Int16 localData = (short)2; var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); Int16 localData = (short)2; var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertInt161(); var result = Sse2.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Insert(_fld, _scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16 scalarData, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != 0)) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Insert)}<Int16>(Vector128<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using V2.PaidTimeOffDAL.Framework; using V2.PaidTimeOffDAL; namespace V2.PaidTimeOffBLL.Framework { #region ENTNotificationENTUserAccountEO [Serializable()] public class ENTNotificationENTUserAccountEO : ENTBaseEO { #region Members private ENTNotificationENTWFStateEOList _notificationStates; #endregion Memebers #region Constructor public ENTNotificationENTUserAccountEO() { LoadStates = true; _notificationStates = new ENTNotificationENTWFStateEOList(); } #endregion Constructor #region Properties public int ENTNotificationId { get; set; } public int ENTUserAccountId { get; set; } public bool LoadStates { get; set; } public ENTNotificationENTWFStateEOList NotificationStates { get { return _notificationStates; } } #endregion Properties #region Overrides public override bool Load(int id) { //Get the entity object from the DAL. ENTNotificationENTUserAccount eNTNotificationENTUserAccount = new ENTNotificationENTUserAccountData().Select(id); MapEntityToProperties(eNTNotificationENTUserAccount); return eNTNotificationENTUserAccount != null; } protected override void MapEntityToCustomProperties(IENTBaseEntity entity) { ENTNotificationENTUserAccount eNTNotificationENTUserAccount = (ENTNotificationENTUserAccount)entity; ID = eNTNotificationENTUserAccount.ENTNotificationENTUserAccountId; ENTNotificationId = eNTNotificationENTUserAccount.ENTNotificationId; ENTUserAccountId = eNTNotificationENTUserAccount.ENTUserAccountId; if (LoadStates) { _notificationStates.Load(ID); } } public override bool Save(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors, int userAccountId) { if (DBAction == DBActionEnum.Save) { //Validate the object Validate(db, ref validationErrors); //Check if there were any validation errors if (validationErrors.Count == 0) { if (IsNewRecord()) { //Add ID = new ENTNotificationENTUserAccountData().Insert(db, ENTNotificationId, ENTUserAccountId, userAccountId); foreach (ENTNotificationENTWFStateEO notificationState in _notificationStates) { notificationState.ENTNotificationENTUserAccountId = ID; } } else { //Update if (!new ENTNotificationENTUserAccountData().Update(db, ID, ENTNotificationId, ENTUserAccountId, userAccountId, Version)) { UpdateFailed(ref validationErrors); return false; } } //Delete all the states associated with this user _notificationStates.Delete(db, ID); //Add the states that were selected. return _notificationStates.Save(db, ref validationErrors, userAccountId); } else { //Didn't pass validation. return false; } } else { throw new Exception("DBAction not Save."); } } protected override void Validate(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors) { //throw new NotImplementedException(); } protected override void DeleteForReal(HRPaidTimeOffDataContext db) { if (DBAction == DBActionEnum.Delete) { new ENTNotificationENTUserAccountData().Delete(db, ID); } else { throw new Exception("DBAction not delete."); } } protected override void ValidateDelete(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors) { } public override void Init() { } protected override string GetDisplayText() { return ID.ToString(); } #endregion Overrides } #endregion ENTNotificationENTUserAccountEO #region ENTNotificationENTUserAccountEOList [Serializable()] public class ENTNotificationENTUserAccountEOList : ENTBaseEOList<ENTNotificationENTUserAccountEO> { #region Overrides public override void Load() { LoadFromList(new ENTNotificationENTUserAccountData().Select()); } #endregion Overrides #region Private Methods private void LoadFromList(List<ENTNotificationENTUserAccount> eNTNotificationENTUserAccounts) { LoadFromList(eNTNotificationENTUserAccounts, true); } private void LoadFromList(List<ENTNotificationENTUserAccount> eNTNotificationENTUserAccounts, bool loadStates) { if (eNTNotificationENTUserAccounts.Count > 0) { foreach (ENTNotificationENTUserAccount eNTNotificationENTUserAccount in eNTNotificationENTUserAccounts) { ENTNotificationENTUserAccountEO newENTNotificationENTUserAccountEO = new ENTNotificationENTUserAccountEO(); newENTNotificationENTUserAccountEO.LoadStates = loadStates; newENTNotificationENTUserAccountEO.MapEntityToProperties(eNTNotificationENTUserAccount); this.Add(newENTNotificationENTUserAccountEO); } } } #endregion Private Methods #region Internal Methods #endregion Internal Methods public ENTNotificationENTUserAccountEO Get(ENTNotificationEO.NotificationType notificationType) { return this.SingleOrDefault(n => n.ENTNotificationId == (int)notificationType); } internal void Load(int entUserAccountId) { LoadFromList(new ENTNotificationENTUserAccountData().SelectByENTUserAccountId(entUserAccountId)); } internal void Load(HRPaidTimeOffDataContext db, int entWFStateId, ENTNotificationEO.NotificationType notificationType) { LoadFromList(new ENTNotificationENTUserAccountData().SelectByENTWFStateId(db, entWFStateId, (int)notificationType), false); } internal ENTNotificationENTUserAccountEO GetByENTUserAccountId(int entUserAccountId) { return this.SingleOrDefault(n => n.ENTUserAccountId == entUserAccountId); } } #endregion ENTNotificationENTUserAccountEOList }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using FileHelpers.Engines; using FileHelpers.Events; using FileHelpers.Streams; namespace FileHelpers { /// <summary> /// Async engine, reads records from file in background, /// returns them record by record in foreground /// </summary> public sealed class FileHelperAsyncEngine : FileHelperAsyncEngine<object> { #region " Constructor " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> public FileHelperAsyncEngine(Type recordType) : base(recordType) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> /// <param name="encoding">The encoding used by the Engine.</param> public FileHelperAsyncEngine(Type recordType, Encoding encoding) : base(recordType, encoding) { } #endregion } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngine/*'/> /// <include file='Examples.xml' path='doc/examples/FileHelperAsyncEngine/*'/> /// <typeparam name="T">The record type.</typeparam> [DebuggerDisplay( "FileHelperAsyncEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}" )] public class FileHelperAsyncEngine<T> : EventEngineBase<T>, IFileHelperAsyncEngine<T> where T : class { #region " Constructor " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> public FileHelperAsyncEngine() : base(typeof(T)) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/> protected FileHelperAsyncEngine(Type recordType) : base(recordType) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> /// <param name="encoding">The encoding used by the Engine.</param> public FileHelperAsyncEngine(Encoding encoding) : base(typeof(T), encoding) { } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/> /// <param name="encoding">The encoding used by the Engine.</param> /// <param name="recordType">Type of record to read</param> protected FileHelperAsyncEngine(Type recordType, Encoding encoding) : base(recordType, encoding) { } #endregion #region " Readers and Writters " [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ForwardReader mAsyncReader; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private TextWriter mAsyncWriter; #endregion #region " LastRecord " [DebuggerBrowsable(DebuggerBrowsableState.Never)] private T mLastRecord; /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/LastRecord/*'/> public T LastRecord { get { return mLastRecord; } } private object[] mLastRecordValues; /// <summary> /// An array with the values of each field of the current record /// </summary> public object[] LastRecordValues { get { return mLastRecordValues; } } /// <summary> /// Get a field value of the current records. /// </summary> /// <param name="fieldIndex" >The index of the field.</param> public object this[int fieldIndex] { get { if (mLastRecordValues == null) { throw new BadUsageException( "You must be reading something to access this property. Try calling BeginReadFile first."); } return mLastRecordValues[fieldIndex]; } set { if (mAsyncWriter == null) { throw new BadUsageException( "You must be writing something to set a record value. Try calling BeginWriteFile first."); } if (mLastRecordValues == null) mLastRecordValues = new object[RecordInfo.FieldCount]; if (value == null) { if (RecordInfo.Fields[fieldIndex].FieldType.IsValueType) throw new BadUsageException("You can't assign null to a value type."); mLastRecordValues[fieldIndex] = null; } else { if (!RecordInfo.Fields[fieldIndex].FieldType.IsInstanceOfType(value)) { throw new BadUsageException( $"Invalid type: {value.GetType().Name}. Expected: {RecordInfo.Fields[fieldIndex].FieldType.Name}"); } mLastRecordValues[fieldIndex] = value; } } } /// <summary> /// Get a field value of the current records. /// </summary> /// <param name="fieldName" >The name of the field (case sensitive)</param> public object this[string fieldName] { get { if (mLastRecordValues == null) { throw new BadUsageException( "You must be reading something to access this property. Try calling BeginReadFile first."); } int index = RecordInfo.GetFieldIndex(fieldName); return mLastRecordValues[index]; } set { int index = RecordInfo.GetFieldIndex(fieldName); this[index] = value; } } #endregion #region " BeginReadStream" /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadStream/*'/> public IDisposable BeginReadStream(TextReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader), "The TextReader can't be null."); if (mAsyncWriter != null) throw new BadUsageException("You can't start to read while you are writing."); var recordReader = new NewLineDelimitedRecordReader(reader); ResetFields(); HeaderText = string.Empty; mFooterText = string.Empty; if (RecordInfo.IgnoreFirst > 0) { for (int i = 0; i < RecordInfo.IgnoreFirst; i++) { string temp = recordReader.ReadRecordString(); mLineNumber++; if (temp != null) HeaderText += temp + Environment.NewLine; else break; } } mAsyncReader = new ForwardReader(recordReader, RecordInfo.IgnoreLast, mLineNumber) { DiscardForward = true }; State = EngineState.Reading; mStreamInfo = new StreamInfoProvider(reader); mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); return this; } #endregion #region " BeginReadFile " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/> public IDisposable BeginReadFile(string fileName) { BeginReadFile(fileName, DefaultReadBufferSize); return this; } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/> /// <param name="bufferSize">Buffer size to read</param> public IDisposable BeginReadFile(string fileName, int bufferSize) { BeginReadStream(new InternalStreamReader(fileName, mEncoding, true, bufferSize)); return this; } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadString/*'/> public IDisposable BeginReadString(string sourceData) { if (sourceData == null) sourceData = string.Empty; BeginReadStream(new InternalStringReader(sourceData)); return this; } #endregion #region " ReadNext " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNext/*'/> public T ReadNext() { if (mAsyncReader == null) throw new BadUsageException("Before calling ReadNext you must call BeginReadFile or BeginReadStream."); ReadNextRecord(); return mLastRecord; } private int mCurrentRecord = 0; private void ReadNextRecord() { string currentLine = mAsyncReader.ReadNextLine(); mLineNumber++; bool byPass = false; mLastRecord = default(T); var line = new LineInfo(string.Empty) { mReader = mAsyncReader }; if (mLastRecordValues == null) mLastRecordValues = new object[RecordInfo.FieldCount]; while (true) { if (currentLine != null) { try { mTotalRecords++; mCurrentRecord++; line.ReLoad(currentLine); bool skip = false; mLastRecord = (T)RecordInfo.Operations.CreateRecordHandler(); if (MustNotifyProgress) // Avoid object creation { OnProgress(new ProgressEventArgs(mCurrentRecord, -1, mStreamInfo.Position, mStreamInfo.TotalBytes)); } BeforeReadEventArgs<T> e = null; bool mustNotifyReadForRecord = MustNotifyReadForRecord(RecordInfo); if (mustNotifyReadForRecord) { e = new BeforeReadEventArgs<T>(this, mLastRecord, currentLine, LineNumber); skip = OnBeforeReadRecord(e); if (e.RecordLineChanged) line.ReLoad(e.RecordLine); } if (skip == false) { if (RecordInfo.Operations.StringToRecord(mLastRecord, line, mLastRecordValues)) { if (mustNotifyReadForRecord) skip = OnAfterReadRecord(currentLine, mLastRecord, e.RecordLineChanged, LineNumber); if (skip == false) { byPass = true; return; } } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: byPass = true; throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mAsyncReader.LineNumber, mExceptionInfo = ex, mRecordString = currentLine, mRecordTypeName = RecordInfo.RecordType.Name }; mErrorManager.AddError(err); break; } } finally { if (byPass == false) { currentLine = mAsyncReader.ReadNextLine(); mLineNumber = mAsyncReader.LineNumber; } } } else { mLastRecordValues = null; mLastRecord = default(T); if (RecordInfo.IgnoreLast > 0) mFooterText = mAsyncReader.RemainingText; try { mAsyncReader.Close(); //mAsyncReader = null; } catch { } return; } } } /// <summary> /// Return array of object for all data to end of the file /// </summary> /// <returns>Array of objects created from data on file</returns> public T[] ReadToEnd() { return ReadNexts(int.MaxValue); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNexts/*'/> public T[] ReadNexts(int numberOfRecords) { if (mAsyncReader == null) throw new BadUsageException("Before calling ReadNext you must call BeginReadFile or BeginReadStream."); var arr = new List<T>(numberOfRecords); for (int i = 0; i < numberOfRecords; i++) { ReadNextRecord(); if (mLastRecord != null) arr.Add(mLastRecord); else break; } return arr.ToArray(); } #endregion #region " Close " /// <summary> /// Save all the buffered data for write to the disk. /// Useful to opened async engines that wants to save pending values to /// disk or for engines used for logging. /// </summary> public void Flush() { if (mAsyncWriter != null) mAsyncWriter.Flush(); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/Close/*'/> public void Close() { lock (this) { State = EngineState.Closed; try { mLastRecordValues = null; mLastRecord = default(T); var reader = mAsyncReader; if (reader != null) { reader.Close(); mAsyncReader = null; } } catch { } try { var writer = mAsyncWriter; if (writer != null) { WriteFooter(writer); writer.Close(); mAsyncWriter = null; } } catch { } } } #endregion #region " BeginWriteStream" /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteStream/*'/> public IDisposable BeginWriteStream(TextWriter writer) { if (writer == null) throw new ArgumentException("The TextWriter can't be null.", nameof(writer)); if (mAsyncReader != null) throw new BadUsageException("You can't start to write while you are reading."); State = EngineState.Writing; ResetFields(); writer.NewLine = NewLineForWrite; mAsyncWriter = writer; WriteHeader(mAsyncWriter); mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1)); return this; } #endregion #region " BeginWriteFile " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/> public IDisposable BeginWriteFile(string fileName) { return BeginWriteFile(fileName, DefaultWriteBufferSize); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/> /// <param name="bufferSize">Size of the write buffer</param> public IDisposable BeginWriteFile(string fileName, int bufferSize) { BeginWriteStream(new StreamWriter(fileName, false, mEncoding, bufferSize)); return this; } #endregion #region " BeginAppendToFile " /// <summary> /// Begin the append to an existing file /// </summary> /// <param name="fileName">Filename to append to</param> /// <returns>Object to append TODO: ???</returns> public IDisposable BeginAppendToFile(string fileName) { return BeginAppendToFile(fileName, DefaultWriteBufferSize); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginAppendToFile/*'/> /// <param name="bufferSize">Size of the buffer for writing</param> public IDisposable BeginAppendToFile(string fileName, int bufferSize) { if (mAsyncReader != null) throw new BadUsageException("You can't start to write while you are reading."); mAsyncWriter = StreamHelper.CreateFileAppender(fileName, mEncoding, false, true, bufferSize); HeaderText = string.Empty; mFooterText = string.Empty; State = EngineState.Writing; mCurrentRecord = 0; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1)); return this; } #endregion #region " WriteNext " /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNext/*'/> public void WriteNext(T record) { if (mAsyncWriter == null) throw new BadUsageException("Before calling WriteNext you must call BeginWriteFile or BeginWriteStream."); if (record == null) throw new BadUsageException("The record to write can't be null."); if (RecordType.IsAssignableFrom(record.GetType()) == false) throw new BadUsageException("The record must be of type: " + RecordType.Name); mCurrentRecord++; WriteRecord(record, mCurrentRecord, -1, mAsyncWriter, RecordInfo); } /// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNexts/*'/> public void WriteNexts(IEnumerable<T> records) { if (mAsyncWriter == null) throw new BadUsageException("Before calling WriteNext you must call BeginWriteFile or BeginWriteStream."); if (records == null) throw new ArgumentNullException(nameof(records), "The record to write can't be null."); foreach (var rec in records) { mCurrentRecord++; WriteRecord(rec, mCurrentRecord, -1, mAsyncWriter, RecordInfo); } } #endregion #region " WriteNext for LastRecordValues " /// <summary> /// Write the current record values in the buffer. You can use /// engine[0] or engine["YourField"] to set the values. /// </summary> public void WriteNextValues() { if (mAsyncWriter == null) throw new BadUsageException("Before calling WriteNext you must call BeginWriteFile or BeginWriteStream."); if (mLastRecordValues == null) { throw new BadUsageException( "You must set some values of the record before calling this method, or use the overload that has a record as argument."); } string currentLine = null; try { mLineNumber++; mTotalRecords++; currentLine = RecordInfo.Operations.RecordValuesToString(mLastRecordValues); mAsyncWriter.WriteLine(currentLine); } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mLineNumber, mExceptionInfo = ex, mRecordString = currentLine, mRecordTypeName = RecordInfo.RecordType.Name }; mErrorManager.AddError(err); break; } } finally { mLastRecordValues = null; } } #endregion #region " IEnumerable implementation " /// <summary>Allows to loop record by record in the engine</summary> /// <returns>The enumerator</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (mAsyncReader == null) throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop."); return new AsyncEnumerator(this); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection. ///</returns> IEnumerator IEnumerable.GetEnumerator() { if (mAsyncReader == null) throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop."); return new AsyncEnumerator(this); } private class AsyncEnumerator : IEnumerator<T> { T IEnumerator<T>.Current { get { return mEngine.mLastRecord; } } void IDisposable.Dispose() { mEngine.Close(); } private readonly FileHelperAsyncEngine<T> mEngine; public AsyncEnumerator(FileHelperAsyncEngine<T> engine) { mEngine = engine; } public bool MoveNext() { if (mEngine.State == EngineState.Closed) return false; object res = mEngine.ReadNext(); if (res == null) { mEngine.Close(); return false; } return true; } public object Current { get { return mEngine.mLastRecord; } } public void Reset() { // No needed } } #endregion #region " IDisposable implementation " /// <summary>Release Resources</summary> void IDisposable.Dispose() { Close(); GC.SuppressFinalize(this); } /// <summary>Destructor</summary> ~FileHelperAsyncEngine() { Close(); } #endregion #region " State " private StreamInfoProvider mStreamInfo; /// <summary> /// Indicates the current state of the engine. /// </summary> private EngineState State { get; set; } /// <summary> /// Indicates the State of an engine /// </summary> private enum EngineState { /// <summary>The Engine is closed</summary> Closed = 0, /// <summary>The Engine is reading a file, string or stream</summary> Reading, /// <summary>The Engine is writing a file, string or stream</summary> Writing } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; List<string> responsePaths = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory, responsePaths); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool displayVersion = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = LanguageVersion.Default; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> embeddedFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool embedAllSourceFiles = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; ArrayBuilder<InstrumentationKind> instrumentationKinds = ArrayBuilder<InstrumentationKind>.GetInstance(); CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "version": displayVersion = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { foreach (InstrumentationKind instrumentationKind in ParseInstrumentationKinds(value, diagnostics)) { if (!instrumentationKinds.Contains(instrumentationKind)) { instrumentationKinds.Add(instrumentationKind); } } } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (value.StartsWith("0", StringComparison.Ordinal)) { // This error was added in 7.1 to stop parsing versions as ints (behaviour in previous Roslyn compilers), and explicitly // treat them as identifiers (behaviour in native compiler). This error helps users identify that breaking change. AddDiagnostic(diagnostics, ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes, value); } else if (!value.TryParse(out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = value; } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; case "embed": if (string.IsNullOrEmpty(value)) { embedAllSourceFiles = true; continue; } embeddedFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths, responsePaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } if (embedAllSourceFiles) { embeddedFiles.AddRange(sourceFiles); } if (embeddedFiles.Count > 0) { // Restricted to portable PDBs for now, but the IsPortable condition should be removed // and the error message adjusted accordingly when native PDB support is added. if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_CannotEmbedWithoutPdb); } } var parsedFeatures = ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: IsScriptRunner ? SourceCodeKind.Script : SourceCodeKind.Regular, features: parsedFeatures ); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrumentationKinds: instrumentationKinds.ToImmutableAndFree() ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); diagnostics.AddRange(parseOptions.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, DisplayVersion = displayVersion, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer, EmbeddedFiles = embeddedFiles.AsImmutable() }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths, List<string> responsePathsOpt) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); // csi adds paths of the response file(s) to the search paths, so that we can initialize the script environment // with references relative to csi.exe (e.g. System.ValueTuple.dll). if (responsePathsOpt != null) { Debug.Assert(IsScriptRunner); builder.AddRange(responsePathsOpt); } return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { DiagnosticBag outputDiagnostics = DiagnosticBag.GetInstance(); value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else { outputDiagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId)); } } diagnostics = outputDiagnostics.ToReadOnlyAndFree(); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private static IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private static IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } private static IEnumerable<InstrumentationKind> ParseInstrumentationKinds(string value, IList<Diagnostic> diagnostics) { string[] kinds = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var kind in kinds) { switch (kind.ToLower()) { case "testcoverage": yield return InstrumentationKind.TestCoverage; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidInstrumentationKind, kind); break; } } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
/* * 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 SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using Lucene.Net.Index; using Directory = Lucene.Net.Store.Directory; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using English = Lucene.Net.Util.English; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { [TestFixture] public class TestTermVectors:LuceneTestCase { private IndexSearcher searcher; private Directory directory = new MockRAMDirectory(); [SetUp] public override void SetUp() { base.SetUp(); IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); //writer.setUseCompoundFile(true); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); Field.TermVector termVector; int mod3 = i % 3; int mod2 = i % 2; if (mod2 == 0 && mod3 == 0) { termVector = Field.TermVector.WITH_POSITIONS_OFFSETS; } else if (mod2 == 0) { termVector = Field.TermVector.WITH_POSITIONS; } else if (mod3 == 0) { termVector = Field.TermVector.WITH_OFFSETS; } else { termVector = Field.TermVector.YES; } doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED, termVector)); writer.AddDocument(doc); } writer.Close(); searcher = new IndexSearcher(directory); } [Test] public virtual void Test() { Assert.IsTrue(searcher != null); } [Test] public virtual void TestTermVectors_Renamed() { Query query = new TermQuery(new Term("field", "seventy")); try { ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(100, hits.Length); for (int i = 0; i < hits.Length; i++) { TermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].doc); Assert.IsTrue(vector != null); Assert.IsTrue(vector.Length == 1); } } catch (System.IO.IOException e) { Assert.IsTrue(false); } } [Test] public virtual void TestTermVectorsFieldOrder() { Directory dir = new MockRAMDirectory(); IndexWriter writer = new IndexWriter(dir, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); doc.Add(new Field("c", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); doc.Add(new Field("a", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); doc.Add(new Field("b", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); doc.Add(new Field("x", "some content here", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); IndexReader reader = IndexReader.Open(dir); TermFreqVector[] v = reader.GetTermFreqVectors(0); Assert.AreEqual(4, v.Length); System.String[] expectedFields = new System.String[]{"a", "b", "c", "x"}; int[] expectedPositions = new int[]{1, 2, 0}; for (int i = 0; i < v.Length; i++) { TermPositionVector posVec = (TermPositionVector) v[i]; Assert.AreEqual(expectedFields[i], posVec.GetField()); System.String[] terms = posVec.GetTerms(); Assert.AreEqual(3, terms.Length); Assert.AreEqual("content", terms[0]); Assert.AreEqual("here", terms[1]); Assert.AreEqual("some", terms[2]); for (int j = 0; j < 3; j++) { int[] positions = posVec.GetTermPositions(j); Assert.AreEqual(1, positions.Length); Assert.AreEqual(expectedPositions[j], positions[0]); } } } [Test] public virtual void TestTermPositionVectors() { Query query = new TermQuery(new Term("field", "zero")); try { ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); for (int i = 0; i < hits.Length; i++) { TermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].doc); Assert.IsTrue(vector != null); Assert.IsTrue(vector.Length == 1); bool shouldBePosVector = (hits[i].doc % 2 == 0)?true:false; Assert.IsTrue((shouldBePosVector == false) || (shouldBePosVector == true && (vector[0] is TermPositionVector == true))); bool shouldBeOffVector = (hits[i].doc % 3 == 0)?true:false; Assert.IsTrue((shouldBeOffVector == false) || (shouldBeOffVector == true && (vector[0] is TermPositionVector == true))); if (shouldBePosVector || shouldBeOffVector) { TermPositionVector posVec = (TermPositionVector) vector[0]; System.String[] terms = posVec.GetTerms(); Assert.IsTrue(terms != null && terms.Length > 0); for (int j = 0; j < terms.Length; j++) { int[] positions = posVec.GetTermPositions(j); TermVectorOffsetInfo[] offsets = posVec.GetOffsets(j); if (shouldBePosVector) { Assert.IsTrue(positions != null); Assert.IsTrue(positions.Length > 0); } else Assert.IsTrue(positions == null); if (shouldBeOffVector) { Assert.IsTrue(offsets != null); Assert.IsTrue(offsets.Length > 0); } else Assert.IsTrue(offsets == null); } } else { try { TermPositionVector posVec = (TermPositionVector) vector[0]; Assert.IsTrue(false); } catch (System.InvalidCastException ignore) { TermFreqVector freqVec = vector[0]; System.String[] terms = freqVec.GetTerms(); Assert.IsTrue(terms != null && terms.Length > 0); } } } } catch (System.IO.IOException e) { Assert.IsTrue(false); } } [Test] public virtual void TestTermOffsetVectors() { Query query = new TermQuery(new Term("field", "fifty")); try { ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(100, hits.Length); for (int i = 0; i < hits.Length; i++) { TermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].doc); Assert.IsTrue(vector != null); Assert.IsTrue(vector.Length == 1); //Assert.IsTrue(); } } catch (System.IO.IOException e) { Assert.IsTrue(false); } } [Test] public virtual void TestKnownSetOfDocuments() { System.String test1 = "eating chocolate in a computer lab"; //6 terms System.String test2 = "computer in a computer lab"; //5 terms System.String test3 = "a chocolate lab grows old"; //5 terms System.String test4 = "eating chocolate with a chocolate lab in an old chocolate colored computer lab"; //13 terms System.Collections.IDictionary test4Map = new System.Collections.Hashtable(); test4Map["chocolate"] = 3; test4Map["lab"] = 2; test4Map["eating"] = 1; test4Map["computer"] = 1; test4Map["with"] = 1; test4Map["a"] = 1; test4Map["colored"] = 1; test4Map["in"] = 1; test4Map["an"] = 1; test4Map["computer"] = 1; test4Map["old"] = 1; Document testDoc1 = new Document(); SetupDoc(testDoc1, test1); Document testDoc2 = new Document(); SetupDoc(testDoc2, test2); Document testDoc3 = new Document(); SetupDoc(testDoc3, test3); Document testDoc4 = new Document(); SetupDoc(testDoc4, test4); Directory dir = new MockRAMDirectory(); try { IndexWriter writer = new IndexWriter(dir, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Assert.IsTrue(writer != null); writer.AddDocument(testDoc1); writer.AddDocument(testDoc2); writer.AddDocument(testDoc3); writer.AddDocument(testDoc4); writer.Close(); IndexSearcher knownSearcher = new IndexSearcher(dir); TermEnum termEnum = knownSearcher.reader_ForNUnit.Terms(); TermDocs termDocs = knownSearcher.reader_ForNUnit.TermDocs(); //System.out.println("Terms: " + termEnum.size() + " Orig Len: " + termArray.length); Similarity sim = knownSearcher.GetSimilarity(); while (termEnum.Next() == true) { Term term = termEnum.Term(); //System.out.println("Term: " + term); termDocs.Seek(term); while (termDocs.Next()) { int docId = termDocs.Doc(); int freq = termDocs.Freq(); //System.out.println("Doc Id: " + docId + " freq " + freq); TermFreqVector vector = knownSearcher.reader_ForNUnit.GetTermFreqVector(docId, "field"); float tf = sim.Tf(freq); float idf = sim.Idf(term, knownSearcher); //float qNorm = sim.queryNorm() //This is fine since we don't have stop words float lNorm = sim.LengthNorm("field", vector.GetTerms().Length); //float coord = sim.coord() //System.out.println("TF: " + tf + " IDF: " + idf + " LenNorm: " + lNorm); Assert.IsTrue(vector != null); System.String[] vTerms = vector.GetTerms(); int[] freqs = vector.GetTermFrequencies(); for (int i = 0; i < vTerms.Length; i++) { if (term.Text().Equals(vTerms[i])) { Assert.IsTrue(freqs[i] == freq); } } } //System.out.println("--------"); } Query query = new TermQuery(new Term("field", "chocolate")); ScoreDoc[] hits = knownSearcher.Search(query, null, 1000).ScoreDocs; //doc 3 should be the first hit b/c it is the shortest match Assert.IsTrue(hits.Length == 3); float score = hits[0].score; /*System.out.println("Hit 0: " + hits.id(0) + " Score: " + hits.score(0) + " String: " + hits.doc(0).toString()); System.out.println("Explain: " + knownSearcher.explain(query, hits.id(0))); System.out.println("Hit 1: " + hits.id(1) + " Score: " + hits.score(1) + " String: " + hits.doc(1).toString()); System.out.println("Explain: " + knownSearcher.explain(query, hits.id(1))); System.out.println("Hit 2: " + hits.id(2) + " Score: " + hits.score(2) + " String: " + hits.doc(2).toString()); System.out.println("Explain: " + knownSearcher.explain(query, hits.id(2)));*/ Assert.IsTrue(hits[0].doc == 2); Assert.IsTrue(hits[1].doc == 3); Assert.IsTrue(hits[2].doc == 0); TermFreqVector vector2 = knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].doc, "field"); Assert.IsTrue(vector2 != null); //System.out.println("Vector: " + vector); System.String[] terms = vector2.GetTerms(); int[] freqs2 = vector2.GetTermFrequencies(); Assert.IsTrue(terms != null && terms.Length == 10); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; //System.out.println("Term: " + term); int freq = freqs2[i]; Assert.IsTrue(test4.IndexOf(term) != - 1); System.Int32 freqInt = -1; try { freqInt = (System.Int32) test4Map[term]; } catch (Exception) { Assert.IsTrue(false); } Assert.IsTrue(freqInt == freq); } SortedTermVectorMapper mapper = new SortedTermVectorMapper(new TermVectorEntryFreqSortedComparator()); knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].doc, mapper); System.Collections.Generic.SortedDictionary<object, object> vectorEntrySet = mapper.GetTermVectorEntrySet(); Assert.IsTrue(vectorEntrySet.Count == 10, "mapper.getTermVectorEntrySet() Size: " + vectorEntrySet.Count + " is not: " + 10); TermVectorEntry last = null; foreach(TermVectorEntry tve in vectorEntrySet.Keys) { if (tve != null && last != null) { Assert.IsTrue(last.GetFrequency() >= tve.GetFrequency(), "terms are not properly sorted"); System.Int32 expectedFreq = (System.Int32) test4Map[tve.GetTerm()]; //we expect double the expectedFreq, since there are two fields with the exact same text and we are collapsing all fields Assert.IsTrue(tve.GetFrequency() == 2 * expectedFreq, "Frequency is not correct:"); } last = tve; } FieldSortedTermVectorMapper fieldMapper = new FieldSortedTermVectorMapper(new TermVectorEntryFreqSortedComparator()); knownSearcher.reader_ForNUnit.GetTermFreqVector(hits[1].doc, fieldMapper); System.Collections.IDictionary map = fieldMapper.GetFieldToTerms(); Assert.IsTrue(map.Count == 2, "map Size: " + map.Count + " is not: " + 2); vectorEntrySet = (System.Collections.Generic.SortedDictionary<Object,Object>) map["field"]; Assert.IsTrue(vectorEntrySet != null, "vectorEntrySet is null and it shouldn't be"); Assert.IsTrue(vectorEntrySet.Count == 10, "vectorEntrySet Size: " + vectorEntrySet.Count + " is not: " + 10); knownSearcher.Close(); } catch (System.IO.IOException e) { System.Console.Error.WriteLine(e.StackTrace); Assert.IsTrue(false); } } private void SetupDoc(Document doc, System.String text) { doc.Add(new Field("field2", text, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); doc.Add(new Field("field", text, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES)); //System.out.println("Document: " + doc); } // Test only a few docs having vectors [Test] public virtual void TestRareVectors() { IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < 100; i++) { Document doc = new Document(); doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO)); writer.AddDocument(doc); } for (int i = 0; i < 10; i++) { Document doc = new Document(); doc.Add(new Field("field", English.IntToEnglish(100 + i), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); } writer.Close(); searcher = new IndexSearcher(directory); Query query = new TermQuery(new Term("field", "hundred")); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(10, hits.Length); for (int i = 0; i < hits.Length; i++) { TermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[i].doc); Assert.IsTrue(vector != null); Assert.IsTrue(vector.Length == 1); } } // In a single doc, for the same field, mix the term // vectors up [Test] public virtual void TestMixedVectrosVectors() { IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO)); doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES)); doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS)); doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS)); doc.Add(new Field("field", "one", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); searcher = new IndexSearcher(directory); Query query = new TermQuery(new Term("field", "one")); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); TermFreqVector[] vector = searcher.reader_ForNUnit.GetTermFreqVectors(hits[0].doc); Assert.IsTrue(vector != null); Assert.IsTrue(vector.Length == 1); TermPositionVector tfv = (TermPositionVector) vector[0]; Assert.IsTrue(tfv.GetField().Equals("field")); System.String[] terms = tfv.GetTerms(); Assert.AreEqual(1, terms.Length); Assert.AreEqual(terms[0], "one"); Assert.AreEqual(5, tfv.GetTermFrequencies()[0]); int[] positions = tfv.GetTermPositions(0); Assert.AreEqual(5, positions.Length); for (int i = 0; i < 5; i++) Assert.AreEqual(i, positions[i]); TermVectorOffsetInfo[] offsets = tfv.GetOffsets(0); Assert.AreEqual(5, offsets.Length); for (int i = 0; i < 5; i++) { Assert.AreEqual(4 * i, offsets[i].GetStartOffset()); Assert.AreEqual(4 * i + 3, offsets[i].GetEndOffset()); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.Threading; abstract class RequestChannel : ChannelBase, IRequestChannel { bool manualAddressing; List<IRequestBase> outstandingRequests = new List<IRequestBase>(); EndpointAddress to; Uri via; ManualResetEvent closedEvent; bool closed; protected RequestChannel(ChannelManagerBase channelFactory, EndpointAddress to, Uri via, bool manualAddressing) : base(channelFactory) { if (!manualAddressing) { if (to == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("to"); } } this.manualAddressing = manualAddressing; this.to = to; this.via = via; } protected bool ManualAddressing { get { return this.manualAddressing; } } public EndpointAddress RemoteAddress { get { return this.to; } } public Uri Via { get { return this.via; } } protected void AbortPendingRequests() { IRequestBase[] requestsToAbort = CopyPendingRequests(false); if (requestsToAbort != null) { foreach (IRequestBase request in requestsToAbort) { request.Abort(this); } } } protected IAsyncResult BeginWaitForPendingRequests(TimeSpan timeout, AsyncCallback callback, object state) { IRequestBase[] pendingRequests = SetupWaitForPendingRequests(); return new WaitForPendingRequestsAsyncResult(timeout, this, pendingRequests, callback, state); } protected void EndWaitForPendingRequests(IAsyncResult result) { WaitForPendingRequestsAsyncResult.End(result); } void FinishClose() { lock (outstandingRequests) { if (!closed) { closed = true; if (closedEvent != null) { this.closedEvent.Close(); } } } } IRequestBase[] SetupWaitForPendingRequests() { return this.CopyPendingRequests(true); } protected void WaitForPendingRequests(TimeSpan timeout) { IRequestBase[] pendingRequests = SetupWaitForPendingRequests(); if (pendingRequests != null) { if (!closedEvent.WaitOne(timeout, false)) { foreach (IRequestBase request in pendingRequests) { request.Abort(this); } } } FinishClose(); } IRequestBase[] CopyPendingRequests(bool createEventIfNecessary) { IRequestBase[] requests = null; lock (outstandingRequests) { if (outstandingRequests.Count > 0) { requests = new IRequestBase[outstandingRequests.Count]; outstandingRequests.CopyTo(requests); outstandingRequests.Clear(); if (createEventIfNecessary && closedEvent == null) { closedEvent = new ManualResetEvent(false); } } } return requests; } protected void FaultPendingRequests() { IRequestBase[] requestsToFault = CopyPendingRequests(false); if (requestsToFault != null) { foreach (IRequestBase request in requestsToFault) { request.Fault(this); } } } public override T GetProperty<T>() { if (typeof(T) == typeof(IRequestChannel)) { return (T)(object)this; } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } return default(T); } protected override void OnAbort() { AbortPendingRequests(); } void ReleaseRequest(IRequestBase request) { if (request != null) { // Synchronization of OnReleaseRequest is the // responsibility of the concrete implementation of request. request.OnReleaseRequest(); } lock (outstandingRequests) { // Remove supports the connection having been removed, so don't need extra Contains() check, // even though this may have been removed by Abort() outstandingRequests.Remove(request); if (outstandingRequests.Count == 0) { if (!closed && closedEvent != null) { closedEvent.Set(); } } } } void TrackRequest(IRequestBase request) { lock (outstandingRequests) { ThrowIfDisposedOrNotOpen(); // make sure that we haven't already snapshot our collection outstandingRequests.Add(request); } } public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state) { return this.BeginRequest(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", timeout, SR.GetString(SR.SFxTimeoutOutOfRange0))); ThrowIfDisposedOrNotOpen(); AddHeadersTo(message); IAsyncRequest asyncRequest = CreateAsyncRequest(message, callback, state); TrackRequest(asyncRequest); bool throwing = true; try { asyncRequest.BeginSendRequest(message, timeout); throwing = false; } finally { if (throwing) { ReleaseRequest(asyncRequest); } } return asyncRequest; } protected abstract IRequest CreateRequest(Message message); protected abstract IAsyncRequest CreateAsyncRequest(Message message, AsyncCallback callback, object state); public Message EndRequest(IAsyncResult result) { if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result"); } IAsyncRequest asyncRequest = result as IAsyncRequest; if (asyncRequest == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("result", SR.GetString(SR.InvalidAsyncResult)); } try { Message reply = asyncRequest.End(); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.RequestChannelReplyReceived, SR.GetString(SR.TraceCodeRequestChannelReplyReceived), reply); } return reply; } finally { ReleaseRequest(asyncRequest); } } public Message Request(Message message) { return this.Request(message, this.DefaultSendTimeout); } public Message Request(Message message, TimeSpan timeout) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", timeout, SR.GetString(SR.SFxTimeoutOutOfRange0))); ThrowIfDisposedOrNotOpen(); AddHeadersTo(message); IRequest request = CreateRequest(message); TrackRequest(request); try { Message reply; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); TimeSpan savedTimeout = timeoutHelper.RemainingTime(); try { request.SendRequest(message, savedTimeout); } catch (TimeoutException timeoutException) { throw TraceUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.RequestChannelSendTimedOut, savedTimeout), timeoutException), message); } savedTimeout = timeoutHelper.RemainingTime(); try { reply = request.WaitForReply(savedTimeout); } catch (TimeoutException timeoutException) { throw TraceUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.RequestChannelWaitForReplyTimedOut, savedTimeout), timeoutException), message); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.RequestChannelReplyReceived, SR.GetString(SR.TraceCodeRequestChannelReplyReceived), reply); } return reply; } finally { ReleaseRequest(request); } } protected virtual void AddHeadersTo(Message message) { if (!manualAddressing && to != null) { to.ApplyTo(message); } } class WaitForPendingRequestsAsyncResult : AsyncResult { static WaitOrTimerCallback completeWaitCallBack = new WaitOrTimerCallback(OnCompleteWaitCallBack); IRequestBase[] pendingRequests; RequestChannel requestChannel; TimeSpan timeout; RegisteredWaitHandle waitHandle; public WaitForPendingRequestsAsyncResult(TimeSpan timeout, RequestChannel requestChannel, IRequestBase[] pendingRequests, AsyncCallback callback, object state) : base(callback, state) { this.requestChannel = requestChannel; this.pendingRequests = pendingRequests; this.timeout = timeout; if (this.timeout == TimeSpan.Zero || this.pendingRequests == null) { AbortRequests(); CleanupEvents(); Complete(true); } else { this.waitHandle = ThreadPool.RegisterWaitForSingleObject(this.requestChannel.closedEvent, completeWaitCallBack, this, TimeoutHelper.ToMilliseconds(timeout), true); } } void AbortRequests() { if (pendingRequests != null) { foreach (IRequestBase request in pendingRequests) { request.Abort(this.requestChannel); } } } void CleanupEvents() { if (requestChannel.closedEvent != null) { if (waitHandle != null) { waitHandle.Unregister(requestChannel.closedEvent); } requestChannel.FinishClose(); } } static void OnCompleteWaitCallBack(object state, bool timedOut) { WaitForPendingRequestsAsyncResult thisPtr = (WaitForPendingRequestsAsyncResult)state; Exception completionException = null; try { if (timedOut) { thisPtr.AbortRequests(); } thisPtr.CleanupEvents(); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } public static void End(IAsyncResult result) { AsyncResult.End<WaitForPendingRequestsAsyncResult>(result); } } } interface IRequestBase { void Abort(RequestChannel requestChannel); void Fault(RequestChannel requestChannel); void OnReleaseRequest(); } interface IRequest : IRequestBase { void SendRequest(Message message, TimeSpan timeout); Message WaitForReply(TimeSpan timeout); } interface IAsyncRequest : IAsyncResult, IRequestBase { void BeginSendRequest(Message message, TimeSpan timeout); Message End(); } }
using System.Collections.Generic; namespace MongoDB { /// <summary> /// Staticly typed way of using MongoDB update modifiers. /// </summary> public class Mo : Document { /// <summary> /// Initializes a new instance of the <see cref="Mo"/> class. /// </summary> private Mo() { } /// <summary> /// Initializes a new instance of the <see cref="Mo"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> private Mo(string name,object value){ Add(name, value); } /// <summary> /// Increments field by the number value. If field is present in the object, /// otherwise sets field to the number value. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Mo Inc(string field,object value){ return new Mo("$inc", new Document(field, value)); } /// <summary> /// Sets field to value. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks> /// All datatypes are supported with $set. /// </remarks> public static new Mo Set(string field, object value){ return new Mo("$set", new Document(field, value)); } /// <summary> /// Deletes a given field. /// </summary> /// <param name="field">The field.</param> /// <returns></returns> /// <remarks> /// Supported version in MongoDB 1.3 and up. /// </remarks> public static Mo Unset(string field) { return new Mo("$unset", new Document(field, 1)); } /// <summary> /// Deletes the given fields. /// </summary> /// <param name="fields">The fields.</param> /// <returns></returns> /// <remarks> /// Supported version in MongoDB 1.3 and up. /// </remarks> public static Mo Unset(IEnumerable<string> fields) { var document = new Document(); foreach(var field in fields) document.Add(field, 1); return new Mo("$unset", document); } /// <summary> /// Appends value to field, if field is an existing array. /// Otherwise sets field to the array and add value if field is not present. /// If field is present but is not an array, an error condition is raised. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Mo Push(string field,object value){ return new Mo("$push", new Document(field, value)); } /// <summary> /// Appends each value in values to field, /// if field is an existing array. /// Otherwise sets field to the array values if field is not present. /// If field is present but is not an array, an error /// condition is raised. /// </summary> /// <param name="field">The field.</param> /// <param name="values">The values.</param> /// <returns></returns> public static Mo PushAll(string field, IEnumerable<object> values){ return new Mo("$pushAll", new Document(field, values)); } /// <summary> /// Adds value to the array only if its not in the array already. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Mo AddToSet(string field, object value){ return new Mo("$addToSet", new Document(field, value)); } /// <summary> /// Adds values to the array only if its not in the array already. /// </summary> /// <param name="field">The field.</param> /// <param name="values">The values.</param> /// <returns></returns> public static Mo AddToSet(string field, IEnumerable<object> values){ return new Mo("$addToSet", new Document(field, new Document("$each", values))); } /// <summary> /// Removes the first element in an array. /// </summary> /// <param name="field">The field.</param> /// <returns></returns> /// <remarks> /// Supported in MongoDB 1.1 and up. /// </remarks> public static Mo PopFirst(string field){ return new Mo("$pop", new Document(field, -1)); } /// <summary> /// Removes the last element in an array. /// </summary> /// <param name="field">The field.</param> /// <returns></returns> /// <remarks> /// Supported in MongoDB 1.1 and up. /// </remarks> public static Mo PopLast(string field) { return new Mo("$pop", new Document(field, 1)); } /// <summary> /// Removes all occurrences of value from field, if field is an array. /// If field is present but is not an array, an error condition is raised. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <returns></returns> public static Mo Pull(string field, object value){ return new Mo("$pull", new Document(field, value)); } /// <summary> /// Removes all occurrences of each value in values from field, /// if field is an array. /// If field is present but is not an array, an error condition is raised. /// </summary> /// <param name="field">The field.</param> /// <param name="values">The values.</param> /// <returns></returns> public static Mo PullAll(string field, IEnumerable<object> values){ return new Mo("$pullAll", new Document(field, values)); } /// <summary> /// Implements the operator &amp;. This is used for conjunctions. /// </summary> /// <param name="modifier1">The modifier1.</param> /// <param name="modifier2">The modifier2.</param> /// <returns>The result of the modifier.</returns> public static Mo operator &(Mo modifier1, Mo modifier2){ var mo = new Mo(); //Todo: move as DeepMerge to Document foreach(var key in modifier1.Keys) mo[key] = modifier1[key]; foreach(var pair2 in modifier2) { object value1; if(mo.TryGetValue(pair2.Key, out value1)) { if(pair2.Value is Document && value1 is Document) { mo[pair2.Key] = new Document() .Merge((Document)value1) .Merge((Document)pair2.Value); } else mo[pair2.Key] = pair2.Value; } else mo.Add(pair2.Key, pair2.Value); } return mo; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Avatar.Chat; namespace OpenSim.Region.OptionalModules.Avatar.Concierge { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ConciergeModule")] public class ConciergeModule : ChatModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private List<IScene> m_scenes = new List<IScene>(); private List<IScene> m_conciergedScenes = new List<IScene>(); private bool m_replacingChatModule = false; private IConfig m_config; private string m_whoami = "conferencier"; private Regex m_regions = null; private string m_welcomes = null; private int m_conciergeChannel = 42; private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)"; private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)"; private string m_xmlRpcPassword = String.Empty; private string m_brokerURI = String.Empty; private int m_brokerUpdateTimeout = 300; internal object m_syncy = new object(); internal bool m_enabled = false; #region ISharedRegionModule Members public override void Initialise(IConfigSource config) { m_config = config.Configs["Concierge"]; if (null == m_config) return; if (!m_config.GetBoolean("enabled", false)) return; m_enabled = true; // check whether ChatModule has been disabled: if yes, // then we'll "stand in" try { if (config.Configs["Chat"] == null) { // if Chat module has not been configured it's // enabled by default, so we are not going to // replace it. m_replacingChatModule = false; } else { m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true); } } catch (Exception) { m_replacingChatModule = false; } m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); // take note of concierge channel and of identity m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); m_whoami = m_config.GetString("whoami", "conferencier"); m_welcomes = m_config.GetString("welcomes", m_welcomes); m_announceEntering = m_config.GetString("announce_entering", m_announceEntering); m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving); m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword); m_brokerURI = m_config.GetString("broker", m_brokerURI); m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout); m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami); // calculate regions Regex if (m_regions == null) { string regions = m_config.GetString("regions", String.Empty); if (!String.IsNullOrEmpty(regions)) { m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); } } } public override void AddRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false); lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName)) m_conciergedScenes.Add(scene); // subscribe to NewClient events scene.EventManager.OnNewClient += OnNewClient; // subscribe to *Chat events scene.EventManager.OnChatFromWorld += OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient += OnChatFromClient; scene.EventManager.OnChatBroadcast += OnChatBroadcast; // subscribe to agent change events scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; } } m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName); } public override void RemoveRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.RemoveXmlRPCHandler("concierge_update_welcome"); lock (m_syncy) { // unsubscribe from NewClient events scene.EventManager.OnNewClient -= OnNewClient; // unsubscribe from *Chat events scene.EventManager.OnChatFromWorld -= OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient -= OnChatFromClient; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; // unsubscribe from agent change events scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; scene.EventManager.OnMakeChildAgent -= OnMakeChildAgent; if (m_scenes.Contains(scene)) { m_scenes.Remove(scene); } if (m_conciergedScenes.Contains(scene)) { m_conciergedScenes.Remove(scene); } } m_log.InfoFormat("[Concierge]: removed {0}", scene.RegionInfo.RegionName); } public override void PostInitialise() { } public override void Close() { } new public Type ReplaceableInterface { get { return null; } } public override string Name { get { return "ConciergeModule"; } } #endregion #region ISimChat Members public override void OnChatBroadcast(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // distribute chat message to each and every avatar in // the region base.OnChatBroadcast(sender, c); } // TODO: capture logic return; } public override void OnChatFromClient(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // replacing ChatModule: need to redistribute // ChatFromClient to interested subscribers c = FixPositionOfChatMessage(c); Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } // redistribution will be done by base class base.OnChatFromClient(sender, c); } // TODO: capture chat return; } public override void OnChatFromWorld(Object sender, OSChatMessage c) { if (m_replacingChatModule) { if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } base.OnChatFromWorld(sender, c); } return; } #endregion public override void OnNewClient(IClientAPI client) { client.OnLogout += OnClientLoggedOut; if (m_replacingChatModule) client.OnChatFromClient += OnChatFromClient; } public void OnClientLoggedOut(IClientAPI client) { client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; if (m_conciergedScenes.Contains(client.Scene)) { Scene scene = client.Scene as Scene; m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeRootAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); WelcomeAvatar(agent, scene); AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeChildAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } internal class BrokerState { public string Uri; public string Payload; public HttpWebRequest Poster; public Timer Timer; public BrokerState(string uri, string payload, HttpWebRequest poster) { Uri = uri; Payload = payload; Poster = poster; } } protected void UpdateBroker(Scene scene) { if (String.IsNullOrEmpty(m_brokerURI)) return; string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID); // create XML sniplet StringBuilder list = new StringBuilder(); list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n", scene.GetRootAgentCount(), scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, DateTime.UtcNow.ToString("s"))); scene.ForEachRootScenePresence(delegate(ScenePresence sp) { list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID)); }); list.Append("</avatars>"); string payload = list.ToString(); // post via REST to broker HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest; updatePost.Method = "POST"; updatePost.ContentType = "text/xml"; updatePost.ContentLength = payload.Length; updatePost.UserAgent = "OpenSim.Concierge"; BrokerState bs = new BrokerState(uri, payload, updatePost); bs.Timer = new Timer(delegate(object state) { BrokerState b = state as BrokerState; b.Poster.Abort(); b.Timer.Dispose(); m_log.Debug("[Concierge]: async broker POST abort due to timeout"); }, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite); try { updatePost.BeginGetRequestStream(UpdateBrokerSend, bs); m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri); } catch (WebException we) { m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status); } } private void UpdateBrokerSend(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; string payload = bs.Payload; HttpWebRequest updatePost = bs.Poster; using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result))) { payloadStream.Write(payload); payloadStream.Close(); } updatePost.BeginGetResponse(UpdateBrokerDone, bs); } catch (WebException we) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status); } catch (Exception) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri); } } private void UpdateBrokerDone(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; HttpWebRequest updatePost = bs.Poster; using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse) { m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode); } bs.Timer.Dispose(); } catch (WebException we) { m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status); if (null != we.Response) { using (HttpWebResponse resp = we.Response as HttpWebResponse) { m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode); m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription); m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server); if (resp.ContentLength > 0) { StreamReader content = new StreamReader(resp.GetResponseStream()); m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); content.Close(); } } } } } protected void WelcomeAvatar(ScenePresence agent, Scene scene) { // welcome mechanics: check whether we have a welcomes // directory set and wether there is a region specific // welcome file there: if yes, send it to the agent if (!String.IsNullOrEmpty(m_welcomes)) { string[] welcomes = new string[] { Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName), Path.Combine(m_welcomes, "DEFAULT")}; foreach (string welcome in welcomes) { if (File.Exists(welcome)) { try { string[] welcomeLines = File.ReadAllLines(welcome); foreach (string l in welcomeLines) { AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami)); } } catch (IOException ioe) { m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}", welcome, scene.RegionInfo.RegionName, agent.Name, ioe); } catch (FormatException fe) { m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); } } return; } m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); } } static private Vector3 PosOfGod = new Vector3(128, 128, 9999); // protected void AnnounceToAgentsRegion(Scene scene, string msg) // { // ScenePresence agent = null; // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) // AnnounceToAgentsRegion(agent, msg); // else // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); // } protected void AnnounceToAgentsRegion(IScene scene, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = scene; if (scene is Scene) (scene as Scene).EventManager.TriggerOnChatBroadcast(this, c); } protected void AnnounceToAgent(ScenePresence agent, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = agent.Scene; agent.ControllingClient.SendChatMessage( msg, (byte) ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } private static void checkStringParameters(XmlRpcRequest request, string[] param) { Hashtable requestData = (Hashtable) request.Params[0]; foreach (string p in param) { if (!requestData.Contains(p)) throw new Exception(String.Format("missing string parameter {0}", p)); if (String.IsNullOrEmpty((string)requestData[p])) throw new Exception(String.Format("parameter {0} is empty", p)); } } public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[Concierge]: processing UpdateWelcome request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region", "welcome" }); // check password if (!String.IsNullOrEmpty(m_xmlRpcPassword) && (string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password"); if (String.IsNullOrEmpty(m_welcomes)) throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini"); string msg = (string)requestData["welcome"]; if (String.IsNullOrEmpty(msg)) throw new Exception("empty parameter \"welcome\""); string regionName = (string)requestData["region"]; IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); if (scene == null) throw new Exception(String.Format("unknown region \"{0}\"", regionName)); if (!m_conciergedScenes.Contains(scene)) throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName)); string welcome = Path.Combine(m_welcomes, regionName); if (File.Exists(welcome)) { m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome); string welcomeBackup = String.Format("{0}~", welcome); if (File.Exists(welcomeBackup)) File.Delete(welcomeBackup); File.Move(welcome, welcomeBackup); } File.WriteAllText(welcome, msg); responseData["success"] = "true"; response.Value = responseData; } catch (Exception e) { m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message); responseData["success"] = "false"; responseData["error"] = e.Message; response.Value = responseData; } m_log.Debug("[Concierge]: done processing UpdateWelcome request"); return response; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, 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.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal static class LayoutParser { internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool? throwConfigExceptions, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested) { //possible escape char `\` if (ch == '\\') { sr.Read(); var nextChar = sr.Peek(); //escape chars if (EndOfLayout(nextChar)) { //read next char and append sr.Read(); literalBuf.Append((char)nextChar); } else { //don't treat \ as escape char and just read it literalBuf.Append('\\'); } continue; } if (EndOfLayout(ch)) { //end of innerlayout. // `}` is when double nested inner layout. // `:` when single nested layout break; } } sr.Read(); //detect `${` (new layout-renderer) if (ch == '$' && sr.Peek() == '{') { //stash already found layout-renderer. AddLiteral(literalBuf, result); LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr, throwConfigExceptions); if (CanBeConvertedToLiteral(newLayoutRenderer)) { newLayoutRenderer = ConvertToLiteral(newLayoutRenderer); } // layout renderer result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } AddLiteral(literalBuf, result); int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } /// <summary> /// Add <see cref="LiteralLayoutRenderer"/> to <paramref name="result"/> /// </summary> /// <param name="literalBuf"></param> /// <param name="result"></param> private static void AddLiteral(StringBuilder literalBuf, List<LayoutRenderer> result) { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } } private static bool EndOfLayout(int ch) { return ch == '}' || ch == ':'; } private static string ParseLayoutRendererName(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterName(SimpleStringReader sr) { int ch; int nestLevel = 0; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); nameBuf.Append('$'); if (sr.Peek() == '{') { nameBuf.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { sr.Read(); // issue#3193 if (nestLevel != 0) { nameBuf.Append((char)ch); } // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterValue(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } // Code in this condition was replaced // to support escape codes e.g. '\r' '\n' '\u003a', // which can not be used directly as they are used as tokens by the parser // All escape codes listed in the following link were included // in addition to "\{", "\}", "\:" which are NLog specific: // https://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx if (ch == '\\') { // skip the backslash sr.Read(); var nextChar = (char)sr.Peek(); switch (nextChar) { case ':': case '{': case '}': case '\'': case '"': case '\\': sr.Read(); nameBuf.Append(nextChar); break; case '0': sr.Read(); nameBuf.Append('\0'); break; case 'a': sr.Read(); nameBuf.Append('\a'); break; case 'b': sr.Read(); nameBuf.Append('\b'); break; case 'f': sr.Read(); nameBuf.Append('\f'); break; case 'n': sr.Read(); nameBuf.Append('\n'); break; case 'r': sr.Read(); nameBuf.Append('\r'); break; case 't': sr.Read(); nameBuf.Append('\t'); break; case 'u': sr.Read(); var uChar = GetUnicode(sr, 4); // 4 digits nameBuf.Append(uChar); break; case 'U': sr.Read(); var UChar = GetUnicode(sr, 8); // 8 digits nameBuf.Append(UChar); break; case 'x': sr.Read(); var xChar = GetUnicode(sr, 4); // 1-4 digits nameBuf.Append(xChar); break; case 'v': sr.Read(); nameBuf.Append('\v'); break; } continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static char GetUnicode(SimpleStringReader sr, int maxDigits) { int code = 0; for (int cnt = 0; cnt < maxDigits; cnt++) { var digitCode = sr.Peek(); if (digitCode >= (int)'0' && digitCode <= (int)'9') digitCode = digitCode - (int)'0'; else if (digitCode >= (int)'a' && digitCode <= (int)'f') digitCode = digitCode - (int)'a' + 10; else if (digitCode >= (int)'A' && digitCode <= (int)'F') digitCode = digitCode - (int)'A' + 10; else break; sr.Read(); code = code * 16 + digitCode; } return (char)code; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions) { int ch = stringReader.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(stringReader); var layoutRenderer = GetLayoutRenderer(configurationItemFactory, name, throwConfigExceptions); var wrappers = new Dictionary<Type, LayoutRenderer>(); var orderedWrappers = new List<LayoutRenderer>(); ch = stringReader.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(stringReader).Trim(); if (stringReader.Peek() == '=') { stringReader.Read(); // skip the '=' PropertyInfo propertyInfo; LayoutRenderer parameterTarget = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo)) { propertyInfo = null; } else { parameterTarget = wrapperRenderer; } } } if (propertyInfo == null) { ParseParameterValue(stringReader); } else { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out txt); nestedLayout.SetRenderers(renderers, txt); propertyInfo.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory); propertyInfo.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(stringReader); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName); } ch = stringReader.Read(); } layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); return layoutRenderer; } private static LayoutRenderer GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, string name, bool? throwConfigExceptions) { LayoutRenderer layoutRenderer; try { layoutRenderer = configurationItemFactory.LayoutRenderers.CreateInstance(name); } catch (Exception ex) { if (throwConfigExceptions ?? LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions) { throw; // TODO NLog 5.0 throw NLogConfigurationException. Maybe also include entire input layout-string (if not too long) } InternalLogger.Error(ex, "Error parsing layout {0} will be ignored.", name); // replace with empty values layoutRenderer = new LiteralLayoutRenderer(string.Empty); } return layoutRenderer; } private static void SetDefaultPropertyValue(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, string parameterName) { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) PropertyInfo propertyInfo; if (PropertyHelper.TryGetPropertyInfo(layoutRenderer, string.Empty, out propertyInfo)) { if (typeof(SimpleLayout) == propertyInfo.PropertyType) { propertyInfo.SetValue(layoutRenderer, new SimpleLayout(parameterName), null); } else { string value = parameterName; PropertyHelper.SetPropertyFromString(layoutRenderer, propertyInfo.Name, value, configurationItemFactory); } } else { InternalLogger.Warn("{0} has no default property", layoutRenderer.GetType().FullName); } } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name); if (CanBeConvertedToLiteral(lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(true, lr)) { if (renderable.GetType() == typeof(SimpleLayout)) { continue; } if (!renderable.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(List<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { var lr1 = list[i] as LiteralLayoutRenderer; var lr2 = list[i + 1] as LiteralLayoutRenderer; if (lr1 != null && lr2 != null) { lr1.Text += lr2.Text; list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent())); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static ISet<SyntaxKind> GetPrecedingModifiers( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer); while (true) { switch (token.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.VirtualKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.AsyncKeyword: result.Add(token.Kind()); token = token.GetPreviousToken(includeSkipped: true); continue; case SyntaxKind.IdentifierToken: if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { result.Add(SyntaxKind.AsyncKeyword); token = token.GetPreviousToken(includeSkipped: true); continue; } break; } break; } return result; } public static TypeDeclarationSyntax GetContainingTypeDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault(); } public static BaseTypeDeclarationSyntax GetContainingTypeOrEnumDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault(); } public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<TypeDeclarationSyntax>().Where(t => { return BaseTypeDeclarationContainsPosition(t, position); }); } private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position) { if (position <= declaration.OpenBraceToken.SpanStart) { return false; } if (declaration.CloseBraceToken.IsMissing) { return true; } return position <= declaration.CloseBraceToken.SpanStart; } public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position)); } private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken; private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken; public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken); } public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken); } private static bool IsRightOf( this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) { return false; } return predicate(token.Kind()); } public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.Kind() == SyntaxKind.NumericLiteralToken; } public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { return syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken); } public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); return token.Kind() == kind; } public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) || syntaxTree.IsInInactiveRegion(position, cancellationToken); } public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var inNonUserSingleLineDocComment = syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken); return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || inNonUserSingleLineDocComment; } public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken); } public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Parent is XmlCrefAttributeSyntax) { var attribute = (XmlCrefAttributeSyntax)token.Parent; return token == attribute.StartQuoteToken; } return false; } public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree.IsCrefContext(position, cancellationToken)) { return true; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); return token.GetAncestor<CrefSyntax>() != null; } public static bool IsEntirelyWithinSingleLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax; var trivia = root.FindTrivia(position); // If we ask right at the end of the file, we'll get back nothing. // So move back in that case and ask again. var eofPosition = root.FullWidth(); if (position == eofPosition) { var eof = root.EndOfFileToken; if (eof.HasLeadingTrivia) { trivia = eof.LeadingTrivia.Last(); } } if (trivia.IsSingleLineDocComment()) { var span = trivia.Span; var fullSpan = trivia.FullSpan; var endsWithNewLine = trivia.GetStructure().GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken; if (endsWithNewLine) { if (position > fullSpan.Start && position < fullSpan.End) { return true; } } else { if (position > fullSpan.Start && position <= fullSpan.End) { return true; } } } return false; } public static bool IsEntirelyWithinMultiLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position); if (trivia.IsMultiLineDocComment()) { var span = trivia.FullSpan; if (position > span.Start && position < span.End) { return true; } } return false; } public static bool IsEntirelyWithinMultiLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.IsMultiLineComment()) { var span = trivia.FullSpan; return trivia.IsCompleteMultiLineComment() ? position > span.Start && position < span.End : position > span.Start && position <= span.End; } return false; } public static bool IsEntirelyWithinTopLevelSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken); } if (trivia.IsSingleLineComment() || trivia.IsShebangDirective()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } public static bool IsEntirelyWithinPreProcessorSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // Search inside trivia for directives to ensure that we recognize // single-line comments at the end of preprocessor directives. var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken, findInsideTrivia: true); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true); } if (trivia.IsSingleLineComment()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar) { if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken)) { throw new ArgumentException(CSharpWorkspaceResources.Expected_string_or_char_literal, nameof(token)); } int startLength = 1; if (token.IsVerbatimStringLiteral()) { startLength = 2; } return position == token.Span.End && (token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar)); } public static bool IsEntirelyWithinStringOrCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) || syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken); } public static bool IsEntirelyWithinStringLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. We handle that case // specially for now, though SyntaxTree.FindToken should work at the end of a file. if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken)) { token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.IsKind(SyntaxKind.StringLiteralToken)) { var span = token.Span; // cases: // "|" // "| (e.g. incomplete string literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '"'); } if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.InterpolatedStringEndToken)) { return token.SpanStart < position && token.Span.End > position; } return false; } public static bool IsEntirelyWithinCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax; var token = root.FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindToken should // work at the end of a file. if (position == root.FullWidth()) { token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.Kind() == SyntaxKind.CharacterLiteralToken) { var span = token.Span; // cases: // '|' // '| (e.g. incomplete char literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '\''); } return false; } public static bool IsInInactiveRegion( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); // cases: // $ is EOF // #if false // | // #if false // |$ // #if false // | // #if false // |$ if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken)) { return false; } // The latter two are the hard cases we don't actually have an // DisabledTextTrivia yet. var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return true; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return false; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return false; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax) { var branch = (BranchingDirectiveTriviaSyntax)structure; return !branch.IsActive || !branch.BranchTaken; } } } } return false; } public static IList<MemberDeclarationSyntax> GetMembersInSpan( this SyntaxTree syntaxTree, TextSpan textSpan, CancellationToken cancellationToken) { var token = syntaxTree.GetRoot(cancellationToken).FindToken(textSpan.Start); var firstMember = token.GetAncestors<MemberDeclarationSyntax>().FirstOrDefault(); if (firstMember != null) { var containingType = firstMember.Parent as TypeDeclarationSyntax; if (containingType != null) { var members = GetMembersInSpan(textSpan, containingType, firstMember); if (members != null) { return members; } } } return SpecializedCollections.EmptyList<MemberDeclarationSyntax>(); } private static List<MemberDeclarationSyntax> GetMembersInSpan( TextSpan textSpan, TypeDeclarationSyntax containingType, MemberDeclarationSyntax firstMember) { List<MemberDeclarationSyntax> selectedMembers = null; var members = containingType.Members; var fieldIndex = members.IndexOf(firstMember); if (fieldIndex < 0) { return null; } for (var i = fieldIndex; i < members.Count; i++) { var member = members[i]; if (textSpan.Contains(member.Span)) { selectedMembers = selectedMembers ?? new List<MemberDeclarationSyntax>(); selectedMembers.Add(member); } else if (textSpan.OverlapsWith(member.Span)) { return null; } else { break; } } return selectedMembers; } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { SyntaxToken genericIdentifier; SyntaxToken lessThanToken; return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier) { SyntaxToken lessThanToken; return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { genericIdentifier = default(SyntaxToken); lessThanToken = default(SyntaxToken); int index = 0; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() == SyntaxKind.None) { return false; } // check whether we are under type or member decl if (token.GetAncestor<TypeParameterListSyntax>() != null) { return false; } int stack = 0; while (true) { switch (token.Kind()) { case SyntaxKind.LessThanToken: if (stack == 0) { // got here so we read successfully up to a < now we have to read the // name before that and we're done! lessThanToken = token; token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } // ok // so we've read something like: // ~~~~~~~~~<a,b,... // but we need to know the simple name that precedes the < // it could be // ~~~~~~foo<a,b,... if (token.Kind() == SyntaxKind.IdentifierToken) { // okay now check whether it is actually partially written if (IsFullyWrittenGeneric(token, lessThanToken)) { return false; } genericIdentifier = token; return true; } return false; } else { stack--; break; } case SyntaxKind.GreaterThanGreaterThanToken: stack++; goto case SyntaxKind.GreaterThanToken; // fall through case SyntaxKind.GreaterThanToken: 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: break; case SyntaxKind.CommaToken: if (stack == 0) { index++; } break; 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. return false; } // look backward one token, include skipped tokens, because the parser frequently // does skip them in cases like: "Func<A, B", which get parsed as: expression // statement "Func<A" with missing semicolon, expression statement "B" with missing // semicolon, and the "," is skipped. token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } } } private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken) { var genericName = token.Parent as GenericNameSyntax; return genericName != null && genericName.TypeArgumentList != null && genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using SteamKit2; using SteamTrade.Exceptions; using Newtonsoft.Json.Linq; using SteamTrade.TradeWebAPI; namespace SteamTrade { public partial class Trade { #region Static Public data public static Schema CurrentSchema = null; #endregion // list to store all trade events already processed List<TradeEvent> eventList; // current bot's sid SteamID mySteamId; // If the bot is ready. bool meIsReady = false; // If the other user is ready. bool otherIsReady = false; // Whether or not the trade actually started. bool tradeStarted = false; Dictionary<int, ulong> myOfferedItems; List<ulong> steamMyOfferedItems; // Internal properties needed for Steam API. int numEvents; private readonly TradeSession session; internal Trade(SteamID me, SteamID other, string sessionId, string token, Inventory myInventory, Inventory otherInventory) { mySteamId = me; OtherSID = other; List<uint> InvType = new List<uint>(); session = new TradeSession(sessionId, token, other, "440"); this.eventList = new List<TradeEvent>(); OtherOfferedItems = new List<ulong>(); myOfferedItems = new Dictionary<int, ulong>(); steamMyOfferedItems = new List<ulong>(); OtherInventory = otherInventory; MyInventory = myInventory; } #region Public Properties /// <summary>Gets the other user's steam ID.</summary> public SteamID OtherSID { get; private set; } /// <summary> /// Gets the bot's Steam ID. /// </summary> public SteamID MySteamId { get { return mySteamId; } } /// <summary> /// Gets the inventory of the other user. /// </summary> public Inventory OtherInventory { get; private set; } /// <summary> /// Gets the private inventory of the other user. /// </summary> public ForeignInventory OtherPrivateInventory { get; private set; } /// <summary> /// Gets the inventory of the bot. /// </summary> public Inventory MyInventory { get; private set; } /// <summary> /// Gets the items the user has offered, by itemid. /// </summary> /// <value> /// The other offered items. /// </value> public List<ulong> OtherOfferedItems { get; private set; } /// <summary> /// Gets a value indicating if the other user is ready to trade. /// </summary> public bool OtherIsReady { get { return otherIsReady; } } /// <summary> /// Gets a value indicating if the bot is ready to trade. /// </summary> public bool MeIsReady { get { return meIsReady; } } /// <summary> /// Gets a value indicating if a trade has started. /// </summary> public bool TradeStarted { get { return tradeStarted; } } /// <summary> /// Gets a value indicating if the remote trading partner cancelled the trade. /// </summary> public bool OtherUserCancelled { get; private set; } /// <summary> /// Gets a value indicating whether the trade completed normally. This /// is independent of other flags. /// </summary> public bool HasTradeCompletedOk { get; private set; } #endregion #region Public Events public delegate void CloseHandler (); public delegate void ErrorHandler (string error); public delegate void TimeoutHandler (); public delegate void SuccessfulInit (); public delegate void UserAddItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem); public delegate void UserRemoveItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem); public delegate void MessageHandler (string msg); public delegate void UserSetReadyStateHandler (bool ready); public delegate void UserAcceptHandler (); /// <summary> /// When the trade closes, this is called. It doesn't matter /// whether or not it was a timeout or an error, this is called /// to close the trade. /// </summary> public event CloseHandler OnClose; /// <summary> /// This is for handling errors that may occur, like inventories /// not loading. /// </summary> public event ErrorHandler OnError; /// <summary> /// This occurs after Inventories have been loaded. /// </summary> public event SuccessfulInit OnAfterInit; /// <summary> /// This occurs when the other user adds an item to the trade. /// </summary> public event UserAddItemHandler OnUserAddItem; /// <summary> /// This occurs when the other user removes an item from the /// trade. /// </summary> public event UserAddItemHandler OnUserRemoveItem; /// <summary> /// This occurs when the user sends a message to the bot over /// trade. /// </summary> public event MessageHandler OnMessage; /// <summary> /// This occurs when the user sets their ready state to either /// true or false. /// </summary> public event UserSetReadyStateHandler OnUserSetReady; /// <summary> /// This occurs when the user accepts the trade. /// </summary> public event UserAcceptHandler OnUserAccept; #endregion /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> public bool CancelTrade () { bool ok = session.CancelTradeWebCmd (); if (!ok) throw new TradeException ("The Web command to cancel the trade failed"); if (OnClose != null) OnClose (); return true; } /// <summary> /// Adds a specified item by its itemid. /// </summary> /// <returns><c>false</c> if the item was not found in the inventory.</returns> public bool AddItem (ulong itemid,string appid = "",string contextid ="") { if (appid =="" & MyInventory.GetItem(itemid) == null) return false; var slot = NextTradeSlot(); bool ok = session.AddItemWebCmd(itemid, slot,appid,contextid); if (!ok) throw new TradeException("The Web command to add the Item failed"); myOfferedItems[slot] = itemid; return true; } /// <summary> /// Adds a single item by its Defindex. /// </summary> /// <returns> /// <c>true</c> if an item was found with the corresponding /// defindex, <c>false</c> otherwise. /// </returns> public bool AddItemByDefindex (int defindex) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex); foreach (Inventory.Item item in items) { if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable) { return AddItem (item.Id); } } return false; } /// <summary> /// Adds an entire set of items by Defindex to each successive /// slot in the trade. /// </summary> /// <param name="defindex">The defindex. (ex. 5022 = crates)</param> /// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param> /// <returns>Number of items added.</returns> public uint AddAllItemsByDefindex (int defindex, uint numToAdd = 0) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex); uint added = 0; foreach (Inventory.Item item in items) { if (item != null && !myOfferedItems.ContainsValue(item.Id) && !item.IsNotTradeable) { bool success = AddItem (item.Id); if (success) added++; if (numToAdd > 0 && added >= numToAdd) return added; } } return added; } /// <summary> /// Removes an item by its itemid. /// </summary> /// <returns><c>false</c> the item was not found in the trade.</returns> public bool RemoveItem (ulong itemid,string appid = "",string contextid ="") { int? slot = GetItemSlot (itemid); if (!slot.HasValue) return false; bool ok = session.RemoveItemWebCmd(itemid, slot.Value,appid,contextid); if (!ok) throw new TradeException ("The web command to remove the item failed."); myOfferedItems.Remove (slot.Value); return true; } /// <summary> /// Removes an item with the given Defindex from the trade. /// </summary> /// <returns> /// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise. /// </returns> public bool RemoveItemByDefindex (int defindex) { foreach (ulong id in myOfferedItems.Values) { Inventory.Item item = MyInventory.GetItem (id); if (item.Defindex == defindex) { return RemoveItem (item.Id); } } return false; } /// <summary> /// Removes an entire set of items by Defindex. /// </summary> /// <param name="defindex">The defindex. (ex. 5022 = crates)</param> /// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param> /// <returns>Number of items removed.</returns> public uint RemoveAllItemsByDefindex (int defindex, uint numToRemove = 0) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex); uint removed = 0; foreach (Inventory.Item item in items) { if (item != null && myOfferedItems.ContainsValue (item.Id)) { bool success = RemoveItem (item.Id); if (success) removed++; if (numToRemove > 0 && removed >= numToRemove) return removed; } } return removed; } /// <summary> /// Removes all offered items from the trade. /// </summary> /// <returns>Number of items removed.</returns> public uint RemoveAllItems() { uint removed = 0; var copy = new Dictionary<int, ulong>(myOfferedItems); foreach (var id in copy) { Inventory.Item item = MyInventory.GetItem(id.Value); bool success = RemoveItem(item.Id); if (success) removed++; } return removed; } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> public bool SendMessage (string msg) { bool ok = session.SendMessageWebCmd(msg); if (!ok) throw new TradeException ("The web command to send the trade message failed."); return true; } /// <summary> /// Sets the bot to a ready status. /// </summary> public bool SetReady (bool ready) { // testing ValidateLocalTradeItems (); bool ok = session.SetReadyWebCmd(ready); if (!ok) throw new TradeException ("The web command to set trade ready state failed."); return true; } /// <summary> /// Accepts the trade from the user. Returns a deserialized /// JSON object. /// </summary> public bool AcceptTrade () { ValidateLocalTradeItems (); bool ok = session.AcceptTradeWebCmd(); if (!ok) throw new TradeException ("The web command to accept the trade failed."); return true; } /// <summary> /// This updates the trade. This is called at an interval of a /// default of 800ms, not including the execution time of the /// method itself. /// </summary> /// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns> public bool Poll () { bool otherDidSomething = false; if (!TradeStarted) { tradeStarted = true; // since there is no feedback to let us know that the trade // is fully initialized we assume that it is when we start polling. if (OnAfterInit != null) OnAfterInit (); } TradeStatus status = session.GetStatus(); if (status == null) throw new TradeException ("The web command to get the trade status failed."); switch (status.trade_status) { // Nothing happened. i.e. trade hasn't closed yet. case 0: break; // Successful trade case 1: HasTradeCompletedOk = true; return otherDidSomething; // All other known values (3, 4) correspond to trades closing. default: if (OnError != null) { OnError("Trade was closed by other user. Trade status: " + status.trade_status); } OtherUserCancelled = true; return otherDidSomething; } if (status.newversion) { // handle item adding and removing session.Version = status.version; TradeEvent trdEvent = status.GetLastEvent(); TradeEventType actionType = (TradeEventType) trdEvent.action; HandleTradeVersionChange(status); return true; } else if (status.version > session.Version) { // oh crap! we missed a version update abort so we don't get // scammed. if we could get what steam thinks what's in the // trade then this wouldn't be an issue. but we can only get // that when we see newversion == true throw new TradeException("The trade version does not match. Aborting."); } var events = status.GetAllEvents(); foreach (var tradeEvent in events) { if (eventList.Contains(tradeEvent)) continue; //add event to processed list, as we are taking care of this event now eventList.Add(tradeEvent); bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString(); // dont process if this is something the bot did if (isBot) continue; otherDidSomething = true; /* Trade Action ID's * 0 = Add item (itemid = "assetid") * 1 = remove item (itemid = "assetid") * 2 = Toggle ready * 3 = Toggle not ready * 4 = ? * 5 = ? - maybe some sort of cancel * 6 = ? * 7 = Chat (message = "text") */ switch ((TradeEventType) tradeEvent.action) { case TradeEventType.ItemAdded: FireOnUserAddItem(tradeEvent); break; case TradeEventType.ItemRemoved: FireOnUserRemoveItem(tradeEvent); break; case TradeEventType.UserSetReady: otherIsReady = true; OnUserSetReady(true); break; case TradeEventType.UserSetUnReady: otherIsReady = false; OnUserSetReady(false); break; case TradeEventType.UserAccept: OnUserAccept(); break; case TradeEventType.UserChat: OnMessage(tradeEvent.text); break; default: // Todo: add an OnWarning or similar event if (OnError != null) OnError("Unknown Event ID: " + tradeEvent.action); break; } } // Update Local Variables if (status.them != null) { otherIsReady = status.them.ready == 1; meIsReady = status.me.ready == 1; } if (status.logpos != 0) { session.LogPos = status.logpos; } return otherDidSomething; } void HandleTradeVersionChange(TradeStatus status) { CopyNewAssets(OtherOfferedItems, status.them.GetAssets()); CopyNewAssets(steamMyOfferedItems, status.me.GetAssets()); } private void CopyNewAssets(List<ulong> dest, TradeUserAssets[] assetList) { if (assetList == null) return; //Console.WriteLine("clearing dest"); dest.Clear(); foreach (var asset in assetList) { dest.Add(asset.assetid); //Console.WriteLine(asset.assetid); } } /// <summary> /// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine. /// Passes in null items if something went wrong. /// </summary> /// <param name="tradeEvent">TradeEvent to get item from</param> /// <returns></returns> private void FireOnUserAddItem(TradeEvent tradeEvent) { ulong itemID = tradeEvent.assetid; Inventory.Item item; if (OtherInventory != null) { item = OtherInventory.GetItem(itemID); if (item != null) { Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex); if (schemaItem == null) { Console.WriteLine("User added an unknown item to the trade."); } OnUserAddItem(schemaItem, item); } else { item = new Inventory.Item(); item.Id = itemID; item.AppId = tradeEvent.appid; //Console.WriteLine("User added a non TF2 item to the trade."); OnUserAddItem(null, item); } } else { var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID); if (schemaItem == null) { Console.WriteLine("User added an unknown item to the trade."); } OnUserAddItem(schemaItem, null); // todo: figure out what to send in with Inventory item..... } } private Schema.Item GetItemFromPrivateBp(TradeEvent tradeEvent, ulong itemID) { if (OtherPrivateInventory == null) { // get the foreign inventory var f = session.GetForiegnInventory(OtherSID, tradeEvent.contextid); OtherPrivateInventory = new ForeignInventory(f); } ushort defindex = OtherPrivateInventory.GetDefIndex(itemID); Schema.Item schemaItem = CurrentSchema.GetItem(defindex); return schemaItem; } /// <summary> /// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine. /// Passes in null items if something went wrong. /// </summary> /// <param name="tradeEvent">TradeEvent to get item from</param> /// <returns></returns> private void FireOnUserRemoveItem(TradeEvent tradeEvent) { ulong itemID = (ulong) tradeEvent.assetid; Inventory.Item item; if (OtherInventory != null) { item = OtherInventory.GetItem(itemID); if (item != null) { Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex); if (schemaItem == null) { // TODO: Add log (counldn't find item in CurrentSchema) } OnUserRemoveItem(schemaItem, item); } else { // TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema item = new Inventory.Item(); item.Id = itemID; item.AppId = tradeEvent.appid; OnUserRemoveItem(null, item); } } else { var schemaItem = GetItemFromPrivateBp(tradeEvent, itemID); if (schemaItem == null) { // TODO: Add log (counldn't find item in CurrentSchema) } OnUserRemoveItem(schemaItem, null); } } internal void FireOnCloseEvent() { var onCloseEvent = OnClose; if (onCloseEvent != null) onCloseEvent(); } int NextTradeSlot () { int slot = 0; while (myOfferedItems.ContainsKey (slot)) { slot++; } return slot; } int? GetItemSlot (ulong itemid) { foreach (int slot in myOfferedItems.Keys) { if (myOfferedItems [slot] == itemid) { return slot; } } return null; } void ValidateSteamItemChanged (ulong itemid, bool wasAdded) { // checks to make sure that the Trade polling saw // the correct change for the given item. // check if the correct item was added if (wasAdded && !myOfferedItems.ContainsValue (itemid)) throw new TradeException ("Steam Trade had an invalid item added: " + itemid); // check if the correct item was removed if (!wasAdded && myOfferedItems.ContainsValue (itemid)) throw new TradeException ("Steam Trade had an invalid item removed: " + itemid); } void ValidateLocalTradeItems () { if (myOfferedItems.Count != steamMyOfferedItems.Count) { throw new TradeException ("Error validating local copy of items in the trade: Count mismatch"); } foreach (ulong id in myOfferedItems.Values) { if (!steamMyOfferedItems.Contains (id)) throw new TradeException ("Error validating local copy of items in the trade: Item was not in the Steam Copy."); } } } }
// 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, // MERCHANTABLITY 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.Generic; using System.Linq; using Microsoft.PythonTools.Analysis.Analyzer; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Values { internal struct CallChain : IEnumerable<Node>, IEquatable<CallChain> { private readonly object _chain; private static Node EmptyNode = new NameExpression(null); private static IEnumerable<Node> EmptyNodes { get { while (true) { yield return EmptyNode; } } } private CallChain(object chain) { _chain = chain; } public CallChain(Node call, CallChain preceding, int limit) { if (limit == 1) { _chain = call; } else { _chain = Enumerable.Repeat(call, 1).Concat(preceding).Concat(EmptyNodes).Take(limit).ToArray(); } } public CallChain(Node call, AnalysisUnit unit, int limit) { var fau = unit as CalledFunctionAnalysisUnit; if (fau == null || limit == 1) { _chain = call; } else { _chain = Enumerable.Repeat(call, 1).Concat(fau.CallChain).Concat(EmptyNodes).Take(limit).ToArray(); } } public CallChain Trim(int limit) { object newChain; if (_chain == null || limit == 0) { newChain = null; } else if (_chain is Node) { newChain = _chain; } else if (limit == 1) { newChain = ((Node[])_chain)[0]; } else { newChain = ((Node[])_chain).Take(limit).ToArray(); } return new CallChain(newChain); } public Node this[int index] { get { if (index == 0 && _chain != null) { return (_chain as Node) ?? ((Node[])_chain)[0]; } var arr = _chain as Node[]; if (arr != null) { return arr[index]; } throw new IndexOutOfRangeException(); } } public int Count { get { if (_chain == null) { return 0; } else if (_chain is Node) { return 1; } else { return ((Node[])_chain).Length; } } } public IEnumerator<Node> GetEnumerator() { var single = _chain as Node; if (single != null) { return new SetOfOneEnumerator<Node>(single); } var arr = _chain as IEnumerable<Node>; if (arr != null) { return arr.GetEnumerator(); } return Enumerable.Empty<Node>().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public override int GetHashCode() { return this.Aggregate(13187, (hc, n) => n.GetHashCode() ^ hc); } public override bool Equals(object obj) { if (obj == null) { return false; } var other = (CallChain)obj; return this.SequenceEqual(other); } public bool PrefixMatches(CallChain other, int limit) { return this.Take(limit).SequenceEqual(other.Take(limit)); } public bool Equals(CallChain other) { return this.SequenceEqual(other); } } /// <summary> /// Maintains a mapping from the CallChain to the FunctionAnalysisUnit's used /// for analyzing each unique call. /// /// Entries are stored keyed off the ProjectEntry and get thrown away when /// a new version of the project entry shows up. /// </summary> internal class CallChainSet { private readonly Dictionary<IVersioned, CallChainEntry> _data; public CallChainSet() { _data = new Dictionary<IVersioned, CallChainEntry>(); } public bool TryGetValue(IVersioned entry, CallChain chain, int prefixLength, out FunctionAnalysisUnit value) { value = null; CallChainEntry entryData; lock (_data) { if (!_data.TryGetValue(entry, out entryData)) { return false; } if (entryData.AnalysisVersion != entry.AnalysisVersion) { _data.Remove(entry); return false; } } lock (entryData.Calls) { return entryData.Calls.TryGetValue(chain, out value); } } public void Clear() { lock (_data) { _data.Clear(); } } public int Count { get { var data = _data; if (data == null) { return 0; } lock (data) { return data.Values.Sum(v => v.Calls.Count); } } } public void Add(IVersioned entry, CallChain chain, FunctionAnalysisUnit value) { CallChainEntry entryData; lock (_data) { if (!_data.TryGetValue(entry, out entryData) || entryData.AnalysisVersion != entry.AnalysisVersion) { _data[entry] = entryData = new CallChainEntry( entry.AnalysisVersion, new Dictionary<CallChain, FunctionAnalysisUnit>() ); } } lock (entryData.Calls) { entryData.Calls[chain] = value; } } public IEnumerable<FunctionAnalysisUnit> Values { get { if (_data == null) { return Enumerable.Empty<FunctionAnalysisUnit>(); } return _data.AsLockedEnumerable() .SelectMany(v => v.Value.Calls.Values.AsLockedEnumerable(v.Value.Calls)); } } struct CallChainEntry { public readonly int AnalysisVersion; public readonly Dictionary<CallChain, FunctionAnalysisUnit> Calls; public CallChainEntry(int version, Dictionary<CallChain, FunctionAnalysisUnit> calls) { AnalysisVersion = version; Calls = calls; } } } }
// 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.Tests { public static partial class TimeZoneInfoTests { [Fact] public static void ClearCachedData() { TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(s_strSydney); TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo.ClearCachedData(); Assert.ThrowsAny<ArgumentException>(() => { TimeZoneInfo.ConvertTime(DateTime.Now, local, cst); }); } [Fact] public static void ConvertTime_DateTimeOffset_NullDestination_ArgumentNullException() { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<ArgumentNullException>(time1, null); } public static IEnumerable<object[]> ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData() { yield return new object[] { string.Empty }; yield return new object[] { " " }; yield return new object[] { "\0" }; yield return new object[] { s_strPacific.Substring(0, s_strPacific.Length / 2) }; // whole string must match yield return new object[] { s_strPacific + " Zone" }; // no extra characters yield return new object[] { " " + s_strPacific }; // no leading space yield return new object[] { s_strPacific + " " }; // no trailing space yield return new object[] { "\0" + s_strPacific }; // no leading null yield return new object[] { s_strPacific + "\0" }; // no trailing null yield return new object[] { s_strPacific + "\\ " }; // no trailing null yield return new object[] { s_strPacific + "\\Display" }; yield return new object[] { s_strPacific + "\n" }; // no trailing newline yield return new object[] { new string('a', 100) }; // long string } [Theory] [MemberData(nameof(ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData))] public static void ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException(string destinationId) { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<TimeZoneNotFoundException>(time1, destinationId); } [Fact] public static void ConvertTimeFromUtc() { // destination timezone is null Assert.Throws<ArgumentNullException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0), null); }); // destination timezone is UTC DateTime now = DateTime.UtcNow; DateTime convertedNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Utc); Assert.Equal(now, convertedNow); } [Fact] public static void ConvertTimeToUtc() { // null source VerifyConvertToUtcException<ArgumentNullException>(new DateTime(2007, 5, 3, 12, 16, 0), null); TimeZoneInfo london = CreateCustomLondonTimeZone(); // invalid DateTime DateTime invalidDate = new DateTime(2007, 3, 25, 1, 30, 0); VerifyConvertToUtcException<ArgumentException>(invalidDate, london); // DateTimeKind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Utc), london); // correct UTC conversion DateTime date = new DateTime(2007, 01, 01, 0, 0, 0); Assert.Equal(date.ToUniversalTime(), TimeZoneInfo.ConvertTimeToUtc(date)); } [Fact] public static void ConvertTimeFromToUtc() { TimeZoneInfo london = CreateCustomLondonTimeZone(); DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, back.Kind); Assert.Equal(utc, back); converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); DateTimeKind expectedKind = (TimeZoneInfo.Local == TimeZoneInfo.Utc) ? DateTimeKind.Utc : DateTimeKind.Local; Assert.Equal(expectedKind, converted.Kind); back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Local); Assert.Equal(back.Kind, DateTimeKind.Utc); Assert.Equal(utc, back); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void ConvertTimeFromToUtc_UnixOnly() { // DateTime Kind is Local Assert.ThrowsAny<ArgumentException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0, DateTimeKind.Local), TimeZoneInfo.Local); }); TimeZoneInfo london = CreateCustomLondonTimeZone(); // winter (no DST) DateTime winter = new DateTime(2007, 12, 25, 12, 0, 0); DateTime convertedWinter = TimeZoneInfo.ConvertTimeFromUtc(winter, london); Assert.Equal(winter, convertedWinter); // summer (DST) DateTime summer = new DateTime(2007, 06, 01, 12, 0, 0); DateTime convertedSummer = TimeZoneInfo.ConvertTimeFromUtc(summer, london); Assert.Equal(summer + new TimeSpan(1, 0, 0), convertedSummer); // Kind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Local), london); // Test the ambiguous date DateTime utcAmbiguous = new DateTime(2016, 10, 30, 0, 14, 49, DateTimeKind.Utc); DateTime convertedAmbiguous = TimeZoneInfo.ConvertTimeFromUtc(utcAmbiguous, london); Assert.Equal(DateTimeKind.Unspecified, convertedAmbiguous.Kind); Assert.True(london.IsAmbiguousTime(convertedAmbiguous), $"Expected to have {convertedAmbiguous} is ambiguous"); // convert to London time and back DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, london); Assert.Equal(DateTimeKind.Unspecified, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, london); Assert.Equal(DateTimeKind.Utc, back.Kind); if (london.IsAmbiguousTime(converted)) { // if the time is ambiguous this will not round trip the original value because this ambiguous time can be mapped into // 2 UTC times. usually we return the value with the DST delta added to it. back = back.AddTicks(- london.GetAdjustmentRules()[0].DaylightDelta.Ticks); } Assert.Equal(utc, back); } [Fact] public static void CreateCustomTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // supports DST TimeZoneInfo tz1 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }); Assert.True(tz1.SupportsDaylightSavingTime); // doesn't support DST TimeZoneInfo tz2 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(4, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }, true); Assert.False(tz2.SupportsDaylightSavingTime); TimeZoneInfo tz3 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, null); Assert.False(tz3.SupportsDaylightSavingTime); } [Fact] public static void CreateCustomTimeZone_Invalid() { VerifyCustomTimeZoneException<ArgumentNullException>(null, new TimeSpan(0), null, null); // null Id VerifyCustomTimeZoneException<ArgumentException>("", new TimeSpan(0), null, null); // empty string Id VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(0, 0, 55), null, null); // offset not minutes VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(14, 1, 0), null, null); // offset too big VerifyCustomTimeZoneException<ArgumentException>("mytimezone", - new TimeSpan(14, 1, 0), null, null); // offset too small } [Fact] public static void CreateCustomTimeZone_InvalidTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // AdjustmentRules overlap TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2004, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r2 }); // AdjustmentRules not ordered TimeZoneInfo.AdjustmentRule r3 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2006, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r3, r1 }); // Offset out of range TimeZoneInfo.AdjustmentRule r4 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(3, 0, 0), s1, e1); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r4 }); // overlapping AdjustmentRules for a date TimeZoneInfo.AdjustmentRule r5 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2005, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r5 }); // null AdjustmentRule VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { null }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // TimeZone not found on Windows public static void HasSameRules_RomeAndVatican() { TimeZoneInfo rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vatican"); Assert.True(rome.HasSameRules(vatican)); } [Fact] public static void HasSameRules_NullAdjustmentRules() { TimeZoneInfo utc = TimeZoneInfo.Utc; TimeZoneInfo custom = TimeZoneInfo.CreateCustomTimeZone("Custom", new TimeSpan(0), "Custom", "Custom"); Assert.True(utc.HasSameRules(custom)); } [Fact] public static void ConvertTimeBySystemTimeZoneIdTests() { DateTime now = DateTime.Now; DateTime utcNow = TimeZoneInfo.ConvertTimeToUtc(now); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Utc.Id)); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Utc.Id, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Local.Id, TimeZoneInfo.Utc.Id)); DateTimeOffset offsetNow = new DateTimeOffset(now); DateTimeOffset utcOffsetNow = new DateTimeOffset(utcNow); Assert.Equal(offsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcOffsetNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcOffsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(offsetNow, TimeZoneInfo.Utc.Id)); } public static IEnumerable<object[]> SystemTimeZonesTestData() { foreach (TimeZoneInfo tz in TimeZoneInfo.GetSystemTimeZones()) { yield return new object[] { tz }; } } [ActiveIssue(14797, TestPlatforms.AnyUnix)] [Theory] [MemberData(nameof(SystemTimeZonesTestData))] public static void ToSerializedString_FromSerializedString_RoundTrips(TimeZoneInfo timeZone) { string serialized = timeZone.ToSerializedString(); TimeZoneInfo deserializedTimeZone = TimeZoneInfo.FromSerializedString(serialized); Assert.Equal(timeZone, deserializedTimeZone); Assert.Equal(serialized, deserializedTimeZone.ToSerializedString()); } private static TimeZoneInfo CreateCustomLondonTimeZone() { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 1, 0, 0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end); return TimeZoneInfo.CreateCustomTimeZone("Europe/London", new TimeSpan(0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule }); } private static void VerifyConvertToUtcException<EXCTYPE>(DateTime dateTime, TimeZoneInfo sourceTimeZone) where EXCTYPE : Exception { Assert.ThrowsAny<EXCTYPE>(() => { DateTime dt = TimeZoneInfo.ConvertTimeToUtc(dateTime, sourceTimeZone); }); } private static void VerifyCustomTimeZoneException<ExceptionType>(string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName = null, TimeZoneInfo.AdjustmentRule[] adjustmentRules = null) where ExceptionType : Exception { Assert.ThrowsAny<ExceptionType>(() => { if (daylightDisplayName == null && adjustmentRules == null) { TimeZoneInfo tz = TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName); } else { TimeZoneInfo tz = TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules); } }); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class ReplayRequestEncoder { public const ushort BLOCK_LENGTH = 44; public const ushort TEMPLATE_ID = 6; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private ReplayRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ReplayRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ReplayRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ReplayRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public ReplayRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public ReplayRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public ReplayRequestEncoder RecordingId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int PositionEncodingOffset() { return 24; } public static int PositionEncodingLength() { return 8; } public static long PositionNullValue() { return -9223372036854775808L; } public static long PositionMinValue() { return -9223372036854775807L; } public static long PositionMaxValue() { return 9223372036854775807L; } public ReplayRequestEncoder Position(long value) { _buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int LengthEncodingOffset() { return 32; } public static int LengthEncodingLength() { return 8; } public static long LengthNullValue() { return -9223372036854775808L; } public static long LengthMinValue() { return -9223372036854775807L; } public static long LengthMaxValue() { return 9223372036854775807L; } public ReplayRequestEncoder Length(long value) { _buffer.PutLong(_offset + 32, value, ByteOrder.LittleEndian); return this; } public static int ReplayStreamIdEncodingOffset() { return 40; } public static int ReplayStreamIdEncodingLength() { return 4; } public static int ReplayStreamIdNullValue() { return -2147483648; } public static int ReplayStreamIdMinValue() { return -2147483647; } public static int ReplayStreamIdMaxValue() { return 2147483647; } public ReplayRequestEncoder ReplayStreamId(int value) { _buffer.PutInt(_offset + 40, value, ByteOrder.LittleEndian); return this; } public static int ReplayChannelId() { return 7; } public static string ReplayChannelCharacterEncoding() { return "US-ASCII"; } public static string ReplayChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ReplayChannelHeaderLength() { return 4; } public ReplayRequestEncoder PutReplayChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ReplayRequestEncoder PutReplayChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ReplayRequestEncoder ReplayChannel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ReplayRequestDecoder writer = new ReplayRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
using PlayFab.Json; using PlayFab.Public; using PlayFab.SharedModels; using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; namespace PlayFab.Internal { /// <summary> /// This is a wrapper for Http So we can better separate the functionaity of Http Requests delegated to WWW or HttpWebRequest /// </summary> public class PlayFabHttp : SingletonMonoBehaviour<PlayFabHttp> { private static List<CallRequestContainer> _apiCallQueue = new List<CallRequestContainer>(); // Starts initialized, and is nulled when it's flushed public delegate void ApiProcessingEvent<in TEventArgs>(TEventArgs e); public delegate void ApiProcessErrorEvent(PlayFabRequestCommon request, PlayFabError error); public static event ApiProcessingEvent<ApiProcessingEventArgs> ApiProcessingEventHandler; public static event ApiProcessErrorEvent ApiProcessingErrorEventHandler; public static readonly Dictionary<string, string> GlobalHeaderInjection = new Dictionary<string, string>(); #if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API private static IPlayFabSignalR _internalSignalR; #endif private static IPlayFabLogger _logger; #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API private static IScreenTimeTracker screenTimeTracker = new ScreenTimeTracker(); private const float delayBetweenBatches = 5.0f; #endif #if PLAYFAB_REQUEST_TIMING public struct RequestTiming { public DateTime StartTimeUtc; public string ApiEndpoint; public int WorkerRequestMs; public int MainThreadRequestMs; } public delegate void ApiRequestTimingEvent(RequestTiming time); public static event ApiRequestTimingEvent ApiRequestTimingEventHandler; #endif /// <summary> /// Return the number of api calls that are waiting for results from the server /// </summary> /// <returns></returns> public static int GetPendingMessages() { var transport = PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport); return transport.IsInitialized ? transport.GetPendingMessages() : 0; } /// <summary> /// Optional redirect to allow mocking of transport calls, or use a custom transport utility /// </summary> [Obsolete("This method is deprecated, please use PlayFab.PluginManager.SetPlugin(..) instead.", false)] public static void SetHttp<THttpObject>(THttpObject httpObj) where THttpObject : ITransportPlugin { PluginManager.SetPlugin(httpObj, PluginContract.PlayFab_Transport); } /// <summary> /// Optional redirect to allow mocking of AuthKey /// </summary> /// <param name="authKey"></param> [Obsolete("This method is deprecated, please use PlayFab.IPlayFabTransportPlugin.AuthKey property instead.", false)] public static void SetAuthKey(string authKey) { PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport).AuthKey = authKey; } /// <summary> /// This initializes the GameObject and ensures it is in the scene. /// </summary> public static void InitializeHttp() { if (string.IsNullOrEmpty(PlayFabSettings.TitleId)) throw new PlayFabException(PlayFabExceptionCode.TitleNotSet, "You must set PlayFabSettings.TitleId before making API Calls."); var transport = PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport); if (transport.IsInitialized) return; Application.runInBackground = true; // Http requests respond even if you lose focus transport.Initialize(); CreateInstance(); // Invoke the SingletonMonoBehaviour } /// <summary> /// This initializes the GameObject and ensures it is in the scene. /// </summary> public static void InitializeLogger(IPlayFabLogger setLogger = null) { if (_logger != null) throw new InvalidOperationException("Once initialized, the logger cannot be reset."); if (setLogger == null) setLogger = new PlayFabLogger(); _logger = setLogger; } #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API /// <summary> /// This initializes ScreenTimeTracker object and notifying it to start sending info. /// </summary> /// <param name="playFabUserId">Result of the user's login, represent user ID</param> public static void InitializeScreenTimeTracker(string entityId, string entityType, string playFabUserId) { screenTimeTracker.ClientSessionStart(entityId, entityType, playFabUserId); instance.StartCoroutine(SendScreenTimeEvents(delayBetweenBatches)); } /// <summary> /// This function will send Screen Time events on a periodic basis. /// </summary> /// <param name="secondsBetweenBatches">Delay between batches, in seconds</param> private static IEnumerator SendScreenTimeEvents(float secondsBetweenBatches) { WaitForSeconds delay = new WaitForSeconds(secondsBetweenBatches); while (!PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.Send(); yield return delay; } } #endif #if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API public static void InitializeSignalR(string baseUrl, string hubName, Action onConnected, Action<string>onReceived, Action onReconnected, Action onDisconnected, Action<Exception> onError) { CreateInstance(); if (_internalSignalR != null) return; _internalSignalR = new PlayFabSignalR (onConnected); _internalSignalR.OnReceived += onReceived; _internalSignalR.OnReconnected += onReconnected; _internalSignalR.OnDisconnected += onDisconnected; _internalSignalR.OnError += onError; _internalSignalR.Start(baseUrl, hubName); } public static void SubscribeSignalR(string onInvoked, Action<object[]> callbacks) { _internalSignalR.Subscribe(onInvoked, callbacks); } public static void InvokeSignalR(string methodName, Action callback, params object[] args) { _internalSignalR.Invoke(methodName, callback, args); } public static void StopSignalR() { _internalSignalR.Stop(); } #endif public static void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback) { InitializeHttp(); PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport).SimpleGetCall(fullUrl, successCallback, errorCallback); } public static void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { InitializeHttp(); PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport).SimplePutCall(fullUrl, payload, successCallback, errorCallback); } public static void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) { InitializeHttp(); PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport).SimplePostCall(fullUrl, payload, successCallback, errorCallback); } /// <summary> /// Internal method for Make API Calls /// </summary> protected internal static void MakeApiCall<TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action<TResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null, bool allowQueueing = false) where TResult : PlayFabResultCommon { InitializeHttp(); SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre); var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); var reqContainer = new CallRequestContainer { ApiEndpoint = apiEndpoint, FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint, PlayFabSettings.RequestGetParams), CustomData = customData, Payload = Encoding.UTF8.GetBytes(serializer.SerializeObject(request)), ApiRequest = request, ErrorCallback = errorCallback, RequestHeaders = extraHeaders ?? new Dictionary<string, string>() // Use any headers provided by the customer }; // Append any additional headers foreach (var pair in GlobalHeaderInjection) if (!reqContainer.RequestHeaders.ContainsKey(pair.Key)) reqContainer.RequestHeaders[pair.Key] = pair.Value; #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.StartTimeUtc = DateTime.UtcNow; reqContainer.Timing.ApiEndpoint = apiEndpoint; #endif // Add PlayFab Headers var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true"; // Makes processing PlayFab errors a little easier reqContainer.RequestHeaders["X-PlayFabSDK"] = PlayFabSettings.VersionString; // Tell PlayFab which SDK this is switch (authType) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API || UNITY_EDITOR case AuthType.DevSecretKey: reqContainer.RequestHeaders["X-SecretKey"] = PlayFabSettings.DeveloperSecretKey; break; #endif case AuthType.LoginSession: reqContainer.RequestHeaders["X-Authorization"] = transport.AuthKey; break; case AuthType.EntityToken: reqContainer.RequestHeaders["X-EntityToken"] = transport.EntityToken; break; } // These closures preserve the TResult generic information in a way that's safe for all the devices reqContainer.DeserializeResultJson = () => { reqContainer.ApiResult = serializer.DeserializeObject<TResult>(reqContainer.JsonResponse); }; reqContainer.InvokeSuccessCallback = () => { if (resultCallback != null) { resultCallback((TResult)reqContainer.ApiResult); } }; if (allowQueueing && _apiCallQueue != null) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) if (_apiCallQueue[i].ApiEndpoint == apiEndpoint) _apiCallQueue.RemoveAt(i); _apiCallQueue.Add(reqContainer); } else { transport.MakeApiCall(reqContainer); } } /// <summary> /// Internal code shared by IPlayFabHTTP implementations /// </summary> internal void OnPlayFabApiResult(PlayFabResultCommon result) { #if !DISABLE_PLAYFABENTITY_API var entRes = result as AuthenticationModels.GetEntityTokenResponse; if (entRes != null) { var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); transport.EntityToken = entRes.EntityToken; } #endif #if !DISABLE_PLAYFABCLIENT_API var logRes = result as ClientModels.LoginResult; var regRes = result as ClientModels.RegisterPlayFabUserResult; if (logRes != null) { var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); transport.AuthKey = logRes.SessionTicket; if (logRes.EntityToken != null) transport.EntityToken = logRes.EntityToken.EntityToken; } else if (regRes != null) { var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); transport.AuthKey = regRes.SessionTicket; if (regRes.EntityToken != null) transport.EntityToken = regRes.EntityToken.EntityToken; } #endif } /// <summary> /// MonoBehaviour OnEnable Method /// </summary> private void OnEnable() { if (_logger != null) { _logger.OnEnable(); } #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API if ((screenTimeTracker != null) && !PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.OnEnable(); } #endif } /// <summary> /// MonoBehaviour OnDisable /// </summary> private void OnDisable() { if (_logger != null) { _logger.OnDisable(); } #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API if ((screenTimeTracker != null) && !PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.OnDisable(); } #endif } /// <summary> /// MonoBehaviour OnDestroy /// </summary> private void OnDestroy() { var transport = PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport); if (transport.IsInitialized) { transport.OnDestroy(); } #if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API if (_internalSignalR != null) { _internalSignalR.Stop(); } #endif if (_logger != null) { _logger.OnDestroy(); } #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API if ((screenTimeTracker != null) && !PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.OnDestroy(); } #endif } /// <summary> /// MonoBehaviour OnApplicationFocus /// </summary> public void OnApplicationFocus(bool isFocused) { #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API if ((screenTimeTracker != null) && !PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.OnApplicationFocus(isFocused); } #endif } /// <summary> /// MonoBehaviour OnApplicationQuit /// </summary> public void OnApplicationQuit() { #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API if ((screenTimeTracker != null) && !PlayFabSettings.DisableFocusTimeCollection) { screenTimeTracker.OnApplicationQuit(); } #endif } /// <summary> /// MonoBehaviour Update /// </summary> private void Update() { var transport = PluginManager.GetPlugin<ITransportPlugin>(PluginContract.PlayFab_Transport); if (transport.IsInitialized) { if (_apiCallQueue != null) { foreach (var eachRequest in _apiCallQueue) transport.MakeApiCall(eachRequest); // Flush the queue _apiCallQueue = null; // null this after it's flushed } transport.Update(); } #if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API if (_internalSignalR != null) { _internalSignalR.Update(); } #endif } #region Helpers public static bool IsClientLoggedIn() { var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); return transport.IsInitialized && !string.IsNullOrEmpty(transport.AuthKey); } public static void ForgetAllCredentials() { var transport = PluginManager.GetPlugin<IPlayFabTransportPlugin>(PluginContract.PlayFab_Transport); if (transport.IsInitialized) { transport.AuthKey = null; transport.EntityToken = null; } } protected internal static PlayFabError GeneratePlayFabError(string apiEndpoint, string json, object customData) { JsonObject errorDict = null; Dictionary<string, List<string>> errorDetails = null; var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); try { // Deserialize the error errorDict = serializer.DeserializeObject<JsonObject>(json); } catch (Exception) { /* Unusual, but shouldn't actually matter */ } try { if (errorDict != null && errorDict.ContainsKey("errorDetails")) errorDetails = serializer.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString()); } catch (Exception) { /* Unusual, but shouldn't actually matter */ } return new PlayFabError { ApiEndpoint = apiEndpoint, HttpCode = errorDict != null && errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400, HttpStatus = errorDict != null && errorDict.ContainsKey("status") ? (string)errorDict["status"] : "BadRequest", Error = errorDict != null && errorDict.ContainsKey("errorCode") ? (PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"]) : PlayFabErrorCode.ServiceUnavailable, ErrorMessage = errorDict != null && errorDict.ContainsKey("errorMessage") ? (string)errorDict["errorMessage"] : json, ErrorDetails = errorDetails, CustomData = customData }; } protected internal static void SendErrorEvent(PlayFabRequestCommon request, PlayFabError error) { if (ApiProcessingErrorEventHandler == null) return; try { ApiProcessingErrorEventHandler(request, error); } catch (Exception e) { Debug.LogException(e); } } protected internal static void SendEvent(string apiEndpoint, PlayFabRequestCommon request, PlayFabResultCommon result, ApiProcessingEventType eventType) { if (ApiProcessingEventHandler == null) return; try { ApiProcessingEventHandler(new ApiProcessingEventArgs { ApiEndpoint = apiEndpoint, EventType = eventType, Request = request, Result = result }); } catch (Exception e) { Debug.LogException(e); } } protected internal static void ClearAllEvents() { ApiProcessingEventHandler = null; ApiProcessingErrorEventHandler = null; } #if PLAYFAB_REQUEST_TIMING protected internal static void SendRequestTiming(RequestTiming rt) { if (ApiRequestTimingEventHandler != null) { ApiRequestTimingEventHandler(rt); } } #endif #endregion } #region Event Classes public enum ApiProcessingEventType { Pre, Post } public class ApiProcessingEventArgs { public string ApiEndpoint; public ApiProcessingEventType EventType; public PlayFabRequestCommon Request; public PlayFabResultCommon Result; public TRequest GetRequest<TRequest>() where TRequest : PlayFabRequestCommon { return Request as TRequest; } } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Handlers.Tls { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Net.Security; using System.Runtime.ExceptionServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Common.Concurrency; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public sealed class TlsHandler : ByteToMessageDecoder { readonly TlsSettings settings; const int FallbackReadBufferSize = 256; const int UnencryptedWriteBatchSize = 14 * 1024; static readonly Exception ChannelClosedException = new IOException("Channel is closed"); static readonly Action<Task, object> HandshakeCompletionCallback = new Action<Task, object>(HandleHandshakeCompleted); readonly SslStream sslStream; readonly MediationStream mediationStream; readonly TaskCompletionSource closeFuture; TlsHandlerState state; int packetLength; volatile IChannelHandlerContext capturedContext; BatchingPendingWriteQueue pendingUnencryptedWrites; Task lastContextWriteTask; bool firedChannelRead; IByteBuffer pendingSslStreamReadBuffer; Task<int> pendingSslStreamReadFuture; public TlsHandler(TlsSettings settings) : this(stream => new SslStream(stream, true), settings) { } public TlsHandler(Func<Stream, SslStream> sslStreamFactory, TlsSettings settings) { Contract.Requires(sslStreamFactory != null); Contract.Requires(settings != null); this.settings = settings; this.closeFuture = new TaskCompletionSource(); this.mediationStream = new MediationStream(this); this.sslStream = sslStreamFactory(this.mediationStream); } public static TlsHandler Client(string targetHost) => new TlsHandler(new ClientTlsSettings(targetHost)); public static TlsHandler Client(string targetHost, X509Certificate clientCertificate) => new TlsHandler(new ClientTlsSettings(targetHost, new List<X509Certificate>{ clientCertificate })); public static TlsHandler Server(X509Certificate certificate) => new TlsHandler(new ServerTlsSettings(certificate)); public X509Certificate LocalCertificate => this.sslStream.LocalCertificate; public X509Certificate RemoteCertificate => this.sslStream.RemoteCertificate; bool IsServer => this.settings is ServerTlsSettings; public void Dispose() => this.sslStream?.Dispose(); public override void ChannelActive(IChannelHandlerContext context) { base.ChannelActive(context); if (!this.IsServer) { this.EnsureAuthenticated(); } } public override void ChannelInactive(IChannelHandlerContext context) { // Make sure to release SslStream, // and notify the handshake future if the connection has been closed during handshake. this.HandleFailure(ChannelClosedException); base.ChannelInactive(context); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { if (this.IgnoreException(exception)) { // Close the connection explicitly just in case the transport // did not close the connection automatically. if (context.Channel.Active) { context.CloseAsync(); } } else { base.ExceptionCaught(context, exception); } } bool IgnoreException(Exception t) { if (t is ObjectDisposedException && this.closeFuture.Task.IsCompleted) { return true; } return false; } static void HandleHandshakeCompleted(Task task, object state) { var self = (TlsHandler)state; switch (task.Status) { case TaskStatus.RanToCompletion: { TlsHandlerState oldState = self.state; Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)); self.state = (oldState | TlsHandlerState.Authenticated) & ~(TlsHandlerState.Authenticating | TlsHandlerState.FlushedBeforeHandshake); self.capturedContext.FireUserEventTriggered(TlsHandshakeCompletionEvent.Success); if (oldState.Has(TlsHandlerState.ReadRequestedBeforeAuthenticated) && !self.capturedContext.Channel.Configuration.AutoRead) { self.capturedContext.Read(); } if (oldState.Has(TlsHandlerState.FlushedBeforeHandshake)) { self.Wrap(self.capturedContext); self.capturedContext.Flush(); } break; } case TaskStatus.Canceled: case TaskStatus.Faulted: { // ReSharper disable once AssignNullToNotNullAttribute -- task.Exception will be present as task is faulted TlsHandlerState oldState = self.state; Contract.Assert(!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)); self.state = (oldState | TlsHandlerState.FailedAuthentication) & ~TlsHandlerState.Authenticating; self.HandleFailure(task.Exception); break; } default: throw new ArgumentOutOfRangeException(nameof(task), "Unexpected task status: " + task.Status); } } public override void HandlerAdded(IChannelHandlerContext context) { base.HandlerAdded(context); this.capturedContext = context; this.pendingUnencryptedWrites = new BatchingPendingWriteQueue(context, UnencryptedWriteBatchSize); if (context.Channel.Active && !this.IsServer) { // todo: support delayed initialization on an existing/active channel if in client mode this.EnsureAuthenticated(); } } protected override void HandlerRemovedInternal(IChannelHandlerContext context) { if (!this.pendingUnencryptedWrites.IsEmpty) { // Check if queue is not empty first because create a new ChannelException is expensive this.pendingUnencryptedWrites.RemoveAndFailAll(new ChannelException("Write has failed due to TlsHandler being removed from channel pipeline.")); } } protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output) { int startOffset = input.ReaderIndex; int endOffset = input.WriterIndex; int offset = startOffset; int totalLength = 0; List<int> packetLengths; // if we calculated the length of the current SSL record before, use that information. if (this.packetLength > 0) { if (endOffset - startOffset < this.packetLength) { // input does not contain a single complete SSL record return; } else { packetLengths = new List<int>(4); packetLengths.Add(this.packetLength); offset += this.packetLength; totalLength = this.packetLength; this.packetLength = 0; } } else { packetLengths = new List<int>(4); } bool nonSslRecord = false; while (totalLength < TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { int readableBytes = endOffset - offset; if (readableBytes < TlsUtils.SSL_RECORD_HEADER_LENGTH) { break; } int encryptedPacketLength = TlsUtils.GetEncryptedPacketLength(input, offset); if (encryptedPacketLength == -1) { nonSslRecord = true; break; } Contract.Assert(encryptedPacketLength > 0); if (encryptedPacketLength > readableBytes) { // wait until the whole packet can be read this.packetLength = encryptedPacketLength; break; } int newTotalLength = totalLength + encryptedPacketLength; if (newTotalLength > TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // 1. call unwrap with packet boundaries - call SslStream.ReadAsync only once. // 2. once we're through all the whole packets, switch to reading out using fallback sized buffer // We have a whole packet. // Increment the offset to handle the next packet. packetLengths.Add(encryptedPacketLength); offset += encryptedPacketLength; totalLength = newTotalLength; } if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 input.SkipBytes(totalLength); this.Unwrap(context, input, startOffset, totalLength, packetLengths, output); if (!this.firedChannelRead) { // Check first if firedChannelRead is not set yet as it may have been set in a // previous decode(...) call. this.firedChannelRead = output.Count > 0; } } if (nonSslRecord) { // Not an SSL/TLS packet var ex = new NotSslRecordException( "not an SSL/TLS record: " + ByteBufferUtil.HexDump(input)); input.SkipBytes(input.ReadableBytes); context.FireExceptionCaught(ex); this.HandleFailure(ex); } } public override void ChannelReadComplete(IChannelHandlerContext ctx) { // Discard bytes of the cumulation buffer if needed. this.DiscardSomeReadBytes(); this.ReadIfNeeded(ctx); this.firedChannelRead = false; ctx.FireChannelReadComplete(); } void ReadIfNeeded(IChannelHandlerContext ctx) { // if handshake is not finished yet, we need more data if (!ctx.Channel.Configuration.AutoRead && (!this.firedChannelRead || !this.state.HasAny(TlsHandlerState.AuthenticationCompleted))) { // No auto-read used and no message was passed through the ChannelPipeline or the handshake was not completed // yet, which means we need to trigger the read to ensure we will not stall ctx.Read(); } } /// <summary>Unwraps inbound SSL records.</summary> void Unwrap(IChannelHandlerContext ctx, IByteBuffer packet, int offset, int length, List<int> packetLengths, List<object> output) { Contract.Requires(packetLengths.Count > 0); //bool notifyClosure = false; // todo: netty/issues/137 bool pending = false; IByteBuffer outputBuffer = null; try { ArraySegment<byte> inputIoBuffer = packet.GetIoBuffer(offset, length); this.mediationStream.SetSource(inputIoBuffer.Array, inputIoBuffer.Offset); int packetIndex = 0; while (!this.EnsureAuthenticated()) { this.mediationStream.ExpandSource(packetLengths[packetIndex]); if (++packetIndex == packetLengths.Count) { return; } } Task<int> currentReadFuture = this.pendingSslStreamReadFuture; int outputBufferLength; if (currentReadFuture != null) { // restoring context from previous read Contract.Assert(this.pendingSslStreamReadBuffer != null); outputBuffer = this.pendingSslStreamReadBuffer; outputBufferLength = outputBuffer.WritableBytes; } else { outputBufferLength = 0; } // go through packets one by one (because SslStream does not consume more than 1 packet at a time) for (; packetIndex < packetLengths.Count; packetIndex++) { int currentPacketLength = packetLengths[packetIndex]; this.mediationStream.ExpandSource(currentPacketLength); if (currentReadFuture != null) { // there was a read pending already, so we make sure we completed that first if (!currentReadFuture.IsCompleted) { // we did feed the whole current packet to SslStream yet it did not produce any result -> move to the next packet in input Contract.Assert(this.mediationStream.SourceReadableBytes == 0); continue; } int read = currentReadFuture.Result; // Now output the result of previous read and decide whether to do an extra read on the same source or move forward AddBufferToOutput(outputBuffer, read, output); currentReadFuture = null; if (this.mediationStream.SourceReadableBytes == 0) { // we just made a frame available for reading but there was already pending read so SslStream read it out to make further progress there if (read < outputBufferLength) { // SslStream returned non-full buffer and there's no more input to go through -> // typically it means SslStream is done reading current frame so we skip continue; } // we've read out `read` bytes out of current packet to fulfil previously outstanding read outputBufferLength = currentPacketLength - read; if (outputBufferLength <= 0) { // after feeding to SslStream current frame it read out more bytes than current packet size outputBufferLength = FallbackReadBufferSize; } } else { // SslStream did not get to reading current frame so it completed previous read sync // and the next read will likely read out the new frame outputBufferLength = currentPacketLength; } } else { // there was no pending read before so we estimate buffer of `currentPacketLength` bytes to be sufficient outputBufferLength = currentPacketLength; } outputBuffer = ctx.Allocator.Buffer(outputBufferLength); currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, outputBufferLength); } // read out the rest of SslStream's output (if any) at risk of going async // using FallbackReadBufferSize - buffer size we're ok to have pinned with the SslStream until it's done reading while (true) { if (currentReadFuture != null) { if (!currentReadFuture.IsCompleted) { break; } int read = currentReadFuture.Result; AddBufferToOutput(outputBuffer, read, output); } outputBuffer = ctx.Allocator.Buffer(FallbackReadBufferSize); currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, FallbackReadBufferSize); } pending = true; this.pendingSslStreamReadBuffer = outputBuffer; this.pendingSslStreamReadFuture = currentReadFuture; } catch (Exception ex) { this.HandleFailure(ex); throw; } finally { this.mediationStream.ResetSource(); if (!pending && outputBuffer != null) { if (outputBuffer.IsReadable()) { output.Add(outputBuffer); } else { outputBuffer.Release(); } } } } static void AddBufferToOutput(IByteBuffer outputBuffer, int length, List<object> output) { Contract.Assert(length > 0); output.Add(outputBuffer.SetWriterIndex(outputBuffer.WriterIndex + length)); } Task<int> ReadFromSslStreamAsync(IByteBuffer outputBuffer, int outputBufferLength) { ArraySegment<byte> outlet = outputBuffer.GetIoBuffer(outputBuffer.WriterIndex, outputBufferLength); return this.sslStream.ReadAsync(outlet.Array, outlet.Offset, outlet.Count); } public override void Read(IChannelHandlerContext context) { TlsHandlerState oldState = this.state; if (!oldState.HasAny(TlsHandlerState.AuthenticationCompleted)) { this.state = oldState | TlsHandlerState.ReadRequestedBeforeAuthenticated; } context.Read(); } bool EnsureAuthenticated() { TlsHandlerState oldState = this.state; if (!oldState.HasAny(TlsHandlerState.AuthenticationStarted)) { this.state = oldState | TlsHandlerState.Authenticating; if (this.IsServer) { var serverSettings = (ServerTlsSettings)this.settings; this.sslStream.AuthenticateAsServerAsync(serverSettings.Certificate, serverSettings.NegotiateClientCertificate, serverSettings.EnabledProtocols, serverSettings.CheckCertificateRevocation) .ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } else { var clientSettings = (ClientTlsSettings)this.settings; this.sslStream.AuthenticateAsClientAsync(clientSettings.TargetHost, clientSettings.X509CertificateCollection, clientSettings.EnabledProtocols, clientSettings.CheckCertificateRevocation) .ContinueWith(HandshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } return false; } return oldState.Has(TlsHandlerState.Authenticated); } public override Task WriteAsync(IChannelHandlerContext context, object message) { if (!(message is IByteBuffer)) { return TaskEx.FromException(new UnsupportedMessageTypeException(message, typeof(IByteBuffer))); } return this.pendingUnencryptedWrites.Add(message); } public override void Flush(IChannelHandlerContext context) { if (this.pendingUnencryptedWrites.IsEmpty) { this.pendingUnencryptedWrites.Add(Unpooled.Empty); } if (!this.EnsureAuthenticated()) { this.state |= TlsHandlerState.FlushedBeforeHandshake; return; } try { this.Wrap(context); } finally { // We may have written some parts of data before an exception was thrown so ensure we always flush. context.Flush(); } } void Wrap(IChannelHandlerContext context) { Contract.Assert(context == this.capturedContext); IByteBuffer buf = null; try { while (true) { List<object> messages = this.pendingUnencryptedWrites.Current; if (messages == null || messages.Count == 0) { break; } if (messages.Count == 1) { buf = (IByteBuffer)messages[0]; } else { buf = context.Allocator.Buffer((int)this.pendingUnencryptedWrites.CurrentSize); foreach (IByteBuffer buffer in messages) { buffer.ReadBytes(buf, buffer.ReadableBytes); buffer.Release(); } } buf.ReadBytes(this.sslStream, buf.ReadableBytes); // this leads to FinishWrap being called 0+ times buf.Release(); TaskCompletionSource promise = this.pendingUnencryptedWrites.Remove(); Task task = this.lastContextWriteTask; if (task != null) { task.LinkOutcome(promise); this.lastContextWriteTask = null; } else { promise.TryComplete(); } } } catch (Exception ex) { ReferenceCountUtil.SafeRelease(buf); this.HandleFailure(ex); throw; } } void FinishWrap(byte[] buffer, int offset, int count) { IByteBuffer output; if (count == 0) { output = Unpooled.Empty; } else { output = this.capturedContext.Allocator.Buffer(count); output.WriteBytes(buffer, offset, count); } this.lastContextWriteTask = this.capturedContext.WriteAsync(output); } public override Task CloseAsync(IChannelHandlerContext context) { this.closeFuture.TryComplete(); this.sslStream.Dispose(); return base.CloseAsync(context); } void HandleFailure(Exception cause) { // Release all resources such as internal buffers that SSLEngine // is managing. try { this.sslStream.Dispose(); } catch (Exception) { // todo: evaluate following: // only log in Debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 //string msg = ex.Message; //if (msg == null || !msg.contains("possible truncation attack")) //{ // //Logger.Debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e); //} } this.NotifyHandshakeFailure(cause); this.pendingUnencryptedWrites.RemoveAndFailAll(cause); } void NotifyHandshakeFailure(Exception cause) { if (!this.state.HasAny(TlsHandlerState.AuthenticationCompleted)) { // handshake was not completed yet => TlsHandler react to failure by closing the channel this.state = (this.state | TlsHandlerState.FailedAuthentication) & ~TlsHandlerState.Authenticating; this.capturedContext.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause)); this.CloseAsync(this.capturedContext); } } sealed class MediationStream : Stream { static readonly Action<Task, object> WriteCompleteCallback = HandleChannelWriteComplete; readonly TlsHandler owner; byte[] input; int inputStartOffset; int inputOffset; int inputLength; SynchronousAsyncResult<int> syncReadResult; TaskCompletionSource<int> readCompletionSource; AsyncCallback readCallback; ArraySegment<byte> sslOwnedBuffer; TaskCompletionSource writeCompletion; AsyncCallback writeCallback; public MediationStream(TlsHandler owner) { this.owner = owner; } public int SourceReadableBytes => this.inputLength - this.inputOffset; public void SetSource(byte[] source, int offset) { this.input = source; this.inputStartOffset = offset; this.inputOffset = 0; this.inputLength = 0; } public void ResetSource() { this.input = null; this.inputLength = 0; } public void ExpandSource(int count) { Contract.Assert(this.input != null); this.inputLength += count; TaskCompletionSource<int> promise = this.readCompletionSource; if (promise == null) { // there is no pending read operation - keep for future return; } ArraySegment<byte> sslBuffer = this.sslOwnedBuffer; int read = this.ReadFromInput(sslBuffer.Array, sslBuffer.Offset, sslBuffer.Count); promise.TrySetResult(read); this.readCallback?.Invoke(promise.Task); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (this.inputLength - this.inputOffset > 0) { // we have the bytes available upfront - write out synchronously int read = this.ReadFromInput(buffer, offset, count); return Task.FromResult(read); } // take note of buffer - we will pass bytes there once available this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count); this.readCompletionSource = new TaskCompletionSource<int>(); return this.readCompletionSource.Task; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (this.inputLength - this.inputOffset > 0) { // we have the bytes available upfront - write out synchronously int read = this.ReadFromInput(buffer, offset, count); return this.PrepareSyncReadResult(read, state); } // take note of buffer - we will pass bytes there once available this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count); this.readCompletionSource = new TaskCompletionSource<int>(state); this.readCallback = callback; return this.readCompletionSource.Task; } public override int EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult<int> syncResult = this.syncReadResult; if (ReferenceEquals(asyncResult, syncResult)) { return syncResult.Result; } Contract.Assert(!((Task<int>)asyncResult).IsCanceled); try { return ((Task<int>)asyncResult).Result; } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; // unreachable } finally { this.readCompletionSource = null; this.readCallback = null; this.sslOwnedBuffer = default(ArraySegment<byte>); } } public override void Write(byte[] buffer, int offset, int count) => this.owner.FinishWrap(buffer, offset, count); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { Task task = this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)); switch (task.Status) { case TaskStatus.RanToCompletion: // write+flush completed synchronously (and successfully) var result = new SynchronousAsyncResult<int>(); result.AsyncState = state; callback(result); return result; default: this.writeCallback = callback; var tcs = new TaskCompletionSource(state); this.writeCompletion = tcs; task.ContinueWith(WriteCompleteCallback, this, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } } static void HandleChannelWriteComplete(Task writeTask, object state) { var self = (MediationStream)state; switch (writeTask.Status) { case TaskStatus.RanToCompletion: self.writeCompletion.TryComplete(); break; case TaskStatus.Canceled: self.writeCompletion.TrySetCanceled(); break; case TaskStatus.Faulted: self.writeCompletion.TrySetException(writeTask.Exception); break; default: throw new ArgumentOutOfRangeException("Unexpected task status: " + writeTask.Status); } self.writeCallback?.Invoke(self.writeCompletion.Task); } public override void EndWrite(IAsyncResult asyncResult) { this.writeCallback = null; this.writeCompletion = null; if (asyncResult is SynchronousAsyncResult<int>) { return; } try { ((Task<int>)asyncResult).Wait(); } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } int ReadFromInput(byte[] destination, int destinationOffset, int destinationCapacity) { Contract.Assert(destination != null); byte[] source = this.input; int readableBytes = this.inputLength - this.inputOffset; int length = Math.Min(readableBytes, destinationCapacity); Buffer.BlockCopy(source, this.inputStartOffset + this.inputOffset, destination, destinationOffset, length); this.inputOffset += length; return length; } IAsyncResult PrepareSyncReadResult(int readBytes, object state) { // it is safe to reuse sync result object as it can't lead to leak (no way to attach to it via handle) SynchronousAsyncResult<int> result = this.syncReadResult ?? (this.syncReadResult = new SynchronousAsyncResult<int>()); result.Result = readBytes; result.AsyncState = state; return result; } public override void Flush() { // NOOP: called on SslStream.Close } #region plumbing public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region sync result sealed class SynchronousAsyncResult<T> : IAsyncResult { public T Result { get; set; } public bool IsCompleted => true; public WaitHandle AsyncWaitHandle { get { throw new InvalidOperationException("Cannot wait on a synchronous result."); } } public object AsyncState { get; set; } public bool CompletedSynchronously => true; } #endregion } } [Flags] enum TlsHandlerState { Authenticating = 1, Authenticated = 1 << 1, FailedAuthentication = 1 << 2, ReadRequestedBeforeAuthenticated = 1 << 3, FlushedBeforeHandshake = 1 << 4, AuthenticationStarted = Authenticating | Authenticated | FailedAuthentication, AuthenticationCompleted = Authenticated | FailedAuthentication } static class TlsHandlerStateExtensions { public static bool Has(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) == testValue; public static bool HasAny(this TlsHandlerState value, TlsHandlerState testValue) => (value & testValue) != 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static volatile StrongBox<CURLMcode> s_supportsMaxConnectionsPerServer; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private bool _useDefaultCredentials = HttpHandlerDefaults.DefaultUseDefaultCredentials; private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (NetEventSource.IsEnabled) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } // Make sure the libcurl version we're using supports the option, by setting the value on a temporary multi handle. // We do this once and cache the result. StrongBox<CURLMcode> supported = s_supportsMaxConnectionsPerServer; // benign race condition to read and set this if (supported == null) { using (Interop.Http.SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate()) { s_supportsMaxConnectionsPerServer = supported = new StrongBox<CURLMcode>( Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, value)); } } if (supported.Value != CURLMcode.CURLM_OK) { throw new PlatformNotSupportedException(CurlException.GetCurlErrorString((int)supported.Value, isMulti: true)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return _useDefaultCredentials; } set { CheckDisposedOrStarted(); _useDefaultCredentials = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, _agent, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } NetEventSource.Log.HandlerMessage( (agent?.RunningWorkerId).GetValueOrDefault(), easy?.Task.Id ?? 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. using Burrows.Configuration; using Burrows.Tests.Framework; namespace Burrows.Tests { using System; using System.Collections.Generic; using Context; using Magnum.Extensions; using Magnum.TestFramework; using Messages; using NUnit.Framework; using TestConsumers; using TextFixtures; [TestFixture] public class MessageContext_Specs : LoopbackLocalAndRemoteTestFixture { [Test] public void A_response_should_be_published_if_no_reply_address_is_specified() { var ping = new PingMessage(); var otherConsumer = new TestMessageConsumer<PongMessage>(); RemoteBus.SubscribeInstance(otherConsumer); LocalBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId); LocalBus.SubscribeInstance(consumer); var pong = new FutureMessage<PongMessage>(); RemoteBus.SubscribeHandler<PingMessage>(message => { pong.Set(new PongMessage(message.CorrelationId)); RemoteBus.Context().Respond(pong.Message); }); RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>(); LocalBus.Publish(ping); pong.IsAvailable(8.Seconds()).ShouldBeTrue("No pong generated"); consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); otherConsumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); } [Test] public void A_response_should_be_sent_directly_if_a_reply_address_is_specified() { var ping = new PingMessage(); var otherConsumer = new TestMessageConsumer<PongMessage>(); RemoteBus.SubscribeInstance(otherConsumer); var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId); LocalBus.SubscribeInstance(consumer); var pong = new FutureMessage<PongMessage>(); RemoteBus.SubscribeHandler<PingMessage>(message => { pong.Set(new PongMessage(message.CorrelationId)); RemoteBus.Context().Respond(pong.Message); }); RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>(); LocalBus.Publish(ping, context => context.SendResponseTo(LocalBus)); Assert.IsTrue(pong.IsAvailable(8.Seconds()), "No pong generated"); consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds()); otherConsumer.ShouldNotHaveReceivedMessage(pong.Message, 1.Seconds()); } [Test] public void The_destination_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().DestinationAddress); received.Set(message); }); LocalBus.Publish(new PingMessage()); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_fault_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().FaultAddress); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SendFaultTo(LocalBus)); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_response_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().ResponseAddress); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SendResponseTo(LocalBus)); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_source_address_should_pass() { var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(LocalBus.Endpoint.Address.Uri, LocalBus.Context().SourceAddress); received.Set(message); }); LocalBus.Publish(new PingMessage()); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_request_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().RequestId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetRequestId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_conversation_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().ConversationId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetConversationId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void The_correlation_id_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().CorrelationId); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetCorrelationId(id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } [Test] public void A_random_header_should_pass() { Guid id = Guid.NewGuid(); var received = new FutureMessage<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(message => { Assert.AreEqual(id.ToString(), LocalBus.Context().Headers["RequestId"]); received.Set(message); }); LocalBus.Publish(new PingMessage(), context => context.SetHeader("RequestId", id.ToString())); Assert.IsTrue(received.IsAvailable(5.Seconds()), "No message was received"); } } [TestFixture] public class When_publishing_a_message_with_no_consumers : LoopbackLocalAndRemoteTestFixture { [Test] public void The_method_should_be_called_to_notify_the_caller() { var ping = new PingMessage(); bool noConsumers = false; LocalBus.Publish(ping, x => { x.IfNoSubscribers(() => { noConsumers = true; }); }); Assert.IsTrue(noConsumers, "There should have been no consumers"); } [Test] public void The_method_should_not_carry_over_the_subsequent_calls() { var ping = new PingMessage(); int hitCount = 0; LocalBus.Publish(ping, x => x.IfNoSubscribers(() => hitCount++)); LocalBus.Publish(ping); Assert.AreEqual(1, hitCount, "There should have been no consumers"); } } [TestFixture] public class When_publishing_a_message_with_an_each_consumer_action_specified : LoopbackLocalAndRemoteTestFixture { [Test] public void The_method_should_be_called_for_each_destination_endpoint() { LocalBus.SubscribeHandler<PingMessage>(x => { }); var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(1, consumers.Count); Assert.AreEqual(LocalBus.Endpoint.Address.Uri, consumers[0]); } [Test] public void The_method_should_be_called_for_each_destination_endpoint_when_there_are_multiple() { RemoteBus.SubscribeHandler<PingMessage>(x => { }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); LocalBus.SubscribeHandler<PingMessage>(x => { }); var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(2, consumers.Count); Assert.IsTrue(consumers.Contains(LocalBus.Endpoint.Address.Uri)); Assert.IsTrue(consumers.Contains(RemoteBus.Endpoint.Address.Uri)); } [Test] public void The_method_should_not_be_called_when_there_are_no_subscribers() { var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); Assert.AreEqual(0, consumers.Count); } [Test] public void The_method_should_not_carry_over_to_the_next_call_context() { var ping = new PingMessage(); var consumers = new List<Uri>(); LocalBus.Publish(ping, x => { x.ForEachSubscriber(address => consumers.Add(address.Uri)); }); LocalBus.SubscribeHandler<PingMessage>(x => { }); LocalBus.Publish(ping); Assert.AreEqual(0, consumers.Count); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Text; namespace NET.Remoting.Channels { public class CryptoHelper { private CryptoHelper() { } public static SymmetricAlgorithm GetNewSymmetricProvider(string algorithm) { switch (algorithm.Trim().ToLower()) { case "3des": { return new TripleDESCryptoServiceProvider(); } case "rijndael": { return new RijndaelManaged(); } case "rc2": { return new RC2CryptoServiceProvider(); } case "des": { return new DESCryptoServiceProvider(); } default: { throw new ArgumentException("Provider must be '3DES', 'DES', 'RIJNDAEL', or 'RC2'.", "algorithm"); } } } public static Stream GetEncryptedStream(Stream inStream, SymmetricAlgorithm provider) { if (inStream == null) { throw new ArgumentNullException("Invalid stream.", "inStream"); } if (provider == null) { throw new ArgumentNullException("Invalid provider.", "provider"); } Stream compStream = CompressStream(inStream); MemoryStream outStream = new MemoryStream(); CryptoStream encryptStream = new CryptoStream(outStream, provider.CreateEncryptor(), CryptoStreamMode.Write); // Read the in stream in 1024 byte chunks byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = compStream.Read(buffer, 0, 1024); if (bytesRead > 0) encryptStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); encryptStream.FlushFinalBlock(); outStream.Position = 0; return outStream; } public static Stream GetDecryptedStream(Stream inStream, SymmetricAlgorithm provider) { if (inStream == null) { throw new ArgumentNullException("Invalid stream.", "inStream"); } if (provider == null) { throw new ArgumentNullException("Invalid provider.", "provider"); } CryptoStream decryptStream = new CryptoStream(inStream, provider.CreateDecryptor(), CryptoStreamMode.Read); MemoryStream outStream = new MemoryStream(); // Read the in stream in 1024 byte chunks byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = decryptStream.Read(buffer, 0, 1024); if (bytesRead > 0) outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); outStream.Flush(); Stream unCompStream = DecompressStream(outStream); unCompStream.Position = 0; return unCompStream; } public static Stream CompressStream(Stream inStream) { MemoryStream outStream = new System.IO.MemoryStream(); inStream.Position = 0; using (GZipStream compressedStream = new GZipStream(outStream, CompressionMode.Compress, true)) { // Read the in stream in 1024 byte chunks byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = inStream.Read(buffer, 0, 1024); if (bytesRead > 0) compressedStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } outStream.Seek(0, SeekOrigin.Begin); return outStream; } public static Stream DecompressStream(Stream inStream) { Stream outStream = new System.IO.MemoryStream(); inStream.Position = 0; using (GZipStream decompressedStream = new GZipStream(inStream, CompressionMode.Decompress)) { // Read the in stream in 1024 byte chunks byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = decompressedStream.Read(buffer, 0, 1024); if (bytesRead > 0) outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } outStream.Flush(); outStream.Position = 0; return outStream; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpsWorks.Model { /// <summary> /// Container for the parameters to the UpdateLayer operation. /// Updates a specified layer. /// /// /// <para> /// <b>Required Permissions</b>: To use this action, an IAM user must have a Manage permissions /// level for the stack, or an attached policy that explicitly grants permissions. For /// more information on user permissions, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html">Managing /// User Permissions</a>. /// </para> /// </summary> public partial class UpdateLayerRequest : AmazonOpsWorksRequest { private Dictionary<string, string> _attributes = new Dictionary<string, string>(); private bool? _autoAssignElasticIps; private bool? _autoAssignPublicIps; private string _customInstanceProfileArn; private string _customJson; private Recipes _customRecipes; private List<string> _customSecurityGroupIds = new List<string>(); private bool? _enableAutoHealing; private bool? _installUpdatesOnBoot; private string _layerId; private LifecycleEventConfiguration _lifecycleEventConfiguration; private string _name; private List<string> _packages = new List<string>(); private string _shortname; private bool? _useEbsOptimizedInstances; private List<VolumeConfiguration> _volumeConfigurations = new List<VolumeConfiguration>(); /// <summary> /// Gets and sets the property Attributes. /// <para> /// One or more user-defined key/value pairs to be added to the stack attributes. /// </para> /// </summary> public Dictionary<string, string> Attributes { get { return this._attributes; } set { this._attributes = value; } } // Check to see if Attributes property is set internal bool IsSetAttributes() { return this._attributes != null && this._attributes.Count > 0; } /// <summary> /// Gets and sets the property AutoAssignElasticIps. /// <para> /// Whether to automatically assign an <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html">Elastic /// IP address</a> to the layer's instances. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html">How /// to Edit a Layer</a>. /// </para> /// </summary> public bool AutoAssignElasticIps { get { return this._autoAssignElasticIps.GetValueOrDefault(); } set { this._autoAssignElasticIps = value; } } // Check to see if AutoAssignElasticIps property is set internal bool IsSetAutoAssignElasticIps() { return this._autoAssignElasticIps.HasValue; } /// <summary> /// Gets and sets the property AutoAssignPublicIps. /// <para> /// For stacks that are running in a VPC, whether to automatically assign a public IP /// address to the layer's instances. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html">How /// to Edit a Layer</a>. /// </para> /// </summary> public bool AutoAssignPublicIps { get { return this._autoAssignPublicIps.GetValueOrDefault(); } set { this._autoAssignPublicIps = value; } } // Check to see if AutoAssignPublicIps property is set internal bool IsSetAutoAssignPublicIps() { return this._autoAssignPublicIps.HasValue; } /// <summary> /// Gets and sets the property CustomInstanceProfileArn. /// <para> /// The ARN of an IAM profile to be used for all of the layer's EC2 instances. For more /// information about IAM ARNs, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using /// Identifiers</a>. /// </para> /// </summary> public string CustomInstanceProfileArn { get { return this._customInstanceProfileArn; } set { this._customInstanceProfileArn = value; } } // Check to see if CustomInstanceProfileArn property is set internal bool IsSetCustomInstanceProfileArn() { return this._customInstanceProfileArn != null; } /// <summary> /// Gets and sets the property CustomJson. /// <para> /// A JSON-formatted string containing custom stack configuration and deployment attributes /// to be installed on the layer's instances. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-json-override.html"> /// Using Custom JSON</a>. /// </para> /// </summary> public string CustomJson { get { return this._customJson; } set { this._customJson = value; } } // Check to see if CustomJson property is set internal bool IsSetCustomJson() { return this._customJson != null; } /// <summary> /// Gets and sets the property CustomRecipes. /// <para> /// A <code>LayerCustomRecipes</code> object that specifies the layer's custom recipes. /// </para> /// </summary> public Recipes CustomRecipes { get { return this._customRecipes; } set { this._customRecipes = value; } } // Check to see if CustomRecipes property is set internal bool IsSetCustomRecipes() { return this._customRecipes != null; } /// <summary> /// Gets and sets the property CustomSecurityGroupIds. /// <para> /// An array containing the layer's custom security group IDs. /// </para> /// </summary> public List<string> CustomSecurityGroupIds { get { return this._customSecurityGroupIds; } set { this._customSecurityGroupIds = value; } } // Check to see if CustomSecurityGroupIds property is set internal bool IsSetCustomSecurityGroupIds() { return this._customSecurityGroupIds != null && this._customSecurityGroupIds.Count > 0; } /// <summary> /// Gets and sets the property EnableAutoHealing. /// <para> /// Whether to disable auto healing for the layer. /// </para> /// </summary> public bool EnableAutoHealing { get { return this._enableAutoHealing.GetValueOrDefault(); } set { this._enableAutoHealing = value; } } // Check to see if EnableAutoHealing property is set internal bool IsSetEnableAutoHealing() { return this._enableAutoHealing.HasValue; } /// <summary> /// Gets and sets the property InstallUpdatesOnBoot. /// <para> /// Whether to install operating system and package updates when the instance boots. The /// default value is <code>true</code>. To control when updates are installed, set this /// value to <code>false</code>. You must then update your instances manually by using /// <a>CreateDeployment</a> to run the <code>update_dependencies</code> stack command /// or manually running <code>yum</code> (Amazon Linux) or <code>apt-get</code> (Ubuntu) /// on the instances. /// </para> /// <note> /// <para> /// We strongly recommend using the default value of <code>true</code>, to ensure that /// your instances have the latest security updates. /// </para> /// </note> /// </summary> public bool InstallUpdatesOnBoot { get { return this._installUpdatesOnBoot.GetValueOrDefault(); } set { this._installUpdatesOnBoot = value; } } // Check to see if InstallUpdatesOnBoot property is set internal bool IsSetInstallUpdatesOnBoot() { return this._installUpdatesOnBoot.HasValue; } /// <summary> /// Gets and sets the property LayerId. /// <para> /// The layer ID. /// </para> /// </summary> public string LayerId { get { return this._layerId; } set { this._layerId = value; } } // Check to see if LayerId property is set internal bool IsSetLayerId() { return this._layerId != null; } /// <summary> /// Gets and sets the property LifecycleEventConfiguration. /// <para> /// /// </para> /// </summary> public LifecycleEventConfiguration LifecycleEventConfiguration { get { return this._lifecycleEventConfiguration; } set { this._lifecycleEventConfiguration = value; } } // Check to see if LifecycleEventConfiguration property is set internal bool IsSetLifecycleEventConfiguration() { return this._lifecycleEventConfiguration != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The layer name, which is used by the console. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Packages. /// <para> /// An array of <code>Package</code> objects that describe the layer's packages. /// </para> /// </summary> public List<string> Packages { get { return this._packages; } set { this._packages = value; } } // Check to see if Packages property is set internal bool IsSetPackages() { return this._packages != null && this._packages.Count > 0; } /// <summary> /// Gets and sets the property Shortname. /// <para> /// For custom layers only, use this parameter to specify the layer's short name, which /// is used internally by AWS OpsWorksand by Chef. The short name is also used as the /// name for the directory where your app files are installed. It can have a maximum of /// 200 characters and must be in the following format: /\A[a-z0-9\-\_\.]+\Z/. /// </para> /// /// <para> /// The built-in layers' short names are defined by AWS OpsWorks. For more information, /// see the <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html">Layer /// Reference</a> /// </para> /// </summary> public string Shortname { get { return this._shortname; } set { this._shortname = value; } } // Check to see if Shortname property is set internal bool IsSetShortname() { return this._shortname != null; } /// <summary> /// Gets and sets the property UseEbsOptimizedInstances. /// <para> /// Whether to use Amazon EBS-optimized instances. /// </para> /// </summary> public bool UseEbsOptimizedInstances { get { return this._useEbsOptimizedInstances.GetValueOrDefault(); } set { this._useEbsOptimizedInstances = value; } } // Check to see if UseEbsOptimizedInstances property is set internal bool IsSetUseEbsOptimizedInstances() { return this._useEbsOptimizedInstances.HasValue; } /// <summary> /// Gets and sets the property VolumeConfigurations. /// <para> /// A <code>VolumeConfigurations</code> object that describes the layer's Amazon EBS volumes. /// </para> /// </summary> public List<VolumeConfiguration> VolumeConfigurations { get { return this._volumeConfigurations; } set { this._volumeConfigurations = value; } } // Check to see if VolumeConfigurations property is set internal bool IsSetVolumeConfigurations() { return this._volumeConfigurations != null && this._volumeConfigurations.Count > 0; } } }
using System; using CoreGraphics; using Mitten.Mobile.iOS.Views.Renderers; using Mitten.Mobile.Model; using Mitten.Mobile.Remote; using UIKit; namespace Mitten.Mobile.iOS.ViewControllers { /// <summary> /// Base class for a table cell that displays information for an entity and supports displaying a remote image. /// </summary> public abstract class UIEntityTableViewCell<TEntity> : UITableViewCell where TEntity : Entity { private static class Constants { public const int ActivitySpinnerSize = 30; public const int ActivitySpinnerLineWidth = 4; public const int MaximumImageSize = 2048; } private UIView activitySpinnerView; /// <summary> /// Initializes a new instance of the UIEntityTableViewCell class. /// </summary> /// <param name="handle">Handle.</param> protected UIEntityTableViewCell(IntPtr handle) : base(handle) { this.ActivitySpinnerColor = UIColor.White; this.ShowActivitySpinnerWhenDownloadingImage = true; } /// <summary> /// Initializes a new instance of the UIEntityTableViewCell class. /// </summary> /// <param name="style">The style for the cell.</param> /// <param name="reuseIdentifier">A reuse identifier.</param> protected UIEntityTableViewCell(UITableViewCellStyle style, string reuseIdentifier) : base(style, reuseIdentifier) { this.ActivitySpinnerColor = UIColor.White; this.ShowActivitySpinnerWhenDownloadingImage = true; } /// <summary> /// Gets whether or not the cell currently has a placeholder image. /// </summary> public bool HasPlaceHolderImage { get; private set; } /// <summary> /// Gets whether or not an image download is currently in progress. /// </summary> public bool IsImageDownloadInProgress { get; private set; } /// <summary> /// Gets whether or not the image was successfully downloaded, otherwise false if a download failed. /// </summary> public bool WasImageDownloadedSuccessfully { get; private set; } /// <summary> /// Gets whether or not this cell supports displaying an image downloaded from a remote server. /// </summary> public virtual bool IsRemoteImageSupported { get { return !string.IsNullOrWhiteSpace(this.ImageUrl); } } /// <summary> /// Gets the url for the image to display in the cell. /// </summary> public virtual string ImageUrl { get { return null; } } /// <summary> /// Gets the options for the image to display in the cell. /// </summary> public virtual ImageOptions ImageOptions { get { return new ImageOptions(Constants.MaximumImageSize, Constants.MaximumImageSize, ImageResizeMode.Default); } } /// <summary> /// Gets the entity for the current cell. /// </summary> public TEntity Entity { get; private set; } /// <summary> /// Gets or sets the color to use for the activity spinner, the default is White. /// </summary> protected UIColor ActivitySpinnerColor { get; set; } /// <summary> /// Gets or sets whether or not the acitvity spinner should be shown when downloading an image; the default is true. /// </summary> protected bool ShowActivitySpinnerWhenDownloadingImage { get; set; } /// <summary> /// Lays out the subviews. /// </summary> public override void LayoutSubviews() { base.LayoutSubviews(); if (this.activitySpinnerView != null) { this.CenterDownloadProgressIndicator(); } } /// <summary> /// Initializes the current cell. /// </summary> /// <param name="entity">An entity to bind to.</param> public void Initialize(TEntity entity) { this.Entity = entity; this.Initialize(); this.ResetDownloadProgress(); if (this.IsRemoteImageSupported) { UIImageView imageView = this.GetImageView(); imageView.Image = null; this.HasPlaceHolderImage = true; } } /// <summary> /// Sets the specified image for the cell. /// </summary> /// <param name="image">The image to set.</param> public void SetImage(UIImage image, UIViewContentMode contentMode = UIViewContentMode.ScaleAspectFill) { UIImageView imageView = this.GetImageView(); imageView.ContentMode = contentMode; imageView.Image = image; this.HasPlaceHolderImage = false; } /// <summary> /// Sets that an image download is in progress and shows a progress indicator. /// </summary> public void SetImageDownloadInProgress() { if (this.IsImageDownloadInProgress) { throw new InvalidOperationException("Image download already in progress."); } if (this.ShowActivitySpinnerWhenDownloadingImage) { this.activitySpinnerView = new UIView(); this.GetImageView().AddSubview(activitySpinnerView); this.CenterDownloadProgressIndicator(); ActivitySpinnerRenderer activitySpinnerRenderer = new ActivitySpinnerRenderer(activitySpinnerView, this.ActivitySpinnerColor, Constants.ActivitySpinnerLineWidth); activitySpinnerRenderer.RenderToViewWithAnimation(); } this.IsImageDownloadInProgress = true; } /// <summary> /// Signals that the image download has completed. /// </summary> /// <param name="wasSuccessful">True if the image was downloaded successfully, otherwise the download completed with a failure.</param> public void MarkImageDownloadComplete(bool wasSuccessful) { this.ResetDownloadProgress(); this.WasImageDownloadedSuccessfully = wasSuccessful; } /// <summary> /// Gets the image view for the cell. /// </summary> /// <returns>The image view.</returns> public virtual UIImageView GetImageView() { if (this.IsRemoteImageSupported) { throw new InvalidOperationException("Subclasses must override the GetImageView method."); } throw new NotSupportedException("Images for this cell are not supported."); } /// <summary> /// Initializes the cell. /// </summary> protected abstract void Initialize(); private void ResetDownloadProgress() { if (this.IsImageDownloadInProgress && this.activitySpinnerView != null) { this.activitySpinnerView.RemoveFromSuperview(); this.activitySpinnerView = null; this.IsImageDownloadInProgress = false; } } private void CenterDownloadProgressIndicator() { UIView superView = this.activitySpinnerView.Superview; superView.LayoutIfNeeded(); this.activitySpinnerView.Frame = new CGRect( (superView.Frame.Width / 2 - Constants.ActivitySpinnerSize / 2), (superView.Frame.Height / 2 - Constants.ActivitySpinnerSize / 2), Constants.ActivitySpinnerSize, Constants.ActivitySpinnerSize); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type EventInstancesCollectionRequest. /// </summary> public partial class EventInstancesCollectionRequest : BaseRequest, IEventInstancesCollectionRequest { /// <summary> /// Constructs a new EventInstancesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public EventInstancesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Event to the collection via POST. /// </summary> /// <param name="instancesEvent">The Event to add.</param> /// <returns>The created Event.</returns> public System.Threading.Tasks.Task<Event> AddAsync(Event instancesEvent) { return this.AddAsync(instancesEvent, CancellationToken.None); } /// <summary> /// Adds the specified Event to the collection via POST. /// </summary> /// <param name="instancesEvent">The Event to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Event.</returns> public System.Threading.Tasks.Task<Event> AddAsync(Event instancesEvent, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Event>(instancesEvent, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IEventInstancesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IEventInstancesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<EventInstancesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Expand(Expression<Func<Event, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Select(Expression<Func<Event, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IEventInstancesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityEngine.Experimental.Rendering { public class TextureCache2D : TextureCache { private Texture2DArray m_Cache; public override void TransferToSlice(int sliceIndex, Texture texture) { var mismatch = (m_Cache.width != texture.width) || (m_Cache.height != texture.height); if (texture is Texture2D) { mismatch |= (m_Cache.format != (texture as Texture2D).format); } if (mismatch) { if (!Graphics.ConvertTexture(texture, 0, m_Cache, sliceIndex)) { Debug.LogErrorFormat(texture, "Unable to convert texture \"{0}\" to match renderloop settings ({1}x{2} {3})", texture.name, m_Cache.width, m_Cache.height, m_Cache.format); } } else { Graphics.CopyTexture(texture, 0, m_Cache, sliceIndex); } } public override Texture GetTexCache() { return m_Cache; } public bool AllocTextureArray(int numTextures, int width, int height, TextureFormat format, bool isMipMapped) { var res = AllocTextureArray(numTextures); m_NumMipLevels = GetNumMips(width, height); m_Cache = new Texture2DArray(width, height, numTextures, format, isMipMapped) { hideFlags = HideFlags.HideAndDontSave, wrapMode = TextureWrapMode.Clamp }; return res; } public void Release() { Texture.DestroyImmediate(m_Cache); // do I need this? } } public class TextureCacheCubemap : TextureCache { private CubemapArray m_Cache; // the member variables below are only in use when TextureCache.supportsCubemapArrayTextures is false private Texture2DArray m_CacheNoCubeArray; private RenderTexture[] m_StagingRTs; private int m_NumPanoMipLevels; private Material m_CubeBlitMaterial; private int m_CubeMipLevelPropName; private int m_cubeSrcTexPropName; public override void TransferToSlice(int sliceIndex, Texture texture) { if (!TextureCache.supportsCubemapArrayTextures) TransferToPanoCache(sliceIndex, texture); else { var mismatch = (m_Cache.width != texture.width) || (m_Cache.height != texture.height); if (texture is Cubemap) { mismatch |= (m_Cache.format != (texture as Cubemap).format); } if (mismatch) { bool failed = false; for (int f = 0; f < 6; f++) { if (!Graphics.ConvertTexture(texture, f, m_Cache, 6 * sliceIndex + f)) { failed = true; break; } } if (failed) { Debug.LogErrorFormat(texture, "Unable to convert texture \"{0}\" to match renderloop settings ({1}x{2} {3})", texture.name, m_Cache.width, m_Cache.height, m_Cache.format); } } else { for (int f = 0; f < 6; f++) Graphics.CopyTexture(texture, f, m_Cache, 6 * sliceIndex + f); } } } public override Texture GetTexCache() { return !TextureCache.supportsCubemapArrayTextures ? (Texture)m_CacheNoCubeArray : m_Cache; } public bool AllocTextureArray(int numCubeMaps, int width, TextureFormat format, bool isMipMapped) { var res = AllocTextureArray(numCubeMaps); m_NumMipLevels = GetNumMips(width, width); // will calculate same way whether we have cube array or not if (!TextureCache.supportsCubemapArrayTextures) { if (!m_CubeBlitMaterial) m_CubeBlitMaterial = new Material(Shader.Find("Hidden/CubeToPano")); int panoWidthTop = 4 * width; int panoHeightTop = 2 * width; // create panorama 2D array. Hardcoding the render target for now. No convenient way atm to // map from TextureFormat to RenderTextureFormat and don't want to deal with sRGB issues for now. m_CacheNoCubeArray = new Texture2DArray(panoWidthTop, panoHeightTop, numCubeMaps, TextureFormat.RGBAHalf, isMipMapped) { hideFlags = HideFlags.HideAndDontSave, wrapMode = TextureWrapMode.Repeat, wrapModeV = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear, anisoLevel = 0 }; m_NumPanoMipLevels = isMipMapped ? GetNumMips(panoWidthTop, panoHeightTop) : 1; m_StagingRTs = new RenderTexture[m_NumPanoMipLevels]; for (int m = 0; m < m_NumPanoMipLevels; m++) { m_StagingRTs[m] = new RenderTexture(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), 0, RenderTextureFormat.ARGBHalf); } if (m_CubeBlitMaterial) { m_CubeMipLevelPropName = Shader.PropertyToID("_cubeMipLvl"); m_cubeSrcTexPropName = Shader.PropertyToID("_srcCubeTexture"); } } else { m_Cache = new CubemapArray(width, numCubeMaps, format, isMipMapped) { hideFlags = HideFlags.HideAndDontSave, wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear, anisoLevel = 0 // It is important to set 0 here, else unity force anisotropy filtering }; } return res; } public void Release() { if (m_CacheNoCubeArray) { Texture.DestroyImmediate(m_CacheNoCubeArray); for (int m = 0; m < m_NumPanoMipLevels; m++) { m_StagingRTs[m].Release(); } m_StagingRTs = null; if (m_CubeBlitMaterial) Material.DestroyImmediate(m_CubeBlitMaterial); } if (m_Cache) Texture.DestroyImmediate(m_Cache); } private void TransferToPanoCache(int sliceIndex, Texture texture) { m_CubeBlitMaterial.SetTexture(m_cubeSrcTexPropName, texture); for (int m = 0; m < m_NumPanoMipLevels; m++) { m_CubeBlitMaterial.SetInt(m_CubeMipLevelPropName, Mathf.Min(m_NumMipLevels - 1, m)); Graphics.SetRenderTarget(m_StagingRTs[m]); Graphics.Blit(null, m_CubeBlitMaterial, 0); } for (int m = 0; m < m_NumPanoMipLevels; m++) Graphics.CopyTexture(m_StagingRTs[m], 0, 0, m_CacheNoCubeArray, sliceIndex, m); } } public abstract class TextureCache { protected int m_NumMipLevels; static int s_GlobalTextureCacheVersion = 0; int m_TextureCacheVersion = 0; #if UNITY_EDITOR internal class AssetReloader : UnityEditor.AssetPostprocessor { void OnPostprocessTexture(Texture texture) { s_GlobalTextureCacheVersion++; } } #endif public static bool isMobileBuildTarget { get { #if UNITY_EDITOR switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.iOS: case BuildTarget.Android: case BuildTarget.Tizen: case BuildTarget.WSAPlayer: // Note: We return true on purpose even if Windows Store Apps are running on Desktop. return true; default: return false; } #else return Application.isMobilePlatform; #endif } } public static TextureFormat GetPreferredHdrCompressedTextureFormat { get { var format = TextureFormat.RGBAHalf; var probeFormat = TextureFormat.BC6H; // On editor the texture is uncompressed when operating against mobile build targets #if UNITY_2017_2_OR_NEWER if (SystemInfo.SupportsTextureFormat(probeFormat) && !UnityEngine.Rendering.GraphicsSettings.HasShaderDefine(UnityEngine.Rendering.BuiltinShaderDefine.UNITY_NO_DXT5nm)) format = probeFormat; #else if (SystemInfo.SupportsTextureFormat(probeFormat) && !TextureCache.isMobileBuildTarget) format = probeFormat; #endif return format; } } public static bool supportsCubemapArrayTextures { get { #if UNITY_2017_2_OR_NEWER return !UnityEngine.Rendering.GraphicsSettings.HasShaderDefine(UnityEngine.Rendering.BuiltinShaderDefine.UNITY_NO_CUBEMAP_ARRAY); #else return (SystemInfo.supportsCubemapArrayTextures && !TextureCache.isMobileBuildTarget); #endif } } private struct SSliceEntry { public uint texId; public uint countLRU; }; private int m_NumTextures; private int[] m_SortedIdxArray; private SSliceEntry[] m_SliceArray; Dictionary<uint, int> m_LocatorInSliceArray; private static uint g_MaxFrameCount = unchecked((uint)(-1)); private static uint g_InvalidTexID = (uint)0; public int FetchSlice(Texture texture, bool forceReinject=false) { var sliceIndex = -1; if (texture == null) return sliceIndex; var texId = (uint)texture.GetInstanceID(); //assert(TexID!=g_InvalidTexID); if (texId == g_InvalidTexID) return 0; var bSwapSlice = forceReinject; var bFoundAvailOrExistingSlice = false; // search for existing copy if (m_LocatorInSliceArray.ContainsKey(texId)) { sliceIndex = m_LocatorInSliceArray[texId]; bFoundAvailOrExistingSlice = true; if(m_TextureCacheVersion!=s_GlobalTextureCacheVersion) { m_TextureCacheVersion++; Debug.Assert(m_TextureCacheVersion <= s_GlobalTextureCacheVersion); bSwapSlice = true; // force a reinject. } //assert(m_SliceArray[sliceIndex].TexID==TexID); } // If no existing copy found in the array if (!bFoundAvailOrExistingSlice) { // look for first non zero entry. Will by the least recently used entry // since the array was pre-sorted (in linear time) in NewFrame() var bFound = false; int j = 0, idx = 0; while ((!bFound) && j < m_NumTextures) { idx = m_SortedIdxArray[j]; if (m_SliceArray[idx].countLRU == 0) ++j; // if entry already snagged by a new texture in this frame then ++j else bFound = true; } if (bFound) { // if we are replacing an existing entry delete it from m_locatorInSliceArray. if (m_SliceArray[idx].texId != g_InvalidTexID) { m_LocatorInSliceArray.Remove(m_SliceArray[idx].texId); } m_LocatorInSliceArray.Add(texId, idx); m_SliceArray[idx].texId = texId; sliceIndex = idx; bFoundAvailOrExistingSlice = true; bSwapSlice = true; } } // wrap up //assert(bFoundAvailOrExistingSlice); if (bFoundAvailOrExistingSlice) { m_SliceArray[sliceIndex].countLRU = 0; // mark slice as in use this frame if (bSwapSlice) // if this was a miss { // transfer new slice to sliceIndex from source texture TransferToSlice(sliceIndex, texture); } } return sliceIndex; } public void NewFrame() { var numNonZeros = 0; var tmpBuffer = new int[m_NumTextures]; for (int i = 0; i < m_NumTextures; i++) { tmpBuffer[i] = m_SortedIdxArray[i]; // copy buffer if (m_SliceArray[m_SortedIdxArray[i]].countLRU != 0) ++numNonZeros; } int nonZerosBase = 0, zerosBase = 0; for (int i = 0; i < m_NumTextures; i++) { if (m_SliceArray[tmpBuffer[i]].countLRU == 0) { m_SortedIdxArray[zerosBase + numNonZeros] = tmpBuffer[i]; ++zerosBase; } else { m_SortedIdxArray[nonZerosBase] = tmpBuffer[i]; ++nonZerosBase; } } for (int i = 0; i < m_NumTextures; i++) { if (m_SliceArray[i].countLRU < g_MaxFrameCount) ++m_SliceArray[i].countLRU; // next frame } //for(int q=1; q<m_numTextures; q++) // assert(m_SliceArray[m_SortedIdxArray[q-1]].CountLRU>=m_SliceArray[m_SortedIdxArray[q]].CountLRU); } protected TextureCache() { m_NumTextures = 0; m_NumMipLevels = 0; } public virtual void TransferToSlice(int sliceIndex, Texture texture) { } public virtual Texture GetTexCache() { return null; } protected bool AllocTextureArray(int numTextures) { if (numTextures > 0) { m_SliceArray = new SSliceEntry[numTextures]; m_SortedIdxArray = new int[numTextures]; m_LocatorInSliceArray = new Dictionary<uint, int>(); m_NumTextures = numTextures; for (int i = 0; i < m_NumTextures; i++) { m_SliceArray[i].countLRU = g_MaxFrameCount; // never used before m_SliceArray[i].texId = g_InvalidTexID; m_SortedIdxArray[i] = i; } } //return m_SliceArray != NULL && m_SortedIdxArray != NULL && numTextures > 0; return numTextures > 0; } // should not really be used in general. Assuming lights are culled properly entries will automatically be replaced efficiently. public void RemoveEntryFromSlice(Texture texture) { var texId = (uint)texture.GetInstanceID(); //assert(TexID!=g_InvalidTexID); if (texId == g_InvalidTexID) return; // search for existing copy if (!m_LocatorInSliceArray.ContainsKey(texId)) return; var sliceIndex = m_LocatorInSliceArray[texId]; //assert(m_SliceArray[sliceIndex].TexID==TexID); // locate entry sorted by uCountLRU in m_pSortedIdxArray var foundIdxSortLRU = false; var i = 0; while ((!foundIdxSortLRU) && i < m_NumTextures) { if (m_SortedIdxArray[i] == sliceIndex) foundIdxSortLRU = true; else ++i; } if (!foundIdxSortLRU) return; // relocate sliceIndex to front of m_pSortedIdxArray since uCountLRU will be set to maximum. for (int j = 0; j < i; j++) { m_SortedIdxArray[j + 1] = m_SortedIdxArray[j]; } m_SortedIdxArray[0] = sliceIndex; // delete from m_locatorInSliceArray and m_pSliceArray. m_LocatorInSliceArray.Remove(texId); m_SliceArray[sliceIndex].countLRU = g_MaxFrameCount; // never used before m_SliceArray[sliceIndex].texId = g_InvalidTexID; } protected int GetNumMips(int width, int height) { return GetNumMips(width > height ? width : height); } protected int GetNumMips(int dim) { var uDim = (uint)dim; var iNumMips = 0; while (uDim > 0) { ++iNumMips; uDim >>= 1; } return iNumMips; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class RecoveryServicesProviderOperationsExtensions { /// <summary> /// Deletes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDeleting(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).BeginDeletingAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.BeginDeletingAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Purges a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginPurging(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).BeginPurgingAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Purges a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginPurgingAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.BeginPurgingAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Refreshes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Name of provider /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginRefreshing(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).BeginRefreshingAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Refreshes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Name of provider /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginRefreshingAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.BeginRefreshingAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Deletes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Delete(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).DeleteAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DeleteAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.DeleteAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the server object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the provider object /// </returns> public static RecoveryServicesProviderResponse Get(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).GetAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the server object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the provider object /// </returns> public static Task<RecoveryServicesProviderResponse> GetAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetDeleteStatus(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).GetDeleteStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetDeleteStatusAsync(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetPurgeStatus(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).GetPurgeStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetPurgeStatusAsync(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return operations.GetPurgeStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetRefreshStatus(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).GetRefreshStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetRefreshStatusAsync(this IRecoveryServicesProviderOperations operations, string operationStatusLink) { return operations.GetRefreshStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Get the list of all servers under the vault for given fabric. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list servers operation. /// </returns> public static RecoveryServicesProviderListResponse List(this IRecoveryServicesProviderOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).ListAsync(fabricName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all servers under the vault for given fabric. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list servers operation. /// </returns> public static Task<RecoveryServicesProviderListResponse> ListAsync(this IRecoveryServicesProviderOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(fabricName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the list of all servers under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list servers operation. /// </returns> public static RecoveryServicesProviderListResponse ListAll(this IRecoveryServicesProviderOperations operations, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).ListAllAsync(customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all servers under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list servers operation. /// </returns> public static Task<RecoveryServicesProviderListResponse> ListAllAsync(this IRecoveryServicesProviderOperations operations, CustomRequestHeaders customRequestHeaders) { return operations.ListAllAsync(customRequestHeaders, CancellationToken.None); } /// <summary> /// Purges a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Purge(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).PurgeAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Purges a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Provider Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> PurgeAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.PurgeAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Refreshes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Name of provider /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Refresh(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryServicesProviderOperations)s).RefreshAsync(fabricName, providerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Refreshes a provider /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryServicesProviderOperations. /// </param> /// <param name='fabricName'> /// Required. Name of provider's fabric /// </param> /// <param name='providerName'> /// Required. Name of provider /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> RefreshAsync(this IRecoveryServicesProviderOperations operations, string fabricName, string providerName, CustomRequestHeaders customRequestHeaders) { return operations.RefreshAsync(fabricName, providerName, customRequestHeaders, CancellationToken.None); } } }
// // JsonDeserializer.cs // // Author: // Marek Habersack <[email protected]> // // (C) 2008 Novell, Inc. http://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. // // Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser // (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources. License for the original code // follows: #region Original License /* Copyright (c) 2005 JSON.org 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 shall be used for Good, not Evil. 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 namespace Nancy.Json { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Nancy.Extensions; internal sealed class JsonDeserializer { /* Universal error constant */ const int __ = -1; const int UNIVERSAL_ERROR = __; /* Characters are mapped into these 31 character classes. This allows for a significant reduction in the size of the state transition table. */ const int C_SPACE = 0x00; /* space */ const int C_WHITE = 0x01; /* other whitespace */ const int C_LCURB = 0x02; /* { */ const int C_RCURB = 0x03; /* } */ const int C_LSQRB = 0x04; /* [ */ const int C_RSQRB = 0x05; /* ] */ const int C_COLON = 0x06; /* : */ const int C_COMMA = 0x07; /* , */ const int C_QUOTE = 0x08; /* " */ const int C_BACKS = 0x09; /* \ */ const int C_SLASH = 0x0A; /* / */ const int C_PLUS = 0x0B; /* + */ const int C_MINUS = 0x0C; /* - */ const int C_POINT = 0x0D; /* . */ const int C_ZERO = 0x0E; /* 0 */ const int C_DIGIT = 0x0F; /* 123456789 */ const int C_LOW_A = 0x10; /* a */ const int C_LOW_B = 0x11; /* b */ const int C_LOW_C = 0x12; /* c */ const int C_LOW_D = 0x13; /* d */ const int C_LOW_E = 0x14; /* e */ const int C_LOW_F = 0x15; /* f */ const int C_LOW_L = 0x16; /* l */ const int C_LOW_N = 0x17; /* n */ const int C_LOW_R = 0x18; /* r */ const int C_LOW_S = 0x19; /* s */ const int C_LOW_T = 0x1A; /* t */ const int C_LOW_U = 0x1B; /* u */ const int C_ABCDF = 0x1C; /* ABCDF */ const int C_E = 0x1D; /* E */ const int C_ETC = 0x1E; /* everything else */ const int C_STAR = 0x1F; /* * */ const int C_I = 0x20; /* I */ const int C_LOW_I = 0x21; /* i */ const int C_LOW_Y = 0x22; /* y */ const int C_N = 0x23; /* N */ /* The state codes. */ const int GO = 0x00; /* start */ const int OK = 0x01; /* ok */ const int OB = 0x02; /* object */ const int KE = 0x03; /* key */ const int CO = 0x04; /* colon */ const int VA = 0x05; /* value */ const int AR = 0x06; /* array */ const int ST = 0x07; /* string */ const int ES = 0x08; /* escape */ const int U1 = 0x09; /* u1 */ const int U2 = 0x0A; /* u2 */ const int U3 = 0x0B; /* u3 */ const int U4 = 0x0C; /* u4 */ const int MI = 0x0D; /* minus */ const int ZE = 0x0E; /* zero */ const int IN = 0x0F; /* integer */ const int FR = 0x10; /* fraction */ const int E1 = 0x11; /* e */ const int E2 = 0x12; /* ex */ const int E3 = 0x13; /* exp */ const int T1 = 0x14; /* tr */ const int T2 = 0x15; /* tru */ const int T3 = 0x16; /* true */ const int F1 = 0x17; /* fa */ const int F2 = 0x18; /* fal */ const int F3 = 0x19; /* fals */ const int F4 = 0x1A; /* false */ const int N1 = 0x1B; /* nu */ const int N2 = 0x1C; /* nul */ const int N3 = 0x1D; /* null */ const int FX = 0x1E; /* *.* *eE* */ const int IV = 0x1F; /* invalid input */ const int UK = 0x20; /* unquoted key name */ const int UI = 0x21; /* ignore during unquoted key name construction */ const int I1 = 0x22; /* In */ const int I2 = 0x23; /* Inf */ const int I3 = 0x24; /* Infi */ const int I4 = 0x25; /* Infin */ const int I5 = 0x26; /* Infini */ const int I6 = 0x27; /* Infinit */ const int I7 = 0x28; /* Infinity */ const int V1 = 0x29; /* Na */ const int V2 = 0x2A; /* NaN */ /* Actions */ const int FA = -10; /* false */ const int TR = -11; /* false */ const int NU = -12; /* null */ const int DE = -13; /* double detected by exponent e E */ const int DF = -14; /* double detected by fraction . */ const int SB = -15; /* string begin */ const int MX = -16; /* integer detected by minus */ const int ZX = -17; /* integer detected by zero */ const int IX = -18; /* integer detected by 1-9 */ const int EX = -19; /* next char is escaped */ const int UC = -20; /* Unicode character read */ const int SE = -4; /* string end */ const int AB = -5; /* array begin */ const int AE = -7; /* array end */ const int OS = -6; /* object start */ const int OE = -8; /* object end */ const int EO = -9; /* empty object */ const int CM = -3; /* comma */ const int CA = -2; /* colon action */ const int PX = -21; /* integer detected by plus */ const int KB = -22; /* unquoted key name begin */ const int UE = -23; /* unquoted key name end */ const int IF = -25; /* Infinity */ const int NN = -26; /* NaN */ enum JsonMode { NONE, ARRAY, DONE, KEY, OBJECT }; enum JsonType { NONE = 0, ARRAY_BEGIN, ARRAY_END, OBJECT_BEGIN, OBJECT_END, INTEGER, FLOAT, NULL, TRUE, FALSE, STRING, KEY, MAX }; /* This array maps the 128 ASCII characters into character classes. The remaining Unicode characters should be mapped to C_ETC. Non-whitespace control characters are errors. */ static readonly int[] ascii_class = { __, __, __, __, __, __, __, __, __, C_WHITE, C_WHITE, __, __, C_WHITE, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE, C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH, C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC, C_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC, C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC, C_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC, C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC, C_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC }; static readonly int[,] state_transition_table = { /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the text the state is OK and if the mode is MODE_DONE. white ' 1-9 ABCDF etc space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */ /*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST}, /*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__}, /*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__}, /*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__}, /*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__}, /*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__}, /*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__}, /*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__}, /*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__}, /*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__}, /*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__}, /*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__}, /*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK}, /*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__}, /*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__}, /*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__}, /*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__}, /*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__}, /*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__}, /*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN}, }; JavaScriptSerializer serializer; JavaScriptTypeResolver typeResolver; bool retainCasing; int maxJsonLength; int currentPosition; int recursionLimit; int recursionDepth; Stack <JsonMode> modes; Stack <object> returnValue; JsonType jsonType; bool escaped; int state; Stack <string> currentKey; StringBuilder buffer; char quoteChar; public JsonDeserializer (JavaScriptSerializer serializer) { this.serializer = serializer; this.maxJsonLength = serializer.MaxJsonLength; this.recursionLimit = serializer.RecursionLimit; this.typeResolver = serializer.TypeResolver; this.retainCasing = serializer.RetainCasing; this.modes = new Stack <JsonMode> (); this.currentKey = new Stack <string> (); this.returnValue = new Stack <object> (); this.state = GO; this.currentPosition = 0; this.recursionDepth = 0; } public object Deserialize (string input) { if (input == null) throw new ArgumentNullException ("input"); return Deserialize (new StringReader (input)); } public object Deserialize (TextReader input) { if (input == null) throw new ArgumentNullException ("input"); int value; buffer = new StringBuilder (); while (true) { value = input.Read (); if (value < 0) break; currentPosition++; if (currentPosition > maxJsonLength) throw new ArgumentException ("Maximum JSON input length has been exceeded."); if (!ProcessCharacter ((char) value)) throw new InvalidOperationException ("JSON syntax error."); } object topObject = PeekObject (); if (buffer.Length > 0) { object result; if (ParseBuffer (out result)) { if (topObject != null) StoreValue (result); else PushObject (result); } } if (returnValue.Count > 1) throw new InvalidOperationException ("JSON syntax error."); object ret = PopObject (); return ret; } #if DEBUG void DumpObject (string indent, object obj) { if (obj is Dictionary <string, object>) { Console.WriteLine (indent + "{"); foreach (KeyValuePair <string, object> kvp in (Dictionary <string, object>)obj) { Console.WriteLine (indent + "\t\"{0}\": ", kvp.Key); DumpObject (indent + "\t\t", kvp.Value); } Console.WriteLine (indent + "}"); } else if (obj is object[]) { Console.WriteLine (indent + "["); foreach (object o in (object[])obj) DumpObject (indent + "\t", o); Console.WriteLine (indent + "]"); } else if (obj != null) Console.WriteLine (indent + obj.ToString ()); else Console.WriteLine ("null"); } #endif void DecodeUnicodeChar () { int len = buffer.Length; if (len < 6) throw new ArgumentException ("Invalid escaped unicode character specification (" + currentPosition + ")"); int code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber); buffer.Length = len - 6; buffer.Append ((char)code); } string GetModeMessage (JsonMode expectedMode) { switch (expectedMode) { case JsonMode.ARRAY: return "Invalid array passed in, ',' or ']' expected (" + currentPosition + ")"; case JsonMode.KEY: return "Invalid object passed in, key name or ':' expected (" + currentPosition + ")"; case JsonMode.OBJECT: return "Invalid object passed in, key value expected (" + currentPosition + ")"; default: return "Invalid JSON string"; } } void PopMode (JsonMode expectedMode) { JsonMode mode = PeekMode (); if (mode != expectedMode) throw new ArgumentException (GetModeMessage (mode)); modes.Pop (); } void PushMode (JsonMode newMode) { modes.Push (newMode); } JsonMode PeekMode () { if (modes.Count == 0) return JsonMode.NONE; return modes.Peek (); } void PushObject (object o) { returnValue.Push (o); } object PopObject (bool notIfLast) { int count = returnValue.Count; if (count == 0) return null; if (notIfLast && count == 1) return null; return returnValue.Pop (); } object PopObject () { return PopObject (false); } object PeekObject () { if (returnValue.Count == 0) return null; return returnValue.Peek (); } void RemoveLastCharFromBuffer () { int len = buffer.Length; if (len == 0) return; buffer.Length = len - 1; } bool ParseBuffer (out object result) { result = null; if (jsonType == JsonType.NONE) { buffer.Length = 0; return false; } string s = buffer.ToString (); bool converted = true; int intValue; long longValue; decimal decimalValue; double doubleValue; if (jsonType != JsonType.STRING) { s = s.Trim(); } switch (jsonType) { case JsonType.INTEGER: /* MS AJAX.NET JSON parser promotes big integers to double */ if (Int32.TryParse (s, out intValue)) result = intValue; else if (Int64.TryParse (s, out longValue)) result = longValue; else if (Decimal.TryParse (s, out decimalValue)) result = decimalValue; else if (Double.TryParse (s, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.FLOAT: if (Decimal.TryParse(s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out decimalValue)) result = decimalValue; else if (Double.TryParse (s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.TRUE: if (String.Compare (s, "true", StringComparison.Ordinal) == 0) result = true; else converted = false; break; case JsonType.FALSE: if (String.Compare (s, "false", StringComparison.Ordinal) == 0) result = false; else converted = false; break; case JsonType.NULL: if (String.Compare (s, "null", StringComparison.Ordinal) != 0) converted = false; break; case JsonType.STRING: if (s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) { int tzCharIndex = s.IndexOfAny(new char[] {'+', '-'}, 7); long javaScriptTicks = Convert.ToInt64(s.Substring(6, (tzCharIndex > 0) ? tzCharIndex - 6 : s.Length - 8)); DateTime time = new DateTime((javaScriptTicks*10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc); if (tzCharIndex > 0) { time = time.ToLocalTime(); } result = time; } else result = s; break; default: throw new InvalidOperationException (String.Format ("Internal error: unexpected JsonType ({0})", jsonType)); } if (!converted) throw new ArgumentException ("Invalid JSON primitive: " + s); buffer.Length = 0; return true; } bool ProcessCharacter (char ch) { int next_class, next_state; if (ch >= 128) next_class = C_ETC; else { next_class = ascii_class [ch]; if (next_class <= UNIVERSAL_ERROR) return false; } if (escaped) { escaped = false; RemoveLastCharFromBuffer (); switch (ch) { case 'b': buffer.Append ('\b'); break; case 'f': buffer.Append ('\f'); break; case 'n': buffer.Append ('\n'); break; case 'r': buffer.Append ('\r'); break; case 't': buffer.Append ('\t'); break; case '"': case '\\': case '/': buffer.Append (ch); break; case 'u': buffer.Append ("\\u"); break; default: return false; } } else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE)) buffer.Append (ch); next_state = state_transition_table [state, next_class]; if (next_state >= 0) { state = next_state; return true; } object result; /* An action to perform */ switch (next_state) { case UC: /* Unicode character */ DecodeUnicodeChar (); state = ST; break; case EX: /* Escaped character */ escaped = true; state = ES; break; case MX: /* integer detected by minus */ jsonType = JsonType.INTEGER; state = MI; break; case PX: /* integer detected by plus */ jsonType = JsonType.INTEGER; state = MI; break; case ZX: /* integer detected by zero */ jsonType = JsonType.INTEGER; state = ZE; break; case IX: /* integer detected by 1-9 */ jsonType = JsonType.INTEGER; state = IN; break; case DE: /* floating point number detected by exponent*/ jsonType = JsonType.FLOAT; state = E1; break; case DF: /* floating point number detected by fraction */ jsonType = JsonType.FLOAT; state = FX; break; case SB: /* string begin " or ' */ buffer.Length = 0; quoteChar = ch; jsonType = JsonType.STRING; state = ST; break; case KB: /* unquoted key name begin */ jsonType = JsonType.STRING; state = UK; break; case UE: /* unquoted key name end ':' */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; buffer.Length = 0; break; case NU: /* n */ jsonType = JsonType.NULL; state = N1; break; case FA: /* f */ jsonType = JsonType.FALSE; state = F1; break; case TR: /* t */ jsonType = JsonType.TRUE; state = T1; break; case EO: /* empty } */ result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.KEY); state = OK; break; case OE: /* } */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.OBJECT); jsonType = JsonType.NONE; state = OK; break; case AE: /* ] */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); PopMode (JsonMode.ARRAY); result = PopObject (true); if (result != null) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case OS: /* { */ RemoveLastCharFromBuffer (); CreateObject (); PushMode (JsonMode.KEY); state = OB; break; case AB: /* [ */ RemoveLastCharFromBuffer (); CreateArray (); PushMode (JsonMode.ARRAY); state = AR; break; case SE: /* string end " or ' */ if (ch == quoteChar) { RemoveLastCharFromBuffer (); switch (PeekMode ()) { case JsonMode.KEY: if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; state = CO; buffer.Length = 0; break; case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone string */ jsonType = JsonType.STRING; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: string in unexpected place."); } } break; case CM: /* , */ RemoveLastCharFromBuffer (); // With MS.AJAX, a comma resets the recursion depth recursionDepth = 0; bool doStore = ParseBuffer (out result); switch (PeekMode ()) { case JsonMode.OBJECT: if (doStore) StoreValue (result); PopMode (JsonMode.OBJECT); PushMode (JsonMode.KEY); jsonType = JsonType.NONE; state = KE; break; case JsonMode.ARRAY: jsonType = JsonType.NONE; state = VA; if (doStore) StoreValue (result); break; default: throw new ArgumentException ("Syntax error: unexpected comma."); } break; case CA: /* : */ RemoveLastCharFromBuffer (); // With MS.AJAX a colon increases recursion depth if (++recursionDepth >= recursionLimit) throw new ArgumentException ("Recursion limit has been reached on parsing input."); PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; break; case IF: /* Infinity */ case NN: /* NaN */ jsonType = JsonType.FLOAT; switch (PeekMode ()) { case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone NaN/Infinity */ jsonType = JsonType.FLOAT; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: misplaced NaN/Infinity."); } buffer.Length = 0; break; default: throw new ArgumentException (GetModeMessage (PeekMode ())); } return true; } void CreateArray () { var arr = new ArrayList (); PushObject (arr); } void CreateObject () { var dict = new Dictionary <string, object> (); PushObject (dict); } void StoreKey (object o) { string key = o as string; if (key != null) key = key.Trim (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: key is null, empty or not a string."); key = retainCasing ? key : key.ToPascalCase(); currentKey.Push (key); Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary."); /* MS AJAX.NET silently overwrites existing currentKey value */ dict [key] = null; } void StoreValue (object o) { Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) { ArrayList arr = PeekObject () as ArrayList; if (arr == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary or an array."); arr.Add (o); return; } string key; if (currentKey.Count == 0) key = null; else key = currentKey.Pop (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: object is a dictionary, but no key present."); dict [key] = o; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Newtonsoft.Json.Utilities { internal static class StringUtils { public const string CarriageReturnLineFeed = "\r\n"; public const string Empty = ""; public const char CarriageReturn = '\r'; public const char LineFeed = '\n'; public const char Tab = '\t'; /// <summary> /// Determines whether the string contains white space. /// </summary> /// <param name="s">The string to test for white space.</param> /// <returns> /// <c>true</c> if the string contains white space; otherwise, <c>false</c>. /// </returns> public static bool ContainsWhiteSpace(string s) { if (s == null) throw new ArgumentNullException("s"); for (int i = 0; i < s.Length; i++) { if (char.IsWhiteSpace(s[i])) return true; } return false; } /// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="s">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool IsWhiteSpace(string s) { if (s == null) throw new ArgumentNullException("s"); if (s.Length == 0) return false; for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) return false; } return true; } /// <summary> /// Ensures the target string ends with the specified string. /// </summary> /// <param name="target">The target.</param> /// <param name="value">The value.</param> /// <returns>The target string with the value string at the end.</returns> public static string EnsureEndsWith(string target, string value) { if (target == null) throw new ArgumentNullException("target"); if (value == null) throw new ArgumentNullException("value"); if (target.Length >= value.Length) { if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) == 0) return target; string trimmedString = target.TrimEnd(null); if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) == 0) return target; } return target + value; } /// <summary> /// Determines whether the SqlString is null or empty. /// </summary> /// <param name="s">The string.</param> /// <returns> /// <c>true</c> if the SqlString is null or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty(SqlString s) { if (s.IsNull) return true; else return string.IsNullOrEmpty(s.Value); } public static bool IsNullOrEmptyOrWhiteSpace(string s) { if (string.IsNullOrEmpty(s)) return true; else if (IsWhiteSpace(s)) return true; else return false; } /// <summary> /// Perform an action if the string is not null or empty. /// </summary> /// <param name="value">The value.</param> /// <param name="action">The action to perform.</param> public static void IfNotNullOrEmpty(string value, Action<string> action) { IfNotNullOrEmpty(value, action, null); } private static void IfNotNullOrEmpty(string value, Action<string> trueAction, Action<string> falseAction) { if (!string.IsNullOrEmpty(value)) { if (trueAction != null) trueAction(value); } else { if (falseAction != null) falseAction(value); } } /// <summary> /// Indents the specified string. /// </summary> /// <param name="s">The string to indent.</param> /// <param name="indentation">The number of characters to indent by.</param> /// <returns></returns> public static string Indent(string s, int indentation) { return Indent(s, indentation, ' '); } /// <summary> /// Indents the specified string. /// </summary> /// <param name="s">The string to indent.</param> /// <param name="indentation">The number of characters to indent by.</param> /// <param name="indentChar">The indent character.</param> /// <returns></returns> public static string Indent(string s, int indentation, char indentChar) { if (s == null) throw new ArgumentNullException("s"); if (indentation <= 0) throw new ArgumentException("Must be greater than zero.", "indentation"); StringReader sr = new StringReader(s); StringWriter sw = new StringWriter(); ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) { tw.Write(new string(indentChar, indentation)); tw.Write(line); }); return sw.ToString(); } private delegate void ActionLine(TextWriter textWriter, string line); private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction) { string line; bool firstLine = true; while ((line = textReader.ReadLine()) != null) { if (!firstLine) textWriter.WriteLine(); else firstLine = false; lineAction(textWriter, line); } } /// <summary> /// Numbers the lines. /// </summary> /// <param name="s">The string to number.</param> /// <returns></returns> public static string NumberLines(string s) { if (s == null) throw new ArgumentNullException("s"); StringReader sr = new StringReader(s); StringWriter sw = new StringWriter(); int lineNumber = 1; ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) { tw.Write(lineNumber.ToString().PadLeft(4)); tw.Write(". "); tw.Write(line); lineNumber++; }); return sw.ToString(); } /// <summary> /// Nulls an empty string. /// </summary> /// <param name="s">The string.</param> /// <returns>Null if the string was null, otherwise the string unchanged.</returns> public static string NullEmptyString(string s) { return (string.IsNullOrEmpty(s)) ? null : s; } public static string ReplaceNewLines(string s, string replacement) { StringReader sr = new StringReader(s); StringBuilder sb = new StringBuilder(); bool first = true; string line; while ((line = sr.ReadLine()) != null) { if (first) first = false; else sb.Append(replacement); sb.Append(line); } return sb.ToString(); } public static string RemoveHtml(string s) { return RemoveHtmlInternal(s, null); } public static string RemoveHtml(string s, IList<string> removeTags) { if (removeTags == null) throw new ArgumentNullException("removeTags"); return RemoveHtmlInternal(s, removeTags); } private static string RemoveHtmlInternal(string s, IList<string> removeTags) { List<string> removeTagsUpper = null; if (removeTags != null) { removeTagsUpper = new List<string>(removeTags.Count); foreach (string tag in removeTags) { removeTagsUpper.Add(tag.ToUpperInvariant()); } } Regex anyTag = new Regex(@"<[/]{0,1}\s*(?<tag>\w*)\s*(?<attr>.*?=['""].*?[""'])*?\s*[/]{0,1}>", RegexOptions.Compiled); return anyTag.Replace(s, delegate(Match match) { string tag = match.Groups["tag"].Value.ToUpperInvariant(); if (removeTagsUpper == null) return string.Empty; else if (removeTagsUpper.Contains(tag)) return string.Empty; else return match.Value; }); } public static string Truncate(string s, int maximumLength) { return Truncate(s, maximumLength, "..."); } public static string Truncate(string s, int maximumLength, string suffix) { if (suffix == null) throw new ArgumentNullException("suffix"); if (maximumLength <= 0) throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength"); int subStringLength = maximumLength - suffix.Length; if (subStringLength <= 0) throw new ArgumentException("Length of suffix string is greater or equal to maximumLength"); if (s != null && s.Length > maximumLength) { string truncatedString = s.Substring(0, subStringLength); // incase the last character is a space truncatedString = truncatedString.Trim(); truncatedString += suffix; return truncatedString; } else { return s; } } public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); StringWriter sw = new StringWriter(sb); return sw; } public static int? GetLength(string value) { if (value == null) return null; else return value.Length; } public static string ToCharAsUnicode(char c) { using (StringWriter w = new StringWriter()) { WriteCharAsUnicode(w, c); return w.ToString(); } } public static void WriteCharAsUnicode(TextWriter writer, char c) { ValidationUtils.ArgumentNotNull(writer, "writer"); char h1 = MathUtils.IntToHex((c >> 12) & '\x000f'); char h2 = MathUtils.IntToHex((c >> 8) & '\x000f'); char h3 = MathUtils.IntToHex((c >> 4) & '\x000f'); char h4 = MathUtils.IntToHex(c & '\x000f'); writer.Write('\\'); writer.Write('u'); writer.Write(h1); writer.Write(h2); writer.Write(h3); writer.Write(h4); } } }
namespace EffectEditor.Controls { partial class ComponentEditor { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.componentEditTabs = new System.Windows.Forms.TabControl(); this.componentDesignTab = new System.Windows.Forms.TabPage(); this.shaderProfilePanel = new System.Windows.Forms.Panel(); this.shaderProfileSelector = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.componentAvailabilityPanel = new System.Windows.Forms.Panel(); this.pixelShaderProfileSelector = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.vertexShaderProfileSelector = new System.Windows.Forms.ComboBox(); this.vertexShaderCheckbox = new System.Windows.Forms.CheckBox(); this.label6 = new System.Windows.Forms.Label(); this.pixelShaderCheckbox = new System.Windows.Forms.CheckBox(); this.label5 = new System.Windows.Forms.Label(); this.componentNameBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.componentParameterInputs = new EffectEditor.Controls.ComponentParameterList(); this.componentParameterOutputs = new EffectEditor.Controls.ComponentParameterList(); this.componentCodeEditTab = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.componentFunctionStart = new System.Windows.Forms.RichTextBox(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.componentSelectionBox = new System.Windows.Forms.ComboBox(); this.componentSelectionLabel = new System.Windows.Forms.Label(); this.componentFunctionCode = new System.Windows.Forms.RichTextBox(); this.componentFunctionEnd = new System.Windows.Forms.RichTextBox(); this.componentEditTabs.SuspendLayout(); this.componentDesignTab.SuspendLayout(); this.shaderProfilePanel.SuspendLayout(); this.componentAvailabilityPanel.SuspendLayout(); this.componentCodeEditTab.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.SuspendLayout(); // // componentEditTabs // this.componentEditTabs.Controls.Add(this.componentDesignTab); this.componentEditTabs.Controls.Add(this.componentCodeEditTab); this.componentEditTabs.Dock = System.Windows.Forms.DockStyle.Fill; this.componentEditTabs.Location = new System.Drawing.Point(0, 0); this.componentEditTabs.Name = "componentEditTabs"; this.componentEditTabs.SelectedIndex = 0; this.componentEditTabs.Size = new System.Drawing.Size(576, 494); this.componentEditTabs.TabIndex = 5; // // componentDesignTab // this.componentDesignTab.Controls.Add(this.shaderProfilePanel); this.componentDesignTab.Controls.Add(this.componentAvailabilityPanel); this.componentDesignTab.Controls.Add(this.componentNameBox); this.componentDesignTab.Controls.Add(this.label3); this.componentDesignTab.Controls.Add(this.label2); this.componentDesignTab.Controls.Add(this.label1); this.componentDesignTab.Controls.Add(this.componentParameterInputs); this.componentDesignTab.Controls.Add(this.componentParameterOutputs); this.componentDesignTab.Location = new System.Drawing.Point(4, 22); this.componentDesignTab.Name = "componentDesignTab"; this.componentDesignTab.Padding = new System.Windows.Forms.Padding(3); this.componentDesignTab.Size = new System.Drawing.Size(568, 468); this.componentDesignTab.TabIndex = 0; this.componentDesignTab.Text = "Design"; this.componentDesignTab.UseVisualStyleBackColor = true; // // shaderProfilePanel // this.shaderProfilePanel.Controls.Add(this.shaderProfileSelector); this.shaderProfilePanel.Controls.Add(this.label7); this.shaderProfilePanel.Location = new System.Drawing.Point(0, 30); this.shaderProfilePanel.Name = "shaderProfilePanel"; this.shaderProfilePanel.Size = new System.Drawing.Size(568, 23); this.shaderProfilePanel.TabIndex = 16; this.shaderProfilePanel.Visible = false; // // shaderProfileSelector // this.shaderProfileSelector.FormattingEnabled = true; this.shaderProfileSelector.Location = new System.Drawing.Point(129, 1); this.shaderProfileSelector.Name = "shaderProfileSelector"; this.shaderProfileSelector.Size = new System.Drawing.Size(85, 21); this.shaderProfileSelector.TabIndex = 24; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(6, 4); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(117, 13); this.label7.TabIndex = 23; this.label7.Text = "Minimum Shader Profile"; // // componentAvailabilityPanel // this.componentAvailabilityPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.componentAvailabilityPanel.Controls.Add(this.pixelShaderProfileSelector); this.componentAvailabilityPanel.Controls.Add(this.label4); this.componentAvailabilityPanel.Controls.Add(this.vertexShaderProfileSelector); this.componentAvailabilityPanel.Controls.Add(this.vertexShaderCheckbox); this.componentAvailabilityPanel.Controls.Add(this.label6); this.componentAvailabilityPanel.Controls.Add(this.pixelShaderCheckbox); this.componentAvailabilityPanel.Controls.Add(this.label5); this.componentAvailabilityPanel.Location = new System.Drawing.Point(0, 30); this.componentAvailabilityPanel.Name = "componentAvailabilityPanel"; this.componentAvailabilityPanel.Size = new System.Drawing.Size(568, 45); this.componentAvailabilityPanel.TabIndex = 15; // // pixelShaderProfileSelector // this.pixelShaderProfileSelector.FormattingEnabled = true; this.pixelShaderProfileSelector.Location = new System.Drawing.Point(348, 24); this.pixelShaderProfileSelector.Name = "pixelShaderProfileSelector"; this.pixelShaderProfileSelector.Size = new System.Drawing.Size(85, 21); this.pixelShaderProfileSelector.TabIndex = 22; this.pixelShaderProfileSelector.SelectedIndexChanged += new System.EventHandler(this.pixelShaderProfileSelector_SelectedIndexChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(5, 4); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 13); this.label4.TabIndex = 17; this.label4.Text = "Availability:"; // // vertexShaderProfileSelector // this.vertexShaderProfileSelector.FormattingEnabled = true; this.vertexShaderProfileSelector.Location = new System.Drawing.Point(348, 1); this.vertexShaderProfileSelector.Name = "vertexShaderProfileSelector"; this.vertexShaderProfileSelector.Size = new System.Drawing.Size(85, 21); this.vertexShaderProfileSelector.TabIndex = 21; this.vertexShaderProfileSelector.SelectedIndexChanged += new System.EventHandler(this.vertexShaderProfileSelector_SelectedIndexChanged); // // vertexShaderCheckbox // this.vertexShaderCheckbox.AutoSize = true; this.vertexShaderCheckbox.Location = new System.Drawing.Point(95, 3); this.vertexShaderCheckbox.Name = "vertexShaderCheckbox"; this.vertexShaderCheckbox.Size = new System.Drawing.Size(93, 17); this.vertexShaderCheckbox.TabIndex = 16; this.vertexShaderCheckbox.Text = "Vertex Shader"; this.vertexShaderCheckbox.UseVisualStyleBackColor = true; this.vertexShaderCheckbox.CheckedChanged += new System.EventHandler(this.vertexShaderCheckbox_CheckedChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(225, 27); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(117, 13); this.label6.TabIndex = 20; this.label6.Text = "Minimum Shader Profile"; // // pixelShaderCheckbox // this.pixelShaderCheckbox.AutoSize = true; this.pixelShaderCheckbox.Location = new System.Drawing.Point(95, 26); this.pixelShaderCheckbox.Name = "pixelShaderCheckbox"; this.pixelShaderCheckbox.Size = new System.Drawing.Size(85, 17); this.pixelShaderCheckbox.TabIndex = 18; this.pixelShaderCheckbox.Text = "Pixel Shader"; this.pixelShaderCheckbox.UseVisualStyleBackColor = true; this.pixelShaderCheckbox.CheckedChanged += new System.EventHandler(this.pixelShaderCheckbox_CheckedChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(225, 4); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(117, 13); this.label5.TabIndex = 19; this.label5.Text = "Minimum Shader Profile"; // // componentNameBox // this.componentNameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.componentNameBox.Location = new System.Drawing.Point(47, 4); this.componentNameBox.Name = "componentNameBox"; this.componentNameBox.Size = new System.Drawing.Size(516, 20); this.componentNameBox.TabIndex = 5; this.componentNameBox.TextChanged += new System.EventHandler(this.componentNameBox_TextChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 7); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 13); this.label3.TabIndex = 4; this.label3.Text = "Name"; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(288, 78); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(44, 13); this.label2.TabIndex = 3; this.label2.Text = "Outputs"; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 78); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(36, 13); this.label1.TabIndex = 2; this.label1.Text = "Inputs"; // // componentParameterInputs // this.componentParameterInputs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.componentParameterInputs.Location = new System.Drawing.Point(6, 94); this.componentParameterInputs.Name = "componentParameterInputs"; this.componentParameterInputs.Parameters = null; this.componentParameterInputs.Semantics = null; this.componentParameterInputs.Size = new System.Drawing.Size(276, 368); this.componentParameterInputs.StorageClassEnabled = false; this.componentParameterInputs.TabIndex = 1; this.componentParameterInputs.ParametersChanged += new System.EventHandler(this.componentParameterInputs_ParametersChanged); // // componentParameterOutputs // this.componentParameterOutputs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.componentParameterOutputs.Location = new System.Drawing.Point(287, 94); this.componentParameterOutputs.Name = "componentParameterOutputs"; this.componentParameterOutputs.Parameters = null; this.componentParameterOutputs.Semantics = null; this.componentParameterOutputs.Size = new System.Drawing.Size(276, 368); this.componentParameterOutputs.StorageClassEnabled = false; this.componentParameterOutputs.TabIndex = 0; this.componentParameterOutputs.ParametersChanged += new System.EventHandler(this.componentParameterOutputs_ParametersChanged); // // componentCodeEditTab // this.componentCodeEditTab.Controls.Add(this.splitContainer1); this.componentCodeEditTab.Location = new System.Drawing.Point(4, 22); this.componentCodeEditTab.Name = "componentCodeEditTab"; this.componentCodeEditTab.Padding = new System.Windows.Forms.Padding(3); this.componentCodeEditTab.Size = new System.Drawing.Size(568, 468); this.componentCodeEditTab.TabIndex = 1; this.componentCodeEditTab.Text = "Code"; this.componentCodeEditTab.UseVisualStyleBackColor = true; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(3, 3); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.componentFunctionStart); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Size = new System.Drawing.Size(562, 462); this.splitContainer1.SplitterDistance = 74; this.splitContainer1.TabIndex = 4; // // componentFunctionStart // this.componentFunctionStart.BackColor = System.Drawing.SystemColors.Control; this.componentFunctionStart.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.componentFunctionStart.Dock = System.Windows.Forms.DockStyle.Fill; this.componentFunctionStart.Font = new System.Drawing.Font("Courier New", 9F); this.componentFunctionStart.ForeColor = System.Drawing.SystemColors.GrayText; this.componentFunctionStart.Location = new System.Drawing.Point(0, 0); this.componentFunctionStart.Name = "componentFunctionStart"; this.componentFunctionStart.ReadOnly = true; this.componentFunctionStart.Size = new System.Drawing.Size(562, 74); this.componentFunctionStart.TabIndex = 1; this.componentFunctionStart.Text = ""; this.componentFunctionStart.WordWrap = false; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.componentSelectionBox); this.splitContainer2.Panel1.Controls.Add(this.componentSelectionLabel); this.splitContainer2.Panel1.Controls.Add(this.componentFunctionCode); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.componentFunctionEnd); this.splitContainer2.Size = new System.Drawing.Size(562, 384); this.splitContainer2.SplitterDistance = 308; this.splitContainer2.TabIndex = 5; // // componentSelectionBox // this.componentSelectionBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.componentSelectionBox.FormattingEnabled = true; this.componentSelectionBox.Location = new System.Drawing.Point(102, 287); this.componentSelectionBox.Name = "componentSelectionBox"; this.componentSelectionBox.Size = new System.Drawing.Size(457, 21); this.componentSelectionBox.TabIndex = 5; this.componentSelectionBox.SelectedIndexChanged += new System.EventHandler(this.componentSelectionBox_SelectedIndexChanged); // // componentSelectionLabel // this.componentSelectionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.componentSelectionLabel.AutoSize = true; this.componentSelectionLabel.Location = new System.Drawing.Point(3, 290); this.componentSelectionLabel.Name = "componentSelectionLabel"; this.componentSelectionLabel.Size = new System.Drawing.Size(93, 13); this.componentSelectionLabel.TabIndex = 4; this.componentSelectionLabel.Text = "Insert Component:"; // // componentFunctionCode // this.componentFunctionCode.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.componentFunctionCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.componentFunctionCode.Font = new System.Drawing.Font("Courier New", 9F); this.componentFunctionCode.Location = new System.Drawing.Point(3, 0); this.componentFunctionCode.Name = "componentFunctionCode"; this.componentFunctionCode.Size = new System.Drawing.Size(556, 281); this.componentFunctionCode.TabIndex = 3; this.componentFunctionCode.Text = ""; this.componentFunctionCode.WordWrap = false; this.componentFunctionCode.TextChanged += new System.EventHandler(this.componentFunctionCode_TextChanged); // // componentFunctionEnd // this.componentFunctionEnd.BackColor = System.Drawing.SystemColors.Control; this.componentFunctionEnd.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.componentFunctionEnd.Dock = System.Windows.Forms.DockStyle.Fill; this.componentFunctionEnd.Font = new System.Drawing.Font("Courier New", 9F); this.componentFunctionEnd.ForeColor = System.Drawing.SystemColors.GrayText; this.componentFunctionEnd.Location = new System.Drawing.Point(0, 0); this.componentFunctionEnd.Name = "componentFunctionEnd"; this.componentFunctionEnd.ReadOnly = true; this.componentFunctionEnd.Size = new System.Drawing.Size(562, 72); this.componentFunctionEnd.TabIndex = 2; this.componentFunctionEnd.Text = ""; this.componentFunctionEnd.WordWrap = false; // // ComponentEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.componentEditTabs); this.Name = "ComponentEditor"; this.Size = new System.Drawing.Size(576, 494); this.componentEditTabs.ResumeLayout(false); this.componentDesignTab.ResumeLayout(false); this.componentDesignTab.PerformLayout(); this.shaderProfilePanel.ResumeLayout(false); this.shaderProfilePanel.PerformLayout(); this.componentAvailabilityPanel.ResumeLayout(false); this.componentAvailabilityPanel.PerformLayout(); this.componentCodeEditTab.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel1.PerformLayout(); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl componentEditTabs; private System.Windows.Forms.TabPage componentDesignTab; private System.Windows.Forms.Panel componentAvailabilityPanel; private System.Windows.Forms.ComboBox pixelShaderProfileSelector; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox vertexShaderProfileSelector; private System.Windows.Forms.CheckBox vertexShaderCheckbox; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox pixelShaderCheckbox; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox componentNameBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private ComponentParameterList componentParameterInputs; private ComponentParameterList componentParameterOutputs; private System.Windows.Forms.TabPage componentCodeEditTab; private System.Windows.Forms.RichTextBox componentFunctionStart; private System.Windows.Forms.RichTextBox componentFunctionEnd; private System.Windows.Forms.RichTextBox componentFunctionCode; private System.Windows.Forms.Panel shaderProfilePanel; private System.Windows.Forms.ComboBox shaderProfileSelector; private System.Windows.Forms.Label label7; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.ComboBox componentSelectionBox; private System.Windows.Forms.Label componentSelectionLabel; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Store.Services.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright 2010-2014 Google // 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 Google.OrTools.LinearSolver { using System; using System.Collections.Generic; // Patch the MPSolver class to: // - support custom versions of the array-based APIs (MakeVarArray, etc). // - customize the construction, and the OptimizationProblemType enum. // - support the natural language API. public partial class Solver { public Variable[] MakeVarArray(int count, double lb, double ub, bool integer) { Variable[] array = new Variable[count]; for (int i = 0; i < count; ++i) { array[i] = MakeVar(lb, ub, integer, ""); } return array; } public Variable[] MakeVarArray(int count, double lb, double ub, bool integer, string var_name) { Variable[] array = new Variable[count]; for (int i = 0; i < count; ++i) { array[i] = MakeVar(lb, ub, integer, var_name + i); } return array; } public Variable[,] MakeVarMatrix(int rows, int cols, double lb, double ub, bool integer) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i,j] = MakeVar(lb, ub, integer, ""); } } return matrix; } public Variable[,] MakeVarMatrix(int rows, int cols, double lb, double ub, bool integer, string name) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j +"]"; matrix[i,j] = MakeVar(lb, ub, integer, var_name); } } return matrix; } public Variable[] MakeNumVarArray(int count, double lb, double ub) { return MakeVarArray(count, lb, ub, false); } public Variable[] MakeNumVarArray(int count, double lb, double ub, string var_name) { return MakeVarArray(count, lb, ub, false, var_name); } public Variable[,] MakeNumVarMatrix(int rows, int cols, double lb, double ub) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i,j] = MakeNumVar(lb, ub, ""); } } return matrix; } public Variable[,] MakeNumVarMatrix(int rows, int cols, double lb, double ub, string name) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j +"]"; matrix[i,j] = MakeNumVar(lb, ub, var_name); } } return matrix; } public Variable[] MakeIntVarArray(int count, double lb, double ub) { return MakeVarArray(count, lb, ub, true); } public Variable[] MakeIntVarArray(int count, double lb, double ub, string var_name) { return MakeVarArray(count, lb, ub, true, var_name); } public Variable[,] MakeIntVarMatrix(int rows, int cols, double lb, double ub) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i,j] = MakeIntVar(lb, ub, ""); } } return matrix; } public Variable[,] MakeIntVarMatrix(int rows, int cols, double lb, double ub, string name) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j +"]"; matrix[i,j] = MakeIntVar(lb, ub, var_name); } } return matrix; } public Variable[] MakeBoolVarArray(int count) { return MakeVarArray(count, 0.0, 1.0, true); } public Variable[] MakeBoolVarArray(int count, string var_name) { return MakeVarArray(count, 0.0, 1.0, true, var_name); } public Variable[,] MakeBoolVarMatrix(int rows, int cols) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i,j] = MakeBoolVar(""); } } return matrix; } public Variable[,] MakeBoolVarMatrix(int rows, int cols, string name) { Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j +"]"; matrix[i,j] = MakeBoolVar(var_name); } } return matrix; } public static int GetSolverEnum(String solverType) { System.Reflection.FieldInfo fieldInfo = typeof(Solver).GetField(solverType); if (fieldInfo != null) { return (int)fieldInfo.GetValue(null); } else { throw new System.ApplicationException("Solver not supported"); } } public static Solver CreateSolver(String name, String type) { System.Reflection.FieldInfo fieldInfo = typeof(Solver).GetField(type); if (fieldInfo != null) { return new Solver(name, (int)fieldInfo.GetValue(null)); } else { return null; } } public Constraint Add(LinearConstraint constraint) { return constraint.Extract(this); } public void Minimize(LinearExpr expr) { Objective().Clear(); Objective().SetMinimization(); Dictionary<Variable, double> coefficients = new Dictionary<Variable, double>(); double constant = expr.Visit(coefficients); foreach (KeyValuePair<Variable, double> pair in coefficients) { Objective().SetCoefficient(pair.Key, pair.Value); } Objective().SetOffset(constant); } public void Maximize(LinearExpr expr) { Objective().Clear(); Objective().SetMaximization(); Dictionary<Variable, double> coefficients = new Dictionary<Variable, double>(); double constant = expr.Visit(coefficients); foreach (KeyValuePair<Variable, double> pair in coefficients) { Objective().SetCoefficient(pair.Key, pair.Value); } Objective().SetOffset(constant); } public void Minimize(Variable var) { Objective().Clear(); Objective().SetMinimization(); Objective().SetCoefficient(var, 1.0); } public void Maximize(Variable var) { Objective().Clear(); Objective().SetMaximization(); Objective().SetCoefficient(var, 1.0); } } } // namespace Google.OrTools.LinearSolver
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using Xunit; namespace System.Reflection.Tests { public static partial class AssemblyTests { [Fact] public static void AssemblyGetName() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); AssemblyName name = a.GetName(copiedName: false); Assert.NotNull(name); string fullName = name.FullName; Assert.Equal(TestData.s_SimpleAssemblyFullName, fullName); } } [Fact] public static void AssemblyGetCopiedName() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); AssemblyName name = a.GetName(copiedName: true); // Shadow-copying is irrevant for MetadataLoadContext-loaded assemblies so this parameter is ignored. Assert.NotNull(name); string fullName = name.FullName; Assert.Equal(TestData.s_SimpleAssemblyFullName, fullName); } } [Fact] public static void AssemblyGetNameAlwaysReturnsNewInstance() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); AssemblyName name1 = a.GetName(); AssemblyName name2 = a.GetName(); Assert.NotSame(name1, name2); } } [Fact] public static void AssemblyFullName() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); string fullName = a.FullName; Assert.Equal(TestData.s_SimpleAssemblyFullName, fullName); } } [Fact] public static void AssemblyGlobalAssemblyCache() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.False(a.GlobalAssemblyCache); // This property is meaningless for MetadataLoadContexts and always returns false. } } [Fact] public static void AssemblyHostContext() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Equal(0L, a.HostContext); // This property is meaningless for MetadataLoadContexts and always returns 0. } } [Fact] public static void AssemblyIsDynamic() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.False(a.IsDynamic); } } [Fact] public static void AssemblyReflectionOnly() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.True(a.ReflectionOnly); } } [Fact] public static void AssemblyMetadataVersion4_0() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); string metadataVersion = a.ImageRuntimeVersion; Assert.Equal("v4.0.30319", metadataVersion); } } [Fact] public static void AssemblyMetadataVersion2_0() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_NetFx20AssemblyImage); string metadataVersion = a.ImageRuntimeVersion; Assert.Equal("v2.0.50727", metadataVersion); } } [Fact] public static void AssemblyLocationMemory() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); string location = a.Location; Assert.Equal(string.Empty, location); } } [Fact] public static void AssemblyLocationFile() { using (TempFile tf = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(tf.Path); string location = a.Location; Assert.Equal(tf.Path, location); } } [Fact] public static void AssemblyGetTypesReturnsDifferentObjectsEachTime() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); TestUtils.AssertNewObjectReturnedEachTime<Type>(() => a.GetTypes()); } } [Fact] public static void AssemblyDefinedTypeInfosReturnsDifferentObjectsEachTime() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); TestUtils.AssertNewObjectReturnedEachTime<TypeInfo>(() => a.DefinedTypes); } } [Fact] public static void AssemblyGetReferencedAssemblies() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyReferencesTestImage); AssemblyName[] ans = a.GetReferencedAssemblies(); Assert.Equal(3, ans.Length); { AssemblyName an = ans.Single(an2 => an2.Name == "mscorlib"); Assert.Equal(default(AssemblyNameFlags), an.Flags); Version v = an.Version; Assert.NotNull(v); Assert.Equal(4, v.Major); Assert.Equal(0, v.Minor); Assert.Equal(0, v.Build); Assert.Equal(0, v.Revision); Assert.Equal(string.Empty, an.CultureName); Assert.Null(an.GetPublicKey()); byte[] pkt = an.GetPublicKeyToken(); byte[] expectedPkt = "b77a5c561934e089".HexToByteArray(); Assert.Equal<byte>(expectedPkt, pkt); } { AssemblyName an = ans.Single(an2 => an2.Name == "dep1"); Assert.Equal(default(AssemblyNameFlags), an.Flags); Version v = an.Version; Assert.NotNull(v); Assert.Equal(0, v.Major); Assert.Equal(0, v.Minor); Assert.Equal(0, v.Build); Assert.Equal(0, v.Revision); Assert.Equal(string.Empty, an.CultureName); Assert.Null(an.GetPublicKey()); Assert.Equal(0, an.GetPublicKeyToken().Length); } { AssemblyName an = ans.Single(an2 => an2.Name == "dep2"); Assert.Equal(default(AssemblyNameFlags), an.Flags); Version v = an.Version; Assert.NotNull(v); Assert.Equal(1, v.Major); Assert.Equal(2, v.Minor); Assert.Equal(3, v.Build); Assert.Equal(4, v.Revision); Assert.Equal("ar-LY", an.CultureName); Assert.Null(an.GetPublicKey()); Assert.Equal(0, an.GetPublicKeyToken().Length); } } } [Fact] public static void AssemblyGetReferencedAssembliesFullPublicKeyReference() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { // Ecma-335 allows an assembly reference to specify a full public key rather than the token. Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyRefUsingFullPublicKeyImage); AssemblyName[] ans = a.GetReferencedAssemblies(); Assert.Equal(1, ans.Length); AssemblyName an = ans[0]; Assert.Equal("mscorlib", an.Name); Assert.Equal(AssemblyNameFlags.PublicKey, an.Flags); byte[] expectedPk = "00000000000000000400000000000000".HexToByteArray(); byte[] actualPk = an.GetPublicKey(); Assert.Equal<byte>(expectedPk, actualPk); } } [Fact] public static void AssemblyGetReferencedAssembliesPartialVersions() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_PartialVersionsImage); AssemblyName[] ans = a.GetReferencedAssemblies(); Assert.Equal(6, ans.Length); ans = ans.OrderBy(aname => aname.Name).ToArray(); AssemblyName an; an = ans[0]; Assert.Equal("illegal1", an.Name); Assert.Null(an.Version); an = ans[1]; Assert.Equal("illegal2", an.Name); Assert.Null(an.Version); an = ans[2]; Assert.Equal("illegal3", an.Name); Assert.Null(an.Version); an = ans[3]; Assert.Equal("nobuildrevision", an.Name); Assert.Equal(1, an.Version.Major); Assert.Equal(2, an.Version.Minor); Assert.Equal(-1, an.Version.Build); Assert.Equal(-1, an.Version.Revision); an = ans[4]; Assert.Equal("nobuildrevisionalternate", an.Name); Assert.Equal(1, an.Version.Major); Assert.Equal(2, an.Version.Minor); Assert.Equal(-1, an.Version.Build); Assert.Equal(-1, an.Version.Revision); an = ans[5]; Assert.Equal("norevision", an.Name); Assert.Equal(1, an.Version.Major); Assert.Equal(2, an.Version.Minor); Assert.Equal(3, an.Version.Build); Assert.Equal(-1, an.Version.Revision); } } [Fact] public static void AssemblyGetReferencedAssembliesReturnsDifferentObjectsEachTime() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyReferencesTestImage); AssemblyName[] ans1 = a.GetReferencedAssemblies(); AssemblyName[] ans2 = a.GetReferencedAssemblies(); Assert.Equal(ans1.Length, ans2.Length); if (ans1.Length != 0) { Assert.NotSame(ans1, ans2); // Be absolutely sure we're comparing apples to apples. ans1 = ans1.OrderBy(an => an.Name).ToArray(); ans2 = ans2.OrderBy(an => an.Name).ToArray(); for (int i = 0; i < ans1.Length; i++) { Assert.NotSame(ans1[i], ans2[i]); { byte[] pk1 = ans1[i].GetPublicKey(); byte[] pk2 = ans2[i].GetPublicKey(); if (pk1 != null) { Assert.Equal<byte>(pk1, pk2); if (pk1.Length != 0) { Assert.NotSame(pk1, pk2); } } } { byte[] pkt1 = ans1[i].GetPublicKeyToken(); byte[] pkt2 = ans2[i].GetPublicKeyToken(); if (pkt1 != null) { Assert.Equal<byte>(pkt1, pkt2); if (pkt1.Length != 0) { Assert.NotSame(pkt1, pkt2); } } } } } } } [Fact] public static void AssemblyGetTypes1() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly upper = lc.LoadFromByteArray(TestData.s_UpperImage); Type[] types = upper.GetTypes().OrderBy(t => t.FullName).ToArray(); string[] fullNames = types.Select(t => t.FullName).ToArray(); string[] expected = { "Outer1", "Outer1+Inner1", "Outer1+Inner2", "Outer1+Inner3" ,"Outer1+Inner4" ,"Outer1+Inner5", "Outer2", "Outer2+Inner1", "Outer2+Inner2", "Outer2+Inner3" ,"Outer2+Inner4" ,"Outer2+Inner5", "Upper1", "Upper4" }; Assert.Equal<string>(expected, fullNames); } } [Fact] public static void AssemblyGetExportedTypes1() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly upper = lc.LoadFromByteArray(TestData.s_UpperImage); Type[] types = upper.GetExportedTypes().OrderBy(t => t.FullName).ToArray(); string[] fullNames = types.Select(t => t.FullName).ToArray(); string[] expected = { "Outer1", "Outer1+Inner1", "Upper1" }; Assert.Equal<string>(expected, fullNames); } } [Fact] public static void AssemblyGetForwardedTypes1() { // Note this is using SimpleAssemblyResolver in order to resolve names between assemblies. using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly upper = lc.LoadFromByteArray(TestData.s_UpperImage); Assembly middle = lc.LoadFromByteArray(TestData.s_MiddleImage); Assembly lower = lc.LoadFromByteArray(TestData.s_LowerImage); Type[] types = upper.GetForwardedTypesThunk().OrderBy(t => t.FullName).ToArray(); string[] fullNames = types.Select(t => t.FullName).ToArray(); string[] expected = { "Middle2", "Upper2", "Upper3", "Upper3+Upper3a" }; Assert.Equal<string>(expected, fullNames); } } [Fact] public static void AssemblyGetForwardedTypes2() { // Note this is using SimpleAssemblyResolver in order to resolve names between assemblies. using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly upper = lc.LoadFromByteArray(TestData.s_UpperImage); Assembly middle = lc.LoadFromByteArray(TestData.s_MiddleImage); ReflectionTypeLoadException re = Assert.Throws<ReflectionTypeLoadException>(() => upper.GetForwardedTypesThunk()); Assert.Equal(3, re.Types.Length); Assert.Equal(3, re.LoaderExceptions.Length); Assert.Equal(2, re.Types.Count((t) => t == null)); Assert.Contains<Type>(middle.GetType("Upper2", throwOnError: true), re.Types); Assert.Equal(1, re.LoaderExceptions.Count((t) => t == null)); Assert.True(re.LoaderExceptions.All((t) => t == null || t is FileNotFoundException)); } } [Fact] public static void AssemblyGetForwardedTypes3() { // Note this is using SimpleAssemblyResolver in order to resolve names between assemblies. using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly upper = lc.LoadFromByteArray(TestData.s_UpperImage); Assembly lower = lc.LoadFromByteArray(TestData.s_LowerImage); ReflectionTypeLoadException re = Assert.Throws<ReflectionTypeLoadException>(() => upper.GetForwardedTypesThunk()); Assert.Equal(4, re.Types.Length); Assert.Equal(4, re.LoaderExceptions.Length); Assert.Equal(2, re.Types.Count((t) => t == null)); Assert.Contains<Type>(lower.GetType("Upper3", throwOnError: true), re.Types); Assert.Contains<Type>(lower.GetType("Upper3+Upper3a", throwOnError: true), re.Types); Assert.Equal(2, re.LoaderExceptions.Count((t) => t == null)); Assert.True(re.LoaderExceptions.All((t) => t == null || t is FileNotFoundException)); } } [Fact] public static void AssemblyWithEmbeddedResources() { // Note this is using SimpleAssemblyResolver in order to resolve names between assemblies. using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithEmbeddedResourcesImage); string[] names = a.GetManifestResourceNames().OrderBy(s => s).ToArray(); Assert.Equal<string>(new string[] { "MyRes1", "MyRes2", "MyRes3" }, names); foreach (string name in names) { ManifestResourceInfo mri = a.GetManifestResourceInfo(name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, mri.ResourceLocation); Assert.Null(mri.FileName); Assert.Null(mri.ReferencedAssembly); } using (Stream s = a.GetManifestResourceStream("MyRes1")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes1, res); } using (Stream s = a.GetManifestResourceStream("MyRes2")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes2, res); } using (Stream s = a.GetManifestResourceStream("MyRes3")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes3, res); } } } [Fact] public static void AssemblyWithResourcesInManifestFile() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string myRes1Path = Path.Combine(td.Path, "MyRes1"); string myRes2Path = Path.Combine(td.Path, "MyRes2"); string myRes3Path = Path.Combine(td.Path, "MyRes3"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInManifestFilesImage); File.WriteAllBytes(myRes1Path, TestData.s_MyRes1); File.WriteAllBytes(myRes2Path, TestData.s_MyRes2); File.WriteAllBytes(myRes3Path, TestData.s_MyRes3); using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); string[] names = a.GetManifestResourceNames().OrderBy(s => s).ToArray(); Assert.Equal<string>(new string[] { "MyRes1", "MyRes2", "MyRes3" }, names); foreach (string name in names) { ManifestResourceInfo mri = a.GetManifestResourceInfo(name); Assert.Equal(default(ResourceLocation), mri.ResourceLocation); Assert.Equal(name, mri.FileName); Assert.Null(mri.ReferencedAssembly); } using (Stream s = a.GetManifestResourceStream("MyRes1")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes1, res); } using (Stream s = a.GetManifestResourceStream("MyRes2")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes2, res); } using (Stream s = a.GetManifestResourceStream("MyRes3")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes3, res); } } } } [Fact] public static void AssemblyWithResourcesInModule() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string modulePath = Path.Combine(td.Path, "a.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInModuleImage); File.WriteAllBytes(modulePath, TestData.s_ModuleForAssemblyWithResourcesInModuleImage); using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); string[] names = a.GetManifestResourceNames().OrderBy(s => s).ToArray(); Assert.Equal<string>(new string[] { "MyRes1", "MyRes2", "MyRes3" }, names); foreach (string name in names) { ManifestResourceInfo mri = a.GetManifestResourceInfo(name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, mri.ResourceLocation); Assert.Null(mri.FileName); Assert.Null(mri.ReferencedAssembly); } using (Stream s = a.GetManifestResourceStream("MyRes1")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes1, res); } using (Stream s = a.GetManifestResourceStream("MyRes2")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes2, res); } using (Stream s = a.GetManifestResourceStream("MyRes3")) { byte[] res = s.ToArray(); Assert.Equal<byte>(TestData.s_MyRes3, res); } } } } [Fact] public static void AssemblyEntryPoint1() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithEntryPointImage); MethodInfo m = a.EntryPoint; Assert.Equal(TestData.s_AssemblyWithEntryPointEntryPointToken, m.MetadataToken); Assert.Equal("Main", m.Name); } } [Fact] public static void AssemblyEntryPoint2() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); MethodInfo m = a.EntryPoint; Assert.Null(m); } } [Fact] public static void CrossAssemblyTypeRefToNestedType() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithNestedTypeImage); Assembly n = lc.LoadFromByteArray(TestData.s_AssemblyWithTypeRefToNestedTypeImage); Type nt = n.GetType("N", throwOnError: true); Type bt = nt.BaseType; Type expected = a.GetType("Outer+Inner+ReallyInner", throwOnError: true); Assert.Equal(expected, bt); } } } }
// // ListViewAccessible.cs // // Authors: // Eitan Isaacson <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Eitan Isaacson // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Hyena.Data.Gui; namespace Hyena.Data.Gui.Accessibility { #if ENABLE_ATK public partial class ListViewAccessible<T> : Hyena.Gui.BaseWidgetAccessible, ICellAccessibleParent { private ListView<T> list_view; private Dictionary<int, ColumnCellAccessible> cell_cache; public ListViewAccessible (GLib.Object widget) : base (widget as Gtk.Widget) { list_view = widget as ListView<T>; // TODO replace with list_view.Name? Name = "ListView"; Description = "ListView"; Role = Atk.Role.Table; Parent = list_view.Parent.RefAccessible (); cell_cache = new Dictionary<int, ColumnCellAccessible> (); list_view.ModelChanged += OnModelChanged; list_view.ModelReloaded += OnModelChanged; OnModelChanged (null, null); list_view.SelectionProxy.FocusChanged += OnSelectionFocusChanged; list_view.ActiveColumnChanged += OnSelectionFocusChanged; ListViewAccessible_Selection (); ListViewAccessible_Table (); } protected override Atk.StateSet OnRefStateSet () { Atk.StateSet states = base.OnRefStateSet (); states.AddState (Atk.StateType.ManagesDescendants); return states; } protected override int OnGetIndexInParent () { for (int i=0; i < Parent.NAccessibleChildren; i++) { if (Parent.RefAccessibleChild (i) == this) { return i; } } return -1; } protected override int OnGetNChildren () { return n_columns * n_rows + n_columns; } protected override Atk.Object OnRefChild (int index) { ColumnCellAccessible child; if (cell_cache.ContainsKey (index)) { return cell_cache[index]; } // FIXME workaround to prevent crashing on Grid ListViews if (list_view.ColumnController == null) return null; var columns = list_view.ColumnController.Where (c => c.Visible); if (index - n_columns < 0) { child = columns.ElementAtOrDefault (index) .HeaderCell .GetAccessible (this) as ColumnCellAccessible; } else { int column = (index - n_columns) % n_columns; int row = (index - n_columns) / n_columns; var cell = columns.ElementAtOrDefault (column).GetCell (0); cell.BindListItem (list_view.Model[row]); child = (ColumnCellAccessible) cell.GetAccessible (this); } cell_cache.Add (index, child); return child; } public override Atk.Object RefAccessibleAtPoint (int x, int y, Atk.CoordType coordType) { int row, col; list_view.GetCellAtPoint (x, y, coordType, out row, out col); return RefAt (row, col); } private void OnModelChanged (object o, EventArgs a) { ThreadAssist.ProxyToMain (EmitModelChanged); } private void EmitModelChanged () { GLib.Signal.Emit (this, "model_changed"); cell_cache.Clear (); /*var handler = ModelChanged; if (handler != null) { handler (this, EventArgs.Empty); }*/ } private void OnSelectionFocusChanged (object o, EventArgs a) { ThreadAssist.ProxyToMain (EmitDescendantChanged); } private void EmitDescendantChanged () { var cell = ActiveCell; if (cell != null) { GLib.Signal.Emit (this, "active-descendant-changed", cell.Handle); } } private Atk.Object ActiveCell { get { if (list_view.HeaderFocused) { return OnRefChild (list_view.ActiveColumn); } else { if (list_view.Selection != null) { return RefAt (list_view.Selection.FocusedIndex, list_view.ActiveColumn); } else { return null; } } } } private int n_columns { get { return list_view.ColumnController != null ? list_view.ColumnController.Count (c => c.Visible) : 1; } } private int n_rows { get { return list_view.Model.Count; } } #region ICellAccessibleParent public int GetCellIndex (ColumnCellAccessible cell) { foreach (KeyValuePair<int, ColumnCellAccessible> kv in cell_cache) { if ((ColumnCellAccessible)kv.Value == cell) return (int)kv.Key; } return -1; } public Gdk.Rectangle GetCellExtents (ColumnCellAccessible cell, Atk.CoordType coord_type) { int cache_index = GetCellIndex (cell); int minval = Int32.MinValue; if (cache_index == -1) return new Gdk.Rectangle (minval, minval, minval, minval); if (cache_index - n_columns >= 0) { int column = (cache_index - NColumns)%NColumns; int row = (cache_index - NColumns)/NColumns; return list_view.GetColumnCellExtents (row, column, true, coord_type); } else { return list_view.GetColumnHeaderCellExtents (cache_index, true, coord_type); } } public bool IsCellShowing (ColumnCellAccessible cell) { Gdk.Rectangle cell_extents = GetCellExtents (cell, Atk.CoordType.Window); if (cell_extents.X == Int32.MinValue && cell_extents.Y == Int32.MinValue) return false; return true; } public bool IsCellFocused (ColumnCellAccessible cell) { int cell_index = GetCellIndex (cell); if (cell_index % NColumns != 0) return false; // Only 0 column cells get focus now. int row = cell_index / NColumns; return row == list_view.Selection.FocusedIndex; } public bool IsCellSelected (ColumnCellAccessible cell) { return IsChildSelected (GetCellIndex (cell)); } public bool IsCellActive (ColumnCellAccessible cell) { return (ActiveCell == (Atk.Object)cell); } public void InvokeColumnHeaderMenu (ColumnCellAccessible cell) { list_view.InvokeColumnHeaderMenu (GetCellIndex (cell)); } public void ClickColumnHeader (ColumnCellAccessible cell) { list_view.ClickColumnHeader (GetCellIndex (cell)); } public void CellRedrawn (int column, int row) { int index; if (row >= 0) index = row * n_columns + column + n_columns; else index = column; if (cell_cache.ContainsKey (index)) { cell_cache[index].Redrawn (); } } #endregion } #endif }
using System; using System.Collections.ObjectModel; using System.Collections.Generic; namespace Krs.Ats.IBNet { /// <summary> /// Class to describe a financial security. /// </summary> /// <seealso href="http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/contract.htm">Interactive Brokers Contract Documentation</seealso> [Serializable()] public class Contract { #region Private Variables private Collection<ComboLeg> comboLegs = new Collection<ComboLeg>(); private int contractId; private String comboLegsDescription; // received in open order version 14 and up for all combos private String currency; private String exchange; private String expiry; private bool includeExpired; // can not be set to true for orders. private String localSymbol; private String multiplier; private SecurityIdType secIdType; // CUSIP;SEDOL;ISIN;RIC private String secId; private String tradingClass; private String primaryExchange; // pick a non-aggregate (ie not the SMART exchange) exchange that the contract trades on. DO NOT SET TO SMART. private RightType right; private SecurityType securityType; private double strike; private String symbol; private UnderlyingComponent underlyingComponent; #endregion #region Constructors ///<summary> /// Undefined Contract Constructor ///</summary> public Contract() : this(0, null, SecurityType.Undefined, null, 0, RightType.Undefined, null, null, null, null, null, SecurityIdType.None, string.Empty) { } /// <summary> /// Futures Contract Constructor /// </summary> /// <param name="symbol">This is the symbol of the underlying asset.</param> /// <param name="exchange">The order destination, such as Smart.</param> /// <param name="securityType">This is the security type.</param> /// <param name="currency">Specifies the currency.</param> /// <param name="expiry">The expiration date. Use the format YYYYMM.</param> public Contract(string symbol, string exchange, SecurityType securityType, string currency, string expiry) : this(0, symbol, securityType, expiry, 0, RightType.Undefined, null, exchange, currency, null, null, SecurityIdType.None, string.Empty) { } /// <summary> /// Indice Contract Constructor /// </summary> /// <param name="symbol">This is the symbol of the underlying asset.</param> /// <param name="exchange">The order destination, such as Smart.</param> /// <param name="securityType">This is the security type.</param> /// <param name="currency">Specifies the currency.</param> public Contract(string symbol, string exchange, SecurityType securityType, string currency) : this(0, symbol, securityType, null, 0, RightType.Undefined, null, exchange, currency, null, null, SecurityIdType.None, string.Empty) { } /// <summary> /// Default Contract Constructor /// </summary> /// <param name="contractId">The unique contract identifier.</param> /// <param name="symbol">This is the symbol of the underlying asset.</param> /// <param name="securityType">This is the security type.</param> /// <param name="expiry">The expiration date. Use the format YYYYMM.</param> /// <param name="strike">The strike price.</param> /// <param name="right">Specifies a Put or Call.</param> /// <param name="multiplier">Allows you to specify a future or option contract multiplier. /// This is only necessary when multiple possibilities exist.</param> /// <param name="exchange">The order destination, such as Smart.</param> /// <param name="currency">Specifies the currency.</param> /// <param name="localSymbol">This is the local exchange symbol of the underlying asset.</param> /// <param name="primaryExchange">Identifies the listing exchange for the contract (do not list SMART).</param> /// <param name="secIdType">Security identifier, when querying contract details or when placing orders.</param> /// <param name="secId">Unique identifier for the secIdType.</param> public Contract(int contractId, String symbol, SecurityType securityType, String expiry, double strike, RightType right, String multiplier, string exchange, string currency, string localSymbol, string primaryExchange, SecurityIdType secIdType, string secId) { this.contractId = contractId; this.symbol = symbol; this.securityType = securityType; this.expiry = expiry; this.strike = strike; this.right = right; this.multiplier = multiplier; this.exchange = exchange; this.currency = currency; this.localSymbol = localSymbol; this.primaryExchange = primaryExchange; this.secIdType = secIdType; this.secId = secId; } /// <summary> /// Get a Contract by its unique contractId /// </summary> /// <param name="contractId"></param> public Contract(int contractId) { this.contractId = contractId; } #endregion #region Properties /// <summary> /// This is the symbol of the underlying asset. /// </summary> public string Symbol { get { return symbol; } set { symbol = value; } } /// <summary> /// This is the security type. /// </summary> /// <remarks>Valid security types are: /// <list type="bullet"> /// <item>Stock</item> /// <item>Option</item> /// <item>Future</item> /// <item>Indice</item> /// <item>Option on Future</item> /// <item>Cash</item> /// <item>Bag</item> /// <item>Bond</item> /// </list> /// </remarks> /// <seealso cref="IBNet.SecurityType"/> public SecurityType SecurityType { get { return securityType; } set { securityType = value; } } /// <summary> /// The expiration date. Use the format YYYYMM. /// </summary> public string Expiry { get { return expiry; } set { expiry = value; } } /// <summary> /// The strike price. /// </summary> public double Strike { get { return strike; } set { strike = value; } } /// <summary> /// Specifies a Put or Call. /// </summary> /// <remarks>Valid values are: /// <list type="bullet"> /// <item>Put - the right to sell a security.</item> /// <item>Call - the right to buy a security.</item> /// </list> /// </remarks> /// <seealso cref="RightType"/> public RightType Right { get { return right; } set { right = value; } } /// <summary> /// Allows you to specify a future or option contract multiplier. /// This is only necessary when multiple possibilities exist. /// </summary> public string Multiplier { get { return multiplier; } set { multiplier = value; } } /// <summary> /// The order destination, such as Smart. /// </summary> public string Exchange { get { return exchange; } set { exchange = value; } } /// <summary> /// Specifies the currency. /// </summary> /// <remarks> /// Ambiguities may require that this field be specified, /// for example, when SMART is the exchange and IBM is being requested /// (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity, /// it is a good idea to always specify the currency. /// </remarks> public string Currency { get { return currency; } set { currency = value; } } /// <summary> /// This is the local exchange symbol of the underlying asset. /// </summary> public string LocalSymbol { get { return localSymbol; } set { localSymbol = value; } } /** * @brief The trading class name for this contract. * Available in TWS contract description window as well. For example, GBL Dec '13 future's trading class is "FGBL" */ public string TradingClass { get { return tradingClass; } set { tradingClass = value; } } /// <summary> /// Identifies the listing exchange for the contract (do not list SMART). /// </summary> public string PrimaryExchange { get { return primaryExchange; } set { primaryExchange = value; } } /// <summary> /// If set to true, contract details requests and historical data queries /// can be performed pertaining to expired contracts. /// /// Historical data queries on expired contracts are limited to the /// last year of the contracts life, and are initially only supported for /// expired futures contracts, /// </summary> public bool IncludeExpired { get { return includeExpired; } set { includeExpired = value; } } /// <summary> /// Description for combo legs /// </summary> public string ComboLegsDescription { get { return comboLegsDescription; } set { comboLegsDescription = value; } } /// <summary> /// Dynamic memory structure used to store the leg definitions for this contract. /// </summary> public Collection<ComboLeg> ComboLegs { get { return comboLegs; } set { comboLegs = value; } } /// <summary> /// The unique contract identifier. /// </summary> public int ContractId { get { return contractId; } set { contractId = value; } } /// <summary> /// Underlying Component /// </summary> public UnderlyingComponent UnderlyingComponent { get { return underlyingComponent; } set { underlyingComponent = value; } } /// <summary> /// Security identifier, when querying contract details or when placing orders. Supported identifiers are: /// ISIN (Example: Apple: US0378331005) /// CUSIP (Example: Apple: 037833100) /// SEDOL (Consists of 6-AN + check digit. Example: BAE: 0263494) /// RIC (Consists of exchange-independent RIC Root and a suffix identifying the exchange. Example: AAPL.O for Apple on NASDAQ.) /// </summary> public SecurityIdType SecIdType { get { return secIdType; } set { secIdType = value; } } /// <summary> /// Unique identifier for the secIdType. /// </summary> public String SecId { get { return secId; } set { secId = value; } } #endregion } }
// The MIT License // // Copyright (c) 2012-2015 Jordan E. Terrell // // 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 iSynaptic.Commons.Collections.Generic; using NUnit.Framework; using System.Linq; using System.Collections; using Rhino.Mocks; namespace iSynaptic.Commons.Linq { [TestFixture] public class EnumerableExtensionsTests { [Test] public void CopyTo_WithNullSource_ThrowsException() { IEnumerable<int> source = null; int[] destination = new int[1]; Assert.Throws<ArgumentNullException>(() => source.CopyTo(destination, 0)); } [Test] public void CopyTo_WithNullDestination_ThrowsException() { IEnumerable<int> source = Enumerable.Range(1, 1); int[] destination = null; Assert.Throws<ArgumentNullException>(() => source.CopyTo(destination, 0)); } [Test] public void CopyTo_WithNegativeIndex_ThrowsException() { IEnumerable<int> source = Enumerable.Range(1, 1); int[] destination = new int[1]; Assert.Throws<ArgumentOutOfRangeException>(() => source.CopyTo(destination, -1)); } [Test] public void CopyTo_WithIndexGreaterThanDestinationUpperBound_ThrowsException() { IEnumerable<int> source = Enumerable.Range(1, 1); int[] destination = new int[1]; Assert.Throws<ArgumentException>(() => source.CopyTo(destination, 42)); } [Test] public void CopyTo_WithIndexToHighGivenSourceAndDestinationSize_ThrowsException() { IEnumerable<int> source = Enumerable.Range(1, 3); int[] destination = new int[3]; Assert.Throws<ArgumentException>(() => source.CopyTo(destination, 1)); } [Test] public void CopyTo_WithValidInput_ReturnsCorrectly() { IEnumerable<int> source = Enumerable.Range(1, 3); int[] destination = new int[3]; source.CopyTo(destination, 0); Assert.IsTrue(destination.SequenceEqual(new[] { 1, 2, 3 })); } [Test] public void WithIndex() { int[] items = { 1, 3, 5, 7, 9 }; int index = 0; foreach (var item in items.WithIndex()) { Assert.AreEqual(index, item.Index); Assert.AreEqual(items[index], item.Value); index++; } } [Test] public void LookAheadEnumerable() { int[] items = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; using (var enumerator = items.AsLookAheadable().GetEnumerator()) { Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current.Value); Assert.AreEqual(2, enumerator.Current.LookAhead(0).Value); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current.Value); Assert.AreEqual(3, enumerator.Current.LookAhead(0).Value); Assert.AreEqual(5, enumerator.Current.LookAhead(2).Value); Assert.AreEqual(4, enumerator.Current.LookAhead(1).Value); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(3, enumerator.Current.Value); Assert.AreEqual(4, enumerator.Current.LookAhead(0).Value); } IEnumerable<int> nullEnumerable = null; Assert.Throws<ArgumentNullException>(() => { nullEnumerable.AsLookAheadable(); }); } [Test] public void LookAheadEnumeratorPassesOnReset() { var enumerable = MockRepository.GenerateStub<IEnumerable<int>>(); var enumerator = MockRepository.GenerateMock<IEnumerator<int>>(); enumerable.Stub(x => x.GetEnumerator()).Return(enumerator); enumerator.Expect(x => x.Reset()); var la = enumerable.AsLookAheadable(); var lar = la.GetEnumerator(); lar.Reset(); enumerator.VerifyAllExpectations(); } [Test] public void LookAheadEnumerator_WhenUsedAfterBeingDisposed_ThrowsException() { var lookaheadable = Enumerable.Range(1, 2).AsLookAheadable(); var enumerator = lookaheadable.GetEnumerator(); enumerator.MoveNext(); var value = enumerator.Current; enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = enumerator.Current; }); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => value.LookAhead(0)); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); } [Test] public void LookAheadEnumerableViaNonGenericGetEnumerator() { int[] items = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var enumerable = items.AsLookAheadable(); IEnumerator nonGenericEnumerator = null; using ((IDisposable)(nonGenericEnumerator = ((IEnumerable)enumerable).GetEnumerator())) { Assert.IsTrue(nonGenericEnumerator.MoveNext()); Assert.AreEqual(1, ((LookAheadableValue<int>)nonGenericEnumerator.Current).Value); Assert.AreEqual(2, ((LookAheadableValue<int>)nonGenericEnumerator.Current).LookAhead(0).Value); Assert.IsTrue(nonGenericEnumerator.MoveNext()); Assert.AreEqual(2, ((LookAheadableValue<int>)nonGenericEnumerator.Current).Value); Assert.AreEqual(3, ((LookAheadableValue<int>)nonGenericEnumerator.Current).LookAhead(0).Value); Assert.AreEqual(5, ((LookAheadableValue<int>)nonGenericEnumerator.Current).LookAhead(2).Value); Assert.AreEqual(4, ((LookAheadableValue<int>)nonGenericEnumerator.Current).LookAhead(1).Value); Assert.IsTrue(nonGenericEnumerator.MoveNext()); Assert.AreEqual(3, ((LookAheadableValue<int>)nonGenericEnumerator.Current).Value); Assert.AreEqual(4, ((LookAheadableValue<int>)nonGenericEnumerator.Current).LookAhead(0).Value); } } [Test] public void LookAheadWithNullEnumerator() { MockRepository mocks = new MockRepository(); IEnumerable<int> enumerable = mocks.StrictMock<IEnumerable<int>>(); Expect.Call(enumerable.GetEnumerator()).Return(null); mocks.ReplayAll(); var lookAheadable = enumerable.AsLookAheadable(); Assert.IsNull(lookAheadable.GetEnumerator()); } [Test] public void LookAheadToFar_ReturnsNoValue() { var lookAheadable = Enumerable.Range(1, 1).AsLookAheadable(); foreach (var i in lookAheadable) Assert.AreEqual(Maybe<int>.NoValue, i.LookAhead(0)); } [Test] public void Buffer() { bool enumerationComplete = false; IEnumerable<int> numbers = GetRange(1, 10, () => { enumerationComplete = true; }); Assert.IsFalse(enumerationComplete); numbers = numbers.Buffer(); Assert.IsTrue(enumerationComplete); Assert.IsTrue(numbers.SequenceEqual(Enumerable.Range(1, 10))); IEnumerable<int> nullEnumerable = null; Assert.Throws<ArgumentNullException>(() => { nullEnumerable.Buffer(); }); } [Test] public void Run() { bool enumerationComplete = false; IEnumerable<int> numbers = GetRange(1, 10, () => { enumerationComplete = true; }); Assert.IsFalse(enumerationComplete); numbers.Run(); Assert.IsTrue(enumerationComplete); IEnumerable<int> nullEnumerable = null; Assert.Throws<ArgumentNullException>(() => nullEnumerable.Run()); } [Test] public void Delimit() { IEnumerable<int> range = Enumerable.Range(1, 9); Assert.AreEqual("1, 2, 3, 4, 5, 6, 7, 8, 9", range.Delimit(", ")); IEnumerable<int> nullEnumerable = null; Assert.Throws<ArgumentNullException>(() => nullEnumerable.Delimit("")); Assert.Throws<ArgumentNullException>(() => range.Delimit(null)); Assert.Throws<ArgumentNullException>(() => range.Delimit("", (string)null)); Assert.Throws<ArgumentNullException>(() => range.Delimit("", (Func<int, string>)null)); } [Test] public void ZipAll_WithNullIterables_ThrowsArgumentNullException() { IEnumerable<int> first = null; IEnumerable<int> other = Enumerable.Range(1, 10); Assert.Throws<ArgumentNullException>(() => first.ZipAll(other)); Assert.Throws<ArgumentNullException>(() => other.ZipAll(null)); } [Test] public void ZipAll() { var rangeOne = Enumerable.Range(1, 10); var rangeTwo = Enumerable.Range(10, 10); var zipped = rangeOne.ZipAll(rangeTwo); var expected = new[] { 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7, 16, 8, 17, 9, 18, 10, 19 }; Assert.IsTrue(zipped.SelectMany(x => x).Select(x => x.ValueOrDefault()).SequenceEqual(expected)); } [Test] public void ZipAll_ArrayOfEnumerables() { var array = new[] { Enumerable.Range(1, 10), Enumerable.Range(10, 10) }; var zipped = array.ZipAll(); var expected = new[] { 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7, 16, 8, 17, 9, 18, 10, 19 }; Assert.IsTrue(zipped.SelectMany(x => x).Select(x => x.ValueOrDefault()).SequenceEqual(expected)); } [Test] public void ZipAll_EnumerableOfEnumerables() { var array = new[] { Enumerable.Range(1, 10), Enumerable.Range(10, 10) }; var zipped = array.AsEnumerable().ZipAll(); var expected = new[] { 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7, 16, 8, 17, 9, 18, 10, 19 }; Assert.IsTrue(zipped.SelectMany(x => x).Select(x => x.ValueOrDefault()).SequenceEqual(expected)); } [Test] public void ZipAll_WithDifferentItemCounts() { var left = Enumerable.Range(1, 4); var right = Enumerable.Range(1, 3); var zipped = left.ZipAll(right).SelectMany(x => x); Assert.IsTrue(zipped.SequenceEqual(new[] { 1, 1, 2, 2, 3, 3, 4 }.Select(x => x.ToMaybe()).Concat(new[] { Maybe<int>.NoValue }))); } [Test] public void ZipAll_WithSelector() { var rangeOne = Enumerable.Range(1, 10); var rangeTwo = Enumerable.Range(10, 10); var zipped = rangeOne.ZipAll(rangeTwo, (l, r) => new[]{l.Value, r.Value}); var expected = new[] { 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7, 16, 8, 17, 9, 18, 10, 19 }; Assert.IsTrue(zipped.SelectMany(x => x).Select(x => x).SequenceEqual(expected)); } [Test] public void ToDictionary_WithNull_ThrowsArgumentNullException() { IEnumerable<KeyValuePair<string, string>> pairs = null; Assert.Throws<ArgumentNullException>(() => pairs.ToDictionary()); } [Test] public void Batch_Indexer_ReturnsCorrectValues() { var batches = Enumerable.Range(0, 5).Batch(3).ToArray(); Assert.AreEqual(0, batches[0][0]); Assert.AreEqual(1, batches[0][1]); Assert.AreEqual(2, batches[0][2]); Assert.AreEqual(3, batches[1][0]); Assert.AreEqual(4, batches[1][1]); } [Test] public void Batch_WithBalancedBatches_ReturnsAllItems() { var batches = Enumerable.Range(0, 9).Batch(3).ToArray(); Assert.AreEqual(3, batches.Length); Assert.AreEqual(0, batches[0].Index); Assert.AreEqual(1, batches[1].Index); Assert.AreEqual(2, batches[2].Index); Assert.AreEqual(0, batches[0].ItemIndex); Assert.AreEqual(3, batches[1].ItemIndex); Assert.AreEqual(6, batches[2].ItemIndex); Assert.AreEqual(3, batches[0].Count); Assert.AreEqual(3, batches[1].Count); Assert.AreEqual(3, batches[2].Count); Assert.IsTrue(batches[0].SequenceEqual(new[] { 0, 1, 2 })); Assert.IsTrue(batches[1].SequenceEqual(new[] { 3, 4, 5 })); Assert.IsTrue(batches[2].SequenceEqual(new[] { 6, 7, 8 })); } [Test] public void Batch_WithUnbalancedBatches_ReturnsAllItemsAndLastBatchContainsOnlyRemainingItems() { var batches = Enumerable.Range(0, 10).Batch(3).ToArray(); Assert.AreEqual(4, batches.Length); Assert.AreEqual(0, batches[0].Index); Assert.AreEqual(1, batches[1].Index); Assert.AreEqual(2, batches[2].Index); Assert.AreEqual(3, batches[3].Index); Assert.AreEqual(0, batches[0].ItemIndex); Assert.AreEqual(3, batches[1].ItemIndex); Assert.AreEqual(6, batches[2].ItemIndex); Assert.AreEqual(9, batches[3].ItemIndex); Assert.AreEqual(3, batches[0].Count); Assert.AreEqual(3, batches[1].Count); Assert.AreEqual(3, batches[2].Count); Assert.AreEqual(1, batches[3].Count); Assert.IsTrue(batches[0].SequenceEqual(new[] { 0, 1, 2 })); Assert.IsTrue(batches[1].SequenceEqual(new[] { 3, 4, 5 })); Assert.IsTrue(batches[2].SequenceEqual(new[] { 6, 7, 8 })); Assert.IsTrue(batches[3].SequenceEqual(new[] { 9 })); } [Test] public void Batch_ViaPredicate() { var batches = Enumerable.Range(0, 18) .Batch(x => x%5 != 0) .ToArray(); Assert.AreEqual(4, batches.Length); Assert.IsTrue(batches[0].SequenceEqual(new[] { 0, 1, 2, 3, 4 })); Assert.IsTrue(batches[1].SequenceEqual(new[] { 5, 6, 7, 8, 9 })); Assert.IsTrue(batches[2].SequenceEqual(new[] { 10, 11, 12, 13, 14 })); Assert.IsTrue(batches[3].SequenceEqual(new[] { 15, 16, 17 })); } [Test] public void Batch_WithNeighbors_ViaPredicate() { var batches = Enumerable.Range(1, 18) .WithNeighbors() .Batch((x, i, info) => x.Previous.Select(y => y % 5).ValueOrDefault(-1) != 0, x => x.Value) .ToArray(); Assert.AreEqual(4, batches.Length); Assert.IsTrue(batches[0].SequenceEqual(new[] { 1, 2, 3, 4, 5 })); Assert.IsTrue(batches[1].SequenceEqual(new[] { 6, 7, 8, 9, 10 })); Assert.IsTrue(batches[2].SequenceEqual(new[] { 11, 12, 13, 14, 15 })); Assert.IsTrue(batches[3].SequenceEqual(new[] { 16, 17, 18 })); } [Test] public void Batch_ViaNonGenericEnumerator_ReturnsAllItems() { var batches = Enumerable.Range(0, 9) .Batch(3) .Cast<IEnumerable>() .SelectMany(x => x.OfType<int>().ToArray()) .ToArray(); Assert.IsTrue(batches.SequenceEqual(Enumerable.Range(0, 9))); } [Test] public void Recurse() { var r1 = new Recursive(1, new Recursive(2, new Recursive(4)), new Recursive(3)); var recursives = r1.Recurse(r => r.Recursives).ToArray(); Assert.IsTrue(recursives.Select(x => x.Value).SequenceEqual(new[] { 1, 2, 4, 3 })); } [Test] public void RecurseWhile() { var r1 = new Recursive(1, new Recursive(2, new Recursive(4), new Recursive(5)), new Recursive(3, new Recursive(6), new Recursive(7))); var recursives = r1.RecurseWhile(r => r.Recursives, r => r.Value % 2 == 1).ToArray(); Assert.IsTrue(recursives.Select(x => x.Value).SequenceEqual(new[] { 1, 3, 7 })); } [Test] public void Distinct_WithSelector() { var items = new[] { new TestSubject { Number =1, Text = "Foo"}, new TestSubject { Number =1, Text = "Bar"}, new TestSubject { Number =2, Text = "Foo"}, new TestSubject { Number =3, Text = "Baz"} }; Assert.IsTrue(items.Distinct(x => x.Number).Select(x => x.Text).SequenceEqual(new[] { "Foo", "Foo", "Baz" })); Assert.IsTrue(items.Distinct(x => x.Text).Select(x => x.Text).SequenceEqual(new[] { "Foo", "Bar", "Baz" })); } [Test] public void Or_PicksFirstStream_IfItHasItems() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 6, 7, 8, 9, 10 }; var results = first.Or(second); Assert.IsTrue(results.SequenceEqual(new[] { 1, 2, 3, 4, 5 })); } [Test] public void Or_PicksSecondStream_IfFirstHasNoItems() { var first = new List<int>(); var second = new List<int> { 6, 7, 8, 9, 10 }; var results = first.Or(second); Assert.IsTrue(results.SequenceEqual(new[] { 6,7,8,9,10 })); } [Test] public void TryFirst_WithNullSource_ThrowsException() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>(() => source.TryFirst()); Assert.Throws<ArgumentNullException>(() => source.TryFirst(x => true)); } [Test] public void TryFirst_WithNullPredicate_ThrowsException() { IEnumerable<int> source = new int[0]; Assert.Throws<ArgumentNullException>(() => source.TryFirst(null)); } [Test] public void TryFirst_WithEmptySource_ReturnsNoValue() { IEnumerable<int> source = new int[0]; var result = source.TryFirst(); Assert.IsFalse(result.HasValue); result = source.TryFirst(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TryFirst_WithOneItem_ReturnsItem() { IEnumerable<int> source = new []{42}; var result = source.TryFirst(); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); result = source.TryFirst(x => true); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); } [Test] public void TryFirst_WithManyItems_ReturnsFirstItem() { IEnumerable<int> source = new[] { 42, 84, 168 }; var result = source.TryFirst(); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); result = source.TryFirst(x => true); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); } [Test] public void TryFirst_WithFirstItemNull_ReturnsNoValue() { IEnumerable<string> source = new[] { null, "Foo", "Baz" }; var result = source.TryFirst(); Assert.IsFalse(result.HasValue); result = source.TryFirst(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TryFirst_WherePredicateMatchesItem_ReturnsFirstMatchingItem() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TryFirst(x => x.StartsWith("B")); Assert.IsTrue(result.HasValue); Assert.AreEqual("Baz", result.Value); } [Test] public void TryFirst_WherePredicateMatchesNoItems_ReturnsNoValue() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TryFirst(x => false); Assert.IsFalse(result.HasValue); } [Test] public void TryLast_WithNullSource_ThrowsException() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>(() => source.TryLast()); Assert.Throws<ArgumentNullException>(() => source.TryLast(x => true)); } [Test] public void TryLast_WithNullPredicate_ThrowsException() { IEnumerable<int> source = new int[0]; Assert.Throws<ArgumentNullException>(() => source.TryLast(null)); } [Test] public void TryLast_WithEmptySource_ReturnsNoValue() { IEnumerable<int> source = new int[0]; var result = source.TryLast(); Assert.IsFalse(result.HasValue); result = source.TryLast(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TryLast_WithOneItem_ReturnsItem() { IEnumerable<int> source = new[] { 42 }; var result = source.TryLast(); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); result = source.TryLast(x => true); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); } [Test] public void TryLast_WithManyItems_ReturnsLastItem() { IEnumerable<int> source = new[] { 42, 84, 168 }; var result = source.TryLast(); Assert.IsTrue(result.HasValue); Assert.AreEqual(168, result.Value); result = source.TryLast(x => true); Assert.IsTrue(result.HasValue); Assert.AreEqual(168, result.Value); } [Test] public void TryLast_WithLastItemNull_ReturnsNoValue() { IEnumerable<string> source = new[] { "Foo", "Baz", null }; var result = source.TryLast(); Assert.IsFalse(result.HasValue); result = source.TryLast(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TryLast_WherePredicateMatchesItem_ReturnsLastMatchingItem() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TryLast(x => x.StartsWith("B")); Assert.IsTrue(result.HasValue); Assert.AreEqual("Boo", result.Value); } [Test] public void TryLast_WherePredicateMatchesNoItems_ReturnsNoValue() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TryLast(x => false); Assert.IsFalse(result.HasValue); } [Test] public void TrySingle_WithNullSource_ThrowsException() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>(() => source.TrySingle()); Assert.Throws<ArgumentNullException>(() => source.TrySingle(x => true)); } [Test] public void TrySingle_WithNullPredicate_ThrowsException() { IEnumerable<int> source = new int[0]; Assert.Throws<ArgumentNullException>(() => source.TrySingle(null)); } [Test] public void TrySingle_WithEmptySource_ReturnsNoValue() { IEnumerable<int> source = new int[0]; var result = source.TrySingle(); Assert.IsFalse(result.HasValue); result = source.TrySingle(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TrySingle_WithOneItem_ReturnsItem() { IEnumerable<int> source = new[] { 42 }; var result = source.TrySingle(); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); result = source.TrySingle(x => true); Assert.IsTrue(result.HasValue); Assert.AreEqual(42, result.Value); } [Test] public void TrySingle_WithManyItems_ThrowsExceptionImmediately() { IEnumerable<int> source = new[] { 42, 84, 168 }; var results = source.TrySingle(); Assert.Throws<InvalidOperationException>(() => results.Run()); results = source.TrySingle(x => true); Assert.Throws<InvalidOperationException>(() => results.Run()); } [Test] public void TrySingle_WithOnlyItemNull_ReturnsNoValue() { IEnumerable<string> source = new[] { (string)null }; var result = source.TrySingle(); Assert.IsFalse(result.HasValue); result = source.TrySingle(x => true); Assert.IsFalse(result.HasValue); } [Test] public void TrySingle_WherePredicateMatchesOneItem_ReturnsMatchingItem() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TrySingle(x => x.StartsWith("Bo")); Assert.IsTrue(result.HasValue); Assert.AreEqual("Boo", result.Value); } [Test] public void TrySingle_WherePredicateMatchesMultipleItems_ThrowsException() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var results = source.TrySingle(x => x.StartsWith("B")); Assert.Throws<InvalidOperationException>(() => results.Run()); } [Test] public void TrySingle_WherePredicateMatchesNoItems_ReturnsNoValue() { IEnumerable<string> source = new[] { "Foo", "Baz", "Boo", "Quix" }; var result = source.TrySingle(x => false); Assert.IsFalse(result.HasValue); } [Test] public void Any_WithEnumerableBooleans_ReturnsTrueForAny() { Assert.IsFalse(new[]{ false, false, false }.Any()); Assert.IsTrue(new[] { false, true, false }.Any()); Assert.IsTrue(new[] { true, true, true }.Any()); } [Test] public void AllTrue_WithEnumerableBooleans_ReturnsTrueForAll() { Assert.IsFalse(new[] { false, false, false }.AllTrue()); Assert.IsFalse(new[] { false, true, false }.AllTrue()); Assert.IsTrue(new[] { true, true, true }.AllTrue()); } [Test] public void AllFalse_WithEnumerableBooleans_ReturnsTrueForNone() { Assert.IsTrue(new[] { false, false, false }.AllFalse()); Assert.IsFalse(new[] { false, true, false }.AllFalse()); Assert.IsFalse(new[] { true, true, true }.AllFalse()); } [Test] public void None_WithPredicate_ReturnsTrueForNone() { Assert.IsTrue(new[] { "false", "false", "false" }.None(bool.Parse)); Assert.IsFalse(new[] { "false", "true", "false" }.None(bool.Parse)); Assert.IsFalse(new[] { "true", "true", "true" }.None(bool.Parse)); } [Test] public void None_WithNoPredicate_ReturnsTrueForEmptyEnumerables() { Assert.IsTrue(new String[]{}.None()); Assert.IsFalse(new [] { "Hello, World!" }.None()); } [Test] public void SelectMaybe_OnlyYieldsValuesWhereMaybeHasValue() { Assert.IsTrue(Enumerable.Range(1, 10) .SelectMaybe(x => x.ToMaybe().Where(y => y % 2 == 0)) .SequenceEqual(new[]{2,4,6,8,10})); } [Test] public void SelectMaybe_WithIndexedSelector_OnlyYieldsValuesWhereMaybeHasValue() { Assert.IsTrue(Enumerable.Range(1, 10) .SelectMaybe((i, x) => x.ToMaybe().Where(y => i % 2 == 0)) .SequenceEqual(new[] { 1, 3, 5, 7, 9 })); } private static IEnumerable<int> GetRange(int start, int end, Action after) { foreach (int i in Enumerable.Range(start, end)) yield return i; if (after != null) after(); } public class Recursive { public Recursive(int value, params Recursive[] recursives) { Value = value; Recursives = recursives; } public int Value { get; private set; } public Recursive[] Recursives { get; private set; } } public class TestSubject { public int Number { get; set; } public string Text { get; set; } } } }
using System; using System.Collections.Generic; /// <summary> /// Dictionary.KeyCollection.CopyTo(TKey[],Int32) /// </summary> public class KeyCollectionCopyTo { private const int SIZE = 10; public static int Main() { KeyCollectionCopyTo keycollectCopyTo = new KeyCollectionCopyTo(); TestLibrary.TestFramework.BeginTestCase("KeyCollectionCopyTo"); if (keycollectCopyTo.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method CopyTo in the KeyCollection 1"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; keys.CopyTo(TKeys, 0); string strKeys = null; for (int i = 0; i < TKeys.Length; i++) { if (TKeys[i] != null) { strKeys += TKeys[i].ToString(); } } if (TKeys[0].ToString() != "str1" || TKeys[1].ToString() != "str2" || strKeys != "str1str2") { TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in the KeyCollection 2"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; keys.CopyTo(TKeys, 5); string strKeys = null; for (int i = 0; i < TKeys.Length; i++) { if (TKeys[i] != null) { strKeys += TKeys[i].ToString(); } } if (TKeys[5].ToString() != "str1" || TKeys[6].ToString() != "str2" || strKeys != "str1str2") { TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method CopyTo in the KeyCollection 3"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; keys.CopyTo(TKeys, 0); for (int i = 0; i < TKeys.Length; i++) { if (TKeys[i] != null) { TestLibrary.TestFramework.LogError("005", "the ExpecResult is not the ActualResult"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The argument array is null"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = null; keys.CopyTo(TKeys, 0); TestLibrary.TestFramework.LogError("N001", "The argument array is null but not throw exception"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:The argument index is less than zero"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; int index = -1; keys.CopyTo(TKeys, index); TestLibrary.TestFramework.LogError("N003", "The argument index is less than zero but not throw exception"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3:The argument index is larger than array length"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; int index = SIZE + 1; keys.CopyTo(TKeys, index); TestLibrary.TestFramework.LogError("N005", "The argument index is larger than array length but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4:The number of elements in the source Dictionary.KeyCollection is greater than the available space from index to the end of the destination array"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str1", "Test1"); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; int index = SIZE - 1; keys.CopyTo(TKeys, index); TestLibrary.TestFramework.LogError("N007", "The ExpectResult should throw exception but the ActualResult not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion }
// // 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.Data; using System.Runtime.InteropServices; namespace IBM.Data.DB2 { public class DB2Command : System.ComponentModel.Component, IDbCommand, ICloneable { #region Private data members private WeakReference refDataReader; private string commandText; private CommandType commandType = CommandType.Text; private DB2Connection db2Conn; private DB2Transaction db2Trans; private int commandTimeout = 30; private bool prepared = false; private bool binded = false; private IntPtr hwndStmt = IntPtr.Zero; //Our statement handle private DB2ParameterCollection parameters = new DB2ParameterCollection(); private bool disposed = false; private bool statementOpen; private CommandBehavior previousBehavior; private UpdateRowSource updatedRowSource = UpdateRowSource.Both; private IntPtr statementParametersMemory; private int statementParametersMemorySize; #endregion #region Constructors public DB2Command() { hwndStmt = IntPtr.Zero; } public DB2Command(string commandStr):this() { commandText = commandStr; } public DB2Command(string commandStr, DB2Connection con) : this() { db2Conn = con; commandText = commandStr; if(con != null) { con.AddCommand(this); } } public DB2Command (string commandStr, DB2Connection con, DB2Transaction trans) { commandText = commandStr; db2Conn = con; db2Trans = trans; if(con != null) { con.AddCommand(this); } } #endregion #region Dispose public new void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { if(!disposed) { if(disposing) { ConnectionClosed(); if(db2Conn != null) { db2Conn.RemoveCommand(this); db2Conn = null; } } if(statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } } base.Dispose(disposing); disposed = true; } ~DB2Command() { Dispose(false); } internal void DataReaderClosed() { CloseStatementHandle(false); if((previousBehavior & CommandBehavior.CloseConnection) != 0) Connection.Close(); refDataReader = null; } private void CloseStatementHandle(bool dispose) { if(hwndStmt != IntPtr.Zero) { if(statementOpen) { short sqlRet = DB2CLIWrapper.SQLFreeStmt(hwndStmt, DB2Constants.SQL_CLOSE); } if((!prepared && statementOpen) || dispose) { short sqlRet = DB2CLIWrapper.SQLFreeHandle(DB2Constants.SQL_HANDLE_STMT, hwndStmt); hwndStmt = IntPtr.Zero; prepared = false; } statementOpen = false; } } internal void ConnectionClosed() { DB2DataReader reader = null; if((refDataReader != null) && refDataReader.IsAlive) { reader = (DB2DataReader)refDataReader.Target; } if((reader != null) && refDataReader.IsAlive) { reader.Dispose(); refDataReader = null; } CloseStatementHandle(true); db2Trans = null; } #endregion #region SelfDescribe property /// /// Property dictates whether or not any paramter markers will get their describe info /// from the database, or if the user will supply the information /// bool selfDescribe = false; public bool SelfDescribe { get { return selfDescribe; } set { selfDescribe = value; } } #endregion #region CommandText property /// ///The query; If it gets set, reset the prepared property /// public string CommandText { get { return commandText; } set { prepared = false; commandText = value; } } #endregion #region CommandTimeout property /// /// The Timeout property states how long we wait for results to return /// public int CommandTimeout { get { return commandTimeout; } set { commandTimeout = value; if(hwndStmt != IntPtr.Zero) SetStatementTimeout(); } } #endregion #region CommandType property public CommandType CommandType { get { return commandType; } set { commandType = value; } } #endregion #region Connection property /// /// The connection we'll be executing on. /// IDbConnection IDbCommand.Connection { get { return db2Conn; } set { db2Conn = (DB2Connection)value; } } public DB2Connection Connection { get { return db2Conn; } set { if(db2Conn != null) { db2Conn.RemoveCommand(this); } db2Conn = value; if(db2Conn != null) { db2Conn.AddCommand(this); } } } #endregion #region Parameters property /// /// Parameter list, Not yet implemented /// public DB2ParameterCollection Parameters { get { return parameters; } } IDataParameterCollection IDbCommand.Parameters { get { return parameters; } } #endregion #region Transaction property /// /// The transaction this command is associated with /// IDbTransaction IDbCommand.Transaction { get { return db2Trans; } set { db2Trans = (DB2Transaction)value; } } public DB2Transaction Transaction { get { return db2Trans; } set { db2Trans = value; } } #endregion #region UpdatedRowSource property public UpdateRowSource UpdatedRowSource { get { return updatedRowSource; } set { updatedRowSource = value; } } #endregion #region Statement Handle /// /// returns the DB2Client statement handle /// public IntPtr statementHandle { get { return hwndStmt; } } #endregion #region AllocateStatement function internal void AllocateStatement(string location) { if (db2Conn.DBHandle.ToInt32() == 0) return; short sqlRet; sqlRet = DB2CLIWrapper.SQLAllocHandle(DB2Constants.SQL_HANDLE_STMT, db2Conn.DBHandle, out hwndStmt); if ((sqlRet != DB2Constants.SQL_SUCCESS) && (sqlRet != DB2Constants.SQL_SUCCESS_WITH_INFO)) throw new DB2Exception(DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, location +": Unable to allocate statement handle."); parameters.HwndStmt = hwndStmt; SetStatementTimeout(); } private void SetStatementTimeout() { short sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_QUERY_TIMEOUT, new IntPtr(commandTimeout), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set statement timeout.", db2Conn); } #endregion #region Cancel /// <summary> /// Attempt to cancel an executing command /// </summary> public void Cancel() { if(hwndStmt == IntPtr.Zero) { throw new InvalidOperationException("Nothing to Cancel."); } DB2CLIWrapper.SQLCancel(hwndStmt); } #endregion #region CreateParameter /// ///Returns a parameter /// public IDbDataParameter CreateParameter() { return new DB2Parameter(); } #endregion #region ExecuteNonQuery public int ExecuteNonQuery() { ExecuteNonQueryInternal(CommandBehavior.Default); int numRows; //How many rows affected. numRows will be -1 if we aren't dealing with an Insert, Delete or Update, or if the statement did not execute successfully short sqlRet = DB2CLIWrapper.SQLRowCount(hwndStmt, out numRows); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn); do { sqlRet = DB2CLIWrapper.SQLMoreResults(this.hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "DB2ClientDataReader - SQLMoreResults", db2Conn); } while(sqlRet != DB2Constants.SQL_NO_DATA_FOUND); CloseStatementHandle(false); return numRows; } public void ExecuteNonQueryInternal(CommandBehavior behavior) { short sqlRet; if(prepared && binded) { sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn); return; } if((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); if((refDataReader != null) && (refDataReader.IsAlive)) throw new InvalidOperationException("There is already an open DataReader associated with this Connection which must be closed first."); DB2Transaction connectionTransaction = null; if(db2Conn.WeakRefTransaction != null) connectionTransaction = (DB2Transaction)db2Conn.WeakRefTransaction.Target; if(!Object.ReferenceEquals(connectionTransaction, Transaction)) { if(Transaction == null) throw new InvalidOperationException("A transaction was started in the connection, but the command doesn't specify a transaction"); throw new InvalidOperationException("The transaction specified at the connection doesn't belong to the connection"); } if (hwndStmt == IntPtr.Zero) { AllocateStatement("InternalExecuteNonQuery"); previousBehavior = 0; } if(previousBehavior != behavior) { if(((previousBehavior ^ behavior) & CommandBehavior.SchemaOnly) != 0) { sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_DEFERRED_PREPARE, new IntPtr((behavior & CommandBehavior.SchemaOnly) != 0 ? 0 : 1), 0); // TODO: don't check. what if it is not supported??? DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Defered prepare.", db2Conn); previousBehavior = (previousBehavior & ~CommandBehavior.SchemaOnly) | (behavior & CommandBehavior.SchemaOnly); } if(((previousBehavior ^ behavior) & CommandBehavior.SingleRow) != 0) { sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_MAX_ROWS, new IntPtr((behavior & CommandBehavior.SingleRow) == 0 ? 0 : 1), 0); // TODO: don't check. what if it is not supported??? DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set max rows", db2Conn); previousBehavior = (previousBehavior & ~CommandBehavior.SingleRow) | (behavior & CommandBehavior.SingleRow); } previousBehavior = behavior; } if((Transaction == null) && !db2Conn.openConnection.autoCommit) { sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_AUTOCOMMIT, new IntPtr(DB2Constants.SQL_AUTOCOMMIT_ON), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting AUTOCOMMIT ON in transaction CTOR.", db2Conn); db2Conn.openConnection.autoCommit = true; sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_TXN_ISOLATION, new IntPtr(DB2Constants.SQL_TXN_READ_COMMITTED), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting isolation level.", db2Conn); } if ((commandText == null) ||(commandText.Length == 0)) throw new InvalidOperationException("Command string is empty"); if(CommandType.StoredProcedure == commandType && !commandText.StartsWith("CALL ")) commandText = "CALL " + commandText + " ()"; if((behavior & CommandBehavior.SchemaOnly) != 0) { if(!prepared) { Prepare(); } } else { if(statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } BindParams(); if (prepared) { sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn); } else { sqlRet = DB2CLIWrapper.SQLExecDirect(hwndStmt, commandText, commandText.Length); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn); } statementOpen = true; parameters.GetOutValues(); if(statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } } } #endregion #region ExecuteReader calls /// ///ExecuteReader /// IDataReader IDbCommand.ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) { return ExecuteReader(behavior); } public DB2DataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } public DB2DataReader ExecuteReader(CommandBehavior behavior) { if((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); DB2DataReader reader; ExecuteNonQueryInternal(behavior); reader = new DB2DataReader(db2Conn, this, behavior); refDataReader = new WeakReference(reader); return reader; } #endregion #region ExecuteScalar /// /// ExecuteScalar /// public object ExecuteScalar() { if((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); using(DB2DataReader reader = ExecuteReader(CommandBehavior.SingleResult | CommandBehavior.SingleRow)) { if(reader.Read() && (reader.FieldCount > 0)) { return reader[0]; } } return null; } #endregion #region Prepare () public void Prepare () { if((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); CloseStatementHandle(false); if (hwndStmt == IntPtr.Zero) { AllocateStatement("InternalExecuteNonQuery"); } short sqlRet = 0; IntPtr numParams = IntPtr.Zero; sqlRet = DB2CLIWrapper.SQLPrepare(hwndStmt, commandText, commandText.Length); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLPrepare error.", db2Conn); statementOpen = true; prepared=true; } #endregion private string AddCallParam( string _cmString) { if(_cmString.IndexOf("()") != -1) { return _cmString.Replace("()","(?)"); } return _cmString.Replace(")", ",?)"); } private void BindParams() { if(parameters.Count > 0) { statementParametersMemorySize = 0; int offset = 0; short sqlRet; for(int i = 0; i < parameters.Count; i++) { if(commandType == CommandType.StoredProcedure) { commandText = AddCallParam(commandText); } DB2Parameter param = parameters[i]; param.CalculateRequiredmemory(); statementParametersMemorySize += param.requiredMemory + 8; param.internalBuffer = Marshal.AllocHGlobal(param.requiredMemory); offset += param.requiredMemory; param.internalLengthBuffer = Marshal.AllocHGlobal(4); Marshal.WriteInt32(param.internalLengthBuffer, param.requiredMemory); sqlRet = param.Bind(this.hwndStmt, (short)(i + 1)); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Error binding parameter in DB2Command: ", db2Conn); } binded = true; } } #region ICloneable Members object ICloneable.Clone() { DB2Command clone = new DB2Command(); clone.Connection = Connection; clone.commandText = commandText; clone.commandType = commandType; clone.Transaction = db2Trans; clone.commandTimeout = commandTimeout; clone.updatedRowSource = updatedRowSource; clone.parameters = new DB2ParameterCollection(); for(int i = 0; i < parameters.Count; i++) clone.Parameters.Add(((ICloneable)parameters[i]).Clone()); return clone; } #endregion } }
// // Shuffler.cs // // Author: // Gabriel Burt <[email protected]> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using Mono.Addins; using Hyena; using Hyena.Data; using Hyena.Data.Sqlite; using Banshee.ServiceStack; using Banshee.PlaybackController; using System.Collections.Generic; using Hyena.Collections; namespace Banshee.Collection.Database { public enum ShuffleModificationType { Discard = 0, Insertion = 1 } public class Shuffler { public static readonly Shuffler Playback = new Shuffler (true); private static string shuffles_sql = "INSERT OR REPLACE INTO CoreShuffles (ShufflerID, LastShuffledAt, TrackID) "; private static string modify_sql = "INSERT OR REPLACE INTO CoreShuffleModifications (ShufflerID, LastModifiedAt, ModificationType, TrackID) "; private static HyenaSqliteCommand add_shuffle_cmd = new HyenaSqliteCommand (String.Format ("{0} VALUES (?, ?, ?)", shuffles_sql)); private static HyenaSqliteCommand add_discard_cmd = new HyenaSqliteCommand (String.Format ("{0} VALUES (?, ?, ?, ?)", modify_sql)); private DateTime random_began_at = DateTime.MinValue; private DateTime last_random = DateTime.MinValue; private List<RandomBy> random_modes; private Dictionary<TypeExtensionNode, RandomBy> node_map = new Dictionary<TypeExtensionNode, RandomBy> (); private DatabaseTrackListModel model; private TrackInfo last_track; public string Id { get; private set; } public long DbId { get; private set; } public Action<RandomBy> RandomModeAdded; public Action<RandomBy> RandomModeRemoved; public IList<RandomBy> RandomModes { get { return random_modes; } } private Shuffler (bool playback) : this () { Id = "playback"; DbId = 0; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, Banshee.MediaEngine.PlayerEvent.StartOfStream); } private void OnPlayerEvent (Banshee.MediaEngine.PlayerEventArgs args) { last_track = ServiceManager.PlayerEngine.CurrentTrack; } public Shuffler (string id) : this () { Id = id; LoadOrCreate (); } private Shuffler () { random_modes = new List<RandomBy> (); AddinManager.AddExtensionNodeHandler ("/Banshee/PlaybackController/ShuffleModes", OnExtensionChanged); } private void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { var tnode = (TypeExtensionNode)args.ExtensionNode; RandomBy random_by = null; if (args.Change == ExtensionChange.Add) { lock (random_modes) { try { random_by = (RandomBy) tnode.CreateInstance (); random_by.SetShuffler (this); random_modes.Add (random_by); node_map[tnode] = random_by; } catch (Exception e) { Log.Exception (String.Format ("Failed to load RandomBy extension: {0}", args.Path), e); } } if (random_by != null) { if (!random_by.GetType ().AssemblyQualifiedName.Contains ("Banshee.Service")) { Log.DebugFormat ("Loaded new mode into {0} shuffler: {1}", this.Id, random_by.Id); } var handler = RandomModeAdded; if (handler != null) { handler (random_by); } } } else { lock (random_modes) { if (node_map.ContainsKey (tnode)) { random_by = node_map[tnode]; node_map.Remove (tnode); random_modes.Remove (random_by); } } if (random_by != null) { Log.DebugFormat ("Removed mode from {0} shuffler: {1}", this.Id, random_by.Id); var handler = RandomModeRemoved; if (handler != null) { handler (random_by); } } } } public void SetModelAndCache (DatabaseTrackListModel model, IDatabaseTrackModelCache cache) { this.model = model; foreach (var random in random_modes) { random.SetModelAndCache (model, cache); } } public TrackInfo GetRandom (DateTime notPlayedSince, string mode, bool repeat, bool resetSinceTime) { lock (this) { if (this == Playback) { if (model.Count == 0) { return null; } } else { if (model.UnfilteredCount == 0) { return null; } } if (random_began_at < notPlayedSince) { random_began_at = last_random = notPlayedSince; } TrackInfo track = GetRandomTrack (mode, repeat, resetSinceTime); if (track == null && (repeat || mode != "off")) { random_began_at = (random_began_at == last_random) ? DateTime.Now : last_random; track = GetRandomTrack (mode, repeat, true); } last_random = DateTime.Now; return track; } } internal void RecordShuffle (DatabaseTrackInfo track) { if (track != null) { RecordShuffle (track.TrackId); } } internal void RecordShuffle (long trackId) { ServiceManager.DbConnection.Execute (add_shuffle_cmd, this.DbId, DateTime.Now, trackId); } public void RecordShuffleModification (long trackId, ShuffleModificationType type) { ServiceManager.DbConnection.Execute (add_discard_cmd, this.DbId, DateTime.Now, (int)type, trackId); } public void RecordInsertions (DatabaseTrackListModel model, RangeCollection.Range range) { RecordShuffleModifications (model, range, ShuffleModificationType.Insertion); } public void RecordShuffleModifications (DatabaseTrackListModel model, RangeCollection.Range range, ShuffleModificationType type) { ServiceManager.DbConnection.Execute (String.Format ("{0} SELECT ?, ?, ?, {1}", modify_sql, model.TrackIdsSql), DbId, DateTime.Now, (int)type, model.CacheId, range.Start, range.Count); } private TrackInfo GetRandomTrack (string mode, bool repeat, bool resetSinceTime) { foreach (var r in random_modes) { if (resetSinceTime || r.Id != mode) { r.Reset (); } } var random = random_modes.FirstOrDefault (r => r.Id == mode); if (random != null) { if (last_track != null && !resetSinceTime) { random.SetLastTrack (last_track); } if (!random.IsReady) { if (!random.Next (random_began_at) && repeat) { random_began_at = last_random; random.Next (random_began_at); } } if (random.IsReady) { return random.GetTrack (random_began_at); } } return null; } private void LoadOrCreate () { var db = ServiceManager.DbConnection; long res = db.Query<long> ("SELECT ShufflerID FROM CoreShufflers WHERE ID = ?", Id); if (res > 0) { DbId = res; } else { DbId = db.Execute ("INSERT INTO CoreShufflers (ID) VALUES (?)", Id); } } } }
// <copyright file="SparseMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single { /// <summary> /// Sparse matrix tests. /// </summary> public class SparseMatrixTests : MatrixTests { /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<float> CreateMatrix(int rows, int columns) { return new SparseMatrix(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<float> CreateMatrix(float[,] data) { return SparseMatrix.OfArray(data); } /// <summary> /// Can create a matrix form array. /// </summary> [Test] public void CanCreateMatrixFrom1DArray() { var testData = new Dictionary<string, Matrix<float>> { {"Singular3x3", SparseMatrix.OfColumnMajor(3, 3, new float[] {1, 1, 1, 1, 1, 1, 2, 2, 2})}, {"Square3x3", SparseMatrix.OfColumnMajor(3, 3, new[] {-1.1f, 0.0f, -4.4f, -2.2f, 1.1f, 5.5f, -3.3f, 2.2f, 6.6f})}, {"Square4x4", SparseMatrix.OfColumnMajor(4, 4, new[] {-1.1f, 0.0f, 1.0f, -4.4f, -2.2f, 1.1f, 2.1f, 5.5f, -3.3f, 2.2f, 6.2f, 6.6f, -4.4f, 3.3f, 4.3f, -7.7f})}, {"Tall3x2", SparseMatrix.OfColumnMajor(3, 2, new[] {-1.1f, 0.0f, -4.4f, -2.2f, 1.1f, 5.5f})}, {"Wide2x3", SparseMatrix.OfColumnMajor(2, 3, new[] {-1.1f, 0.0f, -2.2f, 1.1f, -3.3f, 2.2f})} }; foreach (var name in testData.Keys) { Assert.AreEqual(TestMatrices[name], testData[name]); } } /// <summary> /// Matrix from array is a copy. /// </summary> [Test] public void MatrixFrom1DArrayIsCopy() { // Sparse Matrix copies values from float[], but no remember reference. var data = new float[] {1, 1, 1, 1, 1, 1, 2, 2, 2}; var matrix = SparseMatrix.OfColumnMajor(3, 3, data); matrix[0, 0] = 10.0f; Assert.AreNotEqual(10.0f, data[0]); } /// <summary> /// Matrix from two-dimensional array is a copy. /// </summary> [Test] public void MatrixFrom2DArrayIsCopy() { var matrix = SparseMatrix.OfArray(TestData2D["Singular3x3"]); matrix[0, 0] = 10.0f; Assert.AreEqual(1.0f, TestData2D["Singular3x3"][0, 0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = SparseMatrix.OfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = SparseMatrix.CreateIdentity(5); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0f : 0.0f, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => SparseMatrix.CreateIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeSparseMatrix() { var matrix = new SparseMatrix(500, 1000); var nonzero = 0; var rnd = new System.Random(0); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { var value = rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10); if (value != 0) { nonzero++; } matrix[i, j] = value; } } Assert.AreEqual(matrix.NonZerosCount, nonzero); } /// <summary> /// Test whether order matters when adding sparse matrices. /// </summary> [Test] public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); var sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); var denseResult = new DenseMatrix(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); } /// <summary> /// Test whether order matters when subtracting sparse matrices. /// </summary> [Test] public void CanSubtractSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); var diff1 = m1 - m2; var diff2 = m2 - m1; Assert.IsTrue(diff1.Equals(m2.Negate())); Assert.IsTrue(diff1.Equals(diff2.Negate())); var sparseResult = new SparseMatrix(1, 3); sparseResult.Subtract(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Subtract(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(diff2)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); m1.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new float[,] { { 0, 1, 1 } }); sparseResult.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(0*diff1)); var denseResult = new DenseMatrix(1, 3); denseResult.Subtract(m2, denseResult); Assert.IsTrue(denseResult.Equals(diff1)); denseResult = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); denseResult.Subtract(m1, denseResult); Assert.IsTrue(denseResult.Equals(diff2)); var m3 = DenseMatrix.OfArray(new float[,] {{0, 1, 1}}); var diff3 = m1 - m3; var diff4 = m3 - m1; Assert.IsTrue(diff3.Equals(m3.Negate())); Assert.IsTrue(diff3.Equals(diff4.Negate())); } /// <summary> /// Test whether we can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeMatrix() { const int Order = 1000000; var matrix = new SparseMatrix(Order); Assert.AreEqual(Order, matrix.RowCount); Assert.AreEqual(Order, matrix.ColumnCount); Assert.DoesNotThrow(() => matrix[0, 0] = 1); } } }
namespace iTin.Export.Model { using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; using Helpers; /// <inheritdoc /> /// <summary> /// Reference to set of properties that allow you to specify a writer. /// </summary> /// <remarks> /// <para> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Filter .../&gt; /// </code> /// </para> /// <para><strong>Attributes</strong></para> /// <table> /// <thead> /// <tr> /// <th>Attribute</th> /// <th>Optional</th> /// <th>Description</th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td><see cref="P:iTin.Export.Model.FilterModel.Author" /></td> /// <td align="center">Yes</td> /// <td>Author of writer. Select * for any author. The default is "<c>*</c>".</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.FilterModel.Company" /></td> /// <td align="center">Yes</td> /// <td>Company name of the writer. Select * for any author. The default is "<c>*</c>".</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.FilterModel.Version" /></td> /// <td align="center">Yes</td> /// <td>Version of the writer, value greater than 0. Select * for any author. The default is "<c>*</c>".</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.FilterModel.Path" /></td> /// <td align="center">Yes</td> /// <td>Path where is located the writer. To specify a relative path use the character (~). The default is "<c>Default</c>".</td> /// </tr> /// </tbody> /// </table> /// </remarks> public partial class FilterModel { #region private constants [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultAuthor = "*"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultCompany = "*"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultVersion = "*"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultPath = "Default"; #endregion #region field members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string _path; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private WriterModelBase _parent; #endregion #region constructor/s #region [public] FilterModel(): Initializes a new instance of this class /// <summary> /// Initializes a new instance of the <see cref="T:iTin.Export.Model.FilterModel"/> class. /// </summary> public FilterModel() { Path = DefaultPath; Author = DefaultAuthor; Company = DefaultCompany; Version = DefaultVersion; } #endregion #endregion #region public properties #region [public] (string) Author: Gets or sets the author of writer /// <summary> /// Gets or sets the author of writer. Select * for any author. /// </summary> /// <value> /// Author of writer. Select * for any author. The default is "<c>*</c>". /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Filter Author="*|string" .../&gt; /// </code> /// </remarks> [XmlAttribute] [DefaultValue(DefaultAuthor)] public string Author { get; set; } #endregion #region [public] (string) Company: Gets or sets the company name of the writer /// <summary> /// Gets or sets the company name of the writer. /// </summary> /// <value> /// Company name of the writer. Select * for any author. The default is "<c>*</c>". /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Filter Company="*|string" .../&gt; /// </code> /// </remarks> [XmlAttribute] [DefaultValue(DefaultCompany)] public string Company { get; set; } #endregion #region [public] (string) Version: Gets or sets the version of the writer /// <summary> /// Gets or sets the version of the writer. /// </summary> /// <value> /// Version of the writer, value greater than 0. Select * for any author. The default is "<c>*</c>". /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Filter Version="*|string" .../&gt; /// </code> /// </remarks> [XmlAttribute] [DefaultValue(DefaultVersion)] public string Version { get; set; } #endregion #region [public] (WriterModelBase) Parent: Gets the parent element of the element /// <summary> /// Gets the parent element of the element. /// </summary> /// <value> /// The element that represents the container element of the element. /// </value> [XmlIgnore] [Browsable(false)] public WriterModelBase Parent => _parent; #endregion #region [public] (string) Path: Gets or sets the path where is located the writer /// <summary> /// Gets or sets the path where is located the writer. /// </summary> /// <value> /// Path where is located the writer. To specify a relative path use the character (~). The default is "<c>Default</c>". /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;Filter Path="Default|string" .../&gt; /// </code> /// </remarks> /// <exception cref="T:System.ArgumentNullException">If <paramref name="value" /> is <strong>null</strong>.</exception> /// <exception cref="T:iTin.Export.Model.InvalidPathNameException">If <paramref name="value" /> is an invalid path name.</exception> [XmlAttribute] [DefaultValue(DefaultPath)] public string Path { get => _path; set { SentinelHelper.ArgumentNull(value); SentinelHelper.IsFalse(RegularExpressionHelper.IsValidPath(value), new InvalidPathNameException(ErrorMessageHelper.ModelPathErrorMessage("Path", value))); _path = value; } } #endregion #region [public] (KnownWriterFilter) WriterStyles: Gets a value that represents the different attributes defined for a writer /// <summary> /// Gets a value that represents the different attributes defined for a writer. /// </summary> /// <value> /// Writer attributes. /// </value> public KnownWriterFilter WriterStyles { get { var writerStyles = KnownWriterFilter.Name; if (!Author.Equals(DefaultAuthor)) { writerStyles = writerStyles | KnownWriterFilter.Author; } if (!Version.Equals(DefaultVersion)) { writerStyles = writerStyles | KnownWriterFilter.Version; } if (!Company.Equals(DefaultCompany)) { writerStyles = writerStyles | KnownWriterFilter.Company; } return writerStyles; } } #endregion #endregion #region public override properties #region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default /// <inheritdoc /> /// <summary> /// Gets a value indicating whether this instance is default. /// </summary> /// <value> /// <strong>true</strong> if this instance contains the default; otherwise <strong>false</strong>. /// </value> public override bool IsDefault => Path.Equals(DefaultPath) && Author.Equals(DefaultAuthor) && Company.Equals(DefaultCompany) && Version.Equals(DefaultVersion); #endregion #endregion #region internal methods #region [internal] (void) SetParent(WriterModelBase): Sets the parent element of the element /// <summary> /// Sets the parent element of the element. /// </summary> /// <param name="reference">Reference to parent.</param> internal void SetParent(WriterModelBase reference) { _parent = reference; } #endregion #endregion } }
// // Task.cs // // Author: // Antonius Riha <[email protected]> // // Copyright (c) 2012 Antonius Riha // // 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.ComponentModel; using System.Collections.ObjectModel; using System.Diagnostics; namespace Tasque { public abstract class Task : IComparable<Task>, INotifyPropertyChanged { protected Task (string name, TaskNoteSupport noteSupport) { Name = name; notes = new ObservableCollection<TaskNote> (); Notes = new ReadOnlyObservableCollection<TaskNote> (notes); NoteSupport = noteSupport; } #region Properties public string Name { get { return name; } set { if (value == null) throw new ArgumentNullException ("name"); if (value != name) { name = value; OnNameChanged (); OnPropertyChanged ("Name"); } } } public DateTime DueDate { get { return dueDate; } set { if (value != dueDate) { Debug.WriteLine ("Setting new task due date"); dueDate = value; OnDueDateChanged (); OnPropertyChanged ("DueDate"); } } } public DateTime CompletionDate { get { return completionDate; } protected set { if (value != completionDate) { Debug.WriteLine ("Setting new task completion date"); completionDate = value; OnCompletionDateChanged (); OnPropertyChanged ("CompletionDate"); } } } public bool HasNotes { get { return Notes.Count > 0; } } public bool IsComplete { get { return State == TaskState.Completed; } } public bool IsCompletionDateSet { get { return CompletionDate != DateTime.MinValue; } } public bool IsDueDateSet { get { return DueDate != DateTime.MinValue; } } public ReadOnlyObservableCollection<TaskNote> Notes { get; private set; } public TaskPriority Priority { get { return priority; } set { if (value != priority) { Debug.WriteLine ("Setting new task priority"); priority = value; OnPriorityChanged (); OnPropertyChanged ("Priority"); } } } public TaskState State { get { return state; } protected set { if (state != value) { state = value; OnStateChanged (); OnPropertyChanged ("State"); } } } public uint TimerID { get; set; } public TaskNoteSupport NoteSupport { get; private set; } #endregion #region Methods public void Activate () { Debug.WriteLine ("Task.Activate ()"); CompletionDate = DateTime.MinValue; State = TaskState.Active; OnActivate (); } protected virtual void OnActivate () {} public void Inactivate () { Debug.WriteLine ("Task.Inactivate ()"); CompletionDate = DateTime.Now; State = TaskState.Inactive; OnInactivate (); } protected virtual void OnInactivate () {} public void AddNote (TaskNote note) { if (note == null) throw new ArgumentNullException ("note"); if (notes.Contains (note)) return; OnAddNote (note); notes.Add (note); } public int CompareTo (Task task) { if (task == null) return 1; bool isSameDate = true; if (DueDate.Year != task.DueDate.Year || DueDate.DayOfYear != task.DueDate.DayOfYear) isSameDate = false; if (!isSameDate) { if (DueDate == DateTime.MinValue) { // No due date set on this task. Since we already tested to see // if the dates were the same above, we know that the passed-in // task has a due date set and it should be "higher" in a sort. return 1; } else if (task.DueDate == DateTime.MinValue) { // This task has a due date and should be "first" in sort order. return -1; } int result = DueDate.CompareTo (task.DueDate); if (result != 0) return result; } // The due dates match, so now sort based on priority and name return CompareToByPriorityAndName (task); } public void Complete () { Debug.WriteLine ("Task.Complete ()"); CompletionDate = DateTime.Now; State = TaskState.Completed; OnComplete (); } protected virtual void OnComplete () {} public abstract TaskNote CreateNote (string text); public void Delete () { Debug.WriteLine ("Task.Delete ()"); State = TaskState.Deleted; OnDelete (); } protected virtual void OnDelete () {} public bool RemoveNote (TaskNote note) { if (notes.Contains (note)) OnRemoveNote (note); return notes.Remove (note); } protected virtual void OnAddNote (TaskNote note) {} protected virtual void OnCompletionDateChanged () {} protected virtual void OnDueDateChanged () {} protected virtual void OnNameChanged () {} protected virtual void OnPriorityChanged () {} protected void OnPropertyChanged (string propertyName) { if (PropertyChanged != null) PropertyChanged (this, new PropertyChangedEventArgs (propertyName)); } protected virtual void OnRemoveNote (TaskNote note) {} protected virtual void OnStateChanged () {} #endregion public event PropertyChangedEventHandler PropertyChanged; internal int CompareToByPriorityAndName (Task task) { // The due dates match, so now sort based on priority if (Priority != task.Priority) { switch (Priority) { case TaskPriority.High: return -1; case TaskPriority.Medium: if (task.Priority == TaskPriority.High) return 1; else return -1; case TaskPriority.Low: if (task.Priority == TaskPriority.None) return -1; else return 1; case TaskPriority.None: return 1; } } // Due dates and priorities match, now sort by name return Name.CompareTo (task.Name); } DateTime completionDate; DateTime dueDate; string name; ObservableCollection<TaskNote> notes; TaskPriority priority; TaskState state; } }
//----------------------------------------------------------------------- // <copyright file="<file>.cs" company="The Outercurve Foundation"> // Copyright (c) 2011, The Outercurve Foundation. // // Licensed under the MIT License (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.opensource.org/licenses/mit-license.php // // 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> // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir ShresTha (prabir.me)</author> // <website>https://github.com/facebook-csharp-sdk/simple-json</website> //----------------------------------------------------------------------- namespace SimpleJsonTests.DataContractTests { using System.Runtime.Serialization; #region Fields [DataContract] public class DataContractPublicReadOnlyFields { [DataMember] public readonly string DataMemberWithoutName = "dmv"; [DataMember(Name = "name")] public readonly string DatMemberWithName = "dmnv"; [IgnoreDataMember] public readonly string IgnoreDataMember = "idm"; public readonly string NoDataMember = "ndm"; } [DataContract] public class DataContractPublicFields { [DataMember] public string DataMemberWithoutName = "dmv"; [DataMember(Name = "name")] public string DatMemberWithName = "dmnv"; [IgnoreDataMember] public string IgnoreDataMember = "idm"; public string NoDataMember = "ndm"; } // Supress is assigned by its value is never used #pragma warning disable 0414 [DataContract] public class DataContractPrivateReadOnlyFields { [DataMember] private readonly string DataMemberWithoutName = "dmv"; [DataMember(Name = "name")] private readonly string DatMemberWithName = "dmnv"; [IgnoreDataMember] private readonly string IgnoreDataMember = "idm"; private readonly string NoDataMember = "ndm"; } [DataContract] public class DataContractPrivateFields { [DataMember] private string DataMemberWithoutName = "dmv"; [DataMember(Name = "name")] private string DatMemberWithName = "dmnv"; [IgnoreDataMember] private string IgnoreDataMember = "idm"; private string NoDataMember = "ndm"; } #pragma warning restore 0414 #endregion #region Getter [DataContract] public class DataContractPublicGetters { [DataMember] public string DataMemberWithoutName { get { return "dmv"; } } [DataMember(Name = "name")] public string DatMemberWithName { get { return "dmnv"; } } [IgnoreDataMember] public string IgnoreDataMember { get { return "idm"; } } public string NoDataMember { get { return "ndm"; } } } [DataContract] public class DataContractPrivateGetters { [DataMember] private string DataMemberWithoutName { get { return "dmv"; } } [DataMember(Name = "name")] private string DatMemberWithName { get { return "dmnv"; } } [IgnoreDataMember] private string IgnoreDataMember { get { return "idm"; } } private string NoDataMember { get { return "ndm"; } } } #endregion #region Setter [DataContract] public class DataContractPublicSetters { [DataMember] public string DataMemberWithoutName { set { } } [DataMember(Name = "name")] public string DatMemberWithName { set { } } [IgnoreDataMember] public string IgnoreDataMember { set { } } public string NoDataMember { set { } } } [DataContract] public class DataContractPrivateSetters { [DataMember] private string DataMemberWithoutName { set { } } [DataMember(Name = "name")] private string DatMemberWithName { set { } } [IgnoreDataMember] private string IgnoreDataMember { set { } } private string NoDataMember { set { } } } #endregion #region Getter/Setters [DataContract] public class DataContractPublicGetterSetters { public DataContractPublicGetterSetters() { DataMemberWithoutName = "dmv"; DatMemberWithName = "dmnv"; IgnoreDataMember = "idm"; NoDataMember = "ndm"; } [DataMember] public string DataMemberWithoutName { get; set; } [DataMember(Name = "name")] public string DatMemberWithName { get; set; } [IgnoreDataMember] public string IgnoreDataMember { get; set; } public string NoDataMember { get; set; } } [DataContract] public class DataContractPrivateGetterSetters { public DataContractPrivateGetterSetters() { DataMemberWithoutName = "dmv"; DatMemberWithName = "dmnv"; IgnoreDataMember = "idm"; NoDataMember = "ndm"; } [DataMember] private string DataMemberWithoutName { get; set; } [DataMember(Name = "name")] private string DatMemberWithName { get; set; } [IgnoreDataMember] private string IgnoreDataMember { get; set; } private string NoDataMember { get; set; } } #endregion }
using System; using System.Globalization; // Ported over to CoreCLR from Co7529TryParse_all.cs // Tests Int64.TryParse(String), Int64.TryParse(String, NumberStyles, IFormatProvider, ref Int64) // 2003/04/01 KatyK // 2007/06/28 adapted by MarielY public class Int64TryParse { static bool verbose = false; public static int Main() { bool passed = true; try { // Make the test culture independent TestLibrary.Utilities.CurrentCulture = CultureInfo.InvariantCulture; // Set up NFIs to use NumberFormatInfo goodNFI = new NumberFormatInfo(); NumberFormatInfo corruptNFI = new NumberFormatInfo(); // DecimalSeparator == GroupSeparator corruptNFI.NumberDecimalSeparator = "."; corruptNFI.NumberGroupSeparator = "."; corruptNFI.CurrencyDecimalSeparator = "."; corruptNFI.CurrencyGroupSeparator = "."; corruptNFI.CurrencySymbol = "$"; NumberFormatInfo swappedNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator swapped swappedNFI.NumberDecimalSeparator = "."; swappedNFI.NumberGroupSeparator = ","; swappedNFI.CurrencyDecimalSeparator = ","; swappedNFI.CurrencyGroupSeparator = "."; swappedNFI.CurrencySymbol = "$"; NumberFormatInfo distinctNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator distinct distinctNFI.NumberDecimalSeparator = "."; distinctNFI.NumberGroupSeparator = ","; distinctNFI.CurrencyDecimalSeparator = ":"; distinctNFI.CurrencyGroupSeparator = ";"; distinctNFI.CurrencySymbol = "$"; NumberFormatInfo customNFI = new NumberFormatInfo(); customNFI.NegativeSign = "^"; NumberFormatInfo ambigNFI = new NumberFormatInfo(); ambigNFI.NegativeSign = "^"; ambigNFI.CurrencySymbol = "^"; CultureInfo germanCulture = new CultureInfo("de-DE"); CultureInfo japaneseCulture; try { japaneseCulture = new CultureInfo("ja-JP"); } catch (Exception) { TestLibrary.Logging.WriteLine("East Asian Languages are not installed. Skiping Japanese culture tests."); japaneseCulture = null; } // Parse tests included for comparison/regression passed &= VerifyInt64Parse("5", 5); passed &= VerifyInt64Parse("-5", -5); passed &= VerifyInt64Parse("5 ", 5); passed &= VerifyInt64Parse("5\0", 5); passed &= VerifyInt64Parse("893382737", 893382737); passed &= VerifyInt64Parse("-893382737", -893382737); passed &= VerifyInt64Parse("1234567891", 1234567891); passed &= VerifyInt64Parse("-1234567891", -1234567891); passed &= VerifyInt64Parse("123456789123456789", 123456789123456789); passed &= VerifyInt64Parse("-123456789123456789", -123456789123456789); passed &= VerifyInt64Parse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyInt64Parse("-5", NumberStyles.Integer, CultureInfo.InvariantCulture, -5); passed &= VerifyInt64Parse("5 \0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyInt64Parse("5\0\0\0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyInt64Parse("12", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0x12); passed &= VerifyInt64Parse("fF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF); passed &= VerifyInt64Parse("FFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFFFFFFFF); passed &= VerifyInt64Parse("FFFFFFFFFFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, -1); passed &= VerifyInt64Parse("123", NumberStyles.Integer, germanCulture, 123); passed &= VerifyInt64Parse("123", NumberStyles.Integer, japaneseCulture, 123); passed &= VerifyInt64Parse("123.000", NumberStyles.Any, germanCulture, 123000); passed &= VerifyInt64Parse("123,000", NumberStyles.Any, japaneseCulture, 123000); passed &= VerifyInt64Parse("123,000", NumberStyles.AllowDecimalPoint, germanCulture, 123); passed &= VerifyInt64Parse("123.000", NumberStyles.AllowDecimalPoint, japaneseCulture, 123); passed &= VerifyInt64Parse("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5); // currency passed &= VerifyInt64Parse("5", NumberStyles.Integer, goodNFI, 5); passed &= VerifyInt64Parse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5); // passed &= VerifyInt64Parse("5", NumberStyles.Integer, corruptNFI, 5); passed &= VerifyInt64Parse("5", NumberStyles.Number, corruptNFI, 5); passed &= VerifyInt64Parse("5.0", NumberStyles.Number, corruptNFI, 5); passed &= VerifyInt64ParseException("5,0", NumberStyles.Number, corruptNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5.0.0", NumberStyles.Number, corruptNFI, typeof(FormatException)); passed &= VerifyInt64Parse("$5.0", NumberStyles.Currency, corruptNFI, 5); passed &= VerifyInt64ParseException("$5,0", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("$5.0.0", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5.0", NumberStyles.Currency, corruptNFI, 5); passed &= VerifyInt64ParseException("5,0", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5.0.0", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5.0", NumberStyles.Any, corruptNFI, 5); passed &= VerifyInt64ParseException("5,0", NumberStyles.Any, corruptNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5.0.0", NumberStyles.Any, corruptNFI, typeof(FormatException)); // passed &= VerifyInt64Parse("5", NumberStyles.Integer, swappedNFI, 5); passed &= VerifyInt64ParseException("1,234", NumberStyles.Integer, swappedNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5", NumberStyles.Number, swappedNFI, 5); passed &= VerifyInt64Parse("5.0", NumberStyles.Number, swappedNFI, 5); passed &= VerifyInt64Parse("1,234", NumberStyles.Number, swappedNFI, 1234); passed &= VerifyInt64Parse("1,234.0", NumberStyles.Number, swappedNFI, 1234); passed &= VerifyInt64ParseException("5.000.000", NumberStyles.Number, swappedNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5.000,00", NumberStyles.Number, swappedNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5.000", NumberStyles.Currency, swappedNFI, 5); //??? passed &= VerifyInt64ParseException("5.000,00", NumberStyles.Currency, swappedNFI, typeof(FormatException)); //??? passed &= VerifyInt64Parse("$5.000", NumberStyles.Currency, swappedNFI, 5000); passed &= VerifyInt64Parse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000); passed &= VerifyInt64Parse("5.000", NumberStyles.Any, swappedNFI, 5); //? passed &= VerifyInt64ParseException("5.000,00", NumberStyles.Any, swappedNFI, typeof(FormatException)); //? passed &= VerifyInt64Parse("$5.000", NumberStyles.Any, swappedNFI, 5000); passed &= VerifyInt64Parse("$5.000,00", NumberStyles.Any, swappedNFI, 5000); passed &= VerifyInt64Parse("5,0", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyInt64Parse("$5,0", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyInt64Parse("5,000", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyInt64Parse("$5,000", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyInt64ParseException("5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("$5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5,000", NumberStyles.Any, swappedNFI, 5); passed &= VerifyInt64Parse("$5,000", NumberStyles.Any, swappedNFI, 5); passed &= VerifyInt64ParseException("5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("$5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException)); // passed &= VerifyInt64Parse("5.0", NumberStyles.Number, distinctNFI, 5); passed &= VerifyInt64Parse("1,234.0", NumberStyles.Number, distinctNFI, 1234); passed &= VerifyInt64Parse("5.0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyInt64Parse("1,234.0", NumberStyles.Currency, distinctNFI, 1234); passed &= VerifyInt64Parse("5.0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyInt64Parse("1,234.0", NumberStyles.Any, distinctNFI, 1234); passed &= VerifyInt64ParseException("$5.0", NumberStyles.Currency, distinctNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("$5.0", NumberStyles.Any, distinctNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5:0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("5;0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyInt64ParseException("$5:0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyInt64Parse("5:0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyInt64Parse("5:000", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyInt64Parse("5;000", NumberStyles.Currency, distinctNFI, 5000); passed &= VerifyInt64Parse("$5:0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyInt64Parse("$5;0", NumberStyles.Currency, distinctNFI, 50); passed &= VerifyInt64Parse("5:0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyInt64Parse("5;0", NumberStyles.Any, distinctNFI, 50); passed &= VerifyInt64Parse("$5:0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyInt64Parse("$5;0", NumberStyles.Any, distinctNFI, 50); passed &= VerifyInt64ParseException("123,456;789.0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyInt64Parse("123,456;789.0", NumberStyles.Currency, distinctNFI, 123456789); passed &= VerifyInt64Parse("123,456;789.0", NumberStyles.Any, distinctNFI, 123456789); passed &= VerifyInt64ParseException("$123,456;789.0", NumberStyles.Any, distinctNFI, typeof(FormatException)); // passed &= VerifyInt64ParseException("123456789123456789123", typeof(OverflowException)); passed &= VerifyInt64ParseException("-123456789123456789123", typeof(OverflowException)); passed &= VerifyInt64ParseException("18446744073709551615", typeof(OverflowException)); passed &= VerifyInt64ParseException("Garbage", typeof(FormatException)); passed &= VerifyInt64ParseException("5\0Garbage", typeof(FormatException)); passed &= VerifyInt64ParseException(null, typeof(ArgumentNullException)); passed &= VerifyInt64ParseException("123456789123456789", NumberStyles.HexNumber, CultureInfo.InvariantCulture, typeof(OverflowException)); passed &= VerifyInt64ParseException("5.3", NumberStyles.AllowDecimalPoint, goodNFI, typeof(OverflowException)); //weird that it's Overflow, but consistent with v1 passed &= VerifyInt64ParseException("5", NumberStyles.AllowHexSpecifier | NumberStyles.AllowParentheses, null, typeof(ArgumentException)); passed &= VerifyInt64ParseException("4", (NumberStyles)(-1), typeof(ArgumentException)); passed &= VerifyInt64ParseException("4", (NumberStyles)0x10000, typeof(ArgumentException)); passed &= VerifyInt64ParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyInt64ParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyInt64ParseException("123.000.000.000.000.000.000", NumberStyles.Any, germanCulture, typeof(OverflowException)); passed &= VerifyInt64ParseException("123,000,000,000,000,000,000", NumberStyles.Any, japaneseCulture, typeof(OverflowException)); passed &= VerifyInt64ParseException("123,000,000,000,000,000,000", NumberStyles.Integer, germanCulture, typeof(FormatException)); passed &= VerifyInt64ParseException("123.000.000.000.000.000.000", NumberStyles.Integer, japaneseCulture, typeof(FormatException)); passed &= VerifyInt64ParseException("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Integer, germanCulture, typeof(FormatException)); // currency /////////// TryParse(String) //// Pass cases passed &= VerifyInt64TryParse("5", 5, true); passed &= VerifyInt64TryParse("-5", -5, true); passed &= VerifyInt64TryParse(" 5 ", 5, true); passed &= VerifyInt64TryParse("5\0", 5, true); passed &= VerifyInt64TryParse("5 \0", 5, true); passed &= VerifyInt64TryParse("5\0\0\0", 5, true); passed &= VerifyInt64TryParse("10000", 10000, true); passed &= VerifyInt64TryParse("893382737", 893382737, true); passed &= VerifyInt64TryParse("-893382737", -893382737, true); passed &= VerifyInt64TryParse("1234567891", 1234567891, true); passed &= VerifyInt64TryParse("-1234567891", -1234567891, true); passed &= VerifyInt64TryParse("123456789123456789", 123456789123456789, true); passed &= VerifyInt64TryParse("-123456789123456789", -123456789123456789, true); passed &= VerifyInt64TryParse(Int64.MaxValue.ToString(), Int64.MaxValue, true); passed &= VerifyInt64TryParse(Int64.MinValue.ToString(), Int64.MinValue, true); //// Fail cases passed &= VerifyInt64TryParse(null, 0, false); passed &= VerifyInt64TryParse("", 0, false); passed &= VerifyInt64TryParse("Garbage", 0, false); passed &= VerifyInt64TryParse("5\0Garbage", 0, false); passed &= VerifyInt64TryParse("18446744073709551615", 0, false); passed &= VerifyInt64TryParse("123456789123456789123", 0, false); passed &= VerifyInt64TryParse("-123456789123456789123", 0, false); passed &= VerifyInt64TryParse("FF", 0, false); passed &= VerifyInt64TryParse("27.3", 0, false); passed &= VerifyInt64TryParse("23 5", 0, false); /////////// TryParse(TryParse(String, NumberStyles, IFormatProvider, ref Int64) //// Pass cases passed &= VerifyInt64TryParse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5, true); passed &= VerifyInt64TryParse("-5", NumberStyles.Integer, CultureInfo.InvariantCulture, -5, true); // Variations on NumberStyles passed &= VerifyInt64TryParse("12", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0x12, true); passed &= VerifyInt64TryParse("FF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF, true); passed &= VerifyInt64TryParse("fF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF, true); passed &= VerifyInt64TryParse("FFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFFFFFFFF, true); passed &= VerifyInt64TryParse("FFFFFFFFFFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, -1, true); passed &= VerifyInt64TryParse(" 5", NumberStyles.AllowLeadingWhite, goodNFI, 5, true); passed &= VerifyInt64TryParse("5", NumberStyles.Number, goodNFI, 5, true); passed &= VerifyInt64TryParse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5, true); // Variations on IFP passed &= VerifyInt64TryParse("5", NumberStyles.Integer, goodNFI, 5, true); passed &= VerifyInt64TryParse("5", NumberStyles.Integer, null, 5, true); passed &= VerifyInt64TryParse("5", NumberStyles.Integer, new DateTimeFormatInfo(), 5, true); passed &= VerifyInt64TryParse("^42", NumberStyles.Any, customNFI, -42, true); passed &= VerifyInt64TryParse("123", NumberStyles.Integer, germanCulture, 123, true); passed &= VerifyInt64TryParse("123", NumberStyles.Integer, japaneseCulture, 123, true); passed &= VerifyInt64TryParse("123.000", NumberStyles.Any, germanCulture, 123000, true); passed &= VerifyInt64TryParse("123,000", NumberStyles.Any, japaneseCulture, 123000, true); passed &= VerifyInt64TryParse("123,000", NumberStyles.AllowDecimalPoint, germanCulture, 123, true); passed &= VerifyInt64TryParse("123.000", NumberStyles.AllowDecimalPoint, japaneseCulture, 123, true); passed &= VerifyInt64TryParse("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5, true); // currency //// Fail cases passed &= VerifyInt64TryParse("FF", NumberStyles.Integer, CultureInfo.InvariantCulture, 0, false); passed &= VerifyInt64TryParse("123456789123456789", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0, false); passed &= VerifyInt64TryParse("-42", NumberStyles.Any, customNFI, 0, false); passed &= VerifyInt64TryParse("5.3", NumberStyles.AllowDecimalPoint, goodNFI, 0, false); passed &= VerifyInt64TryParse("5 ", NumberStyles.AllowLeadingWhite, goodNFI, 0, false); passed &= VerifyInt64TryParse("123.000.000.000.000.000.000", NumberStyles.Any, germanCulture, 0, false); passed &= VerifyInt64TryParse("123,000,000,000,000,000,000", NumberStyles.Any, japaneseCulture, 0, false); passed &= VerifyInt64TryParse("123,000,000,000,000,000,000", NumberStyles.Integer, germanCulture, 0, false); passed &= VerifyInt64TryParse("123.000.000.000.000.000.000", NumberStyles.Integer, japaneseCulture, 0, false); //// Exception cases passed &= VerifyInt64TryParseException("5", NumberStyles.AllowHexSpecifier | NumberStyles.AllowParentheses, null, typeof(ArgumentException)); passed &= VerifyInt64TryParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyInt64TryParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException)); // NumberStyles/NFI variations // passed &= VerifyInt64TryParse("5", NumberStyles.Integer, corruptNFI, 5, true); passed &= VerifyInt64TryParse("5", NumberStyles.Number, corruptNFI, 5, true); passed &= VerifyInt64TryParse("5.0", NumberStyles.Number, corruptNFI, 5, true); passed &= VerifyInt64TryParse("5,0", NumberStyles.Number, corruptNFI, 0, false); passed &= VerifyInt64TryParse("5.0.0", NumberStyles.Number, corruptNFI, 0, false); passed &= VerifyInt64TryParse("$5.0", NumberStyles.Currency, corruptNFI, 5, true); passed &= VerifyInt64TryParse("$5,0", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyInt64TryParse("$5.0.0", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyInt64TryParse("5.0", NumberStyles.Currency, corruptNFI, 5, true); passed &= VerifyInt64TryParse("5,0", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyInt64TryParse("5.0.0", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyInt64TryParse("5.0", NumberStyles.Any, corruptNFI, 5, true); passed &= VerifyInt64TryParse("5,0", NumberStyles.Any, corruptNFI, 0, false); passed &= VerifyInt64TryParse("5.0.0", NumberStyles.Any, corruptNFI, 0, false); // passed &= VerifyInt64TryParse("5", NumberStyles.Integer, swappedNFI, 5, true); passed &= VerifyInt64TryParse("1,234", NumberStyles.Integer, swappedNFI, 0, false); passed &= VerifyInt64TryParse("5", NumberStyles.Number, swappedNFI, 5, true); passed &= VerifyInt64TryParse("5.0", NumberStyles.Number, swappedNFI, 5, true); passed &= VerifyInt64TryParse("1,234", NumberStyles.Number, swappedNFI, 1234, true); passed &= VerifyInt64TryParse("1,234.0", NumberStyles.Number, swappedNFI, 1234, true); passed &= VerifyInt64TryParse("5.000.000", NumberStyles.Number, swappedNFI, 0, false); passed &= VerifyInt64TryParse("5.000,00", NumberStyles.Number, swappedNFI, 0, false); passed &= VerifyInt64TryParse("5.000", NumberStyles.Currency, swappedNFI, 5, true); //??? passed &= VerifyInt64TryParse("5.000,00", NumberStyles.Currency, swappedNFI, 0, false); //??? passed &= VerifyInt64TryParse("$5.000", NumberStyles.Currency, swappedNFI, 5000, true); passed &= VerifyInt64TryParse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000, true); passed &= VerifyInt64TryParse("5.000", NumberStyles.Any, swappedNFI, 5, true); //? passed &= VerifyInt64TryParse("5.000,00", NumberStyles.Any, swappedNFI, 0, false); //? passed &= VerifyInt64TryParse("$5.000", NumberStyles.Any, swappedNFI, 5000, true); passed &= VerifyInt64TryParse("$5.000,00", NumberStyles.Any, swappedNFI, 5000, true); passed &= VerifyInt64TryParse("5,0", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyInt64TryParse("$5,0", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyInt64TryParse("5,000", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyInt64TryParse("$5,000", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyInt64TryParse("5,000.0", NumberStyles.Currency, swappedNFI, 0, false); passed &= VerifyInt64TryParse("$5,000.0", NumberStyles.Currency, swappedNFI, 0, false); passed &= VerifyInt64TryParse("5,000", NumberStyles.Any, swappedNFI, 5, true); passed &= VerifyInt64TryParse("$5,000", NumberStyles.Any, swappedNFI, 5, true); passed &= VerifyInt64TryParse("5,000.0", NumberStyles.Any, swappedNFI, 0, false); passed &= VerifyInt64TryParse("$5,000.0", NumberStyles.Any, swappedNFI, 0, false); // passed &= VerifyInt64TryParse("5.0", NumberStyles.Number, distinctNFI, 5, true); passed &= VerifyInt64TryParse("1,234.0", NumberStyles.Number, distinctNFI, 1234, true); passed &= VerifyInt64TryParse("5.0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyInt64TryParse("1,234.0", NumberStyles.Currency, distinctNFI, 1234, true); passed &= VerifyInt64TryParse("5.0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyInt64TryParse("1,234.0", NumberStyles.Any, distinctNFI, 1234, true); passed &= VerifyInt64TryParse("$5.0", NumberStyles.Currency, distinctNFI, 0, false); passed &= VerifyInt64TryParse("$5.0", NumberStyles.Any, distinctNFI, 0, false); passed &= VerifyInt64TryParse("5:0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyInt64TryParse("5;0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyInt64TryParse("$5:0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyInt64TryParse("5:0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyInt64TryParse("5:000", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyInt64TryParse("5;000", NumberStyles.Currency, distinctNFI, 5000, true); passed &= VerifyInt64TryParse("$5:0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyInt64TryParse("$5;0", NumberStyles.Currency, distinctNFI, 50, true); passed &= VerifyInt64TryParse("5:0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyInt64TryParse("5;0", NumberStyles.Any, distinctNFI, 50, true); passed &= VerifyInt64TryParse("$5:0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyInt64TryParse("$5;0", NumberStyles.Any, distinctNFI, 50, true); passed &= VerifyInt64TryParse("123,456;789.0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyInt64TryParse("123,456;789.0", NumberStyles.Currency, distinctNFI, 123456789, true); passed &= VerifyInt64TryParse("123,456;789.0", NumberStyles.Any, distinctNFI, 123456789, true); passed &= VerifyInt64TryParse("$123,456;789.0", NumberStyles.Any, distinctNFI, 0, false); // Should these pass or fail? Current parse behavior is to pass, so they might be // parse bugs, but they're not tryparse bugs. passed &= VerifyInt64Parse("5", NumberStyles.Float, goodNFI, 5); passed &= VerifyInt64TryParse("5", NumberStyles.Float, goodNFI, 5, true); passed &= VerifyInt64Parse("5", NumberStyles.AllowDecimalPoint, goodNFI, 5); passed &= VerifyInt64TryParse("5", NumberStyles.AllowDecimalPoint, goodNFI, 5, true); // I expect ArgumentException with an ambiguous NFI passed &= VerifyInt64Parse("^42", NumberStyles.Any, ambigNFI, -42); passed &= VerifyInt64TryParse("^42", NumberStyles.Any, ambigNFI, -42, true); /// END TEST CASES } catch (Exception e) { TestLibrary.Logging.WriteLine("Unexpected exception!! " + e.ToString()); passed = false; } if (passed) { TestLibrary.Logging.WriteLine("paSs"); return 100; } else { TestLibrary.Logging.WriteLine("FAiL"); return 1; } } public static bool VerifyInt64TryParse(string value, Int64 expectedResult, bool expectedReturn) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.TryParse, Value = '{0}', Expected Result = {1}, Expected Return = {2}", value, expectedResult, expectedReturn); } Int64 result = 0; try { bool returnValue = Int64.TryParse(value, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedReturn, returnValue); return false; } if (result != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyInt64TryParse(string value, NumberStyles style, IFormatProvider provider, Int64 expectedResult, bool expectedReturn) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Result = {3}, Expected Return = {4}", value, style, provider, expectedResult, expectedReturn); } Int64 result = 0; try { bool returnValue = Int64.TryParse(value, style, provider, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Style = {1}, Provider = {2}, Expected Return = {3}, Actual Return = {4}", value, style, provider, expectedReturn, returnValue); return false; } if (result != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyInt64TryParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}", value, style, provider, exceptionType); } try { Int64 result = 0; Boolean returnValue = Int64.TryParse(value, style, provider, out result); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyInt64Parse(string value, Int64 expectedResult) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.Parse, Value = '{0}', Expected Result, {1}", value, expectedResult); } try { Int64 returnValue = Int64.Parse(value); if (returnValue != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyInt64Parse(string value, NumberStyles style, IFormatProvider provider, Int64 expectedResult) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.Parse, Value = '{0}', Style = {1}, provider = {2}, Expected Result = {3}", value, style, provider, expectedResult); } try { Int64 returnValue = Int64.Parse(value, style, provider); if (returnValue != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyInt64ParseException(string value, Type exceptionType) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.Parse, Value = '{0}', Expected Exception, {1}", value, exceptionType); } try { Int64 returnValue = Int64.Parse(value); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyInt64ParseException(string value, NumberStyles style, Type exceptionType) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.Parse, Value = '{0}', Style = {1}, Expected Exception = {3}", value, style, exceptionType); } try { Int64 returnValue = Int64.Parse(value, style); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyInt64ParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Int64.Parse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}", value, style, provider, exceptionType); } try { Int64 returnValue = Int64.Parse(value, style, provider); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } }
/* Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Inc. * Copyright 2010, Real-Time Innovations, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DDS.ConversionUtils; using org.omg.dds.core; using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace org.omg.dds.type.dynamic { public interface DynamicData : DDSObject, ICloneable { DynamicType GetType(); /// <summary> /// Modifying an element of the given list modifies the descriptor of this /// DynamicData object, not a copy. Adding to or removing from the list /// is not allowed. /// </summary> /// <returns></returns> List<MemberDescriptor> GetDescriptors(); int GetMemberIdByName(string name); int GetMemberIdAtIndex(int index); void ClearAllValues(); void ClearNonkeyValues(); void ClearValue(int id); DynamicData LoanValue(int id); void ReturnLoanedValue(DynamicData value); int GetInt32Value(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt32Value(int id, int value); short GetInt16Value(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt16Value(int id, short value); long GetInt64Value(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt64Value(int id, long value); BigInteger GetBigIntegerValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBigIntegerValue(int id, BigInteger value); float GetFloat32Value(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetFloat32Value(int id, float value); double GetFloat64Value(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetFloat64Value(int id, double value); BigDecimal GetBigDecimalValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBigDecimalValue(int id, BigDecimal value); char GetCharValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetCharValue(int id, char value); byte GetByteValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData setByteValue(int id, byte value); bool GetBooleanValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBooleanValue(int id, bool value); string GetstringValue(int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetstringValue(int id, CharSequence value); DynamicData GetComplexValue(DynamicData value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetComplexValue(int id, DynamicData value); int GetInt32Values(int[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetInt32Values(int id, int[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt32Values(int id, params int[] value); int GetInt16Values(short[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetInt16Values(int id, short[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt16Values(int id, params short[] value); int GetInt64Values(long[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetInt64Values(int id, long[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetInt64Values(int id, params long[] value); int GetBigIntegerValues(BigInteger[] value, int offset, int length, int id); List<BigInteger> GetBigIntegerValues(List<BigInteger> value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetBigIntegerValues(int id, BigInteger[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBigIntegerValues(int id, List<BigInteger> value); int GetFloat32Values(float[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetFloat32Values(int id, float[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetFloat32Values(int id, params float[] value); int GetFloat64Values(double[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetFloat64Values(int id, double[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetFloat64Values(int id, params double[] value); int GetBigDecimalValues(BigDecimal[] value, int offset, int length, int id); List<BigDecimal> GetBigDecimalValues(List<BigDecimal> value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetBigDecimalValues(int id, BigDecimal[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBigDecimalValues(int id, List<BigDecimal> value); int GetCharValues(char[] value, int offset, int length, int id); StringBuilder GetCharValues(StringBuilder value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetCharValues(int id, char[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetCharValues(int id, params char[] value); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetCharValues(int id, CharSequence value); int GetByteValues(byte[] value, int offset, int length, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetByteValues(int id, byte[] value, int offset, int length); int GetBooleanValues( bool[] value, int offset, int length, int id); void GetBooleanValues(List<bool> value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetBooleanValues(int id, bool[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetBooleanValues(int id, params bool[] value); int GetstringValues( string[] value, int offset, int length, int id); void GetstringValues(List<string> value, int id); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns>this</returns> DynamicData SetstringValues(int id, string[] value, int offset, int length); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetstringValues(int id, params string[] value); /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns>this</returns> DynamicData SetstringValues(int id, List<string> value); //DynamicData clone(); } }
// 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.Composition.Hosting; using System.Composition.Hosting.Core; using System.Composition.Runtime; using System.Composition.UnitTests.Util; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Composition.UnitTests { public class ExportFactoryTests : ContainerTests { private static class Boundaries { public const string DataConsistency = "DataConsistency"; public const string UserIdentity = "UserIdentity"; } [Shared, Export] public class SharedUnbounded { } [Shared(Boundaries.DataConsistency), Export] public class SharedBoundedByDC { } [Export] public class DataConsistencyBoundaryProvider { [Import, SharingBoundary(Boundaries.DataConsistency)] public ExportFactory<CompositionContext> SharingScopeFactory { get; set; } } [Export] public class SharedPartConsumer { public SharedBoundedByDC Sc1, Sc2; [ImportingConstructor] public SharedPartConsumer(SharedBoundedByDC sc1, SharedBoundedByDC sc2) { Sc1 = sc1; Sc2 = sc2; } } public interface IA { } [Export(typeof(IA))] public class A : IA, IDisposable { public bool IsDisposed; public void Dispose() { IsDisposed = true; } } [Shared, Export] public class GloballySharedWithDependency { public IA A; [ImportingConstructor] public GloballySharedWithDependency(IA a) { A = a; } } [Export] public class UseExportFactory { [Import] public ExportFactory<IA> AFactory { get; set; } } [Export] public class DisposesFactoryProduct : IDisposable { private readonly ExportFactory<IA> _factory; [ImportingConstructor] public DisposesFactoryProduct(ExportFactory<IA> factory) { _factory = factory; } public Export<IA> Product { get; set; } public void CreateProduct() { Product = _factory.CreateExport(); } public void Dispose() { Product.Dispose(); } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void SharedPartsAreSharedBetweenAllScopes() { var cc = CreateContainer(typeof(SharedUnbounded), typeof(DataConsistencyBoundaryProvider)); var bp = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory; var x = bp.CreateExport().Value.GetExport<SharedUnbounded>(); var y = bp.CreateExport().Value.GetExport<SharedUnbounded>(); Assert.Same(x, y); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void TheSameSharedInstanceIsReusedWithinItsSharingBoundary() { var cc = CreateContainer(typeof(SharedBoundedByDC), typeof(SharedPartConsumer), typeof(DataConsistencyBoundaryProvider)); var sf = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory; var s = sf.CreateExport(); var s2 = sf.CreateExport(); var x = s.Value.GetExport<SharedPartConsumer>(); var y = s2.Value.GetExport<SharedPartConsumer>(); Assert.Same(x.Sc1, x.Sc2); Assert.NotSame(x.Sc1, y.Sc1); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void NonSharedInstancesCreatedByAnExportFactoryAreControlledByTheirExportLifetimeContext() { var cc = CreateContainer(typeof(A), typeof(UseExportFactory)); var bef = cc.GetExport<UseExportFactory>(); var a = bef.AFactory.CreateExport(); Assert.IsAssignableFrom<A>(a.Value); Assert.False(((A)a.Value).IsDisposed); a.Dispose(); Assert.True(((A)a.Value).IsDisposed); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void DependenciesOfSharedPartsAreResolvedInTheGlobalScope() { var cc = new ContainerConfiguration() .WithParts(typeof(GloballySharedWithDependency), typeof(A), typeof(DataConsistencyBoundaryProvider)) .CreateContainer(); var s = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory.CreateExport(); var g = s.Value.GetExport<GloballySharedWithDependency>(); s.Dispose(); var a = (A)g.A; Assert.False(a.IsDisposed); cc.Dispose(); Assert.True(a.IsDisposed); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WhenABoundaryIsPresentBoundedPartsCannotBeCreatedOutsideIt() { var container = CreateContainer(typeof(DataConsistencyBoundaryProvider), typeof(SharedBoundedByDC)); var x = Assert.Throws<CompositionFailedException>(() => container.GetExport<SharedBoundedByDC>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void TheProductOfAnExportFactoryCanBeDisposedDuringDisposalOfTheParent() { var container = new ContainerConfiguration() .WithPart<DisposesFactoryProduct>() .WithPart<A>() .CreateContainer(); var dfp = container.GetExport<DisposesFactoryProduct>(); dfp.CreateProduct(); var a = dfp.Product.Value as A; container.Dispose(); Assert.True(a.IsDisposed); } [Export("Special", typeof(IA))] public class A1 : IA { } [Export("Special", typeof(IA))] public class A2 : IA { } [Export] public class AConsumer { [ImportMany("Special")] public ExportFactory<IA>[] AFactories { get; set; } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ExportFactoryCanBeComposedWithImportManyAndNames() { var cc = CreateContainer(typeof(AConsumer), typeof(A1), typeof(A2)); var cons = cc.GetExport<AConsumer>(); Assert.Equal(2, cons.AFactories.Length); } [Export] public class Disposable : IDisposable { public bool IsDisposed { get; set; } public void Dispose() { IsDisposed = true; } } [Export] public class HasDisposableDependency { [Import] public Disposable Dependency { get; set; } } [Export] public class HasFactory { [Import] public ExportFactory<HasDisposableDependency> Factory { get; set; } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WhenReleasingAnExportFromAnExportFactoryItsNonSharedDependenciesAreDisposed() { var cc = CreateContainer(typeof(Disposable), typeof(HasDisposableDependency), typeof(HasFactory)); var hf = cc.GetExport<HasFactory>(); var hddx = hf.Factory.CreateExport(); var hdd = hddx.Value; hddx.Dispose(); Assert.True(hdd.Dependency.IsDisposed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Drawing.Printing { /// <summary> /// Controls how a document is printed. /// </summary> public abstract class PrintController { // DEVMODEs are pretty expensive, so we cache one here and share it with the // Standard and Preview print controllers. If it weren't for all the rules about API changes, // I'd consider making this protected. #region SafeDeviceModeHandle Class /// <summary> /// Represents a SafeHandle for a Printer's Device Mode struct handle (DEVMODE) /// </summary> internal sealed class SafeDeviceModeHandle : SafeHandle { // This constructor is used by the P/Invoke marshaling layer // to allocate a SafeHandle instance. P/Invoke then does the // appropriate method call, storing the handle in this class. private SafeDeviceModeHandle() : base(IntPtr.Zero, true) { return; } internal SafeDeviceModeHandle(IntPtr handle) : base(IntPtr.Zero, true) // "true" means "owns the handle" { SetHandle(handle); } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } // Specifies how to free the handle. // The boolean returned should be true for success and false if the runtime // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that // MDA is enabled. protected override bool ReleaseHandle() { if (!IsInvalid) { SafeNativeMethods.GlobalFree(new HandleRef(this, handle)); } handle = IntPtr.Zero; return true; } public static implicit operator IntPtr(SafeDeviceModeHandle handle) { return (handle == null) ? IntPtr.Zero : handle.handle; } public static explicit operator SafeDeviceModeHandle(IntPtr handle) { return new SafeDeviceModeHandle(handle); } } #endregion internal SafeDeviceModeHandle modeHandle = null; /// <summary> /// Initializes a new instance of the <see cref='PrintController'/> class. /// </summary> protected PrintController() { } /// <summary> /// This is new public property which notifies if this controller is used for PrintPreview. /// </summary> public virtual bool IsPreview { get { return false; } } // WARNING: if you have nested PrintControllers, this method won't get called on the inner one. // Add initialization code to StartPrint or StartPage instead. internal void Print(PrintDocument document) { // // Get the PrintAction for this event PrintAction printAction; if (IsPreview) { printAction = PrintAction.PrintToPreview; } else { printAction = document.PrinterSettings.PrintToFile ? PrintAction.PrintToFile : PrintAction.PrintToPrinter; } // Check that user has permission to print to this particular printer PrintEventArgs printEvent = new PrintEventArgs(printAction); document._OnBeginPrint(printEvent); if (printEvent.Cancel) { document._OnEndPrint(printEvent); return; } OnStartPrint(document, printEvent); if (printEvent.Cancel) { document._OnEndPrint(printEvent); OnEndPrint(document, printEvent); return; } bool canceled = true; try { // To enable optimization of the preview dialog, add the following to the config file: // <runtime > // <!-- AppContextSwitchOverrides values are in the form of 'key1=true|false;key2=true|false --> // <AppContextSwitchOverrides value = "Switch.System.Drawing.Printing.OptimizePrintPreview=true" /> // </runtime > canceled = LocalAppContextSwitches.OptimizePrintPreview ? PrintLoopOptimized(document) : PrintLoop(document); } finally { try { document._OnEndPrint(printEvent); printEvent.Cancel = canceled | printEvent.Cancel; } finally { OnEndPrint(document, printEvent); } } } // Returns true if print was aborted. // WARNING: if you have nested PrintControllers, this method won't get called on the inner one // Add initialization code to StartPrint or StartPage instead. private bool PrintLoop(PrintDocument document) { QueryPageSettingsEventArgs queryEvent = new QueryPageSettingsEventArgs((PageSettings)document.DefaultPageSettings.Clone()); for (;;) { document._OnQueryPageSettings(queryEvent); if (queryEvent.Cancel) { return true; } PrintPageEventArgs pageEvent = CreatePrintPageEvent(queryEvent.PageSettings); Graphics graphics = OnStartPage(document, pageEvent); pageEvent.SetGraphics(graphics); try { document._OnPrintPage(pageEvent); OnEndPage(document, pageEvent); } finally { pageEvent.Dispose(); } if (pageEvent.Cancel) { return true; } else if (!pageEvent.HasMorePages) { return false; } else { // loop } } } private bool PrintLoopOptimized(PrintDocument document) { PrintPageEventArgs pageEvent = null; PageSettings documentPageSettings = (PageSettings)document.DefaultPageSettings.Clone(); QueryPageSettingsEventArgs queryEvent = new QueryPageSettingsEventArgs(documentPageSettings); for (;;) { queryEvent.PageSettingsChanged = false; document._OnQueryPageSettings(queryEvent); if (queryEvent.Cancel) { return true; } if (!queryEvent.PageSettingsChanged) { // QueryPageSettings event handler did not change the page settings, // thus we use default page settings from the document object. if (pageEvent == null) { pageEvent = CreatePrintPageEvent(queryEvent.PageSettings); } else { // This is not the first page and the settings had not changed since the previous page, // thus don't re-apply them. pageEvent.CopySettingsToDevMode = false; } Graphics graphics = OnStartPage(document, pageEvent); pageEvent.SetGraphics(graphics); } else { // Page settings were customized, so use the customized ones in the start page event. pageEvent = CreatePrintPageEvent(queryEvent.PageSettings); Graphics graphics = OnStartPage(document, pageEvent); pageEvent.SetGraphics(graphics); } try { document._OnPrintPage(pageEvent); OnEndPage(document, pageEvent); } finally { pageEvent.Graphics.Dispose(); pageEvent.SetGraphics(null); } if (pageEvent.Cancel) { return true; } else if (!pageEvent.HasMorePages) { return false; } } } private PrintPageEventArgs CreatePrintPageEvent(PageSettings pageSettings) { Debug.Assert((modeHandle != null), "modeHandle is null. Someone must have forgot to call base.StartPrint"); Rectangle pageBounds = pageSettings.GetBounds(modeHandle); Rectangle marginBounds = new Rectangle(pageSettings.Margins.Left, pageSettings.Margins.Top, pageBounds.Width - (pageSettings.Margins.Left + pageSettings.Margins.Right), pageBounds.Height - (pageSettings.Margins.Top + pageSettings.Margins.Bottom)); PrintPageEventArgs pageEvent = new PrintPageEventArgs(null, marginBounds, pageBounds, pageSettings); return pageEvent; } /// <summary> /// When overridden in a derived class, begins the control sequence of when and how to print a document. /// </summary> public virtual void OnStartPrint(PrintDocument document, PrintEventArgs e) { modeHandle = (SafeDeviceModeHandle)document.PrinterSettings.GetHdevmode(document.DefaultPageSettings); } /// <summary> /// When overridden in a derived class, begins the control sequence of when and how to print a page in a document. /// </summary> public virtual Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { return null; } /// <summary> /// When overridden in a derived class, completes the control sequence of when and how to print a page in a document. /// </summary> public virtual void OnEndPage(PrintDocument document, PrintPageEventArgs e) { } /// <summary> /// When overridden in a derived class, completes the control sequence of when and how to print a document. /// </summary> public virtual void OnEndPrint(PrintDocument document, PrintEventArgs e) { Debug.Assert((modeHandle != null), "modeHandle is null. Someone must have forgot to call base.StartPrint"); if (modeHandle != null) { modeHandle.Close(); } } } }
// 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.Collections.Immutable; using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { public sealed class MetadataAggregator { // For each heap handle and each delta contains aggregate heap lengths. // heapSizes[heap kind][reader index] == Sum { 0..index | reader[i].XxxHeapLength } private readonly ImmutableArray<ImmutableArray<int>> _heapSizes; private readonly ImmutableArray<ImmutableArray<RowCounts>> _rowCounts; // internal for testing internal struct RowCounts : IComparable<RowCounts> { public int AggregateInserts; public int Updates; public int CompareTo(RowCounts other) { return AggregateInserts - other.AggregateInserts; } public override string ToString() { return string.Format("+0x{0:x} ~0x{1:x}", AggregateInserts, Updates); } } public MetadataAggregator(MetadataReader baseReader, IReadOnlyList<MetadataReader> deltaReaders) : this(baseReader, null, null, deltaReaders) { } public MetadataAggregator( IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) : this(null, baseTableRowCounts, baseHeapSizes, deltaReaders) { } private MetadataAggregator( MetadataReader baseReader, IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) { if (baseTableRowCounts == null) { if (baseReader == null) { throw new ArgumentNullException("deltaReaders"); } if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0) { throw new ArgumentException("Base reader must be a full metadata reader.", "baseReader"); } CalculateBaseCounts(baseReader, out baseTableRowCounts, out baseHeapSizes); } else { if (baseTableRowCounts == null) { throw new ArgumentNullException("baseTableRowCounts"); } if (baseTableRowCounts.Count != MetadataTokens.TableCount) { throw new ArgumentException("Must have " + MetadataTokens.TableCount + " elements", "baseTableRowCounts"); } if (baseHeapSizes == null) { throw new ArgumentNullException("baseHeapSizes"); } if (baseHeapSizes.Count != MetadataTokens.HeapCount) { throw new ArgumentException("Must have " + MetadataTokens.HeapCount + " elements", "baseTableRowCounts"); } } if (deltaReaders == null || deltaReaders.Count == 0) { throw new ArgumentException("Must not be empty.", "deltaReaders"); } for (int i = 0; i < deltaReaders.Count; i++) { if (deltaReaders[i].GetTableRowCount(TableIndex.EncMap) == 0 || !deltaReaders[i].IsMinimalDelta) { throw new ArgumentException("All delta readers must be minimal delta metadata readers.", "deltaReaders"); } } _heapSizes = CalculateHeapSizes(baseHeapSizes, deltaReaders); _rowCounts = CalculateRowCounts(baseTableRowCounts, deltaReaders); } // for testing only internal MetadataAggregator(RowCounts[][] rowCounts, int[][] heapSizes) { _rowCounts = ToImmutable(rowCounts); _heapSizes = ToImmutable(heapSizes); } private static void CalculateBaseCounts( MetadataReader baseReader, out IReadOnlyList<int> baseTableRowCounts, out IReadOnlyList<int> baseHeapSizes) { int[] rowCounts = new int[MetadataTokens.TableCount]; int[] heapSizes = new int[MetadataTokens.HeapCount]; for (int i = 0; i < rowCounts.Length; i++) { rowCounts[i] = baseReader.GetTableRowCount((TableIndex)i); } for (int i = 0; i < heapSizes.Length; i++) { heapSizes[i] = baseReader.GetHeapSize((HeapIndex)i); } baseTableRowCounts = rowCounts; baseHeapSizes = heapSizes; } private static ImmutableArray<ImmutableArray<int>> CalculateHeapSizes( IReadOnlyList<int> baseSizes, IReadOnlyList<MetadataReader> deltaReaders) { // GUID heap index is multiple of sizeof(Guid) == 16 const int guidSize = 16; int generationCount = 1 + deltaReaders.Count; var userStringSizes = new int[generationCount]; var stringSizes = new int[generationCount]; var blobSizes = new int[generationCount]; var guidSizes = new int[generationCount]; userStringSizes[0] = baseSizes[(int)HeapIndex.UserString]; stringSizes[0] = baseSizes[(int)HeapIndex.String]; blobSizes[0] = baseSizes[(int)HeapIndex.Blob]; guidSizes[0] = baseSizes[(int)HeapIndex.Guid] / guidSize; for (int r = 0; r < deltaReaders.Count; r++) { userStringSizes[r + 1] = userStringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.UserString); stringSizes[r + 1] = stringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.String); blobSizes[r + 1] = blobSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Blob); guidSizes[r + 1] = guidSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Guid) / guidSize; } return ImmutableArray.Create( userStringSizes.ToImmutableArray(), stringSizes.ToImmutableArray(), blobSizes.ToImmutableArray(), guidSizes.ToImmutableArray()); } private static ImmutableArray<ImmutableArray<RowCounts>> CalculateRowCounts( IReadOnlyList<int> baseRowCounts, IReadOnlyList<MetadataReader> deltaReaders) { // TODO: optimize - we don't need to allocate all these arrays var rowCounts = GetBaseRowCounts(baseRowCounts, generations: 1 + deltaReaders.Count); for (int generation = 1; generation <= deltaReaders.Count; generation++) { CalculateDeltaRowCountsForGeneration(rowCounts, generation, ref deltaReaders[generation - 1].EncMapTable); } return ToImmutable(rowCounts); } private static ImmutableArray<ImmutableArray<T>> ToImmutable<T>(T[][] array) { var immutable = new ImmutableArray<T>[array.Length]; for (int i = 0; i < array.Length; i++) { immutable[i] = array[i].ToImmutableArray(); } return immutable.ToImmutableArray(); } // internal for testing internal static RowCounts[][] GetBaseRowCounts(IReadOnlyList<int> baseRowCounts, int generations) { var rowCounts = new RowCounts[TableIndexExtensions.Count][]; for (int t = 0; t < rowCounts.Length; t++) { rowCounts[t] = new RowCounts[generations]; rowCounts[t][0].AggregateInserts = baseRowCounts[t]; } return rowCounts; } // internal for testing internal static void CalculateDeltaRowCountsForGeneration(RowCounts[][] rowCounts, int generation, ref EnCMapTableReader encMapTable) { foreach (var tableRowCounts in rowCounts) { tableRowCounts[generation].AggregateInserts = tableRowCounts[generation - 1].AggregateInserts; } int mapRowCount = encMapTable.NumberOfRows; for (int mapRid = 1; mapRid <= mapRowCount; mapRid++) { uint token = encMapTable.GetToken(mapRid); int rid = (int)(token & TokenTypeIds.RIDMask); var tableRowCounts = rowCounts[token >> TokenTypeIds.RowIdBitCount]; if (rid > tableRowCounts[generation].AggregateInserts) { if (rid != tableRowCounts[generation].AggregateInserts + 1) { throw new BadImageFormatException(MetadataResources.EnCMapNotSorted); } // insert: tableRowCounts[generation].AggregateInserts = rid; } else { // update: tableRowCounts[generation].Updates++; } } } public Handle GetGenerationHandle(Handle handle, out int generation) { if (handle.IsVirtual) { // TODO: if a virtual handle is connected to real handle then translate the rid, // otherwise return vhandle and base. throw new NotSupportedException(); } if (handle.IsHeapHandle) { int heapOffset = handle.Offset; HeapIndex heapIndex; MetadataTokens.TryGetHeapIndex(handle.Kind, out heapIndex); var sizes = _heapSizes[(int)heapIndex]; generation = sizes.BinarySearch(heapOffset); if (generation >= 0) { Debug.Assert(sizes[generation] == heapOffset); // the index points to the start of the next generation that added data to the heap: do { generation++; } while (generation < sizes.Length && sizes[generation] == heapOffset); } else { generation = ~generation; } if (generation >= sizes.Length) { throw new ArgumentException(MetadataResources.HandleBelongsToFutureGeneration, "handle"); } // GUID heap accumulates - previous heap is copied to the next generation int relativeHeapOffset = (handle.Type == HandleType.Guid || generation == 0) ? heapOffset : heapOffset - sizes[generation - 1]; return new Handle((byte)handle.Type, relativeHeapOffset); } else { int rowId = handle.RowId; var sizes = _rowCounts[(int)handle.Type]; generation = sizes.BinarySearch(new RowCounts { AggregateInserts = rowId }); if (generation >= 0) { Debug.Assert(sizes[generation].AggregateInserts == rowId); // the row is in a generation that inserted exactly one row -- the one that we are looking for; // or it's in a preceding generation if the current one didn't insert any rows of the kind: while (generation > 0 && sizes[generation - 1].AggregateInserts == rowId) { generation--; } } else { // the row is in a generation that inserted multiple new rows: generation = ~generation; if (generation >= sizes.Length) { throw new ArgumentException(MetadataResources.HandleBelongsToFutureGeneration, "handle"); } } // In each delta table updates always precede inserts. int relativeRowId = (generation == 0) ? rowId : rowId - sizes[generation - 1].AggregateInserts + sizes[generation].Updates; return new Handle((byte)handle.Type, relativeRowId); } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Monitoring.V3.Tests { using Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Monitoring.V3; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Xunit; /// <summary>Generated unit tests</summary> public class GeneratedMetricServiceClientTest { [Fact] public void GetMonitoredResourceDescriptor() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMonitoredResourceDescriptorRequest expectedRequest = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; MonitoredResourceDescriptor expectedResponse = new MonitoredResourceDescriptor { Name = "name2-1052831874", Type = "type3575610", DisplayName = "displayName1615086568", Description = "description-1724546052", }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetMonitoredResourceDescriptorAsync() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMonitoredResourceDescriptorRequest expectedRequest = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; MonitoredResourceDescriptor expectedResponse = new MonitoredResourceDescriptor { Name = "name2-1052831874", Type = "type3575610", DisplayName = "displayName1615086568", Description = "description-1724546052", }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MonitoredResourceDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); MonitoredResourceDescriptor response = await client.GetMonitoredResourceDescriptorAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetMonitoredResourceDescriptor2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; MonitoredResourceDescriptor expectedResponse = new MonitoredResourceDescriptor { Name = "name2-1052831874", Type = "type3575610", DisplayName = "displayName1615086568", Description = "description-1724546052", }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetMonitoredResourceDescriptorAsync2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; MonitoredResourceDescriptor expectedResponse = new MonitoredResourceDescriptor { Name = "name2-1052831874", Type = "type3575610", DisplayName = "displayName1615086568", Description = "description-1724546052", }; mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MonitoredResourceDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MonitoredResourceDescriptor response = await client.GetMonitoredResourceDescriptorAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetMetricDescriptor() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMetricDescriptorRequest expectedRequest = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); MetricDescriptor response = client.GetMetricDescriptor(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetMetricDescriptorAsync() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMetricDescriptorRequest expectedRequest = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MetricDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); MetricDescriptor response = await client.GetMetricDescriptorAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetMetricDescriptor2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptor response = client.GetMetricDescriptor(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetMetricDescriptorAsync2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MetricDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptor response = await client.GetMetricDescriptorAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateMetricDescriptor() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateMetricDescriptorRequest expectedRequest = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ProjectName name = new ProjectName("[PROJECT]"); MetricDescriptor metricDescriptor = new MetricDescriptor(); MetricDescriptor response = client.CreateMetricDescriptor(name, metricDescriptor); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateMetricDescriptorAsync() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateMetricDescriptorRequest expectedRequest = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MetricDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ProjectName name = new ProjectName("[PROJECT]"); MetricDescriptor metricDescriptor = new MetricDescriptor(); MetricDescriptor response = await client.CreateMetricDescriptorAsync(name, metricDescriptor); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateMetricDescriptor2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptor response = client.CreateMetricDescriptor(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateMetricDescriptorAsync2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; MetricDescriptor expectedResponse = new MetricDescriptor { Name = "name2-1052831874", Type = "type3575610", Unit = "unit3594628", Description = "description-1724546052", DisplayName = "displayName1615086568", }; mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<MetricDescriptor>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptor response = await client.CreateMetricDescriptorAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteMetricDescriptor() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); DeleteMetricDescriptorRequest expectedRequest = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); client.DeleteMetricDescriptor(name); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteMetricDescriptorAsync() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); DeleteMetricDescriptorRequest expectedRequest = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); await client.DeleteMetricDescriptorAsync(name); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteMetricDescriptor2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.DeleteMetricDescriptor(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteMetricDescriptorAsync2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteMetricDescriptorAsync(request); mockGrpcClient.VerifyAll(); } [Fact] public void CreateTimeSeries() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateTimeSeriesRequest expectedRequest = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.CreateTimeSeries(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ProjectName name = new ProjectName("[PROJECT]"); IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>(); client.CreateTimeSeries(name, timeSeries); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateTimeSeriesAsync() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateTimeSeriesRequest expectedRequest = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); ProjectName name = new ProjectName("[PROJECT]"); IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>(); await client.CreateTimeSeriesAsync(name, timeSeries); mockGrpcClient.VerifyAll(); } [Fact] public void CreateTimeSeries2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.CreateTimeSeries(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); client.CreateTimeSeries(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateTimeSeriesAsync2() { Mock<MetricService.MetricServiceClient> mockGrpcClient = new Mock<MetricService.MetricServiceClient>(MockBehavior.Strict); CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null); await client.CreateTimeSeriesAsync(request); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using ReMi.BusinessEntities.Auth; using ReMi.BusinessEntities.ReleaseCalendar; using ReMi.BusinessEntities.ReleaseExecution; using ReMi.BusinessLogic; using ReMi.Common.Constants.ReleaseCalendar; using ReMi.Common.Constants.Subscriptions; using ReMi.Common.Utils; using ReMi.TestUtils.UnitTests; using ReMi.Contracts.Cqrs.Events; using ReMi.Contracts.Plugins.Services.Email; using ReMi.DataAccess.BusinessEntityGateways.ReleaseCalendar; using ReMi.DataAccess.BusinessEntityGateways.ReleaseExecution; using ReMi.DataAccess.BusinessEntityGateways.Subscriptions; using ReMi.DataAccess.Exceptions; using ReMi.EventHandlers.ReleaseExecution; using ReMi.Events.ReleaseExecution; namespace ReMi.EventHandlers.Tests.ReleaseExecution { public class SignOffHandlerTests : TestClassFor<SignOffHandler> { private const String AddedToSignOffsSubject = " Added to sign offs"; private const String RemovedFromSignOffsSubject = " Removed from signed offs"; private const String ReleaseSignedOffSubject = " Release signed off"; private Mock<IEmailTextProvider> _emailTextProviderMock; private Mock<IEmailService> _emailClientMock; private Mock<IReleaseWindowGateway> _releaseWindowGatewayMock; private Mock<ISignOffGateway> _signOffGatewayMock; private Mock<IAccountNotificationGateway> _accountNotificationGatewayMock; private String _email; private ReleaseWindow _window; private Account _account; private List<SignOff> _signOffs; private List<Account> _members; protected override SignOffHandler ConstructSystemUnderTest() { return new SignOffHandler { EmailService = _emailClientMock.Object, EmailTextProvider = _emailTextProviderMock.Object, ReleaseWindowGatewayFactory = () => _releaseWindowGatewayMock.Object, SignOffGatewayFactory = () => _signOffGatewayMock.Object, AccountNotificationGatewayFactory = () => _accountNotificationGatewayMock.Object }; } protected override void TestInitialize() { _emailClientMock = new Mock<IEmailService>(); _emailTextProviderMock = new Mock<IEmailTextProvider>(); _releaseWindowGatewayMock = new Mock<IReleaseWindowGateway>(); _signOffGatewayMock = new Mock<ISignOffGateway>(); _accountNotificationGatewayMock = new Mock<IAccountNotificationGateway>(); _email = RandomData.RandomString(100, 400); _emailTextProviderMock.Setup(e => e.GetText(It.IsAny<String>(), It.IsAny<Dictionary<String, Object>>())) .Returns(_email); _window = new ReleaseWindow { Sprint = RandomData.RandomString(5, 8), StartTime = SystemTime.Now.AddHours(3), Products = new[] { RandomData.RandomString(5) }, ReleaseType = ReleaseType.Scheduled }; _releaseWindowGatewayMock.Setup(r => r.GetByExternalId(_window.ExternalId, false, It.IsAny<bool>())) .Returns(_window); _account = new Account { ExternalId = Guid.NewGuid(), FullName = RandomData.RandomString(15, 34), Email = RandomData.RandomEmail() }; _signOffs = new List<SignOff> { new SignOff { Signer = new Account {FullName = RandomData.RandomString(20, 25), Email = RandomData.RandomEmail()} } , new SignOff { Signer = new Account {FullName = RandomData.RandomString(20, 25), Email = RandomData.RandomEmail()} } }; _signOffGatewayMock.Setup(s => s.GetSignOffs(_window.ExternalId)).Returns(_signOffs); _members = new List<Account> { new Account {FullName = RandomData.RandomString(20, 25), Email = RandomData.RandomEmail()} }; _members.AddRange(_signOffs.Select(x => x.Signer)); base.TestInitialize(); } [Test, ExpectedException(typeof(ReleaseWindowNotFoundException))] public void Handle_ShouldThrowException_WhenSignersAddedAndReleaseWindowNotFound() { Sut.Handle( new ReleaseSignersAddedEvent { ReleaseWindowId = Guid.NewGuid() }); } [Test] public void Handle_ShouldSendEmail_WhenSignersAdded() { var evnt = new ReleaseSignersAddedEvent { ReleaseWindowId = _window.ExternalId, SignOffs = new List<SignOff> { new SignOff { Signer = new Account { FullName = RandomData.RandomString(11, 33), Email = RandomData.RandomEmail(), ExternalId = Guid.NewGuid() } }, new SignOff { Signer = new Account { FullName = RandomData.RandomString(11, 33), Email = RandomData.RandomEmail(), ExternalId = Guid.NewGuid() } } } }; _accountNotificationGatewayMock.Setup(x => x.GetSubscribers(NotificationType.Signing, _window.Products)) .Returns(evnt.SignOffs.Select(s => s.Signer).ToList()); Sut.Handle(evnt); _accountNotificationGatewayMock.Verify(x => x.GetSubscribers(NotificationType.Signing, _window.Products)); _releaseWindowGatewayMock.Verify(r => r.GetByExternalId(_window.ExternalId, false, It.IsAny<bool>())); _emailTextProviderMock.Verify(e => e.GetText("SignOffAddedToReleaseWindowEmail", It.Is<Dictionary<String, Object>>(d => d.Any(s => s.Key == "Assignee" && s.Value.ToString() == evnt.SignOffs[0].Signer.FullName) && //d.Any(s => s.Key == "Products" && s.Value.ToString() == string.Join(", ", _window.Products)) && d.Any(s => s.Key == "Sprint" && s.Value.ToString() == _window.Sprint) && d.Any( s => s.Key == "StartTime" && s.Value.ToString() == String.Format("{0:dd/MM/yyyy HH:mm}", _window.StartTime.ToLocalTime())) && d.Any(s => s.Key == "ReleasePlanUrl") ))); _emailTextProviderMock.Verify(e => e.GetText("SignOffAddedToReleaseWindowEmail", It.Is<Dictionary<String, Object>>(d => d.Any(s => s.Key == "Assignee" && s.Value.ToString() == evnt.SignOffs[1].Signer.FullName) && //d.Any(s => s.Key == "Products" && s.Value.ToString() == string.Join(", ", _window.Products)) && d.Any(s => s.Key == "Sprint" && s.Value.ToString() == _window.Sprint) && d.Any( s => s.Key == "StartTime" && s.Value.ToString() == String.Format("{0:dd/MM/yyyy HH:mm}", _window.StartTime.ToLocalTime())) && d.Any(s => s.Key == "ReleasePlanUrl") ))); _emailClientMock.Verify(e => e.Send(evnt.SignOffs[0].Signer.Email, string.Join(", ", _window.Products) + AddedToSignOffsSubject, _email)); _emailClientMock.Verify(e => e.Send(evnt.SignOffs[1].Signer.Email, string.Join(", ", _window.Products) + AddedToSignOffsSubject, _email)); } [Test, ExpectedException(typeof(ReleaseWindowNotFoundException))] public void Handle_ShouldThrowException_WhenSignerRemovedAndReleaseWindowNotFound() { Sut.Handle( new RemoveSignOffEvent { ReleaseWindowGuid = Guid.NewGuid() }); } [Test] public void Handle_ShouldSendEmail_WhenSignerRemoved() { var evnt = new RemoveSignOffEvent { ReleaseWindowGuid = _window.ExternalId, SignOffId = Guid.NewGuid(), AccountId = _account.ExternalId }; var acc = new Account { FullName = _account.FullName, ExternalId = evnt.AccountId, Email = _account.Email }; _accountNotificationGatewayMock.Setup(x => x.GetSubscribers(NotificationType.Signing, _window.Products)) .Returns(new List<Account> {acc}); Sut.Handle(evnt); _accountNotificationGatewayMock.Verify(x => x.GetSubscribers(NotificationType.Signing, _window.Products)); _releaseWindowGatewayMock.Verify(r => r.GetByExternalId(_window.ExternalId, false, false)); _emailTextProviderMock.Verify(e => e.GetText("SignOffRemovedFromReleaseWindowEmail", It.Is<Dictionary<String, Object>>(d => d.Any(s => s.Key == "Assignee" && s.Value.ToString() == _account.FullName) && d.Any(s => s.Key == "Products" && s.Value.ToString() == string.Join(", ", _window.Products)) && d.Any(s => s.Key == "Sprint" && s.Value.ToString() == _window.Sprint) && d.Any( s => s.Key == "StartTime" && s.Value.ToString() == String.Format("{0:dd/MM/yyyy HH:mm}", _window.StartTime.ToLocalTime())) && d.Any(s => s.Key == "ReleasePlanUrl") ))); _emailClientMock.Verify(e => e.Send(_account.Email, string.Join(", ", _window.Products) + RemovedFromSignOffsSubject, _email)); } [Test] public void Handle_ShouldSendEmail_WhenReleaseSignedOff() { var evnt = new ReleaseWindowSignedOffEvent { ReleaseWindow = _window, Context = new EventContext { UserId = Guid.NewGuid() } }; var acc = new Account { FullName = _account.FullName, Email = _account.Email }; _accountNotificationGatewayMock.Setup(x => x.GetSubscribers(NotificationType.Signing, _window.Products)) .Returns(new List<Account> { acc }); Sut.Handle(evnt); _accountNotificationGatewayMock.Verify(s => s.GetSubscribers(NotificationType.Signing, _window.Products)); _emailTextProviderMock.Verify(e => e.GetText("ReleaseWindowFullySignedOffEmail", It.Is<Dictionary<String, Object>>(d => d.Any( s => s.Key == "ListOfSignOffs" && s.Value.ToString() == string.Format("<table style='border: none'><tr><td style=\"padding-right:200px;\">Signer</td><td>Sign off criteria</td></tr><tr><td>{0}</td></tr></table>", string.Join("</td></tr><tr><td>", _signOffs.Select(x => x.Signer.FullName + "</td><td>" + x.Comment)))) && d.Any(s => s.Key == "Products" && s.Value.ToString() == string.Join(", ", _window.Products)) && d.Any(s => s.Key == "Sprint" && s.Value.ToString() == _window.Sprint) && d.Any( s => s.Key == "StartTime" && s.Value.ToString() == String.Format("{0:dd/MM/yyyy HH:mm}", _window.StartTime.ToLocalTime())) && d.Any(s => s.Key == "ReleasePlanUrl") ))); _emailClientMock.Verify(e => e.Send(It.Is<List<String>> (c => c.Contains(acc.Email)) , string.Join(", ", _window.Products) + ReleaseSignedOffSubject, _email)); } } }
using System; using UnityEditor.Experimental.GraphView; using UnityEngine; using System.Collections.Generic; using System.Reflection; using System.Linq; using Object = UnityEngine.Object; using System.Collections.ObjectModel; using UnityEngine.Experimental.VFX; namespace UnityEditor.VFX.UI { abstract class VFXNodeController : VFXController<VFXModel>, IGizmoController { protected List<VFXDataAnchorController> m_InputPorts = new List<VFXDataAnchorController>(); protected List<VFXDataAnchorController> m_OutputPorts = new List<VFXDataAnchorController>(); public ReadOnlyCollection<VFXDataAnchorController> inputPorts { get { return m_InputPorts.AsReadOnly(); } } public ReadOnlyCollection<VFXDataAnchorController> outputPorts { get { return m_OutputPorts.AsReadOnly(); } } public VFXNodeController(VFXModel model, VFXViewController viewController) : base(viewController, model) { var settings = model.GetSettings(true); m_Settings = new VFXSettingController[settings.Count()]; int cpt = 0; foreach (var setting in settings) { var settingController = new VFXSettingController(); settingController.Init(this.slotContainer, setting.Name, setting.FieldType); m_Settings[cpt++] = settingController; } } public virtual void ForceUpdate() { ModelChanged(model); } protected virtual void NewInputSet(List<VFXDataAnchorController> newInputs) { } public bool CouldLink(VFXDataAnchorController myAnchor, VFXDataAnchorController otherAnchor, VFXDataAnchorController.CanLinkCache cache) { if (myAnchor.direction == Direction.Input) return CouldLinkMyInputTo(myAnchor, otherAnchor, cache); else return otherAnchor.sourceNode.CouldLinkMyInputTo(otherAnchor, myAnchor, cache); } protected virtual bool CouldLinkMyInputTo(VFXDataAnchorController myInput, VFXDataAnchorController otherOutput, VFXDataAnchorController.CanLinkCache cache) { return false; } public void UpdateAllEditable() { foreach (var port in inputPorts) { port.UpdateEditable(); } } protected override void ModelChanged(UnityEngine.Object obj) { var inputs = inputPorts; var newAnchors = new List<VFXDataAnchorController>(); m_SyncingSlots = true; bool changed = UpdateSlots(newAnchors, slotContainer.inputSlots, true, true); NewInputSet(newAnchors); foreach (var anchorController in m_InputPorts.Except(newAnchors)) { anchorController.OnDisable(); } m_InputPorts = newAnchors; newAnchors = new List<VFXDataAnchorController>(); changed |= UpdateSlots(newAnchors, slotContainer.outputSlots, true, false); foreach (var anchorController in m_OutputPorts.Except(newAnchors)) { anchorController.OnDisable(); } m_OutputPorts = newAnchors; m_SyncingSlots = false; // Call after base.ModelChanged which ensure the ui has been refreshed before we try to create potiential new edges. if (changed) viewController.DataEdgesMightHaveChanged(); NotifyChange(AnyThing); } public virtual Vector2 position { get { return model.position; } set { model.position = new Vector2(Mathf.Round(value.x), Mathf.Round(value.y)); } } public virtual bool superCollapsed { get { return model.superCollapsed; } set { model.superCollapsed = value; if (model.superCollapsed) { model.collapsed = false; } } } public virtual string title { get { return model.name; } } public override IEnumerable<Controller> allChildren { get { return inputPorts.Cast<Controller>().Concat(outputPorts.Cast<Controller>()).Concat(m_Settings.Cast<Controller>()); } } public virtual int id { get {return 0; } } bool m_SyncingSlots; public void DataEdgesMightHaveChanged() { if (viewController != null && !m_SyncingSlots) { viewController.DataEdgesMightHaveChanged(); } } public virtual void NodeGoingToBeRemoved() { var outputEdges = outputPorts.SelectMany(t => t.connections); foreach (var edge in outputEdges) { edge.input.sourceNode.OnEdgeGoingToBeRemoved(edge.input); } } public virtual void OnEdgeGoingToBeRemoved(VFXDataAnchorController myInput) { } public virtual void WillCreateLink(ref VFXSlot myInput, ref VFXSlot otherOutput) { } protected virtual bool UpdateSlots(List<VFXDataAnchorController> newAnchors, IEnumerable<VFXSlot> slotList, bool expanded, bool input) { VFXSlot[] slots = slotList.ToArray(); bool changed = false; foreach (VFXSlot slot in slots) { VFXDataAnchorController propController = GetPropertyController(slot, input); if (propController == null) { propController = AddDataAnchor(slot, input, !expanded); changed = true; } newAnchors.Add(propController); if (!VFXDataAnchorController.SlotShouldSkipFirstLevel(slot)) { changed |= UpdateSlots(newAnchors, slot.children, expanded && propController.expandedSelf, input); } else { VFXSlot firstSlot = slot.children.First(); changed |= UpdateSlots(newAnchors, firstSlot.children, expanded && propController.expandedSelf, input); } } return changed; } public VFXDataAnchorController GetPropertyController(VFXSlot slot, bool input) { VFXDataAnchorController result = null; if (input) result = inputPorts.Cast<VFXDataAnchorController>().Where(t => t.model == slot).FirstOrDefault(); else result = outputPorts.Cast<VFXDataAnchorController>().Where(t => t.model == slot).FirstOrDefault(); return result; } protected abstract VFXDataAnchorController AddDataAnchor(VFXSlot slot, bool input, bool hidden); public IVFXSlotContainer slotContainer { get { return model as IVFXSlotContainer; } } public VFXSettingController[] settings { get { return m_Settings; } } public virtual bool expanded { get { return !slotContainer.collapsed; } set { if (value != !slotContainer.collapsed) { slotContainer.collapsed = !value; } } } public virtual void DrawGizmos(VisualEffect component) { m_GizmoableAnchors.Clear(); foreach (VFXDataAnchorController controller in inputPorts) { if (controller.model != null && controller.model.IsMasterSlot() && VFXGizmoUtility.HasGizmo(controller.portType)) { m_GizmoableAnchors.Add(controller); } } if (m_GizmoedAnchor == null) { m_GizmoedAnchor = m_GizmoableAnchors.FirstOrDefault(); } if (m_GizmoedAnchor != null) { ((VFXDataAnchorController)m_GizmoedAnchor).DrawGizmo(component); } } public virtual Bounds GetGizmoBounds(VisualEffect component) { if (m_GizmoedAnchor != null) return ((VFXDataAnchorController)m_GizmoedAnchor).GetGizmoBounds(component); return new Bounds(); } public virtual bool gizmoNeedsComponent { get { if (m_GizmoedAnchor == null) return false; return ((VFXDataAnchorController)m_GizmoedAnchor).gizmoNeedsComponent; } } public virtual bool gizmoIndeterminate { get { if (m_GizmoedAnchor == null) return true; return ((VFXDataAnchorController)m_GizmoedAnchor).gizmoIndeterminate; } } IGizmoable m_GizmoedAnchor; protected List<IGizmoable> m_GizmoableAnchors = new List<IGizmoable>(); public ReadOnlyCollection<IGizmoable> gizmoables { get { return m_GizmoableAnchors.AsReadOnly(); } } public IGizmoable currentGizmoable { get { return m_GizmoedAnchor; } set { m_GizmoedAnchor = value; } } private VFXSettingController[] m_Settings; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TableLib { public class TableString { internal List<byte> bytes; /// <summary> /// Gets the encoded text. /// </summary> /// <value>The encoded text as a byte array.</value> public byte[] Text { get { return bytes.ToArray (); } } /// <summary> /// The end token. /// </summary> public string EndToken { get; set; } public TableString() { bytes = new List<byte>(); } } public class TextEncoder { /// <summary> /// Gets the string table. /// </summary> /// <value>The string table.</value> public List<TableString> StringTable { get; private set; } /// <summary> /// Gets a value indicating whether to add end tokens for this <see cref="TableLib.TextEncoder"/>. /// </summary> /// <value><c>true</c> if end token are to be added; otherwise, <c>false</c>.</value> public bool AddEndToken { get; set; } /// <summary> /// Gets the errors encountered when loading the table file. /// </summary> /// <value>The list of errors.</value> public List<TableError> Errors { get { return Table.TableErrors; } } private TableReader Table; /// <summary> /// Initializes a new instance of the <see cref="TableLib.TextEncoder"/> class. /// </summary> public TextEncoder () { StringTable = new List<TableString>(); AddEndToken = true; Table = new TableReader(TableReaderType.ReadTypeInsert); } /// <summary> /// Encodes rawStrings as an IEnumerable of byte arrays /// </summary> /// <param name="tableName">The table file name.</param> /// <param name="addEndTokens">If set to <c>true</c>, add end tokens.</param> /// <param name="rawStrings">The collection of strings to encode.</param> /// <returns>The encoded strings.</returns> public IEnumerable<byte[]> EncodeStream (string tableName, bool addEndTokens, IEnumerable<string> rawStrings) { OpenTable(tableName); AddEndToken = addEndTokens; return rawStrings.Select(s => EncodeStream(s)).SelectMany(b => b); } /// <summary> /// Encodes rawStrings as an IEnumerable of byte arrays /// </summary> /// <param name="rawStrings">The collection of strings to encode.</param> /// <returns></returns> public IEnumerable<byte[]> EncodeStream(IEnumerable<string> rawStrings) { return rawStrings.Select(s => EncodeStream(s).SelectMany(b => b).ToArray()); } /// <summary> /// Encodes the stream. /// </summary> /// <param name="scriptBuf">The string to encode.</param> /// <returns>The encoded strings.</returns> public IEnumerable<byte[]> EncodeStream(string scriptBuf) { var start = StringTable.Count; int badCharOffset = 0; int bytesEncoded = EncodeStream(scriptBuf, ref badCharOffset); if (bytesEncoded < 0) { throw new Exception("Encountered unmapped string beginning with '" + scriptBuf[badCharOffset] + "'"); } if (StringTable.Count == 0) { return null; } if (start == 0) { return StringTable.Select(s => s.Text); } return Enumerable.Range(start, StringTable.Count - start).Select(n => StringTable[n].Text); } /// <summary> /// Encodes a string. /// </summary> /// <param name="scriptBuf">The string to encode.</param> /// <param name="BadCharOffset">The Bad char offset.</param> /// <returns>The size of the encoded stream.</returns> public int EncodeStream (string scriptBuf, ref int BadCharOffset) { TableString tablestring = new TableString(); string hexstr = string.Empty; string subtextstr = string.Empty; int i = 0; int EncodedSize = 0; int BufOffset = 0; BadCharOffset = 0; if (string.IsNullOrEmpty(scriptBuf)) { return 0; } if (StringTable.Count > 0) { TableString restoreString = StringTable[StringTable.Count - 1]; if (string.IsNullOrEmpty(restoreString.EndToken)) { StringTable.RemoveAt(StringTable.Count - 1); tablestring.bytes = restoreString.bytes; } } while (BufOffset < scriptBuf.Length) { int longestText = Table.LongestText[scriptBuf[BufOffset]]; for (i = longestText; i > 0; --i) { if (BufOffset + i >= scriptBuf.Length) { subtextstr = scriptBuf.Substring(BufOffset); } else { subtextstr = scriptBuf.Substring(BufOffset, i); } if (Table.LookupValue.ContainsKey(subtextstr)) { hexstr = Table.LookupValue[subtextstr]; EncodedSize += hexstr.Length; if (Table.EndTokens.Contains(subtextstr)) { if (AddEndToken) { AddToTable(hexstr, tablestring); } tablestring.EndToken = subtextstr; StringTable.Add(tablestring); tablestring = new TableString(); } else { AddToTable(hexstr, tablestring); } BufOffset += i; break; } } if (i == 0) { BadCharOffset = BufOffset; return -1; } } if (tablestring.bytes.Count > 0) { StringTable.Add(tablestring); } return EncodedSize; } /// <summary> /// Opens the table. /// </summary> /// <param name="tableFileName">The table file name.</param> /// <returns><c>true</c>, if table was opened successfully, <c>false</c> otherwise.</returns> public bool OpenTable (string tableFileName) { return OpenTable(tableFileName, Encoding.UTF8); } /// <summary> /// Opens the table. /// </summary> /// <param name="tableFileName">The table file name.</param> /// <param name="encoding">The specified character encoding.</param> /// <returns><c>true</c>, if table was opened successfully, <c>false</c> otherwise.</returns> public bool OpenTable (string tableFileName, Encoding encoding) { return Table.OpenTable(tableFileName, encoding); } /// <summary> /// Opens the table. /// </summary> /// <param name="TableFileName">Table file name.</param> /// <param name="encoding">The name of the character encoding</param> /// <returns><c>true</c>, if table was opened, <c>false</c> otherwise.</returns> public bool OpenTable (string tableFileName, string encoding) { return Table.OpenTable(tableFileName, Encoding.GetEncoding(encoding)); } private void AddToTable (string HexString, TableString tableString) { for (int k = 0; k < HexString.Length; k +=2) { tableString.bytes.Add(Convert.ToByte(HexString.Substring(k, 2), 16)); } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Logging.V2 { /// <summary> /// Settings for a <see cref="MetricsServiceV2Client"/>. /// </summary> public sealed partial class MetricsServiceV2Settings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="MetricsServiceV2Settings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="MetricsServiceV2Settings"/>. /// </returns> public static MetricsServiceV2Settings GetDefault() => new MetricsServiceV2Settings(); /// <summary> /// Constructs a new <see cref="MetricsServiceV2Settings"/> object with default settings. /// </summary> public MetricsServiceV2Settings() { } private MetricsServiceV2Settings(MetricsServiceV2Settings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListLogMetricsSettings = existing.ListLogMetricsSettings; GetLogMetricSettings = existing.GetLogMetricSettings; CreateLogMetricSettings = existing.CreateLogMetricSettings; UpdateLogMetricSettings = existing.UpdateLogMetricSettings; DeleteLogMetricSettings = existing.DeleteLogMetricSettings; OnCopy(existing); } partial void OnCopy(MetricsServiceV2Settings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="MetricsServiceV2Client"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Internal"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Internal, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="MetricsServiceV2Client"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 1000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.2</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(1000), delayMultiplier: 1.2 ); /// <summary> /// "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Maximum timeout: 60000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.5 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>MetricsServiceV2Client.ListLogMetrics</c> and <c>MetricsServiceV2Client.ListLogMetricsAsync</c>. /// </summary> /// <remarks> /// The default <c>MetricsServiceV2Client.ListLogMetrics</c> and /// <c>MetricsServiceV2Client.ListLogMetricsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Internal"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 90000 milliseconds. /// </remarks> public CallSettings ListLogMetricsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(90000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>MetricsServiceV2Client.GetLogMetric</c> and <c>MetricsServiceV2Client.GetLogMetricAsync</c>. /// </summary> /// <remarks> /// The default <c>MetricsServiceV2Client.GetLogMetric</c> and /// <c>MetricsServiceV2Client.GetLogMetricAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Internal"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 90000 milliseconds. /// </remarks> public CallSettings GetLogMetricSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(90000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>MetricsServiceV2Client.CreateLogMetric</c> and <c>MetricsServiceV2Client.CreateLogMetricAsync</c>. /// </summary> /// <remarks> /// The default <c>MetricsServiceV2Client.CreateLogMetric</c> and /// <c>MetricsServiceV2Client.CreateLogMetricAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 90000 milliseconds. /// </remarks> public CallSettings CreateLogMetricSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(90000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>MetricsServiceV2Client.UpdateLogMetric</c> and <c>MetricsServiceV2Client.UpdateLogMetricAsync</c>. /// </summary> /// <remarks> /// The default <c>MetricsServiceV2Client.UpdateLogMetric</c> and /// <c>MetricsServiceV2Client.UpdateLogMetricAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 90000 milliseconds. /// </remarks> public CallSettings UpdateLogMetricSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(90000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>MetricsServiceV2Client.DeleteLogMetric</c> and <c>MetricsServiceV2Client.DeleteLogMetricAsync</c>. /// </summary> /// <remarks> /// The default <c>MetricsServiceV2Client.DeleteLogMetric</c> and /// <c>MetricsServiceV2Client.DeleteLogMetricAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Internal"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 90000 milliseconds. /// </remarks> public CallSettings DeleteLogMetricSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(90000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="MetricsServiceV2Settings"/> object.</returns> public MetricsServiceV2Settings Clone() => new MetricsServiceV2Settings(this); } /// <summary> /// MetricsServiceV2 client wrapper, for convenient use. /// </summary> public abstract partial class MetricsServiceV2Client { /// <summary> /// The default endpoint for the MetricsServiceV2 service, which is a host of "logging.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("logging.googleapis.com", 443); /// <summary> /// The default MetricsServiceV2 scopes. /// </summary> /// <remarks> /// The default MetricsServiceV2 scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/cloud-platform.read-only"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.admin"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.read"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.write"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read", "https://www.googleapis.com/auth/logging.write", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="MetricsServiceV2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param> /// <returns>The task representing the created <see cref="MetricsServiceV2Client"/>.</returns> public static async Task<MetricsServiceV2Client> CreateAsync(ServiceEndpoint endpoint = null, MetricsServiceV2Settings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="MetricsServiceV2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param> /// <returns>The created <see cref="MetricsServiceV2Client"/>.</returns> public static MetricsServiceV2Client Create(ServiceEndpoint endpoint = null, MetricsServiceV2Settings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="MetricsServiceV2Client"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param> /// <returns>The created <see cref="MetricsServiceV2Client"/>.</returns> public static MetricsServiceV2Client Create(Channel channel, MetricsServiceV2Settings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); MetricsServiceV2.MetricsServiceV2Client grpcClient = new MetricsServiceV2.MetricsServiceV2Client(channel); return new MetricsServiceV2ClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, MetricsServiceV2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, MetricsServiceV2Settings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, MetricsServiceV2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, MetricsServiceV2Settings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC MetricsServiceV2 client. /// </summary> public virtual MetricsServiceV2.MetricsServiceV2Client GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="parent"> /// Required. The name of the project containing the metrics: /// /// "projects/[PROJECT_ID]" /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="LogMetric"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync( ParentNameOneof parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListLogMetricsAsync( new ListLogMetricsRequest { ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="parent"> /// Required. The name of the project containing the metrics: /// /// "projects/[PROJECT_ID]" /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="LogMetric"/> resources. /// </returns> public virtual PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics( ParentNameOneof parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListLogMetrics( new ListLogMetricsRequest { ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="LogMetric"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync( ListLogMetricsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="LogMetric"/> resources. /// </returns> public virtual PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics( ListLogMetricsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the desired metric: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> GetLogMetricAsync( MetricNameOneof metricName, CallSettings callSettings = null) => GetLogMetricAsync( new GetLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), }, callSettings); /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the desired metric: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> GetLogMetricAsync( MetricNameOneof metricName, CancellationToken cancellationToken) => GetLogMetricAsync( metricName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the desired metric: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric GetLogMetric( MetricNameOneof metricName, CallSettings callSettings = null) => GetLogMetric( new GetLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), }, callSettings); /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> GetLogMetricAsync( GetLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric GetLogMetric( GetLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="parent"> /// The resource name of the project in which to create the metric: /// /// "projects/[PROJECT_ID]" /// /// The new metric must be provided in the request. /// </param> /// <param name="metric"> /// The new logs-based metric, which must not have an identifier that /// already exists. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> CreateLogMetricAsync( ParentNameOneof parent, LogMetric metric, CallSettings callSettings = null) => CreateLogMetricAsync( new CreateLogMetricRequest { ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)), Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)), }, callSettings); /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="parent"> /// The resource name of the project in which to create the metric: /// /// "projects/[PROJECT_ID]" /// /// The new metric must be provided in the request. /// </param> /// <param name="metric"> /// The new logs-based metric, which must not have an identifier that /// already exists. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> CreateLogMetricAsync( ParentNameOneof parent, LogMetric metric, CancellationToken cancellationToken) => CreateLogMetricAsync( parent, metric, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="parent"> /// The resource name of the project in which to create the metric: /// /// "projects/[PROJECT_ID]" /// /// The new metric must be provided in the request. /// </param> /// <param name="metric"> /// The new logs-based metric, which must not have an identifier that /// already exists. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric CreateLogMetric( ParentNameOneof parent, LogMetric metric, CallSettings callSettings = null) => CreateLogMetric( new CreateLogMetricRequest { ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)), Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)), }, callSettings); /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> CreateLogMetricAsync( CreateLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric CreateLogMetric( CreateLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to update: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// /// The updated metric must be provided in the request and it's /// `name` field must be the same as `[METRIC_ID]` If the metric /// does not exist in `[PROJECT_ID]`, then a new metric is created. /// </param> /// <param name="metric"> /// The updated metric. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> UpdateLogMetricAsync( MetricNameOneof metricName, LogMetric metric, CallSettings callSettings = null) => UpdateLogMetricAsync( new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)), }, callSettings); /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to update: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// /// The updated metric must be provided in the request and it's /// `name` field must be the same as `[METRIC_ID]` If the metric /// does not exist in `[PROJECT_ID]`, then a new metric is created. /// </param> /// <param name="metric"> /// The updated metric. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> UpdateLogMetricAsync( MetricNameOneof metricName, LogMetric metric, CancellationToken cancellationToken) => UpdateLogMetricAsync( metricName, metric, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to update: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// /// The updated metric must be provided in the request and it's /// `name` field must be the same as `[METRIC_ID]` If the metric /// does not exist in `[PROJECT_ID]`, then a new metric is created. /// </param> /// <param name="metric"> /// The updated metric. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric UpdateLogMetric( MetricNameOneof metricName, LogMetric metric, CallSettings callSettings = null) => UpdateLogMetric( new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)), }, callSettings); /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogMetric> UpdateLogMetricAsync( UpdateLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogMetric UpdateLogMetric( UpdateLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to delete: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteLogMetricAsync( MetricNameOneof metricName, CallSettings callSettings = null) => DeleteLogMetricAsync( new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), }, callSettings); /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to delete: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteLogMetricAsync( MetricNameOneof metricName, CancellationToken cancellationToken) => DeleteLogMetricAsync( metricName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="metricName"> /// The resource name of the metric to delete: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteLogMetric( MetricNameOneof metricName, CallSettings callSettings = null) => DeleteLogMetric( new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)), }, callSettings); /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteLogMetricAsync( DeleteLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteLogMetric( DeleteLogMetricRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// MetricsServiceV2 client wrapper implementation, for convenient use. /// </summary> public sealed partial class MetricsServiceV2ClientImpl : MetricsServiceV2Client { private readonly ApiCall<ListLogMetricsRequest, ListLogMetricsResponse> _callListLogMetrics; private readonly ApiCall<GetLogMetricRequest, LogMetric> _callGetLogMetric; private readonly ApiCall<CreateLogMetricRequest, LogMetric> _callCreateLogMetric; private readonly ApiCall<UpdateLogMetricRequest, LogMetric> _callUpdateLogMetric; private readonly ApiCall<DeleteLogMetricRequest, Empty> _callDeleteLogMetric; /// <summary> /// Constructs a client wrapper for the MetricsServiceV2 service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="MetricsServiceV2Settings"/> used within this client </param> public MetricsServiceV2ClientImpl(MetricsServiceV2.MetricsServiceV2Client grpcClient, MetricsServiceV2Settings settings) { GrpcClient = grpcClient; MetricsServiceV2Settings effectiveSettings = settings ?? MetricsServiceV2Settings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callListLogMetrics = clientHelper.BuildApiCall<ListLogMetricsRequest, ListLogMetricsResponse>( GrpcClient.ListLogMetricsAsync, GrpcClient.ListLogMetrics, effectiveSettings.ListLogMetricsSettings); _callGetLogMetric = clientHelper.BuildApiCall<GetLogMetricRequest, LogMetric>( GrpcClient.GetLogMetricAsync, GrpcClient.GetLogMetric, effectiveSettings.GetLogMetricSettings); _callCreateLogMetric = clientHelper.BuildApiCall<CreateLogMetricRequest, LogMetric>( GrpcClient.CreateLogMetricAsync, GrpcClient.CreateLogMetric, effectiveSettings.CreateLogMetricSettings); _callUpdateLogMetric = clientHelper.BuildApiCall<UpdateLogMetricRequest, LogMetric>( GrpcClient.UpdateLogMetricAsync, GrpcClient.UpdateLogMetric, effectiveSettings.UpdateLogMetricSettings); _callDeleteLogMetric = clientHelper.BuildApiCall<DeleteLogMetricRequest, Empty>( GrpcClient.DeleteLogMetricAsync, GrpcClient.DeleteLogMetric, effectiveSettings.DeleteLogMetricSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(MetricsServiceV2.MetricsServiceV2Client grpcClient, MetricsServiceV2Settings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC MetricsServiceV2 client. /// </summary> public override MetricsServiceV2.MetricsServiceV2Client GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_ListLogMetricsRequest(ref ListLogMetricsRequest request, ref CallSettings settings); partial void Modify_GetLogMetricRequest(ref GetLogMetricRequest request, ref CallSettings settings); partial void Modify_CreateLogMetricRequest(ref CreateLogMetricRequest request, ref CallSettings settings); partial void Modify_UpdateLogMetricRequest(ref UpdateLogMetricRequest request, ref CallSettings settings); partial void Modify_DeleteLogMetricRequest(ref DeleteLogMetricRequest request, ref CallSettings settings); /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="LogMetric"/> resources. /// </returns> public override PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync( ListLogMetricsRequest request, CallSettings callSettings = null) { Modify_ListLogMetricsRequest(ref request, ref callSettings); return new GrpcPagedAsyncEnumerable<ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>(_callListLogMetrics, request, callSettings); } /// <summary> /// Lists logs-based metrics. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="LogMetric"/> resources. /// </returns> public override PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics( ListLogMetricsRequest request, CallSettings callSettings = null) { Modify_ListLogMetricsRequest(ref request, ref callSettings); return new GrpcPagedEnumerable<ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>(_callListLogMetrics, request, callSettings); } /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogMetric> GetLogMetricAsync( GetLogMetricRequest request, CallSettings callSettings = null) { Modify_GetLogMetricRequest(ref request, ref callSettings); return _callGetLogMetric.Async(request, callSettings); } /// <summary> /// Gets a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogMetric GetLogMetric( GetLogMetricRequest request, CallSettings callSettings = null) { Modify_GetLogMetricRequest(ref request, ref callSettings); return _callGetLogMetric.Sync(request, callSettings); } /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogMetric> CreateLogMetricAsync( CreateLogMetricRequest request, CallSettings callSettings = null) { Modify_CreateLogMetricRequest(ref request, ref callSettings); return _callCreateLogMetric.Async(request, callSettings); } /// <summary> /// Creates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogMetric CreateLogMetric( CreateLogMetricRequest request, CallSettings callSettings = null) { Modify_CreateLogMetricRequest(ref request, ref callSettings); return _callCreateLogMetric.Sync(request, callSettings); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogMetric> UpdateLogMetricAsync( UpdateLogMetricRequest request, CallSettings callSettings = null) { Modify_UpdateLogMetricRequest(ref request, ref callSettings); return _callUpdateLogMetric.Async(request, callSettings); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogMetric UpdateLogMetric( UpdateLogMetricRequest request, CallSettings callSettings = null) { Modify_UpdateLogMetricRequest(ref request, ref callSettings); return _callUpdateLogMetric.Sync(request, callSettings); } /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task DeleteLogMetricAsync( DeleteLogMetricRequest request, CallSettings callSettings = null) { Modify_DeleteLogMetricRequest(ref request, ref callSettings); return _callDeleteLogMetric.Async(request, callSettings); } /// <summary> /// Deletes a logs-based metric. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void DeleteLogMetric( DeleteLogMetricRequest request, CallSettings callSettings = null) { Modify_DeleteLogMetricRequest(ref request, ref callSettings); _callDeleteLogMetric.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListLogMetricsRequest : IPageRequest { } public partial class ListLogMetricsResponse : IPageResponse<LogMetric> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<LogMetric> GetEnumerator() => Metrics.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
namespace NEventStore.Persistence.InMemory { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; using NEventStore.Logging; public class InMemoryPersistenceEngine : IPersistStreams { private static readonly ILogger Logger = LogFactory.BuildLogger(typeof(InMemoryPersistenceEngine)); private readonly ConcurrentDictionary<string, Bucket> _buckets = new ConcurrentDictionary<string, Bucket>(); private bool _disposed; private int _checkpoint; private Bucket this[string bucketId] { get { return _buckets.GetOrAdd(bucketId, _ => new Bucket()); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Initialize() { Logger.LogInformation(Resources.InitializingEngine); } public IEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingAllCommitsFromRevision, streamId, bucketId, minRevision, maxRevision); return this[bucketId].GetFrom(streamId, minRevision, maxRevision); } public IEnumerable<ICommit> GetFrom(string bucketId, DateTime start) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingAllCommitsFromTime, bucketId, start); return this[bucketId].GetFrom(start); } public IEnumerable<ICommit> GetFrom(string bucketId, Int64 checkpointToken) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingAllCommitsFromBucketAndCheckpoint, bucketId, checkpointToken); return this[bucketId].GetFrom(checkpointToken); } public IEnumerable<ICommit> GetFromTo(string bucketId, Int64 from, Int64 to) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingCommitsFromBucketAndFromToCheckpoint, bucketId, from, to); return this[bucketId].GetFromTo(from, to); } public IEnumerable<ICommit> GetFrom(Int64 checkpointToken) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingAllCommitsFromCheckpoint, checkpointToken); return _buckets .Values .SelectMany(b => b.GetCommits()) .Where(c => c.CheckpointToken.CompareTo(checkpointToken) > 0) .OrderBy(c => c.CheckpointToken) .ToArray(); } public IEnumerable<ICommit> GetFromTo(Int64 from, Int64 to) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingCommitsFromToCheckpoint, from, to); return _buckets .Values .SelectMany(b => b.GetCommits()) .Where(c => c.CheckpointToken.CompareTo(from) > 0 && c.CheckpointToken.CompareTo(to) <= 0) .OrderBy(c => c.CheckpointToken) .ToArray(); } public IEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingAllCommitsFromToTime, start, end); return this[bucketId].GetFromTo(start, end); } public ICommit Commit(CommitAttempt attempt) { ThrowWhenDisposed(); Logger.LogDebug(Resources.AttemptingToCommit, attempt.CommitId, attempt.StreamId, attempt.BucketId, attempt.CommitSequence); return this[attempt.BucketId].Commit(attempt, Interlocked.Increment(ref _checkpoint)); } public IEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingStreamsToSnapshot, bucketId, maxThreshold); return this[bucketId].GetStreamsToSnapshot(maxThreshold); } public ISnapshot GetSnapshot(string bucketId, string streamId, int maxRevision) { ThrowWhenDisposed(); Logger.LogDebug(Resources.GettingSnapshotForStream, bucketId, streamId, maxRevision); return this[bucketId].GetSnapshot(streamId, maxRevision); } public bool AddSnapshot(ISnapshot snapshot) { ThrowWhenDisposed(); Logger.LogDebug(Resources.AddingSnapshot, snapshot.BucketId, snapshot.StreamId, snapshot.StreamRevision); return this[snapshot.BucketId].AddSnapshot(snapshot); } public void Purge() { ThrowWhenDisposed(); Logger.LogWarning(Resources.PurgingStore); foreach (var bucket in _buckets.Values) { bucket.Purge(); } } public void Purge(string bucketId) { Bucket _; _buckets.TryRemove(bucketId, out _); } public void Drop() { _buckets.Clear(); } public void DeleteStream(string bucketId, string streamId) { Logger.LogWarning(Resources.DeletingStream, streamId, bucketId); if (!_buckets.TryGetValue(bucketId, out Bucket bucket)) { return; } bucket.DeleteStream(streamId); } public bool IsDisposed { get { return _disposed; } } #pragma warning disable RCS1163 // Unused parameter. #pragma warning disable IDE0060 // Remove unused parameter private void Dispose(bool disposing) #pragma warning restore IDE0060 // Remove unused parameter #pragma warning restore RCS1163 // Unused parameter. { _disposed = true; Logger.LogInformation(Resources.DisposingEngine); } private void ThrowWhenDisposed() { if (!_disposed) { return; } Logger.LogWarning(Resources.AlreadyDisposed); throw new ObjectDisposedException(Resources.AlreadyDisposed); } private class InMemoryCommit : Commit { public InMemoryCommit( string bucketId, string streamId, int streamRevision, Guid commitId, int commitSequence, DateTime commitStamp, Int64 checkpointToken, IDictionary<string, object> headers, ICollection<EventMessage> events) : base(bucketId, streamId, streamRevision, commitId, commitSequence, commitStamp, checkpointToken, headers, events) { } } private class IdentityForConcurrencyConflictDetection { protected bool Equals(IdentityForConcurrencyConflictDetection other) { return string.Equals(this.streamId, other.streamId) && string.Equals(this.bucketId, other.bucketId) && this.commitSequence == other.commitSequence; } public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForConcurrencyConflictDetection)obj); } public override int GetHashCode() { unchecked { int hashCode = this.streamId.GetHashCode(); hashCode = (hashCode * 397) ^ this.bucketId.GetHashCode(); return (hashCode * 397) ^ this.commitSequence; } } private readonly int commitSequence; private readonly string bucketId; private readonly string streamId; public IdentityForConcurrencyConflictDetection(CommitAttempt commitAttempt) { bucketId = commitAttempt.BucketId; streamId = commitAttempt.StreamId; commitSequence = commitAttempt.CommitSequence; } public IdentityForConcurrencyConflictDetection(Commit commit) { bucketId = commit.BucketId; streamId = commit.StreamId; commitSequence = commit.CommitSequence; } } private class IdentityForDuplicationDetection { protected bool Equals(IdentityForDuplicationDetection other) { return string.Equals(this.streamId, other.streamId) && string.Equals(this.bucketId, other.bucketId) && this.commitId.Equals(other.commitId); } public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForDuplicationDetection)obj); } public override int GetHashCode() { unchecked { int hashCode = this.streamId.GetHashCode(); hashCode = (hashCode * 397) ^ this.bucketId.GetHashCode(); return (hashCode * 397) ^ this.commitId.GetHashCode(); } } private readonly Guid commitId; private readonly string bucketId; private readonly string streamId; public IdentityForDuplicationDetection(CommitAttempt commitAttempt) { bucketId = commitAttempt.BucketId; streamId = commitAttempt.StreamId; commitId = commitAttempt.CommitId; } public IdentityForDuplicationDetection(Commit commit) { bucketId = commit.BucketId; streamId = commit.StreamId; commitId = commit.CommitId; } } private class Bucket { private readonly IList<InMemoryCommit> _commits = new List<InMemoryCommit>(); private readonly ICollection<IdentityForDuplicationDetection> _potentialDuplicates = new HashSet<IdentityForDuplicationDetection>(); private readonly ICollection<IdentityForConcurrencyConflictDetection> _potentialConflicts = new HashSet<IdentityForConcurrencyConflictDetection>(); public IEnumerable<InMemoryCommit> GetCommits() { lock (_commits) { return _commits.ToArray(); } } private readonly ICollection<IStreamHead> _heads = new LinkedList<IStreamHead>(); private readonly ICollection<ISnapshot> _snapshots = new LinkedList<ISnapshot>(); private readonly IDictionary<Guid, DateTime> _stamps = new Dictionary<Guid, DateTime>(); public IEnumerable<ICommit> GetFrom(string streamId, int minRevision, int maxRevision) { lock (_commits) { return _commits .Where(x => x.StreamId == streamId && x.StreamRevision >= minRevision && (x.StreamRevision - x.Events.Count + 1) <= maxRevision) .OrderBy(c => c.CommitSequence) .ToArray(); } } public IEnumerable<ICommit> GetFrom(DateTime start) { Guid commitId = _stamps.Where(x => x.Value >= start).Select(x => x.Key).FirstOrDefault(); if (commitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == commitId); return _commits.Skip(_commits.IndexOf(startingCommit)); } public IEnumerable<ICommit> GetFrom(Int64 checkpoint) { InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CheckpointToken.CompareTo(checkpoint) == 0); return _commits.Skip(_commits.IndexOf(startingCommit) + 1 /* GetFrom => after the checkpoint*/); } public IEnumerable<ICommit> GetFromTo(Int64 from, Int64 to) { InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CheckpointToken.CompareTo(from) == 0); return _commits.Skip(_commits.IndexOf(startingCommit) + 1 /* GetFrom => after the checkpoint*/) .TakeWhile(c => c.CheckpointToken <= to); } public IEnumerable<ICommit> GetFromTo(DateTime start, DateTime end) { IEnumerable<Guid> selectedCommitIds = _stamps.Where(x => x.Value >= start && x.Value < end).Select(x => x.Key).ToArray(); Guid firstCommitId = selectedCommitIds.FirstOrDefault(); Guid lastCommitId = selectedCommitIds.LastOrDefault(); if (lastCommitId == Guid.Empty && lastCommitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == firstCommitId); InMemoryCommit endingCommit = _commits.FirstOrDefault(x => x.CommitId == lastCommitId); int startingCommitIndex = (startingCommit == null) ? 0 : _commits.IndexOf(startingCommit); int endingCommitIndex = (endingCommit == null) ? _commits.Count - 1 : _commits.IndexOf(endingCommit); int numberToTake = endingCommitIndex - startingCommitIndex + 1; return _commits.Skip(_commits.IndexOf(startingCommit)).Take(numberToTake); } public ICommit Commit(CommitAttempt attempt, Int64 checkpoint) { lock (_commits) { DetectDuplicate(attempt); var commit = new InMemoryCommit(attempt.BucketId, attempt.StreamId, attempt.StreamRevision, attempt.CommitId, attempt.CommitSequence, attempt.CommitStamp, checkpoint, attempt.Headers, attempt.Events); if (_potentialConflicts.Contains(new IdentityForConcurrencyConflictDetection(commit))) { throw new ConcurrencyException(); } _stamps[commit.CommitId] = commit.CommitStamp; _commits.Add(commit); _potentialDuplicates.Add(new IdentityForDuplicationDetection(commit)); _potentialConflicts.Add(new IdentityForConcurrencyConflictDetection(commit)); IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId); _heads.Remove(head); Logger.LogDebug(Resources.UpdatingStreamHead, commit.StreamId, commit.BucketId); int snapshotRevision = head?.SnapshotRevision ?? 0; _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision)); return commit; } } private void DetectDuplicate(CommitAttempt attempt) { if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt))) { throw new DuplicateCommitException(String.Format(Messages.DuplicateCommitIdException, attempt.StreamId, attempt.BucketId, attempt.CommitId)); } } public IEnumerable<IStreamHead> GetStreamsToSnapshot(int maxThreshold) { lock (_commits) { return _heads .Where(x => x.HeadRevision >= x.SnapshotRevision + maxThreshold) .Select(stream => new StreamHead(stream.BucketId, stream.StreamId, stream.HeadRevision, stream.SnapshotRevision)); } } public ISnapshot GetSnapshot(string streamId, int maxRevision) { lock (_commits) { return _snapshots .Where(x => x.StreamId == streamId && x.StreamRevision <= maxRevision) .OrderByDescending(x => x.StreamRevision) .FirstOrDefault(); } } public bool AddSnapshot(ISnapshot snapshot) { lock (_commits) { IStreamHead currentHead = _heads.FirstOrDefault(h => h.StreamId == snapshot.StreamId); if (currentHead == null) { return false; } // if the snapshot is already there do NOT add it (follow the SQL implementation) // and the original GetSnapshot behavior which was to return the first one that was // added to the collection if (_snapshots.Any(s => s.StreamId == snapshot.StreamId && s.StreamRevision == snapshot.StreamRevision)) { return false; } _snapshots.Add(snapshot); _heads.Remove(currentHead); _heads.Add(new StreamHead(currentHead.BucketId, currentHead.StreamId, currentHead.HeadRevision, snapshot.StreamRevision)); } return true; } public void Purge() { lock (_commits) { _commits.Clear(); _snapshots.Clear(); _heads.Clear(); _potentialConflicts.Clear(); _potentialDuplicates.Clear(); } } public void DeleteStream(string streamId) { lock (_commits) { InMemoryCommit[] commits = _commits.Where(c => c.StreamId == streamId).ToArray(); foreach (var commit in commits) { _commits.Remove(commit); } ISnapshot[] snapshots = _snapshots.Where(s => s.StreamId == streamId).ToArray(); foreach (var snapshot in snapshots) { _snapshots.Remove(snapshot); } IStreamHead streamHead = _heads.SingleOrDefault(s => s.StreamId == streamId); if (streamHead != null) { _heads.Remove(streamHead); } } } } } }
#nullable disable using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using WWT.Imaging; using WWT.PlateFiles; namespace WWT.Providers { [RequestEndpoint("/wwtweb/TileImage.aspx")] public class TileImageProvider : RequestProvider { private readonly IFileNameHasher _hasher; private readonly HttpClient _httpClient; private readonly ITileAccessor _tileAccessor; private readonly string _tempDir; public TileImageProvider(IFileNameHasher hasher, ITileAccessor tileAccessor) { _hasher = hasher; _httpClient = new HttpClient(); _tileAccessor = tileAccessor; _tempDir = Path.Combine(Path.GetTempPath(), "wwt_temp"); if (!Directory.Exists(_tempDir)) { Directory.CreateDirectory(_tempDir); } } public override string ContentType => ContentTypes.XWtml; public override async Task RunAsync(IWwtContext context, CancellationToken token) { { if (context.Request.Params["debug"] != null) { context.Response.ClearHeaders(); context.Response.ContentType = "text/plain"; } string url = ""; if (context.Request.Params["imageurl"] != null) { url = context.Request.Params["imageurl"]; } if (string.IsNullOrEmpty(url)) { url = "http://www.spitzer.caltech.edu/uploaded_files/images/0009/0848/sig12-011.jpg"; } var id = _hasher.HashName(url).ToString(); var filename = await DownloadFileAsync(url, id, token); var wcsImage = WcsImage.FromFile(filename); if (wcsImage != null) { var creator = _tileAccessor.CreateTile(id); if (!await creator.ExistsAsync(token)) { using var bmp = wcsImage.GetBitmap(); wcsImage.AdjustScale(bmp.Width, bmp.Height); await MakeThumbnailAsync(bmp, creator, token); await TileBitmap(bmp, creator, token); } string name = wcsImage.Keywords[0]; bool reverseparity = false; string creditsUrl = wcsImage.CreditsUrl; string credits = wcsImage.Copyright; string thumb = "http://www.worldwidetelescope.org/wwtweb/tilethumb.aspx?name=" + id; double rotation = wcsImage.Rotation; int maxLevels = CalcMaxLevels((int)wcsImage.SizeX, (int)wcsImage.SizeY); double scale = wcsImage.ScaleY * Math.Pow(2, maxLevels) * 256; double y = 0; double x = 0; double dec = wcsImage.CenterY; double ra = wcsImage.CenterX; if (context.Request.Params["debug"] != null) { name = context.Request.Params["name"]; name = name.Replace(",", ""); } if (context.Request.Params["ra"] != null) { ra = Math.Max(0, Math.Min(360.0, Convert.ToDouble(context.Request.Params["ra"]))); } if (context.Request.Params["dec"] != null) { dec = Math.Max(-90, Math.Min(90, Convert.ToDouble(context.Request.Params["dec"]))); } if (context.Request.Params["x"] != null) { x = Convert.ToDouble(context.Request.Params["x"]); } if (context.Request.Params["y"] != null) { y = Convert.ToDouble(context.Request.Params["y"]); } if (context.Request.Params["scale"] != null) { scale = Convert.ToDouble(context.Request.Params["scale"]) * Math.Pow(2, maxLevels) * 256; } if (context.Request.Params["rotation"] != null) { rotation = Convert.ToDouble(context.Request.Params["rotation"]) - 180; } if (context.Request.Params["thumb"] != null) { thumb = context.Request.Params["thumb"]; } if (context.Request.Params["credits"] != null) { credits = context.Request.Params["credits"]; } if (context.Request.Params["creditsUrl"] != null) { creditsUrl = context.Request.Params["creditsUrl"]; } if (context.Request.Params["reverseparity"] != null) { reverseparity = Convert.ToBoolean(context.Request.Params["reverseparity"]); } if (context.Request.Params["goto"] != null) { bool bgoto = Convert.ToBoolean(context.Request.Params["goto"]); } if (scale == 0) { scale = .1; } double zoom = scale * 4; string xml = string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Folder Name=\"{0}\" Group=\"{14}\">\n<Place Name=\"{0}\" RA=\"{1}\" Dec=\"{2}\" ZoomLevel=\"{3}\" DataSetType=\"Sky\" Opacity=\"100\" Thumbnail=\"{10}\" Constellation=\"\">\n <ForegroundImageSet>\n <ImageSet DataSetType=\"Sky\" Name=\"{0}\" BandPass=\"Visible\" Url=\"http://www.worldwidetelescope.org/wwtweb/GetTile.aspx?q={{1}},{{2}},{{3}},{8}\" TileLevels=\"{15}\" WidthFactor=\"1\" Rotation=\"{5}\" Projection=\"Tan\" FileType=\".png\" CenterY=\"{2}\" CenterX=\"{9}\" BottomsUp=\"{13}\" OffsetX=\"{6}\" OffsetY=\"{7}\" BaseTileLevel=\"0\" BaseDegreesPerTile=\"{4}\">\n<Credits>{11}</Credits>\n<CreditsUrl>{12}</CreditsUrl>\n<ThumbnailUrl>{10}</ThumbnailUrl>\n</ImageSet>\n</ForegroundImageSet>\n</Place>\n</Folder>", name, ra / 15, dec, zoom, scale, rotation, x, y, id, ra, thumb, credits, creditsUrl, reverseparity, "Explorer", maxLevels); await context.Response.WriteAsync(xml, token); } } } public async Task TileBitmap(Bitmap bmp, ITileCreator creator, CancellationToken token) { int width = bmp.Width; int height = bmp.Height; double aspect = (double)width / (double)height; //narrower int levels = 1; int maxHeight = 256; int maxWidth = 512; do { if (aspect < 2) { if (maxHeight >= height) { break; } } else { if (maxWidth >= width) { break; } } levels++; maxHeight *= 2; maxWidth *= 2; } while (true); int xOffset = (maxWidth - width) / 2; int yOffset = (maxHeight - height) / 2; int l = levels; int gridX = 256; int gridY = 256; while (l > 0) { l--; int currentLevel = l; int tilesX = 2 * (int)Math.Pow(2, l); int tilesY = (int)Math.Pow(2, l); for (int y = 0; y < tilesY; y++) { for (int x = 0; x < tilesX; x++) { if ((((x + 1) * gridX) > xOffset) && (((y + 1) * gridX) > yOffset) && (((x) * gridX) < (xOffset + width)) && (((y) * gridX) < (yOffset + height))) { using Bitmap bmpTile = new Bitmap(256, 256); using (Graphics gfx = Graphics.FromImage(bmpTile)) { gfx.DrawImage(bmp, new Rectangle(0, 0, 256, 256), new Rectangle((x * gridX) - xOffset, (y * gridX) - yOffset, gridX, gridX), GraphicsUnit.Pixel); } using var stream = bmpTile.SaveToStream(ImageFormat.Png); await creator.AddTileAsync(stream, currentLevel, x, y, token); } } } gridX *= 2; gridY *= 2; } } public async Task MakeThumbnailAsync(Bitmap imgOrig, ITileCreator creator, CancellationToken token) { using var stream = CreateThumbnailStream(imgOrig); await creator.AddThumbnailAsync(stream, token); } private Stream CreateThumbnailStream(Bitmap imgOrig) { try { using Bitmap bmpThumb = new Bitmap(96, 45); using (Graphics g = Graphics.FromImage(bmpThumb)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; double imageAspect = ((double)imgOrig.Width) / (imgOrig.Height); double clientAspect = ((double)bmpThumb.Width) / bmpThumb.Height; int cw = bmpThumb.Width; int ch = bmpThumb.Height; if (imageAspect < clientAspect) { ch = (int)((double)cw / imageAspect); } else { cw = (int)((double)ch * imageAspect); } int cx = (bmpThumb.Width - cw) / 2; int cy = ((bmpThumb.Height - ch) / 2); // - 1; Rectangle destRect = new Rectangle(cx, cy, cw, ch); //+ 1); Rectangle srcRect = new Rectangle(0, 0, imgOrig.Width, imgOrig.Height); g.DrawImage(imgOrig, destRect, srcRect, System.Drawing.GraphicsUnit.Pixel); } return bmpThumb.SaveToStream(ImageFormat.Jpeg); } catch { using Bitmap bmp = new Bitmap(96, 45); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Blue); } return bmp.SaveToStream(ImageFormat.Jpeg); } } public int CalcMaxLevels(int SizeX, int SizeY) { int levels = 0; int maxHeight = 256; int maxWidth = 512; double aspect = (double)SizeX / (double)SizeY; do { if (aspect < 2) { if (maxHeight >= SizeY) { break; } } else { if (maxWidth >= SizeX) { break; } } levels++; maxHeight *= 2; maxWidth *= 2; } while (true); return levels; } private async Task<string> DownloadFileAsync(string url, string id, CancellationToken token) { var path = Path.Combine(_tempDir, id); if (File.Exists(path)) { return path; } // should be able to give this the cancellationtoken somehow? using var stream = await _httpClient.GetStreamAsync(url).ConfigureAwait(false); using (var fs = File.OpenWrite(path)) { await stream.CopyToAsync(fs, token).ConfigureAwait(false); } return path; } } }
using System; using BigMath; using NUnit.Framework; using Raksha.Crypto; using Raksha.Crypto.Digests; using Raksha.Crypto.Encodings; using Raksha.Crypto.Engines; using Raksha.Crypto.Parameters; using Raksha.Crypto.Signers; using Raksha.Math; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Crypto { /// <summary> test vectors from ISO 9796-1 and ISO 9796-2 edition 1.</summary> [TestFixture] public class ISO9796Test : SimpleTest { static BigInteger mod1 = new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16); static BigInteger pub1 = new BigInteger("03", 16); static BigInteger pri1 = new BigInteger("2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac9f0783a49dd5f6c5af651f4c9d0dc9281c96a3f16a85f9572d7cc3f2d0f25a9dbf1149e4cdc32273faadd3fda5dcda7", 16); static BigInteger mod2 = new BigInteger("ffffff7fa27087c35ebead78412d2bdffe0301edd494df13458974ea89b364708f7d0f5a00a50779ddf9f7d4cb80b8891324da251a860c4ec9ef288104b3858d", 16); static BigInteger pub2 = new BigInteger("03", 16); static BigInteger pri2 = new BigInteger("2aaaaa9545bd6bf5e51fc7940adcdca5550080524e18cfd88b96e8d1c19de6121b13fac0eb0495d47928e047724d91d1740f6968457ce53ec8e24c9362ce84b5", 16); static byte[] msg1 = Hex.Decode("0cbbaa99887766554433221100"); // // you'll need to see the ISO 9796 to make sense of this // static byte[] sig1 = mod1.Subtract(new BigInteger("309f873d8ded8379490f6097eaafdabc137d3ebfd8f25ab5f138d56a719cdc526bdd022ea65dabab920a81013a85d092e04d3e421caab717c90d89ea45a8d23a", 16)).ToByteArray(); static byte[] msg2 = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); static byte[] sig2 = new BigInteger("319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c", 16).ToByteArray(); static byte[] msg3 = Hex.Decode("0112233445566778899aabbccd"); static byte[] sig3 = mod2.Subtract(new BigInteger("58e59ffb4b1fb1bcdbf8d1fe9afa3730c78a318a1134f5791b7313d480ff07ac319b068edf8f212945cb09cf33df30ace54f4a063fcca0b732f4b662dc4e2454", 16)).ToByteArray(); // // ISO 9796-2 // static BigInteger mod3 = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16); static BigInteger pub3 = new BigInteger("03", 16); static BigInteger pri3 = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16); static BigInteger mod4 = new BigInteger("FFFFFFFF45f1903ebb83d4d363f70dc647b839f2a84e119b8830b2dec424a1ce0c9fd667966b81407e89278283f27ca8857d40979407fc6da4cc8a20ecb4b8913b5813332409bc1f391a94c9c328dfe46695daf922259174544e2bfbe45cc5cd", 16); static BigInteger pub4 = new BigInteger("02", 16); static BigInteger pri4 = new BigInteger("1fffffffe8be3207d7707a9a6c7ee1b8c8f7073e5509c2337106165bd8849439c193faccf2cd70280fd124f0507e4f94cb66447680c6b87b6599d1b61c8f3600854a618262e9c1cb1438e485e47437be036d94b906087a61ee74ab0d9a1accd8", 16); static byte[] msg4 = Hex.Decode("6162636462636465636465666465666765666768666768696768696a68696a6b696a6b6c6a6b6c6d6b6c6d6e6c6d6e6f6d6e6f706e6f7071"); static byte[] sig4 = Hex.Decode("374695b7ee8b273925b4656cc2e008d41463996534aa5aa5afe72a52ffd84e118085f8558f36631471d043ad342de268b94b080bee18a068c10965f581e7f32899ad378835477064abed8ef3bd530fce"); static byte[] msg5 = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); static byte[] sig5 = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae"); // // scheme 2 data // static BigInteger mod6 = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16); static BigInteger pub6 = new BigInteger("11", 16); static BigInteger pri6 = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16); // static byte[] sig6 = new BigInteger("0073FEAF13EB12914A43FE635022BB4AB8188A8F3ABD8D8A9E4AD6C355EE920359C7F237AE36B1212FE947F676C68FE362247D27D1F298CA9302EB21F4A64C26CE44471EF8C0DFE1A54606F0BA8E63E87CDACA993BFA62973B567473B4D38FAE73AB228600934A9CC1D3263E632E21FD52D2B95C5F7023DA63DE9509C01F6C7BBC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] sig6 = new BigInteger("0073FEAF13EB12914A43FE635022BB4AB8188A8F3ABD8D8A9E4AD6C355EE920359C7F237AE36B1212FE947F676C68FE362247D27D1F298CA9302EB21F4A64C26CE44471EF8C0DFE1A54606F0BA8E63E87CDACA993BFA62973B567473B4D38FAE73AB228600934A9CC1D3263E632E21FD52D2B95C5F7023DA63DE9509C01F6C7BBC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg7 = Hex.Decode("6162636462636465636465666465666765666768666768696768696A68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F70716F70717270717273"); static byte[] sig7 = new BigInteger("296B06224010E1EC230D4560A5F88F03550AAFCE31C805CE81E811E5E53E5F71AE64FC2A2A486B193E87972D90C54B807A862F21A21919A43ECF067240A8C8C641DE8DCDF1942CF790D136728FFC0D98FB906E7939C1EC0E64C0E067F0A7443D6170E411DF91F797D1FFD74009C4638462E69D5923E7433AEC028B9A90E633CC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg8 = Hex.Decode("FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA98"); static byte[] sig8 = new BigInteger("01402B29ABA104079677CE7FC3D5A84DB24494D6F9508B4596484F5B3CC7E8AFCC4DDE7081F21CAE9D4F94D6D2CCCB43FCEDA0988FFD4EF2EAE72CFDEB4A2638F0A34A0C49664CD9DB723315759D758836C8BA26AC4348B66958AC94AE0B5A75195B57ABFB9971E21337A4B517F2E820B81F26BCE7C66F48A2DB12A8F3D731CC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg9 = Hex.Decode("6162636462636465636465666465666765666768666768696768696A68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F70716F707172707172737172737472737475737475767475767775767778767778797778797A78797A61797A61627A6162636162636462636465"); static byte[] sig9 = new BigInteger("6F2BB97571FE2EF205B66000E9DD06656655C1977F374E8666D636556A5FEEEEAF645555B25F45567C4EE5341F96FED86508C90A9E3F11B26E8D496139ED3E55ECE42860A6FB3A0817DAFBF13019D93E1D382DA07264FE99D9797D2F0B7779357CA7E74EE440D8855B7DDF15F000AC58EE3FFF144845E771907C0C83324A6FBC", 16).ModPow(pri6, mod6).ToByteArray(); public override string Name { get { return "ISO9796"; } } private bool IsSameAs( byte[] a, int off, byte[] b) { if ((a.Length - off) != b.Length) { return false; } for (int i = 0; i != b.Length; i++) { if (a[i + off] != b[i]) { return false; } } return true; } private bool StartsWith( byte[] a, byte[] b) { if (a.Length < b.Length) return false; for (int i = 0; i != b.Length; i++) { if (a[i] != b[i]) return false; } return true; } [Test] public virtual void DoTest1() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod1, pub1); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod1, pri1); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); eng.SetPadBits(4); data = eng.ProcessBlock(msg1, 0, msg1.Length); eng.Init(false, pubParameters); if (!AreEqual(sig1, data)) { Fail("failed ISO9796-1 generation Test 1"); } data = eng.ProcessBlock(data, 0, data.Length); if (!AreEqual(msg1, data)) { Fail("failed ISO9796-1 retrieve Test 1"); } } [Test] public virtual void DoTest2() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod1, pub1); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod1, pri1); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); data = eng.ProcessBlock(msg2, 0, msg2.Length); eng.Init(false, pubParameters); if (!IsSameAs(data, 1, sig2)) { Fail("failed ISO9796-1 generation Test 2"); } data = eng.ProcessBlock(data, 0, data.Length); if (!AreEqual(msg2, data)) { Fail("failed ISO9796-1 retrieve Test 2"); } } [Test] public virtual void DoTest3() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod2, pub2); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod2, pri2); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); eng.SetPadBits(4); data = eng.ProcessBlock(msg3, 0, msg3.Length); eng.Init(false, pubParameters); if (!IsSameAs(sig3, 1, data)) { Fail("failed ISO9796-1 generation Test 3"); } data = eng.ProcessBlock(data, 0, data.Length); if (!IsSameAs(msg3, 0, data)) { Fail("failed ISO9796-1 retrieve Test 3"); } } [Test] public virtual void DoTest4() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - Signing // Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD128Digest()); eng.Init(true, privParameters); eng.Update(msg4[0]); eng.BlockUpdate(msg4, 1, msg4.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig4, 0, data)) { Fail("failed ISO9796-2 generation Test 4"); } eng.Update(msg4[0]); eng.BlockUpdate(msg4, 1, msg4.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 4"); } if (eng.HasFullMessage()) { eng = new Iso9796d2Signer(rsa, new RipeMD128Digest()); eng.Init(false, pubParameters); if (!eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 verify and recover Test 4"); } if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 recovered message Test 4"); } // try update with recovered eng.UpdateWithRecoveredMessage(sig4); if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 updateWithRecovered recovered message Test 4"); } if (!eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4"); } if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 updateWithRecovered recovered verify message Test 4"); } // should fail eng.UpdateWithRecoveredMessage(sig4); eng.BlockUpdate(msg4, 0, msg4.Length); if (eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4"); } } else { Fail("full message flag false - Test 4"); } } [Test] public virtual void DoTest5() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - Signing // Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true); eng.Init(true, privParameters); eng.Update(msg5[0]); eng.BlockUpdate(msg5, 1, msg5.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig5, 0, data)) { Fail("failed ISO9796-2 generation Test 5"); } eng.Update(msg5[0]); eng.BlockUpdate(msg5, 1, msg5.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage true - Test 5"); } if (!StartsWith(msg5, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 partial recovered message Test 5"); } int length = eng.GetRecoveredMessage().Length; if (length >= msg5.Length) { Fail("Test 5 recovered message too long"); } eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true); eng.Init(false, pubParameters); eng.UpdateWithRecoveredMessage(sig5); if (!StartsWith(msg5, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 updateWithRecovered partial recovered message Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage updateWithRecovered true - Test 5"); } for (int i = length ; i != msg5.Length; i++) { eng.Update(msg5[i]); } if (!eng.VerifySignature(sig5)) { Fail("failed ISO9796-2 verify Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage updateWithRecovered true - Test 5"); } // should fail eng.UpdateWithRecoveredMessage(sig5); eng.BlockUpdate(msg5, 0, msg5.Length); if (eng.VerifySignature(sig5)) { Fail("failed ISO9796-2 updateWithRecovered verify fail Test 5"); } } // // against a zero length string // [Test] public virtual void DoTest6() { byte[] salt = Hex.Decode("61DF870C4890FE85D6E3DD87C3DCE3723F91DB49"); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, true); eng.Init(true, sigParameters); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig6, 1, data)) { Fail("failed ISO9796-2 generation Test 6"); } if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 6"); } } [Test] public virtual void DoTest7() { byte[] salt = new byte[0]; RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new Sha1Digest(), 0, false); eng.Init(true, sigParameters); eng.Update(msg7[0]); eng.BlockUpdate(msg7, 1, msg7.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig7, 0, data)) { Fail("failed ISO9796-2 generation Test 7"); } eng.Update(msg7[0]); eng.BlockUpdate(msg7, 1, msg7.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 7"); } if (!IsSameAs(msg7, 0, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 recovery Test 7"); } } [Test] public virtual void DoTest8() { byte[] salt = Hex.Decode("78E293203CBA1B7F92F05F4D171FF8CA3E738FF8"); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, false); eng.Init(true, sigParameters); eng.Update(msg8[0]); eng.BlockUpdate(msg8, 1, msg8.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig8, 0, data)) { Fail("failed ISO9796-2 generation Test 8"); } eng.Update(msg8[0]); eng.BlockUpdate(msg8, 1, msg8.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 8"); } } [Test] public virtual void DoTest9() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 0, true); eng.Init(true, privParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig9, 0, data)) { Fail("failed ISO9796-2 generation Test 9"); } eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 9"); } } [Test] public virtual void DoTest10() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // IDigest dig = new Sha1Digest(); Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize()); // // as the padding is random this test needs to repeat a few times to // make sure // for (int i = 0; i != 500; i++) { eng.Init(true, privParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 10"); } } } [Test] public virtual void DoTest11() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; byte[] m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; byte[] m3 = { 1, 2, 3, 4, 5, 6, 7, 8 }; // // ISO 9796-2 - PSS Signing // IDigest dig = new Sha1Digest(); Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize()); // // check message bounds // eng.Init(true, privParameters); eng.BlockUpdate(m1, 0, m1.Length); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.BlockUpdate(m2, 0, m2.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m2 verify Test 11"); } eng.Init(false, pubParameters); eng.BlockUpdate(m3, 0, m3.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m3 verify Test 11"); } eng.Init(false, pubParameters); eng.BlockUpdate(m1, 0, m1.Length); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 11"); } } [Test] public virtual void DoTest12() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; byte[] m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; byte[] m3 = { 1, 2, 3, 4, 5, 6, 7, 8 }; // // ISO 9796-2 - Regular Signing // IDigest dig = new Sha1Digest(); Iso9796d2Signer eng = new Iso9796d2Signer(rsa, dig); // // check message bounds // eng.Init(true, privParameters); eng.BlockUpdate(m1, 0, m1.Length); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.BlockUpdate(m2, 0, m2.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m2 verify Test 12"); } eng.Init(false, pubParameters); eng.BlockUpdate(m3, 0, m3.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m3 verify Test 12"); } eng.Init(false, pubParameters); eng.BlockUpdate(m1, 0, m1.Length); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 12"); } } public override void PerformTest() { DoTest1(); DoTest2(); DoTest3(); DoTest4(); DoTest5(); DoTest6(); DoTest7(); DoTest8(); DoTest9(); DoTest10(); DoTest11(); DoTest12(); } public static void Main( string[] args) { RunTest(new ISO9796Test()); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class FieldRepresentation : BaseRepresentation { // // This is just a copy of Microsoft.Zelig.MetaData.FieldAttributes, needed to break the dependency of TypeSystem from MetaData. // // Also, it's extended to 32bits, to allow extra values. // [Flags] public enum Attributes : uint { FieldAccessMask = 0x00000007, // member access mask - Use this mask to retrieve accessibility information. PrivateScope = 0x00000000, // Member not referenceable. Private = 0x00000001, // Accessible only by the parent type. FamANDAssem = 0x00000002, // Accessible by sub-types only in this Assembly. Assembly = 0x00000003, // Accessibly by anyone in the Assembly. Family = 0x00000004, // Accessible only by type and sub-types. FamORAssem = 0x00000005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x00000006, // Accessibly by anyone who has visibility to this scope. // end member access mask // field contract attributes. Static = 0x00000010, // Defined on type, else per instance. InitOnly = 0x00000020, // Field may only be initialized, not written to after init. Literal = 0x00000040, // Value is compile time constant. NotSerialized = 0x00000080, // Field does not have to be serialized when type is remoted. SpecialName = 0x00000200, // field is special. Name describes how. // interop attributes PinvokeImpl = 0x00002000, // Implementation is forwarded through pinvoke. // Reserved flags for runtime use only. ReservedMask = 0x00009500, RTSpecialName = 0x00000400, // Runtime(metadata internal APIs) should check name encoding. HasFieldMarshal = 0x00001000, // Field has marshalling information. HasDefault = 0x00008000, // Field has default. HasFieldRVA = 0x00000100, // Field has RVA. // // Values exclusive to Zelig. // IsVolatile = 0x00010000, HasSingleAssignment = 0x00020000, NeverNull = 0x00040000, HasFixedSize = 0x00080000, } public static readonly FieldRepresentation[] SharedEmptyArray = new FieldRepresentation[0]; // // State // protected TypeRepresentation m_ownerType; protected Attributes m_flags; protected string m_name; protected TypeRepresentation m_fieldType; // // This is populated by the DetectConstants analysis. // protected int m_fixedSize; // // This field is synthesized from the analysis of the type hierarchy and the type characteristics. // private int m_offset; // // Constructor Methods // protected FieldRepresentation( TypeRepresentation ownerType , string name ) { CHECKS.ASSERT( ownerType != null, "Cannot create a FieldRepresentation without an owner" ); CHECKS.ASSERT( name != null, "Cannot create a FieldRepresentation without a name" ); m_ownerType = ownerType; m_name = name; m_offset = ownerType is ScalarTypeRepresentation ? 0 : int.MinValue; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is FieldRepresentation) { FieldRepresentation other = (FieldRepresentation)obj; if( m_name == other.m_name && EqualsThroughEquivalence( m_ownerType , other.m_ownerType, set ) && EqualsThroughEquivalence( m_fieldType , other.m_fieldType, set ) ) { CHECKS.ASSERT( this.GetType() == other.GetType(), "Found two inconsistent FieldRepresentation" ); return true; } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_name .GetHashCode() ^ m_ownerType.GetHashCode(); } public static bool operator ==( FieldRepresentation left , FieldRepresentation right ) { return Object.Equals( left, right ); } public static bool operator !=( FieldRepresentation left , FieldRepresentation right ) { return !(left == right); } //--// // // Helper Methods // protected void Done( TypeSystem typeSystem ) { typeSystem.NotifyNewFieldComplete( this ); } internal void PerformFieldAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataField metadata = typeSystem.GetAssociatedMetaData( this ); MetaData.Normalized.SignatureType sig = metadata.FieldSignature.TypeSignature; m_flags = (Attributes)metadata.Flags; m_fieldType = typeSystem.ConvertToIR( sig, context ); if(sig.Modifiers != null) { TypeRepresentation[] modifiers = new TypeRepresentation[sig.Modifiers.Length]; TypeRepresentation tdIsVolatile = typeSystem.WellKnownTypes.System_Runtime_CompilerServices_IsVolatile; for(int i = 0; i < modifiers.Length; i++) { modifiers[i] = typeSystem.ConvertToIR( sig.Modifiers[i], context ); if(modifiers[i] == tdIsVolatile) { m_flags |= Attributes.IsVolatile; } } } Done( typeSystem ); } internal void ProcessCustomAttributes( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataField metadata = typeSystem.GetAssociatedMetaData( this ); typeSystem.ConvertToIR( metadata.CustomAttributes, context, this, -1 ); } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_ownerType ); context.Transform( ref m_flags ); context.Transform( ref m_name ); context.Transform( ref m_fieldType ); context.Transform( ref m_fixedSize ); context.Transform( ref m_offset ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation OwnerType { get { return m_ownerType; } } public Attributes Flags { get { return m_flags; } set { m_flags = value; } } public string Name { get { return m_name; } } public TypeRepresentation FieldType { get { return m_fieldType; } } public int FixedSize { get { return m_fixedSize; } set { m_fixedSize = value; m_flags |= Attributes.HasFixedSize; } } public bool IsOpenField { get { return m_fieldType.IsOpenType; } } //--// public bool ValidLayout { get { return m_offset >= 0; } } public int Offset { get { CHECKS.ASSERT( this.ValidLayout, "Cannot access 'Offset' property on field '{0}' before the field has been laid out", this ); return m_offset; } set { m_offset = value; } } //--// // // Debug Methods // public string ToShortString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString( sb, false ); return sb.ToString(); } protected void PrettyToString( System.Text.StringBuilder sb , bool fPrefix ) { m_fieldType.PrettyToString( sb, fPrefix, true ); sb.Append( " " ); if(m_ownerType != null) { m_ownerType.PrettyToString( sb, fPrefix, false ); sb.Append( "::" ); } sb.Append( m_name ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinUInt16() { var test = new SimpleBinaryOpTest__MinUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinUInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static SimpleBinaryOpTest__MinUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__MinUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Min( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Min( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Min( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse41.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MinUInt16(); var result = Sse41.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { if (result[0] != Math.Min(left[0], right[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Min(left[i], right[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Min)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using Abp.Auditing; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Configuration; using Abp.EntityFramework; using Abp.EntityFramework.Extensions; using Abp.EntityHistory; using Abp.Localization; using Abp.Notifications; using Abp.Organizations; using System.Threading; using System.Threading.Tasks; using Abp.Webhooks; namespace Abp.Zero.EntityFramework { public abstract class AbpZeroCommonDbContext<TRole, TUser> : AbpDbContext where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { /// <summary> /// Roles. /// </summary> public virtual IDbSet<TRole> Roles { get; set; } /// <summary> /// Users. /// </summary> public virtual IDbSet<TUser> Users { get; set; } /// <summary> /// User logins. /// </summary> public virtual IDbSet<UserLogin> UserLogins { get; set; } /// <summary> /// User login attempts. /// </summary> public virtual IDbSet<UserLoginAttempt> UserLoginAttempts { get; set; } /// <summary> /// User roles. /// </summary> public virtual IDbSet<UserRole> UserRoles { get; set; } /// <summary> /// User claims. /// </summary> public virtual IDbSet<UserClaim> UserClaims { get; set; } /// <summary> /// Permissions. /// </summary> public virtual IDbSet<PermissionSetting> Permissions { get; set; } /// <summary> /// Role permissions. /// </summary> public virtual IDbSet<RolePermissionSetting> RolePermissions { get; set; } /// <summary> /// User permissions. /// </summary> public virtual IDbSet<UserPermissionSetting> UserPermissions { get; set; } /// <summary> /// Settings. /// </summary> public virtual IDbSet<Setting> Settings { get; set; } /// <summary> /// Audit logs. /// </summary> public virtual IDbSet<AuditLog> AuditLogs { get; set; } /// <summary> /// Languages. /// </summary> public virtual IDbSet<ApplicationLanguage> Languages { get; set; } /// <summary> /// LanguageTexts. /// </summary> public virtual IDbSet<ApplicationLanguageText> LanguageTexts { get; set; } /// <summary> /// OrganizationUnits. /// </summary> public virtual IDbSet<OrganizationUnit> OrganizationUnits { get; set; } /// <summary> /// UserOrganizationUnits. /// </summary> public virtual IDbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; } /// <summary> /// OrganizationUnitRoles. /// </summary> public virtual IDbSet<OrganizationUnitRole> OrganizationUnitRoles { get; set; } /// <summary> /// Notifications. /// </summary> public virtual IDbSet<NotificationInfo> Notifications { get; set; } /// <summary> /// Tenant notifications. /// </summary> public virtual IDbSet<TenantNotificationInfo> TenantNotifications { get; set; } /// <summary> /// User notifications. /// </summary> public virtual IDbSet<UserNotificationInfo> UserNotifications { get; set; } /// <summary> /// Notification subscriptions. /// </summary> public virtual IDbSet<NotificationSubscriptionInfo> NotificationSubscriptions { get; set; } /// <summary> /// Entity changes. /// </summary> public virtual IDbSet<EntityChange> EntityChanges { get; set; } /// <summary> /// Entity change sets. /// </summary> public virtual IDbSet<EntityChangeSet> EntityChangeSets { get; set; } /// <summary> /// Entity property changes. /// </summary> public virtual IDbSet<EntityPropertyChange> EntityPropertyChanges { get; set; } public IEntityHistoryHelper EntityHistoryHelper { get; set; } /// <summary> /// Webhook information /// </summary> public virtual IDbSet<WebhookEvent> WebhookEvents { get; set; } /// <summary> /// Web subscriptions /// </summary> public virtual IDbSet<WebhookSubscriptionInfo> WebhookSubscriptions { get; set; } /// <summary> /// Webhook work items /// </summary> public virtual IDbSet<WebhookSendAttempt> WebhookSendAttempts { get; set; } /// <summary> /// Default constructor. /// Do not directly instantiate this class. Instead, use dependency injection! /// </summary> protected AbpZeroCommonDbContext() { } /// <summary> /// Constructor with connection string parameter. /// </summary> /// <param name="nameOrConnectionString">Connection string or a name in connection strings in configuration file</param> protected AbpZeroCommonDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected AbpZeroCommonDbContext(DbCompiledModel model) : base(model) { } /// <summary> /// This constructor can be used for unit tests. /// </summary> protected AbpZeroCommonDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected AbpZeroCommonDbContext(string nameOrConnectionString, DbCompiledModel model) : base(nameOrConnectionString, model) { } protected AbpZeroCommonDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { } /// <summary> /// Constructor. /// </summary> protected AbpZeroCommonDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) { } public override int SaveChanges() { var changeSet = EntityHistoryHelper?.CreateEntityChangeSet(this); var result = base.SaveChanges(); EntityHistoryHelper?.Save(this, changeSet); return result; } public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) { var changeSet = EntityHistoryHelper?.CreateEntityChangeSet(this); var result = await base.SaveChangesAsync(cancellationToken); if (EntityHistoryHelper != null) { await EntityHistoryHelper.SaveAsync(this, changeSet); } return result; } /// <summary> /// /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<EntityChange>() .HasMany(e => e.PropertyChanges) .WithRequired() .HasForeignKey(e => e.EntityChangeId); #region EntityChange.IX_EntityChangeSetId modelBuilder.Entity<EntityChange>() .Property(e => e.EntityChangeSetId) .CreateIndex("IX_EntityChangeSetId", 1); #endregion #region EntityChange.IX_EntityTypeFullName_EntityId modelBuilder.Entity<EntityChange>() .Property(e => e.EntityTypeFullName) .CreateIndex("IX_EntityTypeFullName_EntityId", 1); modelBuilder.Entity<EntityChange>() .Property(e => e.EntityId) .CreateIndex("IX_EntityTypeFullName_EntityId", 2); #endregion modelBuilder.Entity<EntityChangeSet>() .HasMany(e => e.EntityChanges) .WithRequired() .HasForeignKey(e => e.EntityChangeSetId); #region EntityChangeSet.IX_TenantId_UserId modelBuilder.Entity<EntityChangeSet>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<EntityChangeSet>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); #endregion #region EntityChangeSet.IX_TenantId_CreationTime modelBuilder.Entity<EntityChangeSet>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_CreationTime", 1); modelBuilder.Entity<EntityChangeSet>() .Property(e => e.CreationTime) .CreateIndex("IX_TenantId_CreationTime", 2); #endregion #region EntityChangeSet.IX_TenantId_Reason modelBuilder.Entity<EntityChangeSet>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Reason", 1); modelBuilder.Entity<EntityChangeSet>() .Property(e => e.Reason) .CreateIndex("IX_TenantId_Reason", 2); #endregion #region EntityPropertyChange.IX_EntityChangeId modelBuilder.Entity<EntityPropertyChange>() .Property(e => e.EntityChangeId) .CreateIndex("IX_EntityChangeId", 1); #endregion modelBuilder.Entity<Setting>() .HasIndex(e => new { e.TenantId, e.Name, e.UserId }) .IsUnique(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using BASeCamp.BASeBlock.Blocks; namespace BASeCamp.BASeBlock.Projectiles { public class LaserShot : Projectile { protected long TimeAlive = 0; protected PointF _ShotPoint; //location it was shot from. public PointF ShotPoint { get { return _ShotPoint; } set { _ShotPoint = value; } } protected int numpoints = 0; protected LinkedList<PointF> LaserPoints = new LinkedList<PointF>(); protected bool _DamagesPaddle = false; protected Pen _LaserPen = null; //if maxbounces is 0,(default) behaviour is to go straight through all "non weak" blocks. //if maxbounces is non-zero, it will go through weak blocks, but will bounce off of other blocks. private int _MaxBounces = 3; private int _NumBounces = 0; public int MaxBounces { get { return _MaxBounces; } set { _MaxBounces = value; } } public delegate void LaserShotFrameFunction(BCBlockGameState gstate, LaserShot shotobject, LinkedList<PointF> LaserPoints); public event LaserShotFrameFunction LaserShotFrame; protected static Pen DefaultPen = new Pen(Color.Blue, 3); public Pen LaserPen { get { if (_LaserPen == null) { _LaserPen = new Pen(Color.Blue, 5); } return _LaserPen; } set { _LaserPen = value; } } public static int DefaultLength = 72; protected float _MaxLength = DefaultLength; public bool _Weak = false; public bool Weak { get { return _Weak; } set { _Weak = value; } } public float MaxLength { get { return _MaxLength; } set { _MaxLength = value; } } public bool DamagesPaddle { get { return _DamagesPaddle; } set { _DamagesPaddle = value; } } protected override PointF getLocation() { return LaserPoints.First(); } protected override void setLocation(PointF newLocation) { LaserPoints.RemoveFirst(); LaserPoints.AddFirst(newLocation); } public LaserShot(PointF Origin) : this(Origin, DefaultPen) { } public LaserShot(PointF Origin, int MaxLength) : this(Origin, DefaultPen, MaxLength) { } public LaserShot(PointF Origin, Pen LaserPen) : this(Origin, LaserPen, DefaultLength) { } public LaserShot(PointF Origin, Pen LaserPen, int MaxLength) : base(Origin, new PointF(0, -5)) { _MaxLength = MaxLength; _LaserPen = LaserPen; ShotPoint = Origin; numpoints = 1; LaserPoints = new LinkedList<PointF>(); LaserPoints.AddFirst(Origin); //LaserPoints[0] = LaserPoints[1] = Origin; } public LaserShot(PointF Origin, PointF pVelocity, int MaxLength) : this(Origin, pVelocity) { _MaxLength = MaxLength; } public LaserShot(PointF Origin, PointF pVelocity) : this(Origin, pVelocity, DefaultPen) { } public LaserShot(PointF Origin, PointF pVelocity, Pen LaserPen) : this(Origin, pVelocity, LaserPen, DefaultLength) { } public LaserShot(PointF Origin, PointF pVelocity, Pen LaserPen, int pMaxLength) : this(Origin, pMaxLength) { //set our velocity... _LaserPen = LaserPen; Velocity = pVelocity; } public LaserShot(PointF Origin, double pAngle, double pSpeed, Pen LaserPen) : this(Origin, pAngle, pSpeed, pSpeed, LaserPen) { } public LaserShot(PointF Origin, double Angle, double Speed) : this(Origin, Angle, Speed, DefaultPen) { } public LaserShot(PointF Origin, double Angle, double minSpeed, double maxSpeed) : this(Origin, Angle, minSpeed, maxSpeed, DefaultPen) { } public LaserShot(PointF Origin, double Angle, double minSpeed, double maxSpeed, Pen LaserPen) : this(Origin, BCBlockGameState.GetRandomVelocity((float)minSpeed, (float)maxSpeed, Angle), LaserPen) { } private List<Block> intersecting = null; private bool ProxyPerform(BCBlockGameState gamestate) { foreach (var removeit in intersecting) { cBall tempball = new cBall(removeit.CenterPoint(), Velocity); tempball.Behaviours.Add(new TempBallBehaviour()); //add a proxy behaviour to remove it as well. //tempball.Behaviours.Add(new ProxyBallBehaviour("ExplosionEffect", null, proxyperformframe, null, null, null, null, null, null)); //gamestate.Balls.AddLast(tempball); List<cBall> discardlist = new List<cBall>(); try { //this is... well, cheating... //we cannot add GameObjects to the List, except by plopping them in the ref AddedObject parameter. //however, we cannot "force" the PerformBlockHit of a block (say a destruction block) to add a GameObject (another ExplosionEffect, in that case) //we cheat. we swap out the entire gamestate.GameObject LinkedList with a new one, call the routine, and then //we add any added GameObjects to our ref parameter, and swap the old list back in, hoping nobody notices our //audacity to fiddle with core game state objects... var copiedref = gamestate.GameObjects; gamestate.GameObjects = new LinkedList<GameObject>(); removeit.PerformBlockHit(gamestate, tempball); if (removeit.MustDestroy()) removeit.StandardSpray(gamestate); var tempadded = gamestate.GameObjects; gamestate.GameObjects = copiedref; //now we add the ones we need to add to our ref array. I feel dirty. gamestate.Defer(() => { foreach (var doiterate in tempadded) { gamestate.GameObjects.AddLast(doiterate); } }); } catch { } //we don't add the ball to our GameState, so we don't have to worry about it persisting :D //the idea is that we want to invoke the actions of the block (which for many blocks will simply be destroyed). //at the same time, some blocks might react weirdly to having temporary balls tossed into their centers, so we make it so the ball will only live for //two frames by adding a proxyballbehaviour that ensure that. try { if (removeit.MustDestroy() && removeit.Destructable) { Debug.Print("Removing Block of type:" + removeit.GetType().Name); gamestate.Blocks.Remove(removeit); } } catch (Exception erroroccur) { Debug.Print("Exception:" + erroroccur.Message + " occured while removing block via LaserShot."); gamestate.Forcerefresh = true; //force a refresh... } finally { } } gamestate.Forcerefresh = true; //force a refresh... return true; } private void InvokeLaserFrame(BCBlockGameState gstate) { var copied = LaserShotFrame; if (copied != null) copied.Invoke(gstate, this, LaserPoints); } private bool BlockStopsLaser(Block testblock) { if (testblock is PolygonBlock) { PolygonBlock Pb = testblock as PolygonBlock; return _Weak || !Pb.Destructable || !testblock.MustDestroy(); } else { return _Weak || !testblock.MustDestroy(); } } private bool LaserIntersects(RectangleF checkrect) { //return (from p in LaserPoints let o = LaserPoints.Find(p) where o.Next != null select o) // .Any((p) => BCBlockGameState.IntersectLine(p.Value, p.Next.Value, checkrect)!=null); return (from p in LaserPoints let o = LaserPoints.Find(p) where o.Next != null select o) .Any((p) => BCBlockGameState.LiangBarsky(checkrect, p.Value, p.Next.Value) != null); } private int MaxPoints = 10; Type[] DamagableEnemies = new Type[]{typeof(EyeGuy)}; private bool stoppedadvance = false; public override bool PerformFrame(BCBlockGameState gamestate) { //only advances if it isn't currently "inside" a block whose MustDestroy returns false. InvokeLaserFrame(gamestate); //if there are no points, "destroy" us. PointF firstpoint = LaserPoints.First(); var nextpoint = LaserPoints.Find(firstpoint).Next; //we use the second LaserPoint, rather than the first. This is because the "collision" will occur when the first point touches it, which will usually mean the second //point is not inside the block, so the normal value will be more reliable for reflecting the vector. PointF? secondpoint = nextpoint != null ? nextpoint.Value : (PointF?)null; PointF testpoint = secondpoint == null ? firstpoint : secondpoint.Value; //check other objects. var resultcheck = (from b in gamestate.GameObjects where !(b is LaserShot) select b); foreach (var iterate in resultcheck) { if (iterate is PolygonObstacle) { PolygonObstacle po = iterate as PolygonObstacle; if (po.Poly.Contains(firstpoint)) { Polygon grabpoly = po.Poly; LineSegment ls; PointF closestPoint = BCBlockGameState.GetClosestPointOnPoly(grabpoly, testpoint, out ls); PointF diffPoint = new PointF(closestPoint.X - nextpoint.Value.X, closestPoint.Y - nextpoint.Value.Y); Velocity = Velocity.Mirror(diffPoint); } } else if(iterate is GameEnemy) { GameEnemy ge = (GameEnemy)iterate; if(DamagableEnemies.Contains(ge.GetType()) && LaserIntersects(ge.GetRectangle())) { ge.HitPoints -= 1; } } } if (numpoints == 0) return true; var hitresult = (from b in gamestate.Blocks where LaserIntersects(b.BlockRectangle) select b).ToList(); if (hitresult.Count > 0) { Debug.Print("Break"); } Block firstblocker = hitresult.FirstOrDefault((w) => w.BlockRectangle.Contains(firstpoint) && BlockStopsLaser(w)); if (firstblocker !=null) { if (_MaxBounces == 0 || _MaxBounces <= _NumBounces) { Debug.Print("Point 1 is not advancing"); stoppedadvance = true; } else { //otherwise, we bounce off firstblocker. Polygon grabpoly = firstblocker.GetPoly(); LineSegment ls; PointF closestPoint = BCBlockGameState.GetClosestPointOnPoly(grabpoly,testpoint,out ls); PointF diffPoint = new PointF(closestPoint.X - nextpoint.Value.X, closestPoint.Y - nextpoint.Value.Y); Velocity = Velocity.Mirror(diffPoint); //PointF normal = new PointF(firstpoint.X - closestPoint.X, firstpoint.Y - closestPoint.Y); //Velocity = BCBlockGameState.ReflectVector(Velocity,ls.Magnitude()); /* Polygon ballpoly = ballhit.GetBallPoly(); Vector Adjustment = new Vector(); GeometryHelper.PolygonCollisionResult pcr = GeometryHelper.PolygonCollision(GetPoly(), ballpoly, new Vector(ballhit.Velocity.X, ballhit.Velocity.Y)); Adjustment = pcr.MinimumTranslationVector; //minimumtranslationvector will be the normal we want to mirror the ball speed through. ballhit.Velocity = ballhit.Velocity.Mirror(pcr.MinimumTranslationVector); ballhit.Velocity = new PointF(ballhit.Velocity.X, ballhit.Velocity.Y); ballhit.Location = new PointF(ballhit.Location.X - Adjustment.X, ballhit.Location.Y - Adjustment.Y); base.PerformBlockHit(parentstate, ballhit, ref ballsadded); BCBlockGameState.Soundman.PlaySound(DefaultHitSound); return Destructable; * */ _NumBounces++; } } intersecting = hitresult; //AddObjects.Add(new ProxyObject(ProxyPerform, null)); //question to past self: Why was I using a Proxy Object?... bool retval = ProxyPerform(gamestate); // if(retval) return retval; gamestate.Forcerefresh = gamestate.Forcerefresh || (intersecting.Any()); //foreach(var destroyblock in intersecting) //defer destruction of those blocks. //check for paddle damage. var ppaddle = gamestate.PlayerPaddle; if (DamagesPaddle && ppaddle != null) { //make sure both points are low enough. //if (BCBlockGameState.LiangBarsky(ppaddle.Getrect(), LaserPoints[0], LaserPoints[1]) != null) if(LaserIntersects(ppaddle.Getrect())) { //do some damage. ppaddle.HP -= 2; } } else { //an additional check for all eyeguys on the playing field... foreach (EyeGuy loopguy in (from n in gamestate.GameObjects where n is EyeGuy select n)) { if(LaserIntersects(loopguy.GetRectangleF())) { loopguy.HitPoints -= 1; } } } TimeAlive++; //final check: if we can bounce, we will bounce off all sides of the playfield but the bottom too. if (_MaxBounces > 0) { if (firstpoint.X < gamestate.GameArea.Left) { Velocity = new PointF(-Velocity.X, Velocity.Y); } else if (firstpoint.X > gamestate.GameArea.Right) { Velocity = new PointF(-Velocity.X, Velocity.Y); } if (firstpoint.Y < gamestate.GameArea.Top) { Velocity = new PointF(Velocity.X, -Velocity.Y); } } //advance. //LaserPoints[1] = new PointF(LaserPoints[1].X + Velocity.X, LaserPoints[1].Y + Velocity.Y); //we advance by adding a new point from the current "head" point if (!stoppedadvance) { PointF newpoint = new PointF(LaserPoints.First().X + Velocity.X, LaserPoints.First().Y + Velocity.Y); LaserPoints.AddFirst(newpoint); numpoints++; //remove the last element too, if we have reached the max. } if (numpoints > MaxPoints || stoppedadvance) { LaserPoints.RemoveLast(); numpoints--; } //this return will not have a problem since it would only occur when the entire shot leaves the playfield. return !LaserPoints.Any((w) => gamestate.GameArea.Contains(new Point((int)w.X, (int)w.Y))); } public override void Draw(Graphics g) { //g.DrawLine(_LaserPen, LaserPoints[0], LaserPoints[1]); LinkedListNode<PointF> currelement = LaserPoints.First; while (currelement.Next != null) { g.DrawLine(_LaserPen, currelement.Value, currelement.Next.Value); currelement = currelement.Next; } } } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.kanban_details". /// </summary> public class KanbanDetail : DbAccess, IKanbanDetailRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "kanban_details". /// </summary> public override string _ObjectName => "kanban_details"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.kanban_details". /// </summary> /// <returns>Returns the number of rows of the table "config.kanban_details".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.kanban_details;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.kanban_details" to return all instances of the "KanbanDetail" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.kanban_details" to return all instances of the "KanbanDetail" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.kanban_details" with a where filter on the column "kanban_detail_id" to return a single instance of the "KanbanDetail" class. /// </summary> /// <param name="kanbanDetailId">The column "kanban_detail_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.KanbanDetail Get(long kanbanDetailId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"KanbanDetail\" filtered by \"KanbanDetailId\" with value {KanbanDetailId} was denied to the user with Login ID {_LoginId}", kanbanDetailId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details WHERE kanban_detail_id=@0;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, kanbanDetailId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.kanban_details". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.KanbanDetail GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"KanbanDetail\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.kanban_details" sorted by kanbanDetailId. /// </summary> /// <param name="kanbanDetailId">The column "kanban_detail_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.KanbanDetail GetPrevious(long kanbanDetailId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"KanbanDetail\" by \"KanbanDetailId\" with value {KanbanDetailId} was denied to the user with Login ID {_LoginId}", kanbanDetailId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details WHERE kanban_detail_id < @0 ORDER BY kanban_detail_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, kanbanDetailId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.kanban_details" sorted by kanbanDetailId. /// </summary> /// <param name="kanbanDetailId">The column "kanban_detail_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.KanbanDetail GetNext(long kanbanDetailId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"KanbanDetail\" by \"KanbanDetailId\" with value {KanbanDetailId} was denied to the user with Login ID {_LoginId}", kanbanDetailId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details WHERE kanban_detail_id > @0 ORDER BY kanban_detail_id LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, kanbanDetailId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.kanban_details". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.KanbanDetail GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"KanbanDetail\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.kanban_details" with a where filter on the column "kanban_detail_id" to return a multiple instances of the "KanbanDetail" class. /// </summary> /// <param name="kanbanDetailIds">Array of column "kanban_detail_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "KanbanDetail" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> Get(long[] kanbanDetailIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. kanbanDetailIds: {kanbanDetailIds}.", this._LoginId, kanbanDetailIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details WHERE kanban_detail_id IN (@0);"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, kanbanDetailIds); } /// <summary> /// Custom fields are user defined form elements for config.kanban_details. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.kanban_details</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.kanban_details' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.kanban_details'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.kanban_details. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.kanban_details</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT kanban_detail_id AS key, kanban_detail_id as value FROM config.kanban_details;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of KanbanDetail class on the database table "config.kanban_details". /// </summary> /// <param name="kanbanDetail">The instance of "KanbanDetail" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic kanbanDetail, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } kanbanDetail.audit_user_id = this._UserId; kanbanDetail.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = kanbanDetail.kanban_detail_id; if (Cast.To<long>(primaryKeyValue) > 0) { this.Update(kanbanDetail, Cast.To<long>(primaryKeyValue)); } else { primaryKeyValue = this.Add(kanbanDetail); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.kanban_details')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.kanban_details', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of KanbanDetail class on the database table "config.kanban_details". /// </summary> /// <param name="kanbanDetail">The instance of "KanbanDetail" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic kanbanDetail) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. {KanbanDetail}", this._LoginId, kanbanDetail); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, kanbanDetail, "config.kanban_details", "kanban_detail_id"); } /// <summary> /// Inserts or updates multiple instances of KanbanDetail class on the database table "config.kanban_details"; /// </summary> /// <param name="kanbanDetails">List of "KanbanDetail" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> kanbanDetails) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. {kanbanDetails}", this._LoginId, kanbanDetails); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic kanbanDetail in kanbanDetails) { line++; kanbanDetail.audit_user_id = this._UserId; kanbanDetail.audit_ts = System.DateTime.UtcNow; object primaryKeyValue = kanbanDetail.kanban_detail_id; if (Cast.To<long>(primaryKeyValue) > 0) { result.Add(kanbanDetail.kanban_detail_id); db.Update("config.kanban_details", "kanban_detail_id", kanbanDetail, kanbanDetail.kanban_detail_id); } else { result.Add(db.Insert("config.kanban_details", "kanban_detail_id", kanbanDetail)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.kanban_details" with an instance of "KanbanDetail" class against the primary key value. /// </summary> /// <param name="kanbanDetail">The instance of "KanbanDetail" class to update.</param> /// <param name="kanbanDetailId">The value of the column "kanban_detail_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic kanbanDetail, long kanbanDetailId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"KanbanDetail\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {KanbanDetail}", kanbanDetailId, this._LoginId, kanbanDetail); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, kanbanDetail, kanbanDetailId, "config.kanban_details", "kanban_detail_id"); } /// <summary> /// Deletes the row of the table "config.kanban_details" against the primary key value. /// </summary> /// <param name="kanbanDetailId">The value of the column "kanban_detail_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(long kanbanDetailId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"KanbanDetail\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", kanbanDetailId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.kanban_details WHERE kanban_detail_id=@0;"; Factory.NonQuery(this._Catalog, sql, kanbanDetailId); } /// <summary> /// Performs a select statement on table "config.kanban_details" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.kanban_details" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.kanban_details ORDER BY kanban_detail_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.kanban_details' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.kanban_details". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "KanbanDetail" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.kanban_details WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.KanbanDetail(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.kanban_details" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.kanban_details WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.KanbanDetail(), filters); sql.OrderBy("kanban_detail_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.kanban_details". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "KanbanDetail" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.kanban_details WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.KanbanDetail(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.kanban_details" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "KanbanDetail" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.kanban_details WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.KanbanDetail(), filters); sql.OrderBy("kanban_detail_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql); } public IEnumerable<Frapid.Config.Entities.KanbanDetail> Get(long[] kanbanIds, object[] resourceIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"KanbanDetail\" was denied to the user with Login ID {LoginId}. KanbanId: {KanbanIds}, ResourceIds {ResourceIds}.", this._LoginId, kanbanIds, resourceIds); throw new UnauthorizedException("Access is denied."); } } if (kanbanIds == null || resourceIds == null || !kanbanIds.Any() || !resourceIds.Any()) { return new List<Frapid.Config.Entities.KanbanDetail>(); } const string sql = "SELECT * FROM config.kanban_details WHERE kanban_id IN(@0) AND resource_id IN (@1);"; return Factory.Get<Frapid.Config.Entities.KanbanDetail>(this._Catalog, sql, kanbanIds, resourceIds); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // BatchedJoinBlock.cs // // // A propagator block that groups individual messages of multiple types // into tuples of arrays of those messages. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,>.DebugView))] public sealed class BatchedJoinBlock<T1, T2> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); if (!dataflowBlockOptions.Greedy) throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions)); if (dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) throw new ArgumentException(SR.Argument_BoundedCapacityNotSupported, nameof(dataflowBlockOptions)); Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>>> filter, out Tuple<IList<T1>, IList<T2>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); _target1.Complete(); _target2.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>> ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2> batchedJoinBlock) { Debug.Assert(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _batchedJoinBlock = batchedJoinBlock; _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> /// <typeparam name="T3">Specifies the type of data accepted by the block's third target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,,>.DebugView))] [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")] public sealed class BatchedJoinBlock<T1, T2, T3> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The target providing inputs of type T3.</summary> private readonly BatchedJoinBlockTarget<T3> _target3; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); if (!dataflowBlockOptions.Greedy || dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) { throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions)); } Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2, T3>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0 || _target3.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages(), _target3.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); _target3 = new BatchedJoinBlockTarget<T3>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2, T3>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2, T3>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2,T3}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <summary>Gets a target that may be used to offer messages of the third type.</summary> public ITargetBlock<T3> Target3 { get { return _target3; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>, IList<T3>>> filter, out Tuple<IList<T1>, IList<T2>, IList<T3>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>, IList<T3>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); Debug.Assert(_target3 != null, "_target3 not initialized"); _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>, IList<T3>> ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2, T3> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2, T3> batchedJoinBlock) { Debug.Assert(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); _batchedJoinBlock = batchedJoinBlock; } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>, IList<T3>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T3> Target3 { get { return _batchedJoinBlock._target3; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>, IList<T3>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } } namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Provides the target used in a BatchedJoin.</summary> /// <typeparam name="T">Specifies the type of data accepted by this target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlockTarget<>.DebugView))] internal sealed class BatchedJoinBlockTarget<T> : ITargetBlock<T>, IDebuggerDisplay { /// <summary>The shared resources used by all targets associated with the same batched join instance.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>Whether this target is declining future messages.</summary> private bool _decliningPermanently; /// <summary>Input messages for the next batch.</summary> private IList<T> _messages = new List<T>(); /// <summary>Initializes the target.</summary> /// <param name="sharedResources">The shared resources used by all targets associated with this batched join.</param> internal BatchedJoinBlockTarget(BatchedJoinBlockTargetSharedResources sharedResources) { Debug.Assert(sharedResources != null, "Targets require a shared resources through which to communicate."); // Store the shared resources, and register with it to let it know there's // another target. This is done in a non-thread-safe manner and must be done // during construction of the batched join instance. _sharedResources = sharedResources; sharedResources._remainingAliveTargets++; } /// <summary>Gets the number of messages buffered in this target.</summary> internal int Count { get { return _messages.Count; } } /// <summary>Gets the messages buffered by this target and then empties the collection.</summary> /// <returns>The messages from the target.</returns> internal IList<T> GetAndEmptyMessages() { Common.ContractAssertMonitorStatus(_sharedResources._incomingLock, held: true); IList<T> toReturn = _messages; _messages = new List<T>(); return toReturn; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { // If we've already stopped accepting messages, decline permanently if (_decliningPermanently || _sharedResources._decliningPermanently) return DataflowMessageStatus.DecliningPermanently; // Consume the message from the source if necessary, and store the message if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } _messages.Add(messageValue); // If this message makes a batch, notify the shared resources that a batch has been completed if (--_sharedResources._remainingItemsInBatch == 0) _sharedResources._batchSizeReachedAction(); return DataflowMessageStatus.Accepted; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { lock (_sharedResources._incomingLock) { // If this is the first time Complete is being called, // note that there's now one fewer targets receiving messages for the batched join. if (!_decliningPermanently) { _decliningPermanently = true; if (--_sharedResources._remainingAliveTargets == 0) _sharedResources._allTargetsDecliningPermanentlyAction(); } } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { if (!_decliningPermanently && !_sharedResources._decliningPermanently) _sharedResources._exceptionAction(exception); } _sharedResources._completionAction(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0} InputCount={1}", Common.GetNameForDebugger(this), _messages.Count); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The batched join block target being viewed.</summary> private readonly BatchedJoinBlockTarget<T> _batchedJoinBlockTarget; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlockTarget">The batched join target being viewed.</param> public DebugView(BatchedJoinBlockTarget<T> batchedJoinBlockTarget) { Debug.Assert(batchedJoinBlockTarget != null, "Need a block with which to construct the debug view."); _batchedJoinBlockTarget = batchedJoinBlockTarget; } /// <summary>Gets the messages waiting to be processed.</summary> public IEnumerable<T> InputQueue { get { return _batchedJoinBlockTarget._messages; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _batchedJoinBlockTarget._decliningPermanently || _batchedJoinBlockTarget._sharedResources._decliningPermanently; } } } } /// <summary>Provides a container for resources shared across all targets used by the same BatchedJoinBlock instance.</summary> internal sealed class BatchedJoinBlockTargetSharedResources { /// <summary>Initializes the shared resources.</summary> /// <param name="batchSize">The size of a batch to create.</param> /// <param name="dataflowBlockOptions">The options used to configure the shared resources. Assumed to be immutable.</param> /// <param name="batchSizeReachedAction">The action to invoke when a batch is completed.</param> /// <param name="allTargetsDecliningAction">The action to invoke when no more targets are accepting input.</param> /// <param name="exceptionAction">The action to invoke when an exception needs to be logged.</param> /// <param name="completionAction">The action to invoke when completing, typically invoked due to a call to Fault.</param> internal BatchedJoinBlockTargetSharedResources( int batchSize, GroupingDataflowBlockOptions dataflowBlockOptions, Action batchSizeReachedAction, Action allTargetsDecliningAction, Action<Exception> exceptionAction, Action completionAction) { Debug.Assert(batchSize >= 1, "A positive batch size is required."); Debug.Assert(batchSizeReachedAction != null, "Need an action to invoke for each batch."); Debug.Assert(allTargetsDecliningAction != null, "Need an action to invoke when all targets have declined."); _incomingLock = new object(); _batchSize = batchSize; // _remainingAliveTargets will be incremented when targets are added. // They must be added during construction of the BatchedJoin<...>. _remainingAliveTargets = 0; _remainingItemsInBatch = batchSize; // Configure what to do when batches are completed and/or all targets start declining _allTargetsDecliningPermanentlyAction = () => { // Invoke the caller's action allTargetsDecliningAction(); // Don't accept any more messages. We should already // be doing this anyway through each individual target's declining flag, // so setting it to true is just a precaution and is also helpful // when onceOnly is true. _decliningPermanently = true; }; _batchSizeReachedAction = () => { // Invoke the caller's action batchSizeReachedAction(); _batchesCreated++; // If this batched join is meant to be used for only a single // batch, invoke the completion logic. if (_batchesCreated >= dataflowBlockOptions.ActualMaxNumberOfGroups) _allTargetsDecliningPermanentlyAction(); // Otherwise, get ready for the next batch. else _remainingItemsInBatch = _batchSize; }; _exceptionAction = exceptionAction; _completionAction = completionAction; } /// <summary> /// A lock used to synchronize all incoming messages on all targets. It protects all of the rest /// of the shared Resources's state and will be held while invoking the delegates. /// </summary> internal readonly object _incomingLock; /// <summary>The size of the batches to generate.</summary> internal readonly int _batchSize; /// <summary>The action to invoke when enough elements have been accumulated to make a batch.</summary> internal readonly Action _batchSizeReachedAction; /// <summary>The action to invoke when all targets are declining further messages.</summary> internal readonly Action _allTargetsDecliningPermanentlyAction; /// <summary>The action to invoke when an exception has to be logged.</summary> internal readonly Action<Exception> _exceptionAction; /// <summary>The action to invoke when the owning block has to be completed.</summary> internal readonly Action _completionAction; /// <summary>The number of items remaining to form a batch.</summary> internal int _remainingItemsInBatch; /// <summary>The number of targets still alive (i.e. not declining all further messages).</summary> internal int _remainingAliveTargets; /// <summary>Whether all targets should decline all further messages.</summary> internal bool _decliningPermanently; /// <summary>The number of batches created.</summary> internal long _batchesCreated; } }
using Svelto.DataStructures; using Svelto.DataStructures.Native; namespace Svelto.ECS { /// <summary> /// This feature must be eventually tied to the new ExclusiveGroup that won't allow the use of custom EntitiesID /// The filters could be updated when entities buffer changes during the submission, while now this process /// is completely manual. /// Making this working properly is not in my priorities right now, as I will need to add the new group type /// AND optimize the submission process to be able to add more overhead /// </summary> public partial class EntitiesDB { public readonly struct Filters { public Filters (FasterDictionary<RefWrapperType, FasterDictionary<ExclusiveGroupStruct, GroupFilters>> filters) { _filters = filters; } public ref FilterGroup CreateOrGetFilterForGroup<T>(int filterID, ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { var refWrapper = TypeRefWrapper<T>.wrapper; return ref CreateOrGetFilterForGroup(filterID, groupID, refWrapper); } internal ref FilterGroup CreateOrGetFilterForGroup (int filterID, ExclusiveGroupStruct groupID, RefWrapperType refWrapper) { var fasterDictionary = _filters.GetOrCreate(refWrapper, () => new FasterDictionary<ExclusiveGroupStruct, GroupFilters>()); GroupFilters filters = fasterDictionary.GetOrCreate( groupID, () => new GroupFilters(new SharedSveltoDictionaryNative<int, FilterGroup>(0), groupID)); return ref filters.CreateOrGetFilter(filterID); } public bool HasFiltersForGroup<T>(ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == false) return false; return fasterDictionary.ContainsKey(groupID); } public bool HasFilterForGroup<T>(int filterID, ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == false) return false; if (fasterDictionary.TryGetValue(groupID, out var result)) return result.HasFilter(filterID); return false; } public ref GroupFilters CreateOrGetFiltersForGroup<T>(ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { var fasterDictionary = _filters.GetOrCreate(TypeRefWrapper<T>.wrapper , () => new FasterDictionary<ExclusiveGroupStruct, GroupFilters>()); return ref fasterDictionary.GetOrCreate( groupID, () => new GroupFilters(new SharedSveltoDictionaryNative<int, FilterGroup>(0), groupID)); } public ref GroupFilters GetFiltersForGroup<T>(ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { #if DEBUG && !PROFILE_SVELTO if (_filters.ContainsKey(TypeRefWrapper<T>.wrapper) == false) throw new ECSException($"trying to fetch not existing filters, type {typeof(T)}"); if (_filters[TypeRefWrapper<T>.wrapper].ContainsKey(groupID) == false) throw new ECSException( $"trying to fetch not existing filters, type {typeof(T)} group {groupID.ToName()}"); #endif return ref _filters[TypeRefWrapper<T>.wrapper].GetValueByRef(groupID); } public ref FilterGroup GetFilterForGroup<T>(int filterId, ExclusiveGroupStruct groupID) where T : struct, IEntityComponent { #if DEBUG && !PROFILE_SVELTO if (_filters.ContainsKey(TypeRefWrapper<T>.wrapper) == false) throw new ECSException($"trying to fetch not existing filters, type {typeof(T)}"); if (_filters[TypeRefWrapper<T>.wrapper].ContainsKey(groupID) == false) throw new ECSException( $"trying to fetch not existing filters, type {typeof(T)} group {groupID.ToName()}"); #endif return ref _filters[TypeRefWrapper<T>.wrapper][groupID].GetFilter(filterId); } public bool TryGetFilterForGroup<T>(int filterId, ExclusiveGroupStruct groupID, out FilterGroup groupFilter) where T : struct, IEntityComponent { groupFilter = default; if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == false) return false; if (fasterDictionary.TryGetValue(groupID, out var groupFilters) == false) return false; if (groupFilters.TryGetFilter(filterId, out groupFilter) == false) return false; return true; } public bool TryGetFiltersForGroup<T>(ExclusiveGroupStruct groupID, out GroupFilters groupFilters) where T : struct, IEntityComponent { groupFilters = default; if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == false) return false; return fasterDictionary.TryGetValue(groupID, out groupFilters); } public void ClearFilter<T>(int filterID, ExclusiveGroupStruct exclusiveGroupStruct) { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == true) { DBC.ECS.Check.Require(fasterDictionary.ContainsKey(exclusiveGroupStruct) , $"trying to clear filter not present in group {exclusiveGroupStruct}"); fasterDictionary[exclusiveGroupStruct].ClearFilter(filterID); } } public void ClearFilters<T>(int filterID) { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == true) { foreach (var filtersPerGroup in fasterDictionary) filtersPerGroup.Value.ClearFilter(filterID); } } public void DisposeFilters<T>(ExclusiveGroupStruct exclusiveGroupStruct) { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == true) { fasterDictionary[exclusiveGroupStruct].DisposeFilters(); fasterDictionary.Remove(exclusiveGroupStruct); } } public void DisposeFilters<T>() { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == true) { foreach (var filtersPerGroup in fasterDictionary) filtersPerGroup.Value.DisposeFilters(); } _filters.Remove(TypeRefWrapper<T>.wrapper); } public void DisposeFilterForGroup<T>(int resetFilterID, ExclusiveGroupStruct @group) { if (_filters.TryGetValue(TypeRefWrapper<T>.wrapper, out var fasterDictionary) == true) { fasterDictionary[group].DisposeFilter(resetFilterID); } } public bool TryRemoveEntityFromFilter<T>(int filtersID, EGID egid) where T : struct, IEntityComponent { if (TryGetFilterForGroup<T>(filtersID, egid.groupID, out var filter)) { return filter.TryRemove(egid.entityID); } return false; } public void RemoveEntityFromFilter<T>(int filtersID, EGID egid) where T : struct, IEntityComponent { ref var filter = ref GetFilterForGroup<T>(filtersID, egid.groupID); filter.Remove(egid.entityID); } public bool AddEntityToFilter<N>(int filtersID, EGID egid, N mapper) where N : IEGIDMapper { ref var filter = ref CreateOrGetFilterForGroup(filtersID, egid.groupID, new RefWrapperType(mapper.entityType)); return filter.Add(egid.entityID, mapper); } readonly FasterDictionary<RefWrapperType, FasterDictionary<ExclusiveGroupStruct, GroupFilters>> _filters; } public Filters GetFilters() { return new Filters(_filters); } FasterDictionary<RefWrapperType, FasterDictionary<ExclusiveGroupStruct, GroupFilters>> _filters => _enginesRoot._groupFilters; } }
/* ==================================================================== 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.XWPF.UserModel { using System; using NPOI.OpenXml4Net.Exceptions; using NPOI.OpenXml4Net.OPC; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.IO; using System.Xml.Serialization; using System.Xml; /** * @author Philipp Epp * */ public class XWPFNumbering : POIXMLDocumentPart { protected List<XWPFAbstractNum> abstractNums = new List<XWPFAbstractNum>(); protected List<XWPFNum> nums = new List<XWPFNum>(); private CT_Numbering ctNumbering; bool isNew; /** *create a new styles object with an existing document */ public XWPFNumbering(PackagePart part, PackageRelationship rel) : base(part, rel) { isNew = true; } /** * create a new XWPFNumbering object for use in a new document */ public XWPFNumbering() { abstractNums = new List<XWPFAbstractNum>(); nums = new List<XWPFNum>(); isNew = true; } /** * read numbering form an existing package */ internal override void OnDocumentRead() { NumberingDocument numberingDoc = null; XmlDocument doc = ConvertStreamToXml(GetPackagePart().GetInputStream()); try { numberingDoc = NumberingDocument.Parse(doc, NamespaceManager); ctNumbering = numberingDoc.Numbering; //get any Nums foreach(CT_Num ctNum in ctNumbering.GetNumList()) { nums.Add(new XWPFNum(ctNum, this)); } foreach(CT_AbstractNum ctAbstractNum in ctNumbering.GetAbstractNumList()){ abstractNums.Add(new XWPFAbstractNum(ctAbstractNum, this)); } isNew = false; } catch (Exception e) { throw new POIXMLException(e); } } /** * save and Commit numbering */ protected internal override void Commit() { /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.SaveSyntheticDocumentElement=(new QName(CTNumbering.type.Name.NamespaceURI, "numbering")); Dictionary<String,String> map = new Dictionary<String,String>(); map.Put("http://schemas.Openxmlformats.org/markup-compatibility/2006", "ve"); map.Put("urn:schemas-microsoft-com:office:office", "o"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/math", "m"); map.Put("urn:schemas-microsoft-com:vml", "v"); map.Put("http://schemas.Openxmlformats.org/drawingml/2006/wordProcessingDrawing", "wp"); map.Put("urn:schemas-microsoft-com:office:word", "w10"); map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w"); map.Put("http://schemas.microsoft.com/office/word/2006/wordml", "wne"); xmlOptions.SaveSuggestedPrefixes=(map);*/ PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); NumberingDocument doc = new NumberingDocument(ctNumbering); //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] { // new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"), // new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"), // new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"), // new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"), // new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"), // new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"), // new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"), // new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main") // }); doc.Save(out1); out1.Close(); } /** * Sets the ctNumbering * @param numbering */ public void SetNumbering(CT_Numbering numbering) { ctNumbering = numbering; } /** * Checks whether number with numID exists * @param numID * @return bool true if num exist, false if num not exist */ public bool NumExist(string numID) { foreach (XWPFNum num in nums) { if (num.GetCTNum().numId.Equals(numID)) return true; } return false; } /** * add a new number to the numbering document * @param num */ public string AddNum(XWPFNum num){ ctNumbering.AddNewNum(); int pos = (ctNumbering.GetNumList().Count) - 1; ctNumbering.SetNumArray(pos, num.GetCTNum()); nums.Add(num); return num.GetCTNum().numId; } /** * Add a new num with an abstractNumID * @return return NumId of the Added num */ public string AddNum(string abstractNumID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (nums.Count + 1).ToString(); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); return ctNum.numId; } /** * Add a new num with an abstractNumID and a numID * @param abstractNumID * @param numID */ public void AddNum(string abstractNumID, string numID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (numID); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); } /** * Get Num by NumID * @param numID * @return abstractNum with NumId if no Num exists with that NumID * null will be returned */ public XWPFNum GetNum(string numID){ foreach(XWPFNum num in nums){ if(num.GetCTNum().numId.Equals(numID)) return num; } return null; } /** * Get AbstractNum by abstractNumID * @param abstractNumID * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID * null will be returned */ public XWPFAbstractNum GetAbstractNum(string abstractNumID){ foreach(XWPFAbstractNum abstractNum in abstractNums){ if(abstractNum.GetAbstractNum().abstractNumId.Equals(abstractNumID)){ return abstractNum; } } return null; } /** * Compare AbstractNum with abstractNums of this numbering document. * If the content of abstractNum Equals with an abstractNum of the List in numbering * the Bigint Value of it will be returned. * If no equal abstractNum is existing null will be returned * * @param abstractNum * @return Bigint */ public string GetIdOfAbstractNum(XWPFAbstractNum abstractNum) { CT_AbstractNum copy = (CT_AbstractNum)abstractNum.GetCTAbstractNum().Copy(); XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); int i; for (i = 0; i < abstractNums.Count; i++) { newAbstractNum.GetCTAbstractNum().abstractNumId = i.ToString(); newAbstractNum.SetNumbering(this); if (newAbstractNum.GetCTAbstractNum().ValueEquals(abstractNums[i].GetCTAbstractNum())) { return newAbstractNum.GetCTAbstractNum().abstractNumId; } } return null; } /** * add a new AbstractNum and return its AbstractNumID * @param abstractNum */ public string AddAbstractNum(XWPFAbstractNum abstractNum) { int pos = abstractNums.Count; if (abstractNum.GetAbstractNum() != null) { // Use the current CTAbstractNum if it exists abstractNum.GetAbstractNum().abstractNumId = pos.ToString(); ctNumbering.AddNewAbstractNum().Set(abstractNum.GetAbstractNum()); } else { ctNumbering.AddNewAbstractNum(); abstractNum.GetAbstractNum().abstractNumId = pos.ToString(); ctNumbering.SetAbstractNumArray(pos, abstractNum.GetAbstractNum()); } abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /// <summary> /// Add a new AbstractNum /// </summary> /// <returns></returns> /// @author antony liu public string AddAbstractNum() { CT_AbstractNum ctAbstractNum = ctNumbering.AddNewAbstractNum(); XWPFAbstractNum abstractNum = new XWPFAbstractNum(ctAbstractNum, this); abstractNum.AbstractNumId = abstractNums.Count.ToString(); abstractNum.MultiLevelType = MultiLevelType.HybridMultilevel; abstractNum.InitLvl(); abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /** * remove an existing abstractNum * @param abstractNumID * @return true if abstractNum with abstractNumID exists in NumberingArray, * false if abstractNum with abstractNumID not exists */ public bool RemoveAbstractNum(string abstractNumID) { if (int.Parse(abstractNumID) < abstractNums.Count) { ctNumbering.RemoveAbstractNum(int.Parse(abstractNumID)); abstractNums.RemoveAt(int.Parse(abstractNumID)); return true; } return false; } /** *return the abstractNumID *If the AbstractNumID not exists *return null * @param numID * @return abstractNumID */ public string GetAbstractNumID(string numID) { XWPFNum num = GetNum(numID); if (num == null) return null; if (num.GetCTNum() == null) return null; if (num.GetCTNum().abstractNumId == null) return null; return num.GetCTNum().abstractNumId.val; } } }
namespace AutoMapper { using System; using System.Linq; using Configuration; using Execution; using Mappers; public class Mapper : IRuntimeMapper { #region Static API private static IConfigurationProvider _configuration; private static IMapper _instance; /// <summary> /// Configuration provider for performing maps /// </summary> public static IConfigurationProvider Configuration { get { if (_configuration == null) throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); return _configuration; } private set { _configuration = value; } } /// <summary> /// Static mapper instance. You can also create a <see cref="Mapper"/> instance directly using the <see cref="Configuration"/> instance. /// </summary> public static IMapper Instance { get { if (_instance == null) throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); return _instance; } private set { _instance = value; } } /// <summary> /// Initialize static configuration instance /// </summary> /// <param name="config">Configuration action</param> public static void Initialize(Action<IMapperConfiguration> config) { Configuration = new MapperConfiguration(config); Instance = new Mapper(Configuration); } /// <summary> /// Execute a mapping from the source object to a new destination object. /// The source type is inferred from the source object. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source) => Instance.Map<TDestination>(source); /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts) => Instance.Map<TDestination>(source, opts); /// <summary> /// Execute a mapping from the source object to a new destination object. /// </summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source) => Instance.Map<TSource, TDestination>(source); /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) => Instance.Map(source, opts); /// <summary> /// Execute a mapping from the source object to the existing destination object. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Dsetination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination) => Instance.Map(source, destination); /// <summary> /// Execute a mapping from the source object to the existing destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="opts">Mapping options</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) => Instance.Map(source, destination, opts); /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType) => Instance.Map(source, sourceType, destinationType); /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options. /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) => Instance.Map(source, sourceType, destinationType, opts); /// <summary> /// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType) => Instance.Map(source, destination, sourceType, destinationType); /// <summary> /// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) => Instance.Map(source, destination, sourceType, destinationType, opts); #endregion private readonly IConfigurationProvider _configurationProvider; private readonly Func<Type, object> _serviceCtor; private readonly MappingOperationOptions _defaultMappingOptions; public Mapper(IConfigurationProvider configurationProvider) : this(configurationProvider, configurationProvider.ServiceCtor) { } public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor) { _configurationProvider = configurationProvider; _serviceCtor = serviceCtor; _defaultMappingOptions = new MappingOperationOptions(_serviceCtor); } Func<Type, object> IMapper.ServiceCtor => _serviceCtor; IConfigurationProvider IMapper.ConfigurationProvider => _configurationProvider; TDestination IMapper.Map<TDestination>(object source) { var types = new TypePair(source.GetType(), typeof(TDestination)); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(types, types)); var context = new ResolutionContext(source, null, types, _defaultMappingOptions, this); return (TDestination) func(source, null, context); } TDestination IMapper.Map<TDestination>(object source, Action<IMappingOperationOptions> opts) { var mappedObject = default(TDestination); if (source == null) return mappedObject; var sourceType = source.GetType(); var destinationType = typeof(TDestination); mappedObject = (TDestination)((IMapper)this).Map(source, sourceType, destinationType, opts); return mappedObject; } TDestination IMapper.Map<TSource, TDestination>(TSource source) { var types = TypePair.Create(source, null, typeof(TSource), typeof (TDestination)); var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types); var destination = default(TDestination); var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this); return func(source, destination, context); } TDestination IMapper.Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) { var types = TypePair.Create(source, null, typeof(TSource), typeof(TDestination)); var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types); var destination = default(TDestination); var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor); opts(typedOptions); var context = new ResolutionContext(source, destination, types, typedOptions, this); return func(source, destination, context); } TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination) { var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination)); var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types); var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this); return func(source, destination, context); } TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) { var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination)); var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types); var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor); opts(typedOptions); var context = new ResolutionContext(source, destination, types, typedOptions, this); return func(source, destination, context); } object IMapper.Map(object source, Type sourceType, Type destinationType) { var types = TypePair.Create(source, null, sourceType, destinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types)); var context = new ResolutionContext(source, null, types, _defaultMappingOptions, this); return func(source, null, context); } object IMapper.Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var types = TypePair.Create(source, null, sourceType, destinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types)); var options = new MappingOperationOptions(_serviceCtor); opts(options); var context = new ResolutionContext(source, null, types, options, this); return func(source, null, context); } object IMapper.Map(object source, object destination, Type sourceType, Type destinationType) { var types = TypePair.Create(source, destination, sourceType, destinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types)); var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this); return func(source, destination, context); } object IMapper.Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var types = TypePair.Create(source, destination, sourceType, destinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types)); var options = new MappingOperationOptions(_serviceCtor); opts(options); var context = new ResolutionContext(source, destination, types, options, this); return func(source, destination, context); } object IRuntimeMapper.Map(ResolutionContext context) { var types = TypePair.Create(context.SourceValue, context.DestinationValue, context.SourceType, context.DestinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(context.SourceType, context.DestinationType), types)); return func(context.SourceValue, context.DestinationValue, context); } object IRuntimeMapper.Map(object source, object destination, Type sourceType, Type destinationType, ResolutionContext parent) { var types = TypePair.Create(source, destination, sourceType, destinationType); var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types)); var context = new ResolutionContext(source, destination, types, parent); return func(source, destination, context); } TDestination IRuntimeMapper.Map<TSource, TDestination>(TSource source, TDestination destination, ResolutionContext parent) { var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination)); var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types); var context = new ResolutionContext(source, destination, types, parent); return func(source, destination, context); } object IRuntimeMapper.CreateObject(ResolutionContext context) { if(context.DestinationValue != null) { return context.DestinationValue; } return !_configurationProvider.AllowNullDestinationValues ? ObjectCreator.CreateNonNullValue(context.DestinationType) : ObjectCreator.CreateObject(context.DestinationType); } TDestination IRuntimeMapper.CreateObject<TDestination>(ResolutionContext context) { if (context.DestinationValue != null) { return (TDestination) context.DestinationValue; } return (TDestination) (!_configurationProvider.AllowNullDestinationValues ? ObjectCreator.CreateNonNullValue(typeof(TDestination)) : ObjectCreator.CreateObject(typeof(TDestination))); } bool IRuntimeMapper.ShouldMapSourceValueAsNull(ResolutionContext context) { if (context.DestinationType.IsValueType() && !context.DestinationType.IsNullableType()) return false; var typeMap = context.GetContextTypeMap(); return typeMap?.Profile.AllowNullDestinationValues ?? _configurationProvider.AllowNullDestinationValues; } bool IRuntimeMapper.ShouldMapSourceCollectionAsNull(ResolutionContext context) { var typeMap = context.GetContextTypeMap(); return typeMap?.Profile.AllowNullCollections ?? _configurationProvider.AllowNullCollections; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: CandleMessage.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Xml.Serialization; using Ecng.Common; using StockSharp.Localization; /// <summary> /// Candle states. /// </summary> [DataContract] [Serializable] public enum CandleStates { /// <summary> /// Empty state (candle doesn't exist). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str1658Key)] None, /// <summary> /// Candle active. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str238Key)] Active, /// <summary> /// Candle finished. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.FinishedKey)] Finished, } /// <summary> /// The message contains information about the candle. /// </summary> [DataContract] [Serializable] public abstract class CandleMessage : Message, ISubscriptionIdMessage, IServerTimeMessage, ISecurityIdMessage, IGeneratedMessage, ISeqNumMessage { /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.SecurityIdKey)] [DescriptionLoc(LocalizedStrings.SecurityIdKey, true)] [MainCategory] public SecurityId SecurityId { get; set; } /// <summary> /// Open time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleOpenTimeKey)] [DescriptionLoc(LocalizedStrings.CandleOpenTimeKey, true)] [MainCategory] public DateTimeOffset OpenTime { get; set; } /// <summary> /// Time of candle high. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleHighTimeKey)] [DescriptionLoc(LocalizedStrings.CandleHighTimeKey, true)] [MainCategory] public DateTimeOffset HighTime { get; set; } /// <summary> /// Time of candle low. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleLowTimeKey)] [DescriptionLoc(LocalizedStrings.CandleLowTimeKey, true)] [MainCategory] public DateTimeOffset LowTime { get; set; } /// <summary> /// Close time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleCloseTimeKey)] [DescriptionLoc(LocalizedStrings.CandleCloseTimeKey, true)] [MainCategory] public DateTimeOffset CloseTime { get; set; } /// <summary> /// Opening price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str79Key)] [DescriptionLoc(LocalizedStrings.Str80Key)] [MainCategory] public decimal OpenPrice { get; set; } /// <summary> /// Highest price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.HighestPriceKey)] [DescriptionLoc(LocalizedStrings.Str82Key)] [MainCategory] public decimal HighPrice { get; set; } /// <summary> /// Lowest price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.LowestPriceKey)] [DescriptionLoc(LocalizedStrings.Str84Key)] [MainCategory] public decimal LowPrice { get; set; } /// <summary> /// Closing price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.ClosingPriceKey)] [DescriptionLoc(LocalizedStrings.Str86Key)] [MainCategory] public decimal ClosePrice { get; set; } /// <summary> /// Volume at open. /// </summary> [DataMember] //[Nullable] public decimal? OpenVolume { get; set; } /// <summary> /// Volume at close. /// </summary> [DataMember] //[Nullable] public decimal? CloseVolume { get; set; } /// <summary> /// Volume at high. /// </summary> [DataMember] //[Nullable] public decimal? HighVolume { get; set; } /// <summary> /// Volume at low. /// </summary> [DataMember] //[Nullable] public decimal? LowVolume { get; set; } /// <summary> /// Relative volume. /// </summary> [DataMember] public decimal? RelativeVolume { get; set; } /// <summary> /// Total price size. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TotalPriceKey)] public decimal TotalPrice { get; set; } /// <summary> /// Total volume. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VolumeKey)] [DescriptionLoc(LocalizedStrings.TotalCandleVolumeKey)] [MainCategory] public decimal TotalVolume { get; set; } /// <summary> /// Open interest. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OIKey)] [DescriptionLoc(LocalizedStrings.OpenInterestKey)] [MainCategory] public decimal? OpenInterest { get; set; } /// <summary> /// Number of ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TicksKey)] [DescriptionLoc(LocalizedStrings.TickCountKey)] [MainCategory] public int? TotalTicks { get; set; } /// <summary> /// Number of up trending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickUpKey)] [DescriptionLoc(LocalizedStrings.TickUpCountKey)] [MainCategory] public int? UpTicks { get; set; } /// <summary> /// Number of down trending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickDownKey)] [DescriptionLoc(LocalizedStrings.TickDownCountKey)] [MainCategory] public int? DownTicks { get; set; } /// <summary> /// State. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.StateKey)] [DescriptionLoc(LocalizedStrings.CandleStateKey, true)] [MainCategory] public CandleStates State { get; set; } /// <summary> /// Price levels. /// </summary> [DataMember] [XmlIgnore] public IEnumerable<CandlePriceLevel> PriceLevels { get; set; } /// <summary> /// Candle arg. /// </summary> public abstract object Arg { get; set; } DataType ISubscriptionIdMessage.DataType => DataType.Create(GetType(), Arg); /// <summary> /// Initialize <see cref="CandleMessage"/>. /// </summary> /// <param name="type">Message type.</param> protected CandleMessage(MessageTypes type) : base(type) { } /// <summary> /// Clone <see cref="Arg"/>. /// </summary> /// <returns>Copy.</returns> public virtual object CloneArg() => Arg; /// <inheritdoc /> [DataMember] public long OriginalTransactionId { get; set; } /// <inheritdoc /> [XmlIgnore] public long SubscriptionId { get; set; } /// <inheritdoc /> [XmlIgnore] public long[] SubscriptionIds { get; set; } /// <inheritdoc /> [DataMember] public DataType BuildFrom { get; set; } /// <inheritdoc /> [DataMember] public long SeqNum { get; set; } /// <summary> /// Copy parameters. /// </summary> /// <param name="copy">Copy.</param> /// <returns>Copy.</returns> protected CandleMessage CopyTo(CandleMessage copy) { base.CopyTo(copy); copy.OriginalTransactionId = OriginalTransactionId; copy.SubscriptionId = SubscriptionId; copy.SubscriptionIds = SubscriptionIds;//?.ToArray(); copy.OpenPrice = OpenPrice; copy.OpenTime = OpenTime; copy.OpenVolume = OpenVolume; copy.ClosePrice = ClosePrice; copy.CloseTime = CloseTime; copy.CloseVolume = CloseVolume; copy.HighPrice = HighPrice; copy.HighVolume = HighVolume; copy.HighTime = HighTime; copy.LowPrice = LowPrice; copy.LowVolume = LowVolume; copy.LowTime = LowTime; copy.OpenInterest = OpenInterest; copy.SecurityId = SecurityId; copy.TotalVolume = TotalVolume; copy.RelativeVolume = RelativeVolume; copy.DownTicks = DownTicks; copy.UpTicks = UpTicks; copy.TotalTicks = TotalTicks; copy.PriceLevels = PriceLevels?/*.Select(l => l.Clone())*/.ToArray(); copy.State = State; copy.BuildFrom = BuildFrom; copy.SeqNum = SeqNum; return copy; } /// <inheritdoc /> public override string ToString() { var str = $"{Type},Sec={SecurityId},A={Arg},T={OpenTime:yyyy/MM/dd HH:mm:ss.fff},O={OpenPrice},H={HighPrice},L={LowPrice},C={ClosePrice},V={TotalVolume},S={State},TransId={OriginalTransactionId}"; if (SeqNum != default) str += $",SQ={SeqNum}"; return str; } DateTimeOffset IServerTimeMessage.ServerTime { get => OpenTime; set => OpenTime = value; } } /// <summary> /// The message contains information about the time-frame candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.TimeFrameCandleKey)] public class TimeFrameCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TimeFrameCandleMessage"/>. /// </summary> public TimeFrameCandleMessage() : this(MessageTypes.CandleTimeFrame) { } /// <summary> /// Initializes a new instance of the <see cref="TimeFrameCandleMessage"/>. /// </summary> /// <param name="type">Message type.</param> protected TimeFrameCandleMessage(MessageTypes type) : base(type) { } /// <summary> /// Time-frame. /// </summary> [DataMember] public TimeSpan TimeFrame { get; set; } /// <summary> /// Create a copy of <see cref="TimeFrameCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TimeFrameCandleMessage { TimeFrame = TimeFrame }); } /// <inheritdoc /> public override object Arg { get => TimeFrame; set => TimeFrame = (TimeSpan)value; } } /// <summary> /// The message contains information about the tick candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.TickCandleKey)] public class TickCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TickCandleMessage"/>. /// </summary> public TickCandleMessage() : base(MessageTypes.CandleTick) { } /// <summary> /// Maximum tick count. /// </summary> [DataMember] public int MaxTradeCount { get; set; } /// <summary> /// Create a copy of <see cref="TickCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TickCandleMessage { MaxTradeCount = MaxTradeCount }); } /// <inheritdoc /> public override object Arg { get => MaxTradeCount; set => MaxTradeCount = (int)value; } } /// <summary> /// The message contains information about the volume candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.VolumeCandleKey)] public class VolumeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="VolumeCandleMessage"/>. /// </summary> public VolumeCandleMessage() : base(MessageTypes.CandleVolume) { } /// <summary> /// Maximum volume. /// </summary> [DataMember] public decimal Volume { get; set; } /// <summary> /// Create a copy of <see cref="VolumeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new VolumeCandleMessage { Volume = Volume }); } /// <inheritdoc /> public override object Arg { get => Volume; set => Volume = (decimal)value; } } /// <summary> /// The message contains information about the range candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.RangeCandleKey)] public class RangeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RangeCandleMessage"/>. /// </summary> public RangeCandleMessage() : base(MessageTypes.CandleRange) { } private Unit _priceRange = new(); /// <summary> /// Range of price. /// </summary> [DataMember] public Unit PriceRange { get => _priceRange; set => _priceRange = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Create a copy of <see cref="RangeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RangeCandleMessage { PriceRange = PriceRange.Clone() }); } /// <inheritdoc /> public override object Arg { get => PriceRange; set => PriceRange = (Unit)value; } /// <inheritdoc /> public override object CloneArg() => PriceRange.Clone(); } /// <summary> /// Point in figure (X0) candle arg. /// </summary> [DataContract] [Serializable] public class PnFArg : Equatable<PnFArg> { private Unit _boxSize = new(); /// <summary> /// Range of price above which increase the candle body. /// </summary> [DataMember] public Unit BoxSize { get => _boxSize; set => _boxSize = value ?? throw new ArgumentNullException(nameof(value)); } private int _reversalAmount = 1; /// <summary> /// The number of boxes required to cause a reversal. /// </summary> [DataMember] public int ReversalAmount { get => _reversalAmount; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219); _reversalAmount = value; } } /// <inheritdoc /> public override string ToString() { return $"Box = {BoxSize} RA = {ReversalAmount}"; } /// <summary> /// Create a copy of <see cref="PnFArg"/>. /// </summary> /// <returns>Copy.</returns> public override PnFArg Clone() { return new PnFArg { BoxSize = BoxSize.Clone(), ReversalAmount = ReversalAmount, }; } /// <summary> /// Compare <see cref="PnFArg"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> protected override bool OnEquals(PnFArg other) { return other.BoxSize == BoxSize && other.ReversalAmount == ReversalAmount; } /// <summary> /// Get the hash code of the object <see cref="PnFArg"/>. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { return BoxSize.GetHashCode() ^ ReversalAmount.GetHashCode(); } } /// <summary> /// The message contains information about the X0 candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.PnFCandleKey)] public class PnFCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="PnFCandleMessage"/>. /// </summary> public PnFCandleMessage() : base(MessageTypes.CandlePnF) { } private PnFArg _pnFArg = new(); /// <summary> /// Value of arguments. /// </summary> [DataMember] public PnFArg PnFArg { get => _pnFArg; set => _pnFArg = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Create a copy of <see cref="PnFCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new PnFCandleMessage { PnFArg = PnFArg.Clone(), //PnFType = PnFType }); } /// <inheritdoc /> public override object Arg { get => PnFArg; set => PnFArg = (PnFArg)value; } /// <inheritdoc /> public override object CloneArg() => PnFArg.Clone(); } /// <summary> /// The message contains information about the renko candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.RenkoCandleKey)] public class RenkoCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RenkoCandleMessage"/>. /// </summary> public RenkoCandleMessage() : base(MessageTypes.CandleRenko) { } private Unit _boxSize = new(); /// <summary> /// Possible price change range. /// </summary> [DataMember] public Unit BoxSize { get => _boxSize; set => _boxSize = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Create a copy of <see cref="RenkoCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RenkoCandleMessage { BoxSize = BoxSize.Clone() }); } /// <inheritdoc /> public override object Arg { get => BoxSize; set => BoxSize = (Unit)value; } /// <inheritdoc /> public override object CloneArg() => BoxSize.Clone(); } /// <summary> /// The message contains information about the Heikin-Ashi candle. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.HeikinAshiKey)] public class HeikinAshiCandleMessage : TimeFrameCandleMessage { /// <summary> /// Initializes a new instance of the <see cref="HeikinAshiCandleMessage"/>. /// </summary> public HeikinAshiCandleMessage() : base(MessageTypes.CandleHeikinAshi) { } /// <summary> /// Create a copy of <see cref="HeikinAshiCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new HeikinAshiCandleMessage { TimeFrame = TimeFrame }); } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.IO; using System.Text; using System.Web; using System.Xml.Serialization; using SubSonic.Utilities; namespace SubSonic { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> [Serializable] public class RecordBase<T> where T : RecordBase<T>, new() { #region State Properties private static readonly object _lockBaseSchema = new object(); private TableSchema.TableColumnCollection _dirtyColumns = new TableSchema.TableColumnCollection(); private bool _isLoaded; internal bool _isNew = true; private bool _validateWhenSaving = true; /// <summary> /// Gets or sets a value indicating whether [validate when saving]. /// </summary> /// <value><c>true</c> if [validate when saving]; otherwise, <c>false</c>.</value> [XmlIgnore] [HiddenForDataBinding(true)] public bool ValidateWhenSaving { get { return _validateWhenSaving; } set { _validateWhenSaving = value; } } /// <summary> /// A collection of column's who's values have been changed during instance scope. Used /// for Update commands. /// </summary> [XmlIgnore] [HiddenForDataBinding(true)] public TableSchema.TableColumnCollection DirtyColumns { get { return _dirtyColumns; } set { _dirtyColumns = value; } } /// <summary> /// Gets or sets a value indicating whether this instance is loaded. /// </summary> /// <value><c>true</c> if this instance is loaded; otherwise, <c>false</c>.</value> [XmlIgnore] [HiddenForDataBinding(true)] public bool IsLoaded { get { return _isLoaded; } set { _isLoaded = value; } } /// <summary> /// Whether or not this is a new record. The value is <c>true</c> if this object /// has yet to be persisted to a database, otherwise it's <c>false</c>. /// </summary> /// <value><c>true</c> if this instance is new; otherwise, <c>false</c>.</value> [XmlIgnore] [HiddenForDataBinding(true)] public bool IsNew { get { return _isNew; } set { _isNew = value; } } /// <summary> /// Whether or not the value of this object differs from that of the persisted /// database. This value is <c>true</c>if data has been changed and differs from DB, /// otherwise it is <c>false</c>. /// </summary> /// <value><c>true</c> if this instance is dirty; otherwise, <c>false</c>.</value> [XmlIgnore] [HiddenForDataBinding(true)] public bool IsDirty { get { return columnSettings.IsDirty; } } /// <summary> /// Name of the table in the database that contains persisted data for this type /// </summary> /// <value>The name of the table.</value> [XmlIgnore] [HiddenForDataBinding(true)] public string TableName { get { return BaseSchema.TableName; } } /// <summary> /// Empty virtual method that may be overridden in user code to perform operations /// at the conclusion of SetDefaults() invocation /// </summary> public virtual void Initialize() {} /// <summary> /// Empty virtual method that may be overridden in user code to perform operations /// at the conclusion of Load() invocation /// </summary> protected virtual void Loaded() {} /// <summary> /// Automatically called upon object creation. Sets IsNew to <c>true</c>; /// </summary> public void MarkNew() { _isNew = true; } /// <summary> /// Called after any property is set. Sets IsDirty to <c>true</c>. /// </summary> public void MarkClean() { foreach(TableSchema.TableColumnSetting setting in columnSettings) setting.IsDirty = false; DirtyColumns.Clear(); } /// <summary> /// Called after Update() invokation. Sets IsNew to <c>false</c>. /// </summary> public void MarkOld() { IsLoaded = true; _isNew = false; } #endregion #region Object Overrides /// <summary> /// Creates a HTML formatted text represententation of the contents of the current record /// </summary> /// <returns></returns> public string Inspect() { return Inspect(true); } /// <summary> /// Creates a formatted text represententation of the contents of the current record /// </summary> /// <param name="useHtml">Whether or not the results should be formatted using HTML</param> /// <returns></returns> public string Inspect(bool useHtml) { StringBuilder sb = new StringBuilder(); string sOut; if(useHtml) { sb.Append(String.Format("<table><tr><td colspan=2><h3>{0} Inspection</h3></td></tr>", BaseSchema.Name)); foreach(TableSchema.TableColumn col in BaseSchema.Columns) sb.AppendFormat("<tr><td><span style=\"font-weight:bold\">{0}</span></td><td>{1}</td></tr>", col.ColumnName, GetColumnValue<object>(col.ColumnName)); sb.Append("</table>"); sOut = sb.ToString(); } else { sb.AppendLine(String.Format("#################{0} Inspection ####################", BaseSchema.Name)); foreach(TableSchema.TableColumn col in BaseSchema.Columns) sb.AppendLine(String.Concat(col.ColumnName, ": ", GetColumnValue<object>(col.ColumnName))); sb.AppendLine("#############################################################################"); sOut = sb.ToString(); } return sOut; } /// <summary> /// Returns the simple string representation of the current record. By convention, this is the "descriptor" column (#2) /// </summary> /// <returns></returns> public override string ToString() { return GetColumnValue<string>(GetSchema().Descriptor.ColumnName); } #endregion #region DB Properties/Methods /// <summary> /// /// </summary> protected static TableSchema.Table table; private string _providerName; /// <summary> /// The column settings hold the current values of the object in a collection /// so that reflection is not needed in the base class to fill out the commands /// </summary> private TableSchema.TableColumnSettingCollection columnSettings; /// <summary> /// The base static class that holds all schema info for the table. /// The class must be instanced at least once to populate this table. /// </summary> protected static TableSchema.Table BaseSchema { get { if(table == null) { lock(_lockBaseSchema) if(table == null) new T(); } return table; } set { table = value; } } /// <summary> /// Gets a value indicating whether this instance is schema initialized. /// The schema is considered initialized if the underlying TableSchema.Table /// object is not null, and column collection has been loaded with one or more columns /// </summary> /// <value> /// <c>true</c> if this instance is schema initialized; otherwise, <c>false</c>. /// </value> protected static bool IsSchemaInitialized { get { return (table != null && table.Columns != null && table.Columns.Count > 0); } } /// <summary> /// Gets or sets the name of the provider. /// </summary> /// <value>The name of the provider.</value> [XmlIgnore] [HiddenForDataBinding(true)] public string ProviderName { get { return _providerName; } protected set { _providerName = value; } } /// <summary> /// Returns a default setting per data type /// </summary> /// <param name="column">The column.</param> /// <returns></returns> protected static object GetDefaultSetting(TableSchema.TableColumn column) { return Utility.GetDefaultSetting(column); } /// <summary> /// Return the underlying DbType for a column /// </summary> /// <param name="columnName">The name of the column whose type is to be returned</param> /// <returns></returns> public DbType GetDBType(string columnName) { TableSchema.TableColumn col = BaseSchema.GetColumn(columnName); return col.DataType; } /// <summary> /// Sets the Primary Key of the object /// </summary> /// <param name="oValue">The o value.</param> protected virtual void SetPrimaryKey(object oValue) { columnSettings.SetValue(BaseSchema.PrimaryKey.ColumnName, oValue); } /// <summary> /// Returns the current value of the primary key /// </summary> /// <returns></returns> public object GetPrimaryKeyValue() { return columnSettings.GetValue<object>(BaseSchema.PrimaryKey.ColumnName); } /// <summary> /// Sets a value for a particular column in the record /// </summary> /// <param name="columnName">Name of the column, as defined in the database</param> /// <param name="oValue">The value to set the type to</param> public void SetColumnValue(string columnName, object oValue) { // Set DBNull to null if (oValue == DBNull.Value) oValue = null; columnSettings = columnSettings ?? new TableSchema.TableColumnSettingCollection(); // add the column to the DirtyColumns // if this instance has already been loaded // and this is a change to existing values if(IsLoaded && !IsNew) { TableSchema.Table schema = GetSchema(); object oldValue = null; string oldValueMsg = "NULL"; string newValueMsg = "NULL"; bool areEqualOrBothNull = false; try { oldValue = columnSettings.GetValue(columnName); } catch {} if(oldValue == null && oValue == null) areEqualOrBothNull = true; else { if(oldValue != null) { oldValueMsg = oldValue.ToString(); areEqualOrBothNull = oldValue.Equals(oValue); } if(oValue != null) newValueMsg = oValue.ToString(); } TableSchema.TableColumn dirtyCol = schema.GetColumn(columnName); if(dirtyCol != null && !areEqualOrBothNull) { string auditMessage = String.Format("Value changed from {0} to {1}{2}", oldValueMsg, newValueMsg, Environment.NewLine); TableSchema.TableColumn dirtyEntry = DirtyColumns.GetColumn(columnName); if(dirtyEntry != null) { DirtyColumns.Remove(dirtyEntry); auditMessage = String.Concat(dirtyCol.AuditMessage, auditMessage); } dirtyCol.AuditMessage = auditMessage; DirtyColumns.Add(dirtyCol); } } columnSettings.SetValue(columnName, oValue); } /// <summary> /// Returns the current value of a column. /// </summary> /// <typeparam name="CT">The type of the T.</typeparam> /// <param name="columnName">Name of the column, as defined in the database</param> /// <returns></returns> public CT GetColumnValue<CT>(string columnName) { CT oOut = default(CT); if(columnSettings != null) oOut = columnSettings.GetValue<CT>(columnName); return oOut; } /// <summary> /// Returns the underly TableSchema.Table object for the given record /// </summary> /// <returns></returns> public TableSchema.Table GetSchema() { return BaseSchema; } #endregion #region WebUI Helper private readonly List<string> errorList = new List<string>(); private string invalidTypeExceptionMessage = "{0} is not a valid {1}"; private string lengthExceptionMessage = "{0} exceeds the maximum length of {1}"; private string nullExceptionMessage = "{0} requires a value"; /// <summary> /// Gets or sets the exception message thrown for non-null conversion errors performed during record validation. /// </summary> /// <value>The null exception message.</value> [XmlIgnore] [HiddenForDataBinding(true)] public string NullExceptionMessage { get { return nullExceptionMessage; } protected set { nullExceptionMessage = value; } } /// <summary> /// Gets or sets the exception message thrown for type conversion errors performed during record validation. /// </summary> /// <value>The invalid type exception message.</value> [XmlIgnore] [HiddenForDataBinding(true)] public string InvalidTypeExceptionMessage { get { return invalidTypeExceptionMessage; } protected set { invalidTypeExceptionMessage = value; } } /// <summary> /// Gets or sets the exception message thrown for value length conversion errors performed during record validation. /// </summary> /// <value>The length exception message.</value> [XmlIgnore] [HiddenForDataBinding(true)] public string LengthExceptionMessage { get { return lengthExceptionMessage; } protected set { lengthExceptionMessage = value; } } /// <summary> /// Gets the collection of error messages for the record. /// </summary> /// <value></value> [HiddenForDataBinding(true)] public List<string> Errors { get { return errorList; } } /// <summary> /// Determines whether this instance has errors. /// </summary> /// <returns> /// <c>true</c> if this instance has errors; otherwise, <c>false</c>. /// </returns> public bool HasErrors() { return errorList.Count > 0; } /// <summary> /// Returns the list of error messages for the record. /// </summary> /// <returns></returns> public List<string> GetErrors() { // TODO: This does the *exact* same thing as the Errors property, why are there two of them? If there is a good reason it should be documented. return errorList; } /// <summary> /// Loops the underlying settings collection to validate type, nullability, and length /// </summary> public void ValidateColumnSettings() { // loop the current settings and make sure they are valid for their type foreach(TableSchema.TableColumnSetting setting in GetColumnSettings()) { Utility.WriteTrace(String.Format("Validating {0}", setting.ColumnName)); object settingValue = setting.CurrentValue; bool isNullValue = (settingValue == null || settingValue == DBNull.Value); TableSchema.TableColumn col = table.GetColumn(setting.ColumnName); if(!col.IsReadOnly) { string formattedName = Utility.ParseCamelToProper(col.ColumnName); Type t = col.GetPropertyType(); //// Convert the existing value to the type for this column //// if there's an error, report it. //// OK to bypass if the column is nullable and this setting is null //// just check for now if the value isn't null - it will be checked //// later for nullability if(!col.IsNullable && !isNullValue) { try { if(col.DataType != DbType.Guid) Convert.ChangeType(settingValue, t); } catch { // there's a conversion problem here // add it to the Exception List<> if(col.IsNumeric) errorList.Add(String.Format(InvalidTypeExceptionMessage, formattedName, "number")); else if(col.IsDateTime) errorList.Add(String.Format(InvalidTypeExceptionMessage, formattedName, "date")); else errorList.Add(String.Format(InvalidTypeExceptionMessage, formattedName, "value")); } } bool isDbControlledAuditField = (Utility.IsAuditField(col.ColumnName) && !String.IsNullOrEmpty(col.DefaultSetting)); // now make sure that this column's null settings match with what's in the setting Utility.WriteTrace(String.Format("Testing nullability of {0}", setting.ColumnName)); if(!col.IsNullable && isNullValue && !isDbControlledAuditField) { Utility.WriteTrace(String.Format("Null Error Caught {0}", setting.ColumnName)); errorList.Add(String.Format(NullExceptionMessage, formattedName)); } // finally, check the length Utility.WriteTrace(String.Format("Testing Max Length of {0}", setting.ColumnName)); if(!isNullValue && col.MaxLength > 0) { if(col.DataType != DbType.Boolean && settingValue.ToString().Length > col.MaxLength) { Utility.WriteTrace(String.Format("Max Length Exceeded {0} (can't exceed {1}); current value is set to {2}", col.ColumnName, col.MaxLength, settingValue.ToString().Length)); errorList.Add(String.Format(LengthExceptionMessage, formattedName, col.MaxLength)); } } } } } /// <summary> /// Loads your object from an ASP.NET form postback /// </summary> public void LoadFromPost() { LoadFromPost(true); } /// <summary> /// Loads your object from an ASP.NET form postback /// </summary> /// <param name="validatePost">Set this to false to skip validation</param> public void LoadFromPost(bool validatePost) { if(HttpContext.Current != null) { // use Request.form, since the ControlCollection can return weird results based on // the container structure. NameValueCollection formPost = HttpContext.Current.Request.Form; TableSchema.TableColumnSettingCollection settings = GetColumnSettings(); if(formPost != null && settings != null) { foreach(string s in formPost.AllKeys) { Utility.WriteTrace(String.Format("Looking at form field {0}", s)); foreach(TableSchema.TableColumnSetting setting in settings) { if(s.EndsWith(String.Concat("_", setting.ColumnName), StringComparison.InvariantCultureIgnoreCase) || s.EndsWith(String.Concat("$", setting.ColumnName), StringComparison.InvariantCultureIgnoreCase) || Utility.IsMatch(s, setting.ColumnName)) { SetColumnValue(setting.ColumnName, formPost[s]); Utility.WriteTrace(String.Format("Matched {0} to {1}", s, setting.ColumnName)); } } } } // validate the settings, since we're setting the object values here, not // using the accessors as we should be. if(validatePost) { ValidateColumnSettings(); if(errorList.Count > 0) { // format this for the web if(HttpContext.Current != null) { // decorate the output StringBuilder errorReport = new StringBuilder("<b>Validation Error:</b><ul>"); foreach(string s in errorList) errorReport.AppendFormat("<li><em>{0}</em></li>", s); errorReport.Append("</ul>"); throw new Exception(errorReport.ToString()); } throw new Exception( "Validation error - catch this and check the ExceptionList property to review the exceptions. You can change the output message as needed by accessing the ExceptionMessage properties of this object"); } } } } #endregion #region Serializers /// <summary> /// Returns and XML representation of the given record /// </summary> /// <returns></returns> public string ToXML() { Type type = typeof(T); XmlSerializer ser = new XmlSerializer(type); using(MemoryStream stm = new MemoryStream()) { // serialize to a memory stream ser.Serialize(stm, this); // reset to beginning so we can read it. stm.Position = 0; // Convert a string. using(StreamReader stmReader = new StreamReader(stm)) { string xmlData = stmReader.ReadToEnd(); return xmlData; } } } /// <summary> /// Returns an object based on the passed-in XML. /// </summary> /// <param name="xml">The XML.</param> /// <returns></returns> public object NewFromXML(string xml) { object oOut = null; Type type = typeof(T); // hydrate based on private string var if(xml.Length > 0) { XmlSerializer serializer = new XmlSerializer(type); StringBuilder sb = new StringBuilder(); sb.Append(xml); using(StringReader sReader = new StringReader(xml)) { oOut = serializer.Deserialize(sReader); sReader.Close(); } } return oOut; } #endregion #region Utility /// <summary> /// Returns the current collection of column settings for the given record. /// </summary> /// <returns></returns> public TableSchema.TableColumnSettingCollection GetColumnSettings() { GetSchema(); return columnSettings; } /// <summary> /// Copies the current instance to a new instance /// </summary> /// <returns>New instance of current object</returns> public T Clone() { T thisInstance = new T(); foreach(TableSchema.TableColumnSetting setting in columnSettings) thisInstance.SetColumnValue(setting.ColumnName, setting.CurrentValue); return thisInstance; } /// <summary> /// Copies current instance to the passed in instance /// </summary> /// <param name="copyInstance">The copy instance.</param> public void CopyTo(T copyInstance) { if(copyInstance == null) copyInstance = new T(); foreach(TableSchema.TableColumnSetting setting in columnSettings) copyInstance.SetColumnValue(setting.ColumnName, setting.CurrentValue); } /// <summary> /// Adds a new row to a Datatable with this record. /// Column names must match for this to work properly. /// </summary> /// <param name="dataTable">The data table.</param> public void CopyTo(DataTable dataTable) { DataRow newRow = dataTable.NewRow(); foreach(TableSchema.TableColumnSetting setting in columnSettings) { try { newRow[setting.ColumnName] = setting.CurrentValue; } catch {} } dataTable.Rows.Add(newRow); } /// <summary> /// Copies a record from a DataTable to this instance. Column names must match. /// </summary> /// <param name="row">The row.</param> public void CopyFrom(DataRow row) { foreach(TableSchema.TableColumnSetting setting in columnSettings) { try { setting.CurrentValue = row[setting.ColumnName]; } catch {} } } /// <summary> /// Copies the passed-in instance settings to this instance /// </summary> /// <param name="copyInstance">The copy instance.</param> public void CopyFrom(T copyInstance) { if(copyInstance == null) throw new ArgumentNullException("copyInstance"); foreach(TableSchema.TableColumnSetting setting in copyInstance.columnSettings) SetColumnValue(setting.ColumnName, setting.CurrentValue); } #endregion #region Loaders /// <summary> /// Initializes the object using the default values for the underlying column data types. /// </summary> protected virtual void SetDefaults() { // initialize to default settings bool connectionClosed = true; bool setDbDefaults = DataService.GetInstance(ProviderName).SetPropertyDefaultsFromDatabase; if(DataService.GetInstance(ProviderName).CurrentSharedConnection != null) connectionClosed = DataService.GetInstance(ProviderName).CurrentSharedConnection.State == ConnectionState.Closed; foreach(TableSchema.TableColumn col in BaseSchema.Columns) { if(setDbDefaults && !String.IsNullOrEmpty(col.DefaultSetting) && connectionClosed) { if(!Utility.IsMatch(col.DefaultSetting, SqlSchemaVariable.DEFAULT)) { QueryCommand cmdDefault = new QueryCommand(String.Concat(SqlFragment.SELECT, col.DefaultSetting), col.Table.Provider.Name); SetColumnValue(col.ColumnName, DataService.ExecuteScalar(cmdDefault)); } } else SetColumnValue(col.ColumnName, Utility.GetDefaultSetting(col)); } Initialize(); } /// <summary> /// Forces object properties to be initialized using the defaults specified in the database schema. /// This method is called only if the provider level setting "useDatabaseDefaults" is set to <c>true</c> /// </summary> protected void ForceDefaults() { foreach(TableSchema.TableColumn col in BaseSchema.Columns) { if(!String.IsNullOrEmpty(col.DefaultSetting)) { if(!Utility.IsMatch(col.DefaultSetting, SqlSchemaVariable.DEFAULT)) { string s = col.DefaultSetting; if (s.StartsWith("=")) { s = s.Substring(1); } QueryCommand cmdDefault = new QueryCommand(SqlFragment.SELECT + s, col.Table.Provider.Name); SetColumnValue(col.ColumnName, DataService.ExecuteScalar(cmdDefault)); } } else SetColumnValue(col.ColumnName, Utility.GetDefaultSetting(col)); } } /// <summary> /// Sets initial record states when a record is loaded. /// </summary> protected void SetLoadState() { IsLoaded = true; IsNew = false; Loaded(); } /// <summary> /// Loads the object with the current reader's values. Assumes the reader is already moved to /// first position in recordset (aka has been "Read()") /// </summary> /// <param name="dataReader">The data reader.</param> public virtual void Load(IDataReader dataReader) { foreach(TableSchema.TableColumn col in BaseSchema.Columns) { try { SetColumnValue(col.ColumnName, dataReader[col.ColumnName]); } catch(Exception) { // turning off the Exception for now // to support partial loads // throw new Exception("Unable to set column value for " + col.ColumnName + ": " + x.Message); } } SetLoadState(); MarkClean(); } /// <summary> /// Loads the object with the current reader's values. Assumes the reader is already moved to /// first position in recordset (aka has been "Read()") /// </summary> /// <param name="dataTable">The data table.</param> public virtual void Load(DataTable dataTable) { if(dataTable.Rows.Count > 0) { DataRow dr = dataTable.Rows[0]; Load(dr); } } /// <summary> /// Loads the object with the current DataRow's values. /// </summary> /// <param name="dr">The dr.</param> public virtual void Load(DataRow dr) { foreach(TableSchema.TableColumn col in BaseSchema.Columns) { try { SetColumnValue(col.ColumnName, dr[col.ColumnName]); } catch(Exception) { // turning off the Exception for now // TODO: move this to a SubSonicLoadException // which collects the exceptions // this will happen only if there's a reader error. // throw new Exception("Unable to set column value for " + col.ColumnName + "; " + x.Message); } } SetLoadState(); } /// <summary> /// Opens the IDataReader, loads the object and closes the IDataReader. Unlike AbstractList.LoadAndCloseReader, /// this method does not assume that reader is open and in the first position! /// </summary> /// <param name="dataReader">The data reader.</param> public void LoadAndCloseReader(IDataReader dataReader) { using(dataReader) { if(dataReader.Read()) Load(dataReader); if(!dataReader.IsClosed) dataReader.Close(); } } #endregion } /// <summary> /// Attribute class used to suppress "internal" properties when databinding. YMMV. /// </summary> [AttributeUsage(AttributeTargets.Property)] internal sealed class HiddenForDataBindingAttribute : Attribute { private readonly bool _isHidden; /// <summary> /// Initializes a new instance of the <see cref="HiddenForDataBindingAttribute"/> class. /// </summary> public HiddenForDataBindingAttribute() {} /// <summary> /// Initializes a new instance of the <see cref="HiddenForDataBindingAttribute"/> class. /// </summary> /// <param name="isHidden">if set to <c>true</c> [is hidden].</param> public HiddenForDataBindingAttribute(bool isHidden) { _isHidden = isHidden; } /// <summary> /// Gets a value indicating whether this instance is hidden. /// </summary> /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value> public bool IsHidden { get { return _isHidden; } } } }
using System; using System.Linq; using System.Reflection; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.DependencyInjection; using Lapis.CommandLineUtils.Converters; using Lapis.CommandLineUtils.Util; using System.Collections.Generic; using Lapis.CommandLineUtils.ResultHandlers; using Lapis.CommandLineUtils.ExceptionHandlers; namespace Lapis.CommandLineUtils.Models { public interface ICommandBinder { void BindCommand(CommandLineApplication app, CommandModel commandModel); } public class CommandBinder : ICommandBinder { public CommandBinder(IServiceProvider serviceProvider, IReadOnlyList<Type> globalConverters, IReadOnlyList<Type> globalResultHandlers, IReadOnlyList<Type> globalExceptionHandlers) { ServiceProvider = serviceProvider; GlobalConverters = globalConverters; GlobalResultHandlers = globalResultHandlers; GlobalExceptionHandlers = globalExceptionHandlers; } public IServiceProvider ServiceProvider { get; } public IReadOnlyList<Type> GlobalConverters { get; } public IReadOnlyList<Type> GlobalResultHandlers { get; } public IReadOnlyList<Type> GlobalExceptionHandlers { get; } public virtual void BindCommand(CommandLineApplication app, CommandModel commandModel) { if (commandModel == null) throw new ArgumentNullException(nameof(commandModel)); app.Command(commandModel.Name, command => { command.Description = commandModel.Description; command.ShowInHelpText = commandModel.ShowInHelpText; command.AllowArgumentSeparator = commandModel.AllowArgumentSeparator; command.ExtendedHelpText = commandModel.ExtendedHelpText; if (commandModel.HelpOption != null) command.HelpOption(commandModel.HelpOption.Template); if (commandModel.VersionOption != null) command.VersionOption( commandModel.VersionOption.Template, commandModel.VersionOption.ShortFormVersion, commandModel.VersionOption.LongFormVersion ); if (commandModel.Method != null) { var parameterInfo = commandModel.Method.GetParameters().ToList(); var parameterFunc = parameterInfo.Select(p => (Func<object>)null).ToList(); if (commandModel.Arguments != null) foreach (var arg in commandModel.Arguments) { var index = parameterInfo.IndexOf(arg.Parameter); if (index < 0) throw new InvalidOperationException($"Method {commandModel.Method.Name} doesn't have parameter {arg.Parameter.Name}."); if (parameterFunc[index] != null) throw new InvalidOperationException($"Parameter {arg.Parameter.Name} alreadly exists."); parameterFunc[index] = BindArgument(command, arg); }; if (commandModel.Options != null) foreach (var opt in commandModel.Options) { var index = parameterInfo.IndexOf(opt.Parameter); if (index < 0) throw new InvalidOperationException($"Method {commandModel.Method.Name} doesn't have parameter {opt.Parameter.Name}."); if (parameterFunc[index] != null) throw new InvalidOperationException($"Parameter {opt.Parameter.Name} alreadly exists."); parameterFunc[index] = BindOption(command, opt); }; { var index = parameterFunc.IndexOf(null); if (index >= 0) throw new InvalidOperationException($"Parameter {parameterInfo[index].Name} cannot be bound to any argument or option."); } var methodInfo = commandModel.Method; var parameters = parameterFunc.Select(func => func.Invoke()); var resultHandler = SelectResultHandler(EnumerateResultHandlerTypes(commandModel)); var exceptionHandler = SelectExceptionHandler(EnumerateExceptionHandlerTypes(commandModel)); if (methodInfo.IsStatic) command.OnExecute(() => { int returnValue = 0; try { var result = methodInfo.Invoke(null, parameters.ToArray()); returnValue = resultHandler?.Invoke(result) ?? 0; } catch (Exception ex) { returnValue = exceptionHandler?.Invoke(ex) ?? ex.HResult; } return returnValue; }); else { var instanceType = methodInfo.DeclaringType; command.OnExecute(() => { int returnValue = 0; try { var instance = ServiceProvider.GetService(instanceType); if (instance == null) { var constructor = instanceType .GetConstructors(BindingFlags.Public | BindingFlags.Instance) .Where(ctor => !ctor.IsAbstract) .FirstOrDefault(ctor => ctor.GetParameters().Length == 0); instance = constructor?.Invoke(null); } var result = methodInfo.Invoke(instance, parameters.ToArray()); returnValue = resultHandler?.Invoke(result) ?? 0; } catch (Exception ex) { returnValue = exceptionHandler?.Invoke(ex) ?? ex.HResult; } return returnValue; }); } } if (commandModel.Commands != null) { foreach (var cmd in commandModel.Commands) BindCommand(command, cmd); } }); } protected virtual Func<object> BindArgument(CommandLineApplication command, CommandModel.ArgumentModel argumentModel) { if (argumentModel == null) throw new ArgumentNullException(nameof(argumentModel)); if (argumentModel.Parameter == null) throw new ArgumentNullException(nameof(argumentModel.Parameter)); if (argumentModel.MultipleValues != true) { var converter = SelectConverter( EnumerateConverterTypes(argumentModel), typeof(string), argumentModel.Parameter.ParameterType ); if (converter != null) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: false); if (argumentModel.Parameter.HasDefaultValue) { var defaultValue = argumentModel.Parameter.RawDefaultValue; return () => argument.Value != null ? converter.Invoke(argument.Value) : defaultValue; } else return () => converter.Invoke(argument.Value); } } if (argumentModel.MultipleValues != false) { var converter = SelectConverter( EnumerateConverterTypes(argumentModel), typeof(List<string>), argumentModel.Parameter.ParameterType ); if (converter != null) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: true); return () => converter.Invoke(argument.Values); } } if (argumentModel.MultipleValues != false) { var converter = SelectConverter( EnumerateConverterTypes(argumentModel), typeof(string[]), argumentModel.Parameter.ParameterType ); if (converter != null) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: true); return () => converter.Invoke(argument.Values.ToArray()); } } if (argumentModel.MultipleValues != true) { if (argumentModel.Parameter.ParameterType.IsAssignableFrom(typeof(string))) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: false); if (argumentModel.Parameter.HasDefaultValue) { var defaultValue = argumentModel.Parameter.RawDefaultValue; return () => argument.Value ?? defaultValue; } else return () => argument.Value; } } if (argumentModel.MultipleValues != false) { if (argumentModel.Parameter.ParameterType.IsAssignableFrom(typeof(List<string>))) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: true); return () => argument.Values; } if (argumentModel.Parameter.ParameterType.IsAssignableFrom(typeof(string[]))) { var argument = command.Argument(argumentModel.Name, argumentModel.Description, arg => arg.ShowInHelpText = argumentModel.ShowInHelpText, multipleValues: true); return () => argument.Values.ToArray(); } } if (argumentModel.MultipleValues == true) throw new NotSupportedException($"No converter from string[] to {argumentModel.Parameter.ParameterType.FullName}."); else throw new NotSupportedException($"No converter from string to {argumentModel.Parameter.ParameterType.FullName}."); } protected virtual Func<object> BindOption(CommandLineApplication command, CommandModel.OptionModel optionModel) { if (optionModel == null) throw new ArgumentNullException(nameof(optionModel)); if (optionModel.Parameter == null) throw new ArgumentNullException(nameof(optionModel.Parameter)); if (optionModel.OptionType != CommandOptionType.MultipleValue && optionModel.OptionType != CommandOptionType.SingleValue) { if (optionModel.Parameter.ParameterType.IsAssignableFrom(typeof(bool))) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.NoValue); option.ShowInHelpText = optionModel.ShowInHelpText; return () => option.HasValue(); } } if (optionModel.OptionType != CommandOptionType.MultipleValue && optionModel.OptionType != CommandOptionType.NoValue) { var converter = SelectConverter( EnumerateConverterTypes(optionModel), typeof(string), optionModel.Parameter.ParameterType ); if (converter != null) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.SingleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? converter.Invoke(option.Value()) : defaultValue; } else return () => option.HasValue() ? converter.Invoke(option.Value()) : null; } } if (optionModel.OptionType != CommandOptionType.SingleValue && optionModel.OptionType != CommandOptionType.NoValue) { var converter = SelectConverter( EnumerateConverterTypes(optionModel), typeof(List<string>), optionModel.Parameter.ParameterType ); if (converter != null) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.MultipleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? converter.Invoke(option.Values) : defaultValue; } else return () => converter.Invoke(option.Values); } } if (optionModel.OptionType != CommandOptionType.SingleValue && optionModel.OptionType != CommandOptionType.NoValue) { var converter = SelectConverter( EnumerateConverterTypes(optionModel), typeof(string[]), optionModel.Parameter.ParameterType ); if (converter != null) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.MultipleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? converter.Invoke(option.Values.ToArray()) : defaultValue; } else return () => converter.Invoke(option.Values.ToArray()); } } if (optionModel.OptionType != CommandOptionType.MultipleValue && optionModel.OptionType != CommandOptionType.NoValue) { if (optionModel.Parameter.ParameterType.IsAssignableFrom(typeof(string))) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.SingleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? option.Value() : defaultValue; } else return () => option.Value(); } } if (optionModel.OptionType != CommandOptionType.SingleValue && optionModel.OptionType != CommandOptionType.NoValue) { if (optionModel.Parameter.ParameterType.IsAssignableFrom(typeof(List<string>))) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.MultipleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? option.Values : defaultValue; } else return () => option.Values; } if (optionModel.Parameter.ParameterType.IsAssignableFrom(typeof(string[]))) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.MultipleValue); option.ShowInHelpText = optionModel.ShowInHelpText; if (optionModel.Parameter.HasDefaultValue) { var defaultValue = optionModel.Parameter.RawDefaultValue; return () => option.HasValue() ? option.Values.ToArray() : defaultValue; } else return () => option.Values.ToArray(); } } if (optionModel.OptionType != CommandOptionType.MultipleValue && optionModel.OptionType != CommandOptionType.SingleValue) { var converter = SelectConverter( EnumerateConverterTypes(optionModel), typeof(bool), optionModel.Parameter.ParameterType ); if (converter != null) { var option = command.Option(optionModel.Template, optionModel.Description, optionType: CommandOptionType.SingleValue); option.ShowInHelpText = optionModel.ShowInHelpText; return () => converter.Invoke(option.HasValue()); } } if (optionModel.OptionType == CommandOptionType.MultipleValue) throw new NotSupportedException($"No converter from string[] to {optionModel.Parameter.ParameterType.FullName}."); else if (optionModel.OptionType == CommandOptionType.NoValue) throw new NotSupportedException($"No converter from bool to {optionModel.Parameter.ParameterType.FullName}."); else throw new NotSupportedException($"No converter from string to {optionModel.Parameter.ParameterType.FullName}."); } private Func<object, object> SelectConverter(IEnumerable<Type> converterTypes, Type sourceType, Type targetType) { return converterTypes.Distinct().Select(type => { var converter = CreateConverter(type); if (converter != null) { if (converter.CanConvert(sourceType, targetType)) return converter; } return null; }) .Where(converter => converter != null) .Select(converter => (Func<object, object>)(source => converter.Convert(source, targetType))) .FirstOrDefault(); } private IConverter CreateConverter(Type type) { if (typeof(IConverter).IsAssignableFrom(type)) { IConverter converter; converter = ServiceProvider.GetService(type) as IConverter; if (converter != null) return converter; if (!type.IsAbstract) { var constructor = type .GetConstructors(BindingFlags.Public | BindingFlags.Instance) .Where(ctor => !ctor.IsAbstract) .FirstOrDefault(ctor => ctor.GetParameters().Length == 0); converter = constructor?.Invoke(null) as IConverter; if (converter != null) return converter; } } return null; } private IEnumerable<Type> EnumerateConverterTypes(CommandModel commandModel) { var converters = commandModel.Converters; if (converters != null) foreach (var converter in converters) yield return converter; var parentConverters = commandModel.Parent?.Converters; if (commandModel.Parent != null) foreach (var converter in EnumerateConverterTypes(commandModel.Parent)) yield return converter; else if (GlobalConverters != null) foreach (var converter in GlobalConverters) yield return converter; } private IEnumerable<Type> EnumerateConverterTypes(CommandModel.ArgumentModel argumentModel) { var converters = argumentModel.Converters; if (converters != null) foreach (var converter in converters) yield return converter; if (argumentModel.Command != null) foreach (var converter in EnumerateConverterTypes(argumentModel.Command)) yield return converter; else if (GlobalConverters != null) foreach (var converter in GlobalConverters) yield return converter; } private IEnumerable<Type> EnumerateConverterTypes(CommandModel.OptionModel optionModel) { var converters = optionModel.Converters; if (converters != null) foreach (var converter in converters) yield return converter; if (optionModel.Command != null) foreach (var converter in EnumerateConverterTypes(optionModel.Command)) yield return converter; else if (GlobalConverters != null) foreach (var converter in GlobalConverters) yield return converter; } private Func<object, int> SelectResultHandler(IEnumerable<Type> resultHandlerTypes) { var handlers = resultHandlerTypes.Distinct().Select(type => CreateResultHandler(type)) .Where(handler => handler != null).ToList(); return value => { int result = 0; foreach (var r in handlers.Select(handler => handler.Handle(value))) { result = r; if (result >= 0) break; else continue; } return result; }; } private IResultHandler CreateResultHandler(Type type) { if (typeof(IResultHandler).IsAssignableFrom(type)) { IResultHandler handler = ServiceProvider.GetService(type) as IResultHandler; if (handler != null) return handler; if (!type.IsAbstract) { var constructor = type .GetConstructors(BindingFlags.Public | BindingFlags.Instance) .Where(ctor => !ctor.IsAbstract) .FirstOrDefault(ctor => ctor.GetParameters().Length == 0); handler = constructor?.Invoke(null) as IResultHandler; if (handler != null) return handler; } } return null; } private IEnumerable<Type> EnumerateResultHandlerTypes(CommandModel commandModel) { var handlers = commandModel.ResultHandlers; if (handlers != null) foreach (var handler in handlers) yield return handler; var parentHandlers = commandModel.Parent?.ResultHandlers; if (commandModel.Parent != null) foreach (var handler in EnumerateResultHandlerTypes(commandModel.Parent)) yield return handler; else if (GlobalResultHandlers != null) foreach (var handler in GlobalResultHandlers) yield return handler; } private Func<Exception, int> SelectExceptionHandler(IEnumerable<Type> exceptionHandlerTypes) { var handlers = exceptionHandlerTypes.Distinct().Select(type => CreateExceptionHandler(type)) .Where(handler => handler != null).ToList(); return ex => { int result = ex.HResult; foreach (var r in handlers.Select(handler => handler.Handle(ex))) { result = r; if (result >= 0) break; else continue; } return result; }; } private IExceptionHandler CreateExceptionHandler(Type type) { if (typeof(IExceptionHandler).IsAssignableFrom(type)) { IExceptionHandler handler = ServiceProvider.GetService(type) as IExceptionHandler; if (handler != null) return handler; if (!type.IsAbstract) { var constructor = type .GetConstructors(BindingFlags.Public | BindingFlags.Instance) .Where(ctor => !ctor.IsAbstract) .FirstOrDefault(ctor => ctor.GetParameters().Length == 0); handler = constructor?.Invoke(null) as IExceptionHandler; if (handler != null) return handler; } } return null; } private IEnumerable<Type> EnumerateExceptionHandlerTypes(CommandModel commandModel) { var handlers = commandModel.ExceptionHandlers; if (handlers != null) foreach (var handler in handlers) yield return handler; var parentHandlers = commandModel.Parent?.ExceptionHandlers; if (commandModel.Parent != null) foreach (var handler in EnumerateExceptionHandlerTypes(commandModel.Parent)) yield return handler; else if (GlobalExceptionHandlers != null) foreach (var handler in GlobalExceptionHandlers) yield return handler; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using Microsoft.Win32; using System.Collections; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.CoreServices { // constants and utility functions useful in working with the registry public class RegistryHelper { /// <summary> /// CLSID registry key /// </summary> public static readonly string CLSID = "CLSID"; /// <summary> /// InprocServer32 registry key /// </summary> public static readonly string INPROC_SERVER_32 = "InprocServer32"; /// <summary> /// Return the passed guid as a string in registry format (i.e. w/ {}) /// </summary> /// <param name="guid">Guid to return reg format for</param> /// <returns></returns> public static string GuidRegFmt(Guid guid) { return guid.ToString("B"); } /// <summary> /// Helper function to recursively delete a sub-key (swallows errors in the /// case of the sub-key not existing /// </summary> /// <param name="root">Root to delete key from</param> /// <param name="subKey">Name of key to delete</param> public static void DeleteSubKeyTree(RegistryKey root, string subKey) { // delete the specified sub-key if if exists (swallow the error if the // sub-key does not exist) try { root.DeleteSubKeyTree(subKey); } catch (ArgumentException) { } } /// <summary> /// Returns the root RegistryKey associated with the HKey value. /// </summary> /// <param name="hkey"></param> /// <returns></returns> private static RegistryKey GetRootRegistryKey(UIntPtr hkey) { if (hkey == HKEY.CLASSES_ROOT) return Registry.ClassesRoot; else if (hkey == HKEY.CURRENT_USER) return Registry.CurrentUser; else if (hkey == HKEY.LOCAL_MACHINE) return Registry.LocalMachine; else if (hkey == HKEY.USERS) return Registry.Users; else if (hkey == HKEY.PERFORMANCE_DATA) return Registry.PerformanceData; else if (hkey == HKEY.CURRENT_CONFIG) return Registry.CurrentConfig; else if (hkey == HKEY.DYN_DATA) { throw new Exception("Unsupported HKEY value: " + hkey); } else { throw new Exception("Unknown HKEY value: " + hkey); } } /// <summary> /// Create the specified registry key. /// </summary> /// <param name="hkey"></param> /// <param name="key"></param> public static void CreateKey(UIntPtr hkey, string key) { RegistryKey regKey = GetKey(hkey, key); regKey.Close(); } public static bool KeyExists(UIntPtr hkey, string key) { RegistryKey currentKey = GetRootRegistryKey(hkey); using (RegistryKey subkey = currentKey.OpenSubKey(key, false)) return subkey != null; } public static string GetAppUserModelID(string progId) { try { using (RegistryKey progIdKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\" + progId)) { if (progIdKey != null) return progIdKey.GetValue("AppUserModelID") as string; } } catch (Exception ex) { Trace.Fail("Exception thrown while getting the AppUserModelID for " + progId); if (!IsRegistryException(ex)) throw; } return null; } private static void DumpKey(RegistryKey key, int depth) { try { string indent = new string(' ', depth * 2); Trace.WriteLine(indent + key); // Enumerate values foreach (string valueName in key.GetValueNames()) { if (String.IsNullOrEmpty(valueName)) { Trace.WriteLine(indent + "Default Value: " + key.GetValue(valueName)); } else { Trace.WriteLine(indent + "Name: " + valueName + " --> Value: " + key.GetValue(valueName)); } } // Enumerate subkeys foreach (string subKeyName in key.GetSubKeyNames()) { using (RegistryKey subKey = key.OpenSubKey(subKeyName)) { DumpKey(subKey, depth + 1); } } } catch (Exception ex) { Trace.Fail("Exception thrown while dumping registry key: " + key + "\r\n" + ex); if (IsRegistryException(ex)) return; throw; } } public static bool IsRegistryException(Exception ex) { return (ex is SecurityException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is IOException || ex is ArgumentNullException); } public static void DumpKey(RegistryKey key, string subkey) { try { if (key == null) throw new ArgumentNullException("key"); if (subkey == null) throw new ArgumentNullException("subkey"); using (RegistryKey extensionKey = key.OpenSubKey(subkey)) { if (extensionKey == null) Trace.WriteLine("Failed to open " + key + @"\" + subkey); else DumpKey(extensionKey); } } catch (Exception ex) { Trace.Fail("Exception thrown while dumping registry key: " + key + "\r\n" + ex); if (IsRegistryException(ex)) return; throw; } } public static void DumpKey(RegistryKey key) { DumpKey(key, 0); } /// <summary> /// Get the specified registry key. /// </summary> /// <param name="hkey"></param> /// <param name="key"></param> public static RegistryKey GetKey(UIntPtr hkey, string key) { ArrayList keyList = new ArrayList(); try { RegistryKey currentKey = GetRootRegistryKey(hkey); keyList.Add(currentKey); foreach (string subKeyName in key.Split('\\')) { currentKey = currentKey.CreateSubKey(subKeyName); keyList.Add(currentKey); } } finally { //close all of the open registry keys for (int i = 0; i < keyList.Count - 1; i++) { RegistryKey regKey = (RegistryKey)keyList[i]; regKey.Close(); } } return keyList[keyList.Count - 1] as RegistryKey; } /// <summary> /// Returns the path of the specified registry key. /// </summary> /// <param name="hkey"></param> /// <param name="key"></param> /// <returns></returns> public static string GetKeyString(UIntPtr hkey, string key) { return String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", GetHKeyString(hkey), key); } private static string GetHKeyString(UIntPtr hkey) { if (hkey == HKEY.CLASSES_ROOT) return "HKEY_CLASSES_ROOT"; else if (hkey == HKEY.CURRENT_USER) return "HKEY_CURRENT_USER"; else if (hkey == HKEY.LOCAL_MACHINE) return "HKEY_LOCAL_MACHINE"; else if (hkey == HKEY.USERS) return "HKEY_USERS"; else if (hkey == HKEY.PERFORMANCE_DATA) return "HKEY_PERFORMANCE_DATA"; else if (hkey == HKEY.CURRENT_CONFIG) return "HKEY_CURRENT_CONFIG"; else if (hkey == HKEY.DYN_DATA) return "HKEY_DYN_DATA"; else { Debug.Fail("unknown HKEY value"); return "HKEY_UNKNOWN"; } } } }
//This code is used in EIC_Particle to determine the position of SpotOnGrid on the arousal valence grid based on input from classifier from OSCListener using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using System.IO; using System.Collections.Generic; using System; public class ParticleMain : MonoBehaviour { [HideInInspector] public bool moveParticleSystemCheck = false; // may not be needed [HideInInspector] public bool changeSceneOnPSClick = false; //may not be needed [HideInInspector] public float fadeSpeed = 0.02f; //may not be needed [HideInInspector] public int drawDepth = -1000; //may not be needed public static Vector3 currentPos; public WhichMode recordPlayMode; private Vector3[] emotionPosArray = new Vector3[12]; //float yCalm = 0f; //float xCalm = 0f; //float yAng = 0f; //float xAng = 0f; //float ySad = 0f; //float xSad = 0f; //float yJoy = 0f; //float xJoy = 0f; //for video private Vector3[] curEmotionPosArray = new Vector3[9]; // private float rate = 0.0f; // private float it = 0.0f; private int counter; //used to test without classifier info from visual studio private float speed; //used to test without classifier info from visual studio // private bool check = false; void Start (){ transform.position = new Vector3(0.0f, 0.0f, 0.0f); //Iniatilze SpotOnGrid position currentPos = transform.position; speed = 10.0f; counter = 0; //Set x,y values for each emotion in emotionPosArray emotionPosArray[6] = new Vector3(35.0f, 6.0f, 0.0f); emotionPosArray[4] = new Vector3(22.0f, 14.0f, 0.0f); emotionPosArray[5] = new Vector3(5.0f, 19.0f, 0.0f); emotionPosArray[7] = new Vector3(-15.0f, 19.0f, 0.0f); emotionPosArray[11] = new Vector3(-35.0f, 14.0f, 0.0f); emotionPosArray[0] = new Vector3(-45.0f, 6.0f, 0.0f); emotionPosArray[10] = new Vector3(-45.0f, -2.0f, 0.0f); emotionPosArray[3] = new Vector3(-37.0f, -9.5f, 0.0f); emotionPosArray[1] = new Vector3(-15.0f, -15.0f, 0.0f); emotionPosArray[2] = new Vector3(5.0f, -15.0f, 0.0f); emotionPosArray[9] = new Vector3(20.0f, -9.5f, 0.0f); emotionPosArray[8] = new Vector3(35.0f, -2.0f, 0.0f); //used when testing without classifier info from visual studio curEmotionPosArray[0] = new Vector3(20.0f, 5.0f, 0.0f); curEmotionPosArray[1] = new Vector3(-20.0f, -6.0f, 0.0f); } //NOT USED ANYMORE //public void SetColor(Color p_color, bool saveColorCheck){ // //GetComponent<ParticleSystem>().startColor = p_color; // if (saveColorCheck == true && WhichMode.currentMode == "Record") // { // // Debug.Log("inside set color record mode"); // // spotLight.color = p_color; // //StoreTrainingInfo(p_color, currentPos); // // recordPlayMode.StoreOrbInfo(currentPos, spotLight.color, saveColorCheck); // // Debug.Log("Set Color in particle main " + spotLight.color); // saveColorCheck = false; // } // if (saveColorCheck == true && WhichMode.currentMode == "Play") // { // // Debug.Log("inside set color play mode"); // //RetreiveOrbInfo(); // //spotLight.color = recordPlayMode.currentColor; // //saveColorCheck = false; // } // } void Update() { // transform.position = WhichMode.currentPosition; //Uncomment for live classifier info from SweEic project. //Only for testing. The position of SpotOnGrid should be determined by classifier. //Use for debugging if (counter <= 1) { transform.position = Vector3.MoveTowards(transform.position, curEmotionPosArray[counter], Time.deltaTime * speed); WhichMode.currentPosition = transform.position; if (transform.position == curEmotionPosArray[counter]) { counter = (counter + 1) % 2; } } //Not needed anymore if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); bool rayhit = Physics.Raycast(ray, out hit); if (hit.collider != null) { if (hit.collider.name == "SpotOnGrid")//"FlareCore-Autumn") { // Debug.Log("In here"); changeSceneOnPSClick = true; } } } //if (Input.GetMouseButtonDown(1)) //{ // RaycastHit hit; // Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // bool rayhit = Physics.Raycast(ray, out hit); // if (hit.collider != null) // { // if (hit.collider.name == "SpotOnGrid") // { // // Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition)); // float x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x; // float y = Camera.main.ScreenToWorldPoint(Input.mousePosition).y; // GameObject.Find("SpotOnGrid").transform.position = new Vector3(x,y); // } // } //} } //Update position of Glowing Orb based on sensor data from OSCListener public void particlePosition(float xAxis, float yAxis) { float newXAxis = (((xAxis + 1.0f) / 2.0f) * 100) - 50; float newYAxis = (((yAxis + 1.0f) / 2.0f) * 38) - 19; currentPos = new Vector3 (newXAxis, newYAxis, 0.0f); transform.position = currentPos; WhichMode.currentPosition = currentPos; } //Not currently in use - May not be needed private void moveParticleSystem() { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Physics.Raycast(ray, out hit); if (hit.collider != null) { if (hit.collider.tag == "particleSystem") { moveParticleSystemCheck = true; } } } //Method to load Particle or Fluid scene in Play mode based on the choice made in Record mode public void LoadPlayScene() { TextReader read; read = new StreamReader(WhichMode.userFullPath + "/EmotionInfo.txt"); String currentLine = read.ReadLine(); read.Close(); //The first line in EmotionInfo.txt is the effect Particle or Fluid chosen in Record mode. if (currentLine != null) { WhichMode.currentEffect = currentLine; } if (WhichMode.currentMode == "Play") { if (WhichMode.currentEffect == "Fluid") { // Debug.Log(currentPos); SceneManager.LoadScene(1); recordPlayMode.GetFluidInfo(currentPos, emotionPosArray); } else if (WhichMode.currentEffect == "Particle") { Debug.Log(WhichMode.currentEffect); recordPlayMode.GetParticleInfo(currentPos, "Play", emotionPosArray); SceneManager.LoadScene(2); } } if (WhichMode.currentMode == "Record") { //recordPlayMode.getPosForChoice(currentPos); SceneManager.LoadScene(0); } } //ALL THIS WAS BEFORE USING RIGID BODY VELOCITY // public float fRotationSpeed, fTranslationSpeed; // private float fRotationStartTime, fTranslationStartTime; // private Vector3 oRotation, oTranslation; // // private float fRotationChangeDelay, fTranslationChangeDelay; // // // Use this for initialization // void Start () { // // fRotationStartTime = Time.time; // fTranslationStartTime = Time.time; // // fRotationChangeDelay = Random.Range (2.0f, 8.0f); // fTranslationChangeDelay = Random.Range (2.0f, 8.0f); // // oRotation = Random.insideUnitSphere * fRotationSpeed; // // //that would be for a 3d translation, but now only using x and z // //oTranslation = Random.insideUnitSphere * fTranslationSpeed; // oTranslation = new Vector3 (Random.Range (.0f, 8.0f), .0f, Random.Range (.0f, 8.0f)); // // } // // // FixedUpdate is called before each physics step // void FixedUpdate () { // // if (Time.time > fRotationChangeDelay * fRotationStartTime) { // oRotation = Random.insideUnitSphere * fRotationSpeed; // fRotationStartTime = Time.time; // } // // if (Time.time > fTranslationChangeDelay * fTranslationStartTime) { // //this would be for 3d translation // //oTranslation = Random.insideUnitSphere * fTranslationSpeed; // oTranslation = new Vector3 (Random.Range (.0f, 8.0f), .0f, Random.Range (.0f, 8.0f)); // fTranslationStartTime = Time.time; // } // // transform.Rotate (oRotation * Time.deltaTime); // transform.Translate (oTranslation * Time.deltaTime); // } //void OnGUI() //{ // if (switchScene == true) // { // alpha += fadeDir * fadeSpeed * Time.deltaTime; // alpha = Mathf.Clamp01(alpha); // GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, alpha); // GUI.depth = drawDepth; // GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeTexture); // // Application.LoadLevel(1); // SceneManager.LoadScene(1); // } //} }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security; abstract class ServerReliableChannelBinder<TChannel> : ReliableChannelBinder<TChannel>, IServerReliableChannelBinder where TChannel : class, IChannel { static string addressedPropertyName = "MessageAddressedByBinderProperty"; IChannelListener<TChannel> listener; static AsyncCallback onAcceptChannelComplete = Fx.ThunkCallback(new AsyncCallback(OnAcceptChannelCompleteStatic)); EndpointAddress cachedLocalAddress; TChannel pendingChannel; InterruptibleWaitObject pendingChannelEvent = new InterruptibleWaitObject(false, false); EndpointAddress remoteAddress; protected ServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(null, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { this.listener = builder.BuildChannelListener<TChannel>(filter, priority); this.remoteAddress = remoteAddress; } protected ServerReliableChannelBinder(TChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { this.cachedLocalAddress = cachedLocalAddress; this.remoteAddress = remoteAddress; } protected override bool CanGetChannelForReceive { get { return true; } } public override EndpointAddress LocalAddress { get { if (this.cachedLocalAddress != null) { return this.cachedLocalAddress; } else { return this.GetInnerChannelLocalAddress(); } } } protected override bool MustCloseChannel { get { return this.MustOpenChannel || this.HasSession; } } protected override bool MustOpenChannel { get { return this.listener != null; } } public override EndpointAddress RemoteAddress { get { return this.remoteAddress; } } void AddAddressedProperty(Message message) { message.Properties.Add(addressedPropertyName, new object()); } protected override void AddOutputHeaders(Message message) { if (this.GetAddressedProperty(message) == null) { this.RemoteAddress.ApplyTo(message); this.AddAddressedProperty(message); } } public bool AddressResponse(Message request, Message response) { if (this.GetAddressedProperty(response) != null) { throw Fx.AssertAndThrow("The binder can't address a response twice"); } try { RequestReplyCorrelator.PrepareReply(response, request); } catch (MessageHeaderException exception) { // ---- it - we don't need to correlate the reply if the MessageId header is bad if (DiagnosticUtility.ShouldTraceInformation) DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } bool sendResponse = true; try { sendResponse = RequestReplyCorrelator.AddressReply(response, request); } catch (MessageHeaderException exception) { // ---- it - we don't need to address the reply if the addressing headers are bad if (DiagnosticUtility.ShouldTraceInformation) DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } if (sendResponse) this.AddAddressedProperty(response); return sendResponse; } protected override IAsyncResult BeginTryGetChannel(TimeSpan timeout, AsyncCallback callback, object state) { return this.pendingChannelEvent.BeginTryWait(timeout, callback, state); } public IAsyncResult BeginWaitForRequest(TimeSpan timeout, AsyncCallback callback, object state) { if (this.DefaultMaskingMode != MaskingMode.None) { throw Fx.AssertAndThrow("This method was implemented only for the case where we do not mask exceptions."); } if (this.ValidateInputOperation(timeout)) { return new WaitForRequestAsyncResult(this, timeout, callback, state); } else { return new CompletedAsyncResult(callback, state); } } bool CompleteAcceptChannel(IAsyncResult result) { TChannel channel = this.listener.EndAcceptChannel(result); if (channel == null) { return false; } if (!this.UseNewChannel(channel)) { channel.Abort(); } return true; } public static IServerReliableChannelBinder CreateBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) { Type type = typeof(TChannel); if (type == typeof(IDuplexChannel)) { return new DuplexServerReliableChannelBinder(builder, remoteAddress, filter, priority, MaskingMode.None, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IDuplexSessionChannel)) { return new DuplexSessionServerReliableChannelBinder(builder, remoteAddress, filter, priority, MaskingMode.None, faultMode, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IReplyChannel)) { return new ReplyServerReliableChannelBinder(builder, remoteAddress, filter, priority, MaskingMode.None, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IReplySessionChannel)) { return new ReplySessionServerReliableChannelBinder(builder, remoteAddress, filter, priority, MaskingMode.None, faultMode, defaultCloseTimeout, defaultSendTimeout); } else { throw Fx.AssertAndThrow("ServerReliableChannelBinder supports creation of IDuplexChannel, IDuplexSessionChannel, IReplyChannel, and IReplySessionChannel only."); } } public static IServerReliableChannelBinder CreateBinder(TChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) { Type type = typeof(TChannel); if (type == typeof(IDuplexChannel)) { return new DuplexServerReliableChannelBinder((IDuplexChannel)channel, cachedLocalAddress, remoteAddress, MaskingMode.All, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IDuplexSessionChannel)) { return new DuplexSessionServerReliableChannelBinder((IDuplexSessionChannel)channel, cachedLocalAddress, remoteAddress, MaskingMode.All, faultMode, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IReplyChannel)) { return new ReplyServerReliableChannelBinder((IReplyChannel)channel, cachedLocalAddress, remoteAddress, MaskingMode.All, defaultCloseTimeout, defaultSendTimeout); } else if (type == typeof(IReplySessionChannel)) { return new ReplySessionServerReliableChannelBinder((IReplySessionChannel)channel, cachedLocalAddress, remoteAddress, MaskingMode.All, faultMode, defaultCloseTimeout, defaultSendTimeout); } else { throw Fx.AssertAndThrow("ServerReliableChannelBinder supports creation of IDuplexChannel, IDuplexSessionChannel, IReplyChannel, and IReplySessionChannel only."); } } protected override bool EndTryGetChannel(IAsyncResult result) { if (!this.pendingChannelEvent.EndTryWait(result)) return false; TChannel abortChannel = null; lock (this.ThisLock) { if (this.State != CommunicationState.Faulted && this.State != CommunicationState.Closing && this.State != CommunicationState.Closed) { if (!this.Synchronizer.SetChannel(this.pendingChannel)) { abortChannel = this.pendingChannel; } this.pendingChannel = null; this.pendingChannelEvent.Reset(); } } if (abortChannel != null) { abortChannel.Abort(); } return true; } public bool EndWaitForRequest(IAsyncResult result) { WaitForRequestAsyncResult waitForRequestResult = result as WaitForRequestAsyncResult; if (waitForRequestResult != null) { return waitForRequestResult.End(); } else { CompletedAsyncResult.End(result); return true; } } object GetAddressedProperty(Message message) { object property; message.Properties.TryGetValue(addressedPropertyName, out property); return property; } protected abstract EndpointAddress GetInnerChannelLocalAddress(); bool IsListenerExceptionNullOrHandleable(Exception e) { if (e == null) { return true; } if (this.listener.State == CommunicationState.Faulted) { return false; } return this.IsHandleable(e); } protected override void OnAbort() { if (this.listener != null) { this.listener.Abort(); } } void OnAcceptChannelComplete(IAsyncResult result) { Exception expectedException = null; Exception unexpectedException = null; bool gotChannel = false; try { gotChannel = this.CompleteAcceptChannel(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (this.IsHandleable(e)) { expectedException = e; } else { unexpectedException = e; } } if (gotChannel) { this.StartAccepting(); } else if (unexpectedException != null) { this.Fault(unexpectedException); } else if ((expectedException != null) && (this.listener.State == CommunicationState.Opened)) { this.StartAccepting(); } else if (this.listener.State == CommunicationState.Faulted) { this.Fault(expectedException); } } static void OnAcceptChannelCompleteStatic(IAsyncResult result) { if (!result.CompletedSynchronously) { ServerReliableChannelBinder<TChannel> binder = (ServerReliableChannelBinder<TChannel>)result.AsyncState; binder.OnAcceptChannelComplete(result); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { if (this.listener != null) { return this.listener.BeginClose(timeout, callback, state); } else { return new CompletedAsyncResult(callback, state); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { if (this.listener != null) { return this.listener.BeginOpen(timeout, callback, state); } else { return new CompletedAsyncResult(callback, state); } } protected abstract IAsyncResult OnBeginWaitForRequest(TChannel channel, TimeSpan timeout, AsyncCallback callback, object state); protected override void OnClose(TimeSpan timeout) { if (this.listener != null) { this.listener.Close(timeout); } } protected override void OnShutdown() { TChannel channel = null; lock (this.ThisLock) { channel = this.pendingChannel; this.pendingChannel = null; this.pendingChannelEvent.Set(); } if (channel != null) channel.Abort(); } protected abstract bool OnWaitForRequest(TChannel channel, TimeSpan timeout); protected override void OnEndClose(IAsyncResult result) { if (this.listener != null) { this.listener.EndClose(result); } else { CompletedAsyncResult.End(result); } } protected override void OnEndOpen(IAsyncResult result) { if (this.listener != null) { this.listener.EndOpen(result); this.StartAccepting(); } else { CompletedAsyncResult.End(result); } } protected abstract bool OnEndWaitForRequest(TChannel channel, IAsyncResult result); protected override void OnOpen(TimeSpan timeout) { if (this.listener != null) { this.listener.Open(timeout); this.StartAccepting(); } } void StartAccepting() { Exception expectedException = null; Exception unexpectedException = null; while (this.listener.State == CommunicationState.Opened) { expectedException = null; unexpectedException = null; try { IAsyncResult result = this.listener.BeginAcceptChannel(TimeSpan.MaxValue, onAcceptChannelComplete, this); if (!result.CompletedSynchronously) { return; } else if (!this.CompleteAcceptChannel(result)) { break; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (this.IsHandleable(e)) { expectedException = e; continue; } else { unexpectedException = e; break; } } } if (unexpectedException != null) { this.Fault(unexpectedException); } else if (this.listener.State == CommunicationState.Faulted) { this.Fault(expectedException); } } protected override bool TryGetChannel(TimeSpan timeout) { if (!this.pendingChannelEvent.Wait(timeout)) return false; TChannel abortChannel = null; lock (this.ThisLock) { if (this.State != CommunicationState.Faulted && this.State != CommunicationState.Closing && this.State != CommunicationState.Closed) { if (!this.Synchronizer.SetChannel(this.pendingChannel)) { abortChannel = this.pendingChannel; } this.pendingChannel = null; this.pendingChannelEvent.Reset(); } } if (abortChannel != null) { abortChannel.Abort(); } return true; } public bool UseNewChannel(IChannel channel) { TChannel oldPendingChannel = null; TChannel oldBinderChannel = null; lock (this.ThisLock) { if (!this.Synchronizer.TolerateFaults || this.State == CommunicationState.Faulted || this.State == CommunicationState.Closing || this.State == CommunicationState.Closed) { return false; } else { oldPendingChannel = this.pendingChannel; this.pendingChannel = (TChannel)channel; oldBinderChannel = this.Synchronizer.AbortCurentChannel(); } } if (oldPendingChannel != null) { oldPendingChannel.Abort(); } this.pendingChannelEvent.Set(); if (oldBinderChannel != null) { oldBinderChannel.Abort(); } return true; } public bool WaitForRequest(TimeSpan timeout) { if (this.DefaultMaskingMode != MaskingMode.None) { throw Fx.AssertAndThrow("This method was implemented only for the case where we do not mask exceptions."); } if (!this.ValidateInputOperation(timeout)) { return true; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); while (true) { bool autoAborted = false; try { TChannel channel; bool success = !this.Synchronizer.TryGetChannelForInput(true, timeoutHelper.RemainingTime(), out channel); if (channel == null) { return success; } try { return this.OnWaitForRequest(channel, timeoutHelper.RemainingTime()); } finally { autoAborted = this.Synchronizer.Aborting; this.Synchronizer.ReturnChannel(); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (!this.HandleException(e, this.DefaultMaskingMode, autoAborted)) { throw; } else { continue; } } } } abstract class DuplexServerReliableChannelBinder<TDuplexChannel> : ServerReliableChannelBinder<TDuplexChannel> where TDuplexChannel : class, IDuplexChannel { protected DuplexServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } protected DuplexServerReliableChannelBinder(TDuplexChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public override bool CanSendAsynchronously { get { return true; } } protected override EndpointAddress GetInnerChannelLocalAddress() { IDuplexChannel channel = this.Synchronizer.CurrentChannel; EndpointAddress localAddress = (channel == null) ? null : channel.LocalAddress; return localAddress; } protected override IAsyncResult OnBeginSend(TDuplexChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state) { return channel.BeginSend(message, timeout, callback, state); } protected override IAsyncResult OnBeginTryReceive(TDuplexChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return channel.BeginTryReceive(timeout, callback, state); } protected override IAsyncResult OnBeginWaitForRequest(TDuplexChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return channel.BeginWaitForMessage(timeout, callback, state); } protected override void OnEndSend(TDuplexChannel channel, IAsyncResult result) { channel.EndSend(result); } protected override bool OnEndTryReceive(TDuplexChannel channel, IAsyncResult result, out RequestContext requestContext) { Message message; bool success = channel.EndTryReceive(result, out message); if (success) { this.OnMessageReceived(message); } requestContext = this.WrapMessage(message); return success; } protected override bool OnEndWaitForRequest(TDuplexChannel channel, IAsyncResult result) { return channel.EndWaitForMessage(result); } protected abstract void OnMessageReceived(Message message); protected override void OnSend(TDuplexChannel channel, Message message, TimeSpan timeout) { channel.Send(message, timeout); } protected override bool OnTryReceive(TDuplexChannel channel, TimeSpan timeout, out RequestContext requestContext) { Message message; bool success = channel.TryReceive(timeout, out message); if (success) { this.OnMessageReceived(message); } requestContext = this.WrapMessage(message); return success; } protected override bool OnWaitForRequest(TDuplexChannel channel, TimeSpan timeout) { return channel.WaitForMessage(timeout); } } sealed class DuplexServerReliableChannelBinder : DuplexServerReliableChannelBinder<IDuplexChannel> { public DuplexServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, TolerateFaultsMode.Never, defaultCloseTimeout, defaultSendTimeout) { } public DuplexServerReliableChannelBinder(IDuplexChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, TolerateFaultsMode.Never, defaultCloseTimeout, defaultSendTimeout) { } public override bool HasSession { get { return false; } } public override ISession GetInnerSession() { return null; } protected override bool HasSecuritySession(IDuplexChannel channel) { return false; } protected override void OnMessageReceived(Message message) { } } sealed class DuplexSessionServerReliableChannelBinder : DuplexServerReliableChannelBinder<IDuplexSessionChannel> { public DuplexSessionServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public DuplexSessionServerReliableChannelBinder(IDuplexSessionChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public override bool HasSession { get { return true; } } protected override IAsyncResult BeginCloseChannel(IDuplexSessionChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return ReliableChannelBinderHelper.BeginCloseDuplexSessionChannel(this, channel, timeout, callback, state); } protected override void CloseChannel(IDuplexSessionChannel channel, TimeSpan timeout) { ReliableChannelBinderHelper.CloseDuplexSessionChannel(this, channel, timeout); } protected override void EndCloseChannel(IDuplexSessionChannel channel, IAsyncResult result) { ReliableChannelBinderHelper.EndCloseDuplexSessionChannel(channel, result); } public override ISession GetInnerSession() { return this.Synchronizer.CurrentChannel.Session; } protected override bool HasSecuritySession(IDuplexSessionChannel channel) { return channel.Session is ISecuritySession; } protected override void OnMessageReceived(Message message) { if (message == null) this.Synchronizer.OnReadEof(); } } abstract class ReplyServerReliableChannelBinder<TReplyChannel> : ServerReliableChannelBinder<TReplyChannel> where TReplyChannel : class, IReplyChannel { public ReplyServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public ReplyServerReliableChannelBinder(TReplyChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public override bool CanSendAsynchronously { get { return false; } } protected override EndpointAddress GetInnerChannelLocalAddress() { IReplyChannel channel = this.Synchronizer.CurrentChannel; EndpointAddress localAddress = (channel == null) ? null : channel.LocalAddress; return localAddress; } protected override IAsyncResult OnBeginTryReceive(TReplyChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return channel.BeginTryReceiveRequest(timeout, callback, state); } protected override IAsyncResult OnBeginWaitForRequest(TReplyChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return channel.BeginWaitForRequest(timeout, callback, state); } protected override bool OnEndTryReceive(TReplyChannel channel, IAsyncResult result, out RequestContext requestContext) { bool success = channel.EndTryReceiveRequest(result, out requestContext); if (success && (requestContext == null)) { this.OnReadNullMessage(); } requestContext = this.WrapRequestContext(requestContext); return success; } protected override bool OnEndWaitForRequest(TReplyChannel channel, IAsyncResult result) { return channel.EndWaitForRequest(result); } protected virtual void OnReadNullMessage() { } protected override bool OnTryReceive(TReplyChannel channel, TimeSpan timeout, out RequestContext requestContext) { bool success = channel.TryReceiveRequest(timeout, out requestContext); if (success && (requestContext == null)) { this.OnReadNullMessage(); } requestContext = this.WrapRequestContext(requestContext); return success; } protected override bool OnWaitForRequest(TReplyChannel channel, TimeSpan timeout) { return channel.WaitForRequest(timeout); } } sealed class ReplyServerReliableChannelBinder : ReplyServerReliableChannelBinder<IReplyChannel> { public ReplyServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, TolerateFaultsMode.Never, defaultCloseTimeout, defaultSendTimeout) { } public ReplyServerReliableChannelBinder(IReplyChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, TolerateFaultsMode.Never, defaultCloseTimeout, defaultSendTimeout) { } public override bool HasSession { get { return false; } } public override ISession GetInnerSession() { return null; } protected override bool HasSecuritySession(IReplyChannel channel) { return false; } } sealed class ReplySessionServerReliableChannelBinder : ReplyServerReliableChannelBinder<IReplySessionChannel> { public ReplySessionServerReliableChannelBinder(ChannelBuilder builder, EndpointAddress remoteAddress, MessageFilter filter, int priority, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(builder, remoteAddress, filter, priority, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public ReplySessionServerReliableChannelBinder(IReplySessionChannel channel, EndpointAddress cachedLocalAddress, EndpointAddress remoteAddress, MaskingMode maskingMode, TolerateFaultsMode faultMode, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) : base(channel, cachedLocalAddress, remoteAddress, maskingMode, faultMode, defaultCloseTimeout, defaultSendTimeout) { } public override bool HasSession { get { return true; } } protected override IAsyncResult BeginCloseChannel(IReplySessionChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return ReliableChannelBinderHelper.BeginCloseReplySessionChannel(this, channel, timeout, callback, state); } protected override void CloseChannel(IReplySessionChannel channel, TimeSpan timeout) { ReliableChannelBinderHelper.CloseReplySessionChannel(this, channel, timeout); } protected override void EndCloseChannel(IReplySessionChannel channel, IAsyncResult result) { ReliableChannelBinderHelper.EndCloseReplySessionChannel(channel, result); } public override ISession GetInnerSession() { return this.Synchronizer.CurrentChannel.Session; } protected override bool HasSecuritySession(IReplySessionChannel channel) { return channel.Session is ISecuritySession; } protected override void OnReadNullMessage() { this.Synchronizer.OnReadEof(); } } sealed class WaitForRequestAsyncResult : InputAsyncResult<ServerReliableChannelBinder<TChannel>> { public WaitForRequestAsyncResult(ServerReliableChannelBinder<TChannel> binder, TimeSpan timeout, AsyncCallback callback, object state) : base(binder, true, timeout, binder.DefaultMaskingMode, callback, state) { if (this.Start()) this.Complete(true); } protected override IAsyncResult BeginInput( ServerReliableChannelBinder<TChannel> binder, TChannel channel, TimeSpan timeout, AsyncCallback callback, object state) { return binder.OnBeginWaitForRequest(channel, timeout, callback, state); } protected override bool EndInput(ServerReliableChannelBinder<TChannel> binder, TChannel channel, IAsyncResult result, out bool complete) { complete = true; return binder.OnEndWaitForRequest(channel, result); } } } }
#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 Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.TestProtos; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Google.ProtocolBuffers { /// <summary> /// Tests for generated service classes. /// TODO(jonskeet): Convert the mocking tests using Rhino.Mocks. /// </summary> [TestClass] public class ServiceTest { private delegate void Action<T1, T2>(T1 t1, T2 t2); private static readonly MethodDescriptor FooDescriptor = TestGenericService.Descriptor.Methods[0]; private static readonly MethodDescriptor BarDescriptor = TestGenericService.Descriptor.Methods[1]; [TestMethod] public void GetRequestPrototype() { TestGenericService service = new TestServiceImpl(); Assert.AreSame(service.GetRequestPrototype(FooDescriptor), FooRequest.DefaultInstance); Assert.AreSame(service.GetRequestPrototype(BarDescriptor), BarRequest.DefaultInstance); } [TestMethod] public void GetResponsePrototype() { TestGenericService service = new TestServiceImpl(); Assert.AreSame(service.GetResponsePrototype(FooDescriptor), FooResponse.DefaultInstance); Assert.AreSame(service.GetResponsePrototype(BarDescriptor), BarResponse.DefaultInstance); } [TestMethod] public void CallMethodFoo() { FooRequest fooRequest = FooRequest.CreateBuilder().Build(); FooResponse fooResponse = FooResponse.CreateBuilder().Build(); IRpcController controller = new RpcTestController(); bool fooCalled = false; TestGenericService service = new TestServiceImpl((request, responseAction) => { Assert.AreSame(fooRequest, request); fooCalled = true; responseAction(fooResponse); }, null, controller); bool doneHandlerCalled = false; Action<IMessage> doneHandler = (response => { Assert.AreSame(fooResponse, response); doneHandlerCalled = true; }); service.CallMethod(FooDescriptor, controller, fooRequest, doneHandler); Assert.IsTrue(doneHandlerCalled); Assert.IsTrue(fooCalled); } [TestMethod] public void CallMethodBar() { BarRequest barRequest = BarRequest.CreateBuilder().Build(); BarResponse barResponse = BarResponse.CreateBuilder().Build(); IRpcController controller = new RpcTestController(); bool barCalled = false; TestGenericService service = new TestServiceImpl(null, (request, responseAction) => { Assert.AreSame(barRequest, request); barCalled = true; responseAction(barResponse); }, controller); bool doneHandlerCalled = false; Action<IMessage> doneHandler = (response => { Assert.AreSame(barResponse, response); doneHandlerCalled = true; }); service.CallMethod(BarDescriptor, controller, barRequest, doneHandler); Assert.IsTrue(doneHandlerCalled); Assert.IsTrue(barCalled); } [TestMethod] public void GeneratedStubFooCall() { IRpcChannel channel = new RpcTestChannel(); IRpcController controller = new RpcTestController(); TestGenericService service = TestGenericService.CreateStub(channel); FooResponse fooResponse = null; Action<FooResponse> doneHandler = r => fooResponse = r; service.Foo(controller, FooRequest.DefaultInstance, doneHandler); Assert.IsNotNull(fooResponse); Assert.IsFalse(controller.Failed); } [TestMethod] public void GeneratedStubBarCallFails() { IRpcChannel channel = new RpcTestChannel(); IRpcController controller = new RpcTestController(); TestGenericService service = TestGenericService.CreateStub(channel); BarResponse barResponse = null; Action<BarResponse> doneHandler = r => barResponse = r; service.Bar(controller, BarRequest.DefaultInstance, doneHandler); Assert.IsNull(barResponse); Assert.IsTrue(controller.Failed); } #region RpcTestController private class RpcTestController : IRpcController { public string TestFailedReason { get; set; } public bool TestCancelled { get; set; } public Action<object> TestCancelledCallback { get; set; } void IRpcController.Reset() { TestFailedReason = null; TestCancelled = false; TestCancelledCallback = null; } bool IRpcController.Failed { get { return TestFailedReason != null; } } string IRpcController.ErrorText { get { return TestFailedReason; } } void IRpcController.StartCancel() { TestCancelled = true; if (TestCancelledCallback != null) TestCancelledCallback(this); } void IRpcController.SetFailed(string reason) { TestFailedReason = reason; } bool IRpcController.IsCanceled() { return TestCancelled; } void IRpcController.NotifyOnCancel(Action<object> callback) { TestCancelledCallback = callback; } } #endregion #region RpcTestChannel private class RpcTestChannel : IRpcChannel { public MethodDescriptor TestMethodCalled { get; set; } void IRpcChannel.CallMethod(MethodDescriptor method, IRpcController controller, IMessage request, IMessage responsePrototype, Action<IMessage> done) { TestMethodCalled = method; try { done(FooResponse.DefaultInstance); } catch (Exception e) { controller.SetFailed(e.Message); } } } #endregion #region TestServiceImpl private class TestServiceImpl : TestGenericService { private readonly Action<FooRequest, Action<FooResponse>> fooHandler; private readonly Action<BarRequest, Action<BarResponse>> barHandler; private readonly IRpcController expectedController; internal TestServiceImpl() { } internal TestServiceImpl(Action<FooRequest, Action<FooResponse>> fooHandler, Action<BarRequest, Action<BarResponse>> barHandler, IRpcController expectedController) { this.fooHandler = fooHandler; this.barHandler = barHandler; this.expectedController = expectedController; } public override void Foo(IRpcController controller, FooRequest request, Action<FooResponse> done) { Assert.AreSame(expectedController, controller); fooHandler(request, done); } public override void Bar(IRpcController controller, BarRequest request, Action<BarResponse> done) { Assert.AreSame(expectedController, controller); barHandler(request, done); } } #endregion } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; namespace Orleans.Runtime { /// <summary> /// The Utils class contains a variety of utility methods for use in application and grain code. /// </summary> public static class Utils { /// <summary> /// Returns a human-readable text string that describes an IEnumerable collection of objects. /// </summary> /// <typeparam name="T">The type of the list elements.</typeparam> /// <param name="collection">The IEnumerable to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use.</param> /// <param name="putInBrackets">Puts elements within brackets</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// elements with square brackets and separating them with commas.</returns> public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null, string separator = ", ", bool putInBrackets = true) { if (collection == null) { if (putInBrackets) return "[]"; else return "null"; } var sb = new StringBuilder(); if (putInBrackets) sb.Append("["); var enumerator = collection.GetEnumerator(); bool firstDone = false; while (enumerator.MoveNext()) { T value = enumerator.Current; string val; if (toString != null) val = toString(value); else val = value == null ? "null" : value.ToString(); if (firstDone) { sb.Append(separator); sb.Append(val); } else { sb.Append(val); firstDone = true; } } if (putInBrackets) sb.Append("]"); return sb.ToString(); } /// <summary> /// Returns a human-readable text string that describes a dictionary that maps objects to objects. /// </summary> /// <typeparam name="T1">The type of the dictionary keys.</typeparam> /// <typeparam name="T2">The type of the dictionary elements.</typeparam> /// <param name="dict">The dictionary to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use. If none specified, the elements should appear separated by a new line.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// pairs with square brackets and separating them with commas. /// Each key-value pair is represented as the string description of the key followed by /// the string description of the value, /// separated by " -> ", and enclosed in curly brackets.</returns> public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null) { if (dict == null || dict.Count == 0) { return "[]"; } if (separator == null) { separator = Environment.NewLine; } var sb = new StringBuilder("["); var enumerator = dict.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { var pair = enumerator.Current; sb.Append("{"); sb.Append(pair.Key); sb.Append(" -> "); string val; if (toString != null) val = toString(pair.Value); else val = pair.Value == null ? "null" : pair.Value.ToString(); sb.Append(val); sb.Append("}"); if (index++ < dict.Count - 1) sb.Append(separator); } sb.Append("]"); return sb.ToString(); } public static string TimeSpanToString(TimeSpan timeSpan) { //00:03:32.8289777 return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } public static long TicksToMilliSeconds(long ticks) { return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds; } public static float AverageTicksToMilliSeconds(float ticks) { return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds; } /// <summary> /// Parse a Uri as an IPEndpoint. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port); } return null; } /// <summary> /// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static SiloAddress ToSiloAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0); } return null; } /// <summary> /// Parse a Uri as a Silo address, excluding the generation identifier. /// </summary> /// <param name="uri">The input Uri</param> public static SiloAddress ToGatewayAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), 0); } return null; } /// <summary> /// Represent an IP end point in the gateway URI format.. /// </summary> /// <param name="ep">The input IP end point</param> /// <returns></returns> public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) { var builder = new UriBuilder("gwy.tcp", ep.Address.ToString(), ep.Port, "0"); return builder.Uri; } /// <summary> /// Represent a silo address in the gateway URI format. /// </summary> /// <param name="address">The input silo address</param> /// <returns></returns> public static Uri ToGatewayUri(this SiloAddress address) { var builder = new UriBuilder("gwy.tcp", address.Endpoint.Address.ToString(), address.Endpoint.Port, address.Generation.ToString()); return builder.Uri; } /// <summary> /// Calculates an integer hash value based on the consistent identity hash of a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> public static int CalculateIdHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. int hash = 0; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i += 4) { int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]); hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } /// <summary> /// Calculates a Guid hash value based on the consistent identity a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> internal static Guid CalculateGuidHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. byte[] hash = new byte[16]; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i ++) { byte tmp = (byte)(hash[i % 16] ^ result[i]); hash[i%16] = tmp; } } finally { sha.Dispose(); } return new Guid(hash); } public static bool TryFindException(Exception original, Type targetType, out Exception target) { if (original.GetType() == targetType) { target = original; return true; } else if (original is AggregateException) { var baseEx = original.GetBaseException(); if (baseEx.GetType() == targetType) { target = baseEx; return true; } else { var newEx = ((AggregateException)original).Flatten(); foreach (var exc in newEx.InnerExceptions) { if (exc.GetType() == targetType) { target = newEx; return true; } } } } target = null; return false; } public static void SafeExecute(Action action, ILogger logger = null, string caller = null) { SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller); } // a function to safely execute an action without any exception being thrown. // callerGetter function is called only in faulty case (now string is generated in the success case). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void SafeExecute(Action action, ILogger logger, Func<string> callerGetter) { try { action(); } catch (Exception exc) { try { if (logger != null) { string caller = null; if (callerGetter != null) { try { caller = callerGetter(); }catch (Exception) { } } foreach (var e in exc.FlattenAggregate()) { logger.Warn(ErrorCode.Runtime_Error_100325, $"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc); } } } catch (Exception) { // now really, really ignore. } } } public static TimeSpan Since(DateTime start) { return DateTime.UtcNow.Subtract(start); } public static List<Exception> FlattenAggregate(this Exception exc) { var result = new List<Exception>(); if (exc is AggregateException) result.AddRange(exc.InnerException.FlattenAggregate()); else result.Add(exc); return result; } public static AggregateException Flatten(this ReflectionTypeLoadException rtle) { // if ReflectionTypeLoadException is thrown, we need to provide the // LoaderExceptions property in order to make it meaningful. var all = new List<Exception> { rtle }; all.AddRange(rtle.LoaderExceptions); throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenience.", all); } /// <summary> /// </summary> public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize) { var batch = new List<T>(batchSize); foreach (var item in sequence) { batch.Add(item); // when we've accumulated enough in the batch, send it out if (batch.Count >= batchSize) { yield return batch; // batch.ToArray(); batch = new List<T>(batchSize); } } if (batch.Count > 0) { yield return batch; //batch.ToArray(); } } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetStackTrace(int skipFrames = 0) { skipFrames += 1; //skip this method from the stack trace #if NETSTANDARD skipFrames += 2; //skip the 2 Environment.StackTrace related methods. var stackTrace = Environment.StackTrace; for (int i = 0; i < skipFrames; i++) { stackTrace = stackTrace.Substring(stackTrace.IndexOf(Environment.NewLine) + Environment.NewLine.Length); } return stackTrace; #else return new System.Diagnostics.StackTrace(skipFrames).ToString(); #endif } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Xml.Serialization; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// CharacterSymbol /// </summary> [Serializable] public class CharacterSymbol : Symbol, ICharacterSymbol { #region Fields private char _character; private Color _color; private string _fontFamilyName; private FontStyle _style; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CharacterSymbol"/> class. /// </summary> public CharacterSymbol() { _character = 'A'; _fontFamilyName = "DotSpatialSymbols"; // CGX // _color = Color.Green; _color = Color.Black; // CGX END _style = FontStyle.Regular; SymbolType = SymbolType.Character; } /// <summary> /// Initializes a new instance of the <see cref="CharacterSymbol"/> class. /// </summary> /// <param name="character">The character to use for the symbol</param> public CharacterSymbol(char character) { _character = character; _fontFamilyName = "DotSpatialSymbols"; _color = Color.Green; _style = FontStyle.Regular; SymbolType = SymbolType.Character; } /// <summary> /// Initializes a new instance of the <see cref="CharacterSymbol"/> class. /// </summary> /// <param name="character">The character to use for the symbol</param> /// <param name="fontFamily">The font family for the character</param> public CharacterSymbol(char character, string fontFamily) { _character = character; _fontFamilyName = fontFamily; _color = Color.Green; _style = FontStyle.Regular; SymbolType = SymbolType.Character; } /// <summary> /// Initializes a new instance of the <see cref="CharacterSymbol"/> class. /// </summary> /// <param name="character">The character to use for the symbol</param> /// <param name="fontFamily">The font family for the character</param> /// <param name="color">The color for the character</param> public CharacterSymbol(char character, string fontFamily, Color color) { _character = character; _fontFamilyName = fontFamily; _color = color; _style = FontStyle.Regular; SymbolType = SymbolType.Character; } /// <summary> /// Initializes a new instance of the <see cref="CharacterSymbol"/> class. /// </summary> /// <param name="character">The character to use for the symbol</param> /// <param name="fontFamily">The font family for the character</param> /// <param name="color">The color for the character</param> /// <param name="size">The size for the symbol</param> public CharacterSymbol(char character, string fontFamily, Color color, double size) { _character = character; _fontFamilyName = fontFamily; _color = color; _style = FontStyle.Regular; Size = new Size2D(size, size); SymbolType = SymbolType.Character; } #endregion #region Properties /// <summary> /// Gets the unicode category for this character. /// </summary> [XmlIgnore] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("Gets the unicode category for this character.")] public UnicodeCategory Category => char.GetUnicodeCategory(_character); /// <summary> /// Gets or sets the character that this represents. /// </summary> [Description("Gets or sets the character for this symbol.")] [Serialize("Character")] public char Character { get { return _character; } set { _character = value; } } /// <summary> /// Gets or sets the character set. Unicode characters consist of 2 bytes. This represents the first byte, /// which can be thought of as specifying a typeset. /// </summary> [XmlIgnore] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("Gets or sets the upper unicode byte, or character set.")] public byte CharacterSet { get { return (byte)(_character / 256); } set { int remainder = _character % 256; _character = (char)(remainder + (value * 256)); } } /// <summary> /// Gets or sets the byte code for the lower 256 values. This represents the /// specific character in a given "typeset" range. /// </summary> /// <remarks> /// // Editor(typeof(CharacterCodeEditor), typeof(UITypeEditor)) /// </remarks> [XmlIgnore] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("Gets or sets the lower unicode byte or character ASCII code")] public byte Code { get { return (byte)(_character % 256); } set { int set = _character / 256; _character = (char)((set * 256) + value); } } /// <summary> /// Gets or sets the color /// </summary> [XmlIgnore] [Description("Gets or sets the color")] public Color Color { get { return _color; } set { _color = value; } } /// <summary> /// Gets or sets the string font family name to use for this character set. /// </summary> /// <remarks> /// // Editor(typeof(FontFamilyNameEditor), typeof(UITypeEditor)), /// </remarks> [Description("Gets or sets the font family name to use when building the font.")] [Serialize("FontFamilyName")] public string FontFamilyName { get { return _fontFamilyName; } set { _fontFamilyName = value; } } /// <summary> /// Gets or sets the opacity as a floating point value ranging from 0 to 1, where /// 0 is fully transparent and 1 is fully opaque. This actually adjusts the alpha of the color value. /// </summary> [Description("Gets or sets the opacity as a floating point value ranging from 0 (transparent) to 1 (opaque)")] [Serialize("Opacity")] public float Opacity { get { return _color.A / 255F; } set { int alpha = (int)(value * 255); if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; if (alpha != _color.A) { _color = Color.FromArgb(alpha, _color); } } } /// <summary> /// Gets or sets the font style to use for this character layer. /// </summary> [Description("Gets or sets the font style to use for this character layer.")] [Serialize("FontStyle")] public FontStyle Style { get { return _style; } set { _style = value; } } /// <summary> /// Gets or sets the xml color. This supports serialization even though Colors can't be serialized. /// </summary> [XmlElement("Color")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Serialize("XmlColor")] public string XmlColor { get { return ColorTranslator.ToHtml(_color); } set { _color = ColorTranslator.FromHtml(value); } } #endregion #region Methods /// <summary> /// Gets the font color of this symbol to represent the color of this symbol /// </summary> /// <returns>The color of this symbol as a font</returns> public override Color GetColor() { return _color; } /// <summary> /// Because there is no easy range calculation supported in dot net (as compared to GDI32) that I can find, I assume that the /// unsupported values will come back as an open box, or at least identical in glyph form to a known unsupported like Arial 1024. /// (Not to be confused with Arial Unicode MS, which has basically everything.) /// </summary> /// <returns>A list of supported character subsets.</returns> public IList<CharacterSubset> GetSupportedSubsets() { List<CharacterSubset> result = new List<CharacterSubset>(); PointF topLeft = new PointF(0F, 0F); Font arialFont = new Font("Arial", 10F, FontStyle.Regular, GraphicsUnit.Pixel); Font testFont = new Font(_fontFamilyName, 10F, FontStyle.Regular, GraphicsUnit.Pixel); // ensure it will fit on bitmap Bitmap empty = new Bitmap(20, 20); Graphics g = Graphics.FromImage(empty); g.DrawString(((char)1024).ToString(), arialFont, Brushes.Black, topLeft); g.Dispose(); BitmapGrid emptyGrid = new BitmapGrid(empty); Array subsets = Enum.GetValues(typeof(CharacterSubset)); foreach (CharacterSubset code in subsets) { char c = (char)code; // first character of each subset Bitmap firstChar = new Bitmap(20, 20); Graphics tg = Graphics.FromImage(firstChar); tg.DrawString(c.ToString(), testFont, Brushes.Black, topLeft); tg.Dispose(); // Bitmap grids allow a byte by byte comparison between values BitmapGrid firstCharGrid = new BitmapGrid(firstChar); if (emptyGrid.Matches(firstCharGrid) == false) { // Since this symbol is different from the default unsuported symbol result.Add(code); } firstCharGrid.Dispose(); } return result; } /// <summary> /// Modifies this symbol in a way that is appropriate for indicating a selected symbol. /// This could mean drawing a cyan outline, or changing the color to cyan. /// </summary> public override void Select() { _color = Color.Cyan; } /// <summary> /// Sets the fill color of this symbol to the specified color /// </summary> /// <param name="color">The Color</param> public override void SetColor(Color color) { _color = color; } /// <summary> /// Gets the string equivalent of the specified character code. /// </summary> /// <returns>A string version of the character</returns> public override string ToString() { return _character.ToString(); } /// <summary> /// Overrides the default behavior and attempts to draw the specified symbol. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="scaleSize">If this should draw in pixels, this should be 1. Otherwise, this should be /// the constant that you multiply against so that drawing using geographic units will draw in pixel units.</param> protected override void OnDraw(Graphics g, double scaleSize) { // base.OnDraw(g, scaleSize); // handle rotation etc. Brush b = new SolidBrush(_color); string txt = new string(new[] { _character }); float fontPointSize = (float)(Size.Height * scaleSize); Font fnt = new Font(_fontFamilyName, fontPointSize, _style, GraphicsUnit.Pixel); SizeF fSize = g.MeasureString(txt, fnt); float x = -fSize.Width / 2; float y = -fSize.Height / 2; if (fSize.Height > fSize.Width * 5) { // Defective fonts sometimes are created with a bad height. // Use the width instead y = -fSize.Width / 2; } g.DrawString(txt, fnt, b, new PointF(x, y)); b.Dispose(); } /// <summary> /// Extends the randomize code to include the character aspects, creating a random character. /// However, since most fonts don't support full unicode values, a character from 0 to 255 is /// chosen. /// </summary> /// <param name="generator">The random class generator</param> protected override void OnRandomize(Random generator) { _color = generator.NextColor(); Opacity = generator.NextFloat(); _character = (char)generator.Next(0, 255); _fontFamilyName = FontFamily.Families[generator.Next(0, FontFamily.Families.Length - 1)].Name; _style = generator.NextEnum<FontStyle>(); base.OnRandomize(generator); } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); //--// class PrepareForRegisterAllocation { // // State // ArmPlatform m_owner; // // Constructor Methods // internal PrepareForRegisterAllocation( ArmPlatform owner ) { m_owner = owner; } // // Helper Methods // //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.LoadIndirectOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.StoreIndirectOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SetIfConditionIsTrueOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConditionalCompareOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AddressAssignmentOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractUnaryOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConversionOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.MultiWayConditionalControlOperator) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveToCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveFromCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.SetStatusRegisterOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.LoadIndirectOperatorWithIndexUpdate ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.StoreIndirectOperatorWithIndexUpdate ) )] private void Handle_GenericOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = nc.CurrentOperator; var cfg = nc.CurrentCFG; if(ConvertToPseudoRegister( cfg, op )) { nc.MarkAsModified(); return; } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SingleAssignmentOperator) )] private void Handle_AssignmentOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ZeligIR.SingleAssignmentOperator)nc.CurrentOperator; var lhs = op.FirstResult; var rhs = op.FirstArgument; var ts = nc.TypeSystem; if(ts.GetLevel( lhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { if(rhs is ZeligIR.ConstantExpression || ts.GetLevel( rhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { // // Constant to stack or stack to stack is not allowed. // if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } } } var lhsRegDesc = ZeligIR.Abstractions.RegisterDescriptor.ExtractFromExpression( lhs ); if(lhsRegDesc != null && lhsRegDesc.IsSystemRegister) { if(rhs is ZeligIR.ConstantExpression || ts.GetLevel( rhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { // // Constant or stack to system register is not allowed. // MoveToPseudoRegister( nc.CurrentCFG, op, rhs ); nc.MarkAsModified(); return; } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.CompareOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.BitTestOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConditionalCompareOperator) )] private void Handle_GenericDataProcessingOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = nc.CurrentOperator; if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } foreach(ZeligIR.Expression ex in op.Arguments) { ZeligIR.ConstantExpression exConst = ex as ZeligIR.ConstantExpression; if(exConst != null) { if(CanBeUsedAsAnImmediateValue( nc, exConst ) == false) { MoveToPseudoRegister( nc.CurrentCFG, op, exConst ); nc.MarkAsModified(); break; } } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractBinaryOperator) )] private void Handle_AbstractBinaryOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ZeligIR.AbstractBinaryOperator)nc.CurrentOperator; if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } foreach(ZeligIR.Expression ex in op.Arguments) { ZeligIR.ConstantExpression exConst = ex as ZeligIR.ConstantExpression; if(exConst != null) { bool fOk = CanBeUsedAsAnImmediateValue( nc, exConst ); if(fOk) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.MUL: // // Multiplication operands should be in registers. // fOk = false; break; case ZeligIR.BinaryOperator.ALU.SHL: case ZeligIR.BinaryOperator.ALU.SHR: // // Left operand should be in a register. // if(exConst == op.FirstArgument) { fOk = false; } break; } } if(fOk == false) { MoveToPseudoRegister( nc.CurrentCFG, op, exConst ); nc.MarkAsModified(); break; } } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.BinaryOperatorWithShift) )] private void Handle_ARM_BinaryOperatorWithShift( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ARM.BinaryOperatorWithShift)nc.CurrentOperator; var cfg = nc.CurrentCFG; if(ConvertToPseudoRegister( cfg, op )) { nc.MarkAsModified(); return; } if(MoveToPseudoRegisterIfConstant( cfg, op, op.FirstArgument )) { nc.MarkAsModified(); return; } if(MoveToPseudoRegisterIfConstant( cfg, op, op.SecondArgument )) { nc.MarkAsModified(); return; } } //--// private bool CanBeUsedAsAnImmediateValue( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , ZeligIR.ConstantExpression exConst ) { ZeligIR.Operator op = nc.CurrentOperator; if(m_owner.HasVFPv2) { if(exConst.IsValueFloatingPoint) { if(exConst.IsEqualToZero() && op is ZeligIR.CompareOperator) { return true; } return false; } } if(exConst.IsEqualToZero()) { return true; } if(exConst.IsValueInteger || exConst.IsValueFloatingPoint ) { ulong val; if(exConst.GetAsRawUlong( out val )) { uint valSeed; uint valRot; if(s_Encoding.check_DataProcessing_ImmediateValue( (uint)val, out valSeed, out valRot ) == true) { return true; } if(s_Encoding.check_DataProcessing_ImmediateValue( ~(uint)val, out valSeed, out valRot ) == true) { var opBin = op as ZeligIR.BinaryOperator; if(opBin != null) { if(opBin.Alu == ZeligIR.AbstractBinaryOperator.ALU.AND) { return true; // This can be represented as a BIC. } } } } } return false; } } public static bool ConvertToPseudoRegister( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Operator op ) { ZeligIR.PseudoRegisterExpression var; bool fModified = false; for(int i = op.Results.Length; --i >= 0; ) { var lhs = op.Results[i]; // Make sure we get the latest Lhs, it might have changed as part of the conversion. var = AllocatePseudoRegisterIfNeeded( cfg, lhs ); if(var != null) { op.AddOperatorAfter( ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, var ) ); op.SubstituteDefinition( lhs, var ); fModified = true; } } if(op is ZeligIR.AddressAssignmentOperator) { // Rvalue must be in stack locations. } else { for(int i = op.Arguments.Length; --i >= 0; ) { var ex = op.Arguments[i]; // Make sure we get the latest Rhs, it might have changed as part of the conversion. bool fConstantOk = true; if(op is ZeligIR.LoadIndirectOperator || op is ARM.LoadIndirectOperatorWithIndexUpdate ) { if(i == 0) // Destination value cannot be a constant. { fConstantOk = false; // // If the pointer is an object allocated at compile-time, // we can leave it alone, it will be removed later, see EmitCode_LoadIndirectOperator. // var constEx = ex as ZeligIR.ConstantExpression; if(constEx != null) { var dd = constEx.Value as ZeligIR.DataManager.DataDescriptor; if(dd != null) { if(dd.CanPropagate) { fConstantOk = true; } } } } } else if(op is ZeligIR.StoreIndirectOperator || op is ARM.StoreIndirectOperatorWithIndexUpdate ) { if(i == 0) // Destination value cannot be a constant. { fConstantOk = false; } if(i == 1) // Source value cannot be a constant. { fConstantOk = false; } } else if(op is ZeligIR.ZeroExtendOperator || op is ZeligIR.SignExtendOperator || op is ZeligIR.TruncateOperator ) { fConstantOk = false; } var = AllocatePseudoRegisterIfNeeded( cfg, ex, fConstantOk ); if(var != null) { op.AddOperatorBefore( ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, var, ex ) ); op.SubstituteUsage( ex, var ); fModified = true; } } } return fModified; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Braintree.Exceptions; namespace Braintree.Tests { //[Ignore("Need fixing")] //TODO: fix unit test [TestFixture(Category = "NeedFix")] //TODO: fix unit test public class MerchantAccountTest { private BraintreeGateway gateway; [SetUp] public void Setup() { gateway = new BraintreeGateway { //Environment = Environment.DEVELOPMENT, //MerchantId = "integration_merchant_id", //PublicKey = "integration_public_key", //PrivateKey = "integration_private_key" }; } [Test] public void Create_DeprecatedWithoutId() { var request = deprecatedCreateRequest(null); Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); MerchantAccount merchantAccount = result.Target; Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status); Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id); Assert.IsTrue(merchantAccount.IsSubMerchant); Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant); Assert.IsTrue(merchantAccount.Id != null); } [Test] public void Create_DeprecatedWithId() { Random random = new Random(); int randomNumber = random.Next(0, 10000); var subMerchantAccountId = "sub_merchant_account_id_" + randomNumber; var request = deprecatedCreateRequest(subMerchantAccountId); Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); MerchantAccount merchantAccount = result.Target; Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status); Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id); Assert.IsTrue(merchantAccount.IsSubMerchant); Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant); Assert.AreEqual(subMerchantAccountId, merchantAccount.Id); } [Test] public void Create_HandlesUnsuccessfulResults() { Result<MerchantAccount> result = gateway.MerchantAccount.Create(new MerchantAccountRequest()); Assert.IsFalse(result.IsSuccess()); List<ValidationError> errors = result.Errors.ForObject("merchant-account").OnField("master-merchant-account-id"); Assert.AreEqual(1, errors.Count); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED, errors[0].Code); } [Test] public void Create_WithoutId() { var request = createRequest(null); Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); MerchantAccount merchantAccount = result.Target; Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status); Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id); Assert.IsTrue(merchantAccount.IsSubMerchant); Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant); Assert.IsTrue(merchantAccount.Id != null); } [Test] public void Create_WithId() { Random random = new Random(); int randomNumber = random.Next(0, 10000); var subMerchantAccountId = "sub_merchant_account_id_" + randomNumber; var request = createRequest(subMerchantAccountId); Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); MerchantAccount merchantAccount = result.Target; Assert.AreEqual(MerchantAccountStatus.PENDING, merchantAccount.Status); Assert.AreEqual("sandbox_master_merchant_account", merchantAccount.MasterMerchantAccount.Id); Assert.IsTrue(merchantAccount.IsSubMerchant); Assert.IsFalse(merchantAccount.MasterMerchantAccount.IsSubMerchant); Assert.AreEqual(subMerchantAccountId, merchantAccount.Id); } [Test] public void Create_AcceptsBankFundingDestination() { var request = createRequest(null); request.Funding.Destination = FundingDestination.BANK; Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void Create_AcceptsMobilePhoneFundingDestination() { var request = createRequest(null); request.Funding.Destination = FundingDestination.MOBILE_PHONE; Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void Create_AcceptsEmailFundingDestination() { var request = createRequest(null); request.Funding.Destination = FundingDestination.EMAIL; Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void Update_UpdatesAllFields() { var request = deprecatedCreateRequest(null); Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsTrue(result.IsSuccess()); var updateRequest = createRequest(null); updateRequest.TosAccepted = null; updateRequest.MasterMerchantAccountId = null; Result<MerchantAccount> updateResult = gateway.MerchantAccount.Update(result.Target.Id, updateRequest); Assert.IsTrue(updateResult.IsSuccess()); MerchantAccount merchantAccount = updateResult.Target; Assert.AreEqual("Job", merchantAccount.IndividualDetails.FirstName); Assert.AreEqual("Leoggs", merchantAccount.IndividualDetails.LastName); Assert.AreEqual("[email protected]", merchantAccount.IndividualDetails.Email); Assert.AreEqual("5555551212", merchantAccount.IndividualDetails.Phone); Assert.AreEqual("1235", merchantAccount.IndividualDetails.SsnLastFour); Assert.AreEqual("193 Credibility St.", merchantAccount.IndividualDetails.Address.StreetAddress); Assert.AreEqual("60611", merchantAccount.IndividualDetails.Address.PostalCode); Assert.AreEqual("Avondale", merchantAccount.IndividualDetails.Address.Locality); Assert.AreEqual("IN", merchantAccount.IndividualDetails.Address.Region); Assert.AreEqual("1985-09-10", merchantAccount.IndividualDetails.DateOfBirth); Assert.AreEqual("coaterie.com", merchantAccount.BusinessDetails.LegalName); Assert.AreEqual("Coaterie", merchantAccount.BusinessDetails.DbaName); Assert.AreEqual("123456780", merchantAccount.BusinessDetails.TaxId); Assert.AreEqual("135 Credibility St.", merchantAccount.BusinessDetails.Address.StreetAddress); Assert.AreEqual("60602", merchantAccount.BusinessDetails.Address.PostalCode); Assert.AreEqual("Gary", merchantAccount.BusinessDetails.Address.Locality); Assert.AreEqual("OH", merchantAccount.BusinessDetails.Address.Region); Assert.AreEqual(FundingDestination.EMAIL, merchantAccount.FundingDetails.Destination); Assert.AreEqual("[email protected]", merchantAccount.FundingDetails.Email); Assert.AreEqual("3125551212", merchantAccount.FundingDetails.MobilePhone); Assert.AreEqual("122100024", merchantAccount.FundingDetails.RoutingNumber); Assert.AreEqual("8798", merchantAccount.FundingDetails.AccountNumberLast4); Assert.AreEqual("Job Leoggs OH", merchantAccount.FundingDetails.Descriptor); } [Test] public void Create_HandlesRequiredValidationErrors() { var request = new MerchantAccountRequest { TosAccepted = true, MasterMerchantAccountId = "sandbox_master_merchant_account" }; Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsFalse(result.IsSuccess()); ValidationErrors errors = result.Errors.ForObject("merchant-account"); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED, errors.ForObject("individual").OnField("first-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED, errors.ForObject("individual").OnField("last-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED, errors.ForObject("individual").OnField("date-of-birth")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED, errors.ForObject("individual").OnField("email")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED, errors.ForObject("individual").ForObject("address").OnField("street-address")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED, errors.ForObject("individual").ForObject("address").OnField("locality")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED, errors.ForObject("individual").ForObject("address").OnField("postal-code")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED, errors.ForObject("individual").ForObject("address").OnField("region")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED, errors.ForObject("funding").OnField("destination")[0].Code); } [Test] public void Create_HandlesInvalidValidationErrors() { var request = new MerchantAccountRequest { Individual = new IndividualRequest { FirstName = "<>", LastName = "<>", Email = "bad", Phone = "999", Address = new AddressRequest { StreetAddress = "nope", PostalCode = "1", Region = "QQ", }, DateOfBirth = "hah", Ssn = "12345", }, Business = new BusinessRequest { LegalName = "``{}", DbaName = "{}``", TaxId = "bad", Address = new AddressRequest { StreetAddress = "nope", PostalCode = "1", Region = "QQ", }, }, Funding = new FundingRequest { Destination = FundingDestination.UNRECOGNIZED, Email = "BILLFOLD", MobilePhone = "TRIFOLD", RoutingNumber = "LEATHER", AccountNumber = "BACK POCKET", }, TosAccepted = true, MasterMerchantAccountId = "sandbox_master_merchant_account" }; Result<MerchantAccount> result = gateway.MerchantAccount.Create(request); Assert.IsFalse(result.IsSuccess()); ValidationErrors errors = result.Errors.ForObject("merchant-account"); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID, errors.ForObject("individual").OnField("first-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID, errors.ForObject("individual").OnField("last-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID, errors.ForObject("individual").OnField("date-of-birth")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID, errors.ForObject("individual").OnField("phone")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID, errors.ForObject("individual").OnField("ssn")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID, errors.ForObject("individual").OnField("email")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID, errors.ForObject("individual").ForObject("address").OnField("street-address")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID, errors.ForObject("individual").ForObject("address").OnField("postal-code")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID, errors.ForObject("individual").ForObject("address").OnField("region")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID, errors.ForObject("business").OnField("dba-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID, errors.ForObject("business").OnField("legal-name")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID, errors.ForObject("business").OnField("tax-id")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID, errors.ForObject("business").ForObject("address").OnField("street-address")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID, errors.ForObject("business").ForObject("address").OnField("postal-code")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID, errors.ForObject("business").ForObject("address").OnField("region")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID, errors.ForObject("funding").OnField("destination")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID, errors.ForObject("funding").OnField("account-number")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID, errors.ForObject("funding").OnField("routing-number")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID, errors.ForObject("funding").OnField("email")[0].Code); Assert.AreEqual(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID, errors.ForObject("funding").OnField("mobile-phone")[0].Code); } [Test] public void Find() { MerchantAccount merchantAccount = gateway.MerchantAccount.Create(createRequest(null)).Target; MerchantAccount foundMerchantAccount = gateway.MerchantAccount.Find(merchantAccount.Id); Assert.AreEqual(merchantAccount.Id, foundMerchantAccount.Id); } [Test] public void Find_FindsErrorsOutOnWhitespaceIds() { try { gateway.MerchantAccount.Find(" "); Assert.Fail("Should throw NotFoundException"); } catch (NotFoundException) {} } private MerchantAccountRequest deprecatedCreateRequest(string id) { return new MerchantAccountRequest { ApplicantDetails = new ApplicantDetailsRequest { CompanyName = "coattree.com", FirstName = "Joe", LastName = "Bloggs", Email = "[email protected]", Phone = "555-555-5555", Address = new AddressRequest { StreetAddress = "123 Credibility St.", PostalCode = "60606", Locality = "Chicago", Region = "IL", }, DateOfBirth = "10/9/1980", Ssn = "123-00-1234", TaxId = "123456789", RoutingNumber = "122100024", AccountNumber = "43759348798" }, TosAccepted = true, Id = id, MasterMerchantAccountId = "sandbox_master_merchant_account" }; } private MerchantAccountRequest createRequest(string id) { return new MerchantAccountRequest { Individual = new IndividualRequest { FirstName = "Job", LastName = "Leoggs", Email = "[email protected]", Phone = "555-555-1212", Address = new AddressRequest { StreetAddress = "193 Credibility St.", PostalCode = "60611", Locality = "Avondale", Region = "IN", }, DateOfBirth = "10/9/1985", Ssn = "123-00-1235", }, Business = new BusinessRequest { LegalName = "coaterie.com", DbaName = "Coaterie", TaxId = "123456780", Address = new AddressRequest { StreetAddress = "135 Credibility St.", PostalCode = "60602", Locality = "Gary", Region = "OH", }, }, Funding = new FundingRequest { Destination = FundingDestination.EMAIL, Email = "[email protected]", MobilePhone = "3125551212", RoutingNumber = "122100024", AccountNumber = "43759348798", Descriptor = "Job Leoggs OH", }, TosAccepted = true, Id = id, MasterMerchantAccountId = "sandbox_master_merchant_account" }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; using Dotnet.Script.DependencyModel.ScriptPackage; using Microsoft.DotNet.PlatformAbstractions; using NuGet.Common; using NuGet.Packaging; using NuGet.ProjectModel; using NuGet.RuntimeModel; using NuGet.Versioning; namespace Dotnet.Script.DependencyModel.Context { public class ScriptDependencyContextReader { private readonly Logger _logger; private readonly ILogger _nuGetLogger; private readonly ScriptFilesDependencyResolver _scriptFilesDependencyResolver; public ScriptDependencyContextReader(LogFactory logFactory, ScriptFilesDependencyResolver scriptFilesDependencyResolver) { _logger = logFactory.CreateLogger<ScriptDependencyContextReader>(); _nuGetLogger = new NuGetLogger(logFactory); _scriptFilesDependencyResolver = scriptFilesDependencyResolver; } public ScriptDependencyContextReader(LogFactory logFactory) : this(logFactory, new ScriptFilesDependencyResolver(logFactory)) { } public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) { var lockFile = GetLockFile(pathToAssetsFile); // Since we execute "dotnet restore -r [rid]" we get two targets in the lock file. // The second target is the one containing the runtime deps for the given RID. var target = GetLockFileTarget(lockFile); var targetLibraries = target.Libraries; var packageFolders = lockFile.PackageFolders.Select(lfi => lfi.Path).ToArray(); var userPackageFolder = packageFolders.First(); var fallbackFolders = packageFolders.Skip(1); var packagePathResolver = new FallbackPackagePathResolver(userPackageFolder, fallbackFolders); List<ScriptDependency> scriptDependencies = new List<ScriptDependency>(); foreach (var targetLibrary in targetLibraries) { var scriptDependency = CreateScriptDependency(targetLibrary.Name, targetLibrary.Version.ToString(), packagePathResolver, targetLibrary); if ( scriptDependency.NativeAssetPaths.Any() || scriptDependency.RuntimeDependencyPaths.Any() || scriptDependency.CompileTimeDependencyPaths.Any() || scriptDependency.ScriptPaths.Any()) { scriptDependencies.Add(scriptDependency); } } if (ScriptEnvironment.Default.NetCoreVersion.Major >= 3) { var netcoreAppRuntimeAssemblyLocation = Path.GetDirectoryName(typeof(object).Assembly.Location); var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty<string>(), Array.Empty<string>(), Array.Empty<string>()); scriptDependencies.Add(netCoreAppDependency); } return new ScriptDependencyContext(scriptDependencies.ToArray()); } private static bool IsAssembly(string file) { // https://docs.microsoft.com/en-us/dotnet/standard/assembly/identify try { AssemblyName.GetAssemblyName(file); return true; } catch (System.Exception) { return false; } } private static LockFileTarget GetLockFileTarget(LockFile lockFile) { if (lockFile.Targets.Count < 2) { string message = $@"The lock file {lockFile.Path} does not contain a runtime target. Make sure that the project file was restored using a RID (runtime identifier)."; throw new InvalidOperationException(message); } return lockFile.Targets[1]; } private LockFile GetLockFile(string pathToAssetsFile) { var lockFile = LockFileUtilities.GetLockFile(pathToAssetsFile, _nuGetLogger); if (lockFile == null) { string message = $@"Unable to read lockfile {pathToAssetsFile}. Make sure that the file exists and that it is a valid 'project.assets.json' file."; throw new InvalidOperationException(message); } return lockFile; } private ScriptDependency CreateScriptDependency(string name, string version, FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { var runtimeDependencyPaths = GetRuntimeDependencyPaths(packagePathResolver, targetLibrary); var compileTimeDependencyPaths = GetCompileTimeDependencyPaths(packagePathResolver, targetLibrary); var nativeAssetPaths = GetNativeAssetPaths(packagePathResolver, targetLibrary); var scriptPaths = GetScriptPaths(packagePathResolver, targetLibrary); return new ScriptDependency(name, version, runtimeDependencyPaths, nativeAssetPaths, compileTimeDependencyPaths.ToArray(), scriptPaths); } private string[] GetScriptPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { if (targetLibrary.ContentFiles.Count == 0) { return Array.Empty<string>(); } var packageFolder = ResolvePackageFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString()); // Note that we can't use content files directly here since that only works for // script packages directly referenced by the script and not script packages having // dependencies to other script packages. var files = _scriptFilesDependencyResolver.GetScriptFileDependencies(packageFolder); return files; } private string[] GetNativeAssetPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { var nativeAssetPaths = new List<string>(); foreach (var runtimeTarget in targetLibrary.NativeLibraries.Where(lfi => !lfi.Path.EndsWith("_._"))) { var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), runtimeTarget.Path); nativeAssetPaths.Add(fullPath); } return nativeAssetPaths.ToArray(); } private static string[] GetRuntimeDependencyPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { var runtimeDependencyPaths = new List<string>(); foreach (var lockFileItem in targetLibrary.RuntimeAssemblies.Where(lfi => !lfi.Path.EndsWith("_._"))) { var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), lockFileItem.Path); runtimeDependencyPaths.Add(fullPath); } return runtimeDependencyPaths.ToArray(); } private static string[] GetCompileTimeDependencyPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary) { var compileTimeDependencyPaths = new List<string>(); foreach (var lockFileItem in targetLibrary.CompileTimeAssemblies.Where(cta => !cta.Path.EndsWith("_._"))) { var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), lockFileItem.Path); compileTimeDependencyPaths.Add(fullPath); } return compileTimeDependencyPaths.ToArray(); } private static string ResolveFullPath(FallbackPackagePathResolver packagePathResolver, string name, string version, string referencePath) { var packageFolder = ResolvePackageFullPath(packagePathResolver, name, version); var fullPath = Path.Combine(packageFolder, referencePath); if (File.Exists(fullPath)) { return fullPath; } string message = $@"The requested dependency ({referencePath}) was not found in the global Nuget cache(s). . Try executing/publishing the script again with the '--no-cache' option"; throw new InvalidOperationException(message); } private static string ResolvePackageFullPath(FallbackPackagePathResolver packagePathResolver, string name, string version) { var packageFolder = packagePathResolver.GetPackageDirectory(name, version); if (packageFolder != null) { return packageFolder; } string message = $@"The requested package ({name},{version}) was not found in the global Nuget cache(s). . Try executing/publishing the script again with the '--no-cache' option"; throw new InvalidOperationException(message); } private class NuGetLogger : LoggerBase { private readonly Logger _logger; public NuGetLogger(LogFactory logFactory) { _logger = logFactory.CreateLogger<NuGetLogger>(); } public override void Log(ILogMessage message) { if (message.Level == NuGet.Common.LogLevel.Debug) { _logger.Debug(message.Message); } else if (message.Level == NuGet.Common.LogLevel.Verbose) { _logger.Trace(message.Message); } else if (message.Level == NuGet.Common.LogLevel.Information) { _logger.Info(message.Message); } else if (message.Level == NuGet.Common.LogLevel.Error) { _logger.Error(message.Message); } else if (message.Level == NuGet.Common.LogLevel.Minimal) { _logger.Info(message.Message); } } public override Task LogAsync(ILogMessage message) { Log(message); return Task.CompletedTask; } } } }
/* * Copyright (c) 2006-2014, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse.Packets; namespace OpenMetaverse { /// <summary> /// /// </summary> public class SoundManager { #region Private Members private readonly GridClient Client; #endregion #region Event Handling /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<AttachedSoundEventArgs> m_AttachedSound; ///<summary>Raises the AttachedSound Event</summary> /// <param name="e">A AttachedSoundEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnAttachedSound(AttachedSoundEventArgs e) { EventHandler<AttachedSoundEventArgs> handler = m_AttachedSound; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_AttachedSoundLock = new object(); /// <summary>Raised when the simulator sends us data containing /// sound</summary> public event EventHandler<AttachedSoundEventArgs> AttachedSound { add { lock (m_AttachedSoundLock) { m_AttachedSound += value; } } remove { lock (m_AttachedSoundLock) { m_AttachedSound -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<AttachedSoundGainChangeEventArgs> m_AttachedSoundGainChange; ///<summary>Raises the AttachedSoundGainChange Event</summary> /// <param name="e">A AttachedSoundGainChangeEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnAttachedSoundGainChange(AttachedSoundGainChangeEventArgs e) { EventHandler<AttachedSoundGainChangeEventArgs> handler = m_AttachedSoundGainChange; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_AttachedSoundGainChangeLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<AttachedSoundGainChangeEventArgs> AttachedSoundGainChange { add { lock (m_AttachedSoundGainChangeLock) { m_AttachedSoundGainChange += value; } } remove { lock (m_AttachedSoundGainChangeLock) { m_AttachedSoundGainChange -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SoundTriggerEventArgs> m_SoundTrigger; ///<summary>Raises the SoundTrigger Event</summary> /// <param name="e">A SoundTriggerEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSoundTrigger(SoundTriggerEventArgs e) { EventHandler<SoundTriggerEventArgs> handler = m_SoundTrigger; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SoundTriggerLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SoundTriggerEventArgs> SoundTrigger { add { lock (m_SoundTriggerLock) { m_SoundTrigger += value; } } remove { lock (m_SoundTriggerLock) { m_SoundTrigger -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<PreloadSoundEventArgs> m_PreloadSound; ///<summary>Raises the PreloadSound Event</summary> /// <param name="e">A PreloadSoundEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnPreloadSound(PreloadSoundEventArgs e) { EventHandler<PreloadSoundEventArgs> handler = m_PreloadSound; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_PreloadSoundLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<PreloadSoundEventArgs> PreloadSound { add { lock (m_PreloadSoundLock) { m_PreloadSound += value; } } remove { lock (m_PreloadSoundLock) { m_PreloadSound -= value; } } } #endregion /// <summary> /// Construct a new instance of the SoundManager class, used for playing and receiving /// sound assets /// </summary> /// <param name="client">A reference to the current GridClient instance</param> public SoundManager(GridClient client) { Client = client; Client.Network.RegisterCallback(PacketType.AttachedSound, AttachedSoundHandler); Client.Network.RegisterCallback(PacketType.AttachedSoundGainChange, AttachedSoundGainChangeHandler); Client.Network.RegisterCallback(PacketType.PreloadSound, PreloadSoundHandler); Client.Network.RegisterCallback(PacketType.SoundTrigger, SoundTriggerHandler); } #region public methods /// <summary> /// Plays a sound in the current region at full volume from avatar position /// </summary> /// <param name="soundID">UUID of the sound to be played</param> public void PlaySound(UUID soundID) { SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f); } /// <summary> /// Plays a sound in the current region at full volume /// </summary> /// <param name="soundID">UUID of the sound to be played.</param> /// <param name="position">position for the sound to be played at. Normally the avatar.</param> public void SendSoundTrigger(UUID soundID, Vector3 position) { SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f); } /// <summary> /// Plays a sound in the current region /// </summary> /// <param name="soundID">UUID of the sound to be played.</param> /// <param name="position">position for the sound to be played at. Normally the avatar.</param> /// <param name="gain">volume of the sound, from 0.0 to 1.0</param> public void SendSoundTrigger(UUID soundID, Vector3 position, float gain) { SendSoundTrigger(soundID, Client.Network.CurrentSim.Handle, position, gain); } /// <summary> /// Plays a sound in the specified sim /// </summary> /// <param name="soundID">UUID of the sound to be played.</param> /// <param name="sim">UUID of the sound to be played.</param> /// <param name="position">position for the sound to be played at. Normally the avatar.</param> /// <param name="gain">volume of the sound, from 0.0 to 1.0</param> public void SendSoundTrigger(UUID soundID, Simulator sim, Vector3 position, float gain) { SendSoundTrigger(soundID, sim.Handle, position, gain); } /// <summary> /// Play a sound asset /// </summary> /// <param name="soundID">UUID of the sound to be played.</param> /// <param name="handle">handle id for the sim to be played in.</param> /// <param name="position">position for the sound to be played at. Normally the avatar.</param> /// <param name="gain">volume of the sound, from 0.0 to 1.0</param> public void SendSoundTrigger(UUID soundID, ulong handle, Vector3 position, float gain) { SoundTriggerPacket soundtrigger = new SoundTriggerPacket(); soundtrigger.SoundData = new SoundTriggerPacket.SoundDataBlock(); soundtrigger.SoundData.SoundID = soundID; soundtrigger.SoundData.ObjectID = UUID.Zero; soundtrigger.SoundData.OwnerID = UUID.Zero; soundtrigger.SoundData.ParentID = UUID.Zero; soundtrigger.SoundData.Handle = handle; soundtrigger.SoundData.Position = position; soundtrigger.SoundData.Gain = gain; Client.Network.SendPacket(soundtrigger); } #endregion #region Packet Handlers /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void AttachedSoundHandler(object sender, PacketReceivedEventArgs e) { if (m_AttachedSound != null) { AttachedSoundPacket sound = (AttachedSoundPacket)e.Packet; OnAttachedSound(new AttachedSoundEventArgs(e.Simulator, sound.DataBlock.SoundID, sound.DataBlock.OwnerID, sound.DataBlock.ObjectID, sound.DataBlock.Gain, (SoundFlags)sound.DataBlock.Flags)); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void AttachedSoundGainChangeHandler(object sender, PacketReceivedEventArgs e) { if (m_AttachedSoundGainChange != null) { AttachedSoundGainChangePacket change = (AttachedSoundGainChangePacket)e.Packet; OnAttachedSoundGainChange(new AttachedSoundGainChangeEventArgs(e.Simulator, change.DataBlock.ObjectID, change.DataBlock.Gain)); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void PreloadSoundHandler(object sender, PacketReceivedEventArgs e) { if (m_PreloadSound != null) { PreloadSoundPacket preload = (PreloadSoundPacket)e.Packet; foreach (PreloadSoundPacket.DataBlockBlock data in preload.DataBlock) { OnPreloadSound(new PreloadSoundEventArgs(e.Simulator, data.SoundID, data.OwnerID, data.ObjectID)); } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void SoundTriggerHandler(object sender, PacketReceivedEventArgs e) { if (m_SoundTrigger != null) { SoundTriggerPacket trigger = (SoundTriggerPacket)e.Packet; OnSoundTrigger(new SoundTriggerEventArgs(e.Simulator, trigger.SoundData.SoundID, trigger.SoundData.OwnerID, trigger.SoundData.ObjectID, trigger.SoundData.ParentID, trigger.SoundData.Gain, trigger.SoundData.Handle, trigger.SoundData.Position)); } } #endregion } #region EventArgs /// <summary>Provides data for the <see cref="SoundManager.AttachedSound"/> event</summary> /// <remarks>The <see cref="SoundManager.AttachedSound"/> event occurs when the simulator sends /// the sound data which emits from an agents attachment</remarks> /// <example> /// The following code example shows the process to subscribe to the <see cref="SoundManager.AttachedSound"/> event /// and a stub to handle the data passed from the simulator /// <code> /// // Subscribe to the AttachedSound event /// Client.Sound.AttachedSound += Sound_AttachedSound; /// /// // process the data raised in the event here /// private void Sound_AttachedSound(object sender, AttachedSoundEventArgs e) /// { /// // ... Process AttachedSoundEventArgs here ... /// } /// </code> /// </example> public class AttachedSoundEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly UUID m_SoundID; private readonly UUID m_OwnerID; private readonly UUID m_ObjectID; private readonly float m_Gain; private readonly SoundFlags m_Flags; /// <summary>Simulator where the event originated</summary> public Simulator Simulator { get { return m_Simulator; } } /// <summary>Get the sound asset id</summary> public UUID SoundID { get { return m_SoundID; } } /// <summary>Get the ID of the owner</summary> public UUID OwnerID { get { return m_OwnerID; } } /// <summary>Get the ID of the Object</summary> public UUID ObjectID { get { return m_ObjectID; } } /// <summary>Get the volume level</summary> public float Gain { get { return m_Gain; } } /// <summary>Get the <see cref="SoundFlags"/></summary> public SoundFlags Flags { get { return m_Flags; } } /// <summary> /// Construct a new instance of the SoundTriggerEventArgs class /// </summary> /// <param name="sim">Simulator where the event originated</param> /// <param name="soundID">The sound asset id</param> /// <param name="ownerID">The ID of the owner</param> /// <param name="objectID">The ID of the object</param> /// <param name="gain">The volume level</param> /// <param name="flags">The <see cref="SoundFlags"/></param> public AttachedSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, float gain, SoundFlags flags) { this.m_Simulator = sim; this.m_SoundID = soundID; this.m_OwnerID = ownerID; this.m_ObjectID = objectID; this.m_Gain = gain; this.m_Flags = flags; } } /// <summary>Provides data for the <see cref="SoundManager.AttachedSoundGainChange"/> event</summary> /// <remarks>The <see cref="SoundManager.AttachedSoundGainChange"/> event occurs when an attached sound /// changes its volume level</remarks> public class AttachedSoundGainChangeEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly UUID m_ObjectID; private readonly float m_Gain; /// <summary>Simulator where the event originated</summary> public Simulator Simulator { get { return m_Simulator; } } /// <summary>Get the ID of the Object</summary> public UUID ObjectID { get { return m_ObjectID; } } /// <summary>Get the volume level</summary> public float Gain { get { return m_Gain; } } /// <summary> /// Construct a new instance of the AttachedSoundGainChangedEventArgs class /// </summary> /// <param name="sim">Simulator where the event originated</param> /// <param name="objectID">The ID of the Object</param> /// <param name="gain">The new volume level</param> public AttachedSoundGainChangeEventArgs(Simulator sim, UUID objectID, float gain) { this.m_Simulator = sim; this.m_ObjectID = objectID; this.m_Gain = gain; } } /// <summary>Provides data for the <see cref="SoundManager.SoundTrigger"/> event</summary> /// <remarks><para>The <see cref="SoundManager.SoundTrigger"/> event occurs when the simulator forwards /// a request made by yourself or another agent to play either an asset sound or a built in sound</para> /// /// <para>Requests to play sounds where the <see cref="SoundTriggerEventArgs.SoundID"/> is not one of the built-in /// <see cref="Sounds"/> will require sending a request to download the sound asset before it can be played</para> /// </remarks> /// <example> /// The following code example uses the <see cref="SoundTriggerEventArgs.OwnerID"/>, <see cref="SoundTriggerEventArgs.SoundID"/> /// and <see cref="SoundTriggerEventArgs.Gain"/> /// properties to display some information on a sound request on the <see cref="Console"/> window. /// <code> /// // subscribe to the event /// Client.Sound.SoundTrigger += Sound_SoundTrigger; /// /// // play the pre-defined BELL_TING sound /// Client.Sound.SendSoundTrigger(Sounds.BELL_TING); /// /// // handle the response data /// private void Sound_SoundTrigger(object sender, SoundTriggerEventArgs e) /// { /// Console.WriteLine("{0} played the sound {1} at volume {2}", /// e.OwnerID, e.SoundID, e.Gain); /// } /// </code> /// </example> public class SoundTriggerEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly UUID m_SoundID; private readonly UUID m_OwnerID; private readonly UUID m_ObjectID; private readonly UUID m_ParentID; private readonly float m_Gain; private readonly ulong m_RegionHandle; private readonly Vector3 m_Position; /// <summary>Simulator where the event originated</summary> public Simulator Simulator { get { return m_Simulator; } } /// <summary>Get the sound asset id</summary> public UUID SoundID { get { return m_SoundID; } } /// <summary>Get the ID of the owner</summary> public UUID OwnerID { get { return m_OwnerID; } } /// <summary>Get the ID of the Object</summary> public UUID ObjectID { get { return m_ObjectID; } } /// <summary>Get the ID of the objects parent</summary> public UUID ParentID { get { return m_ParentID; } } /// <summary>Get the volume level</summary> public float Gain { get { return m_Gain; } } /// <summary>Get the regionhandle</summary> public ulong RegionHandle { get { return m_RegionHandle; } } /// <summary>Get the source position</summary> public Vector3 Position { get { return m_Position; } } /// <summary> /// Construct a new instance of the SoundTriggerEventArgs class /// </summary> /// <param name="sim">Simulator where the event originated</param> /// <param name="soundID">The sound asset id</param> /// <param name="ownerID">The ID of the owner</param> /// <param name="objectID">The ID of the object</param> /// <param name="parentID">The ID of the objects parent</param> /// <param name="gain">The volume level</param> /// <param name="regionHandle">The regionhandle</param> /// <param name="position">The source position</param> public SoundTriggerEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, UUID parentID, float gain, ulong regionHandle, Vector3 position) { this.m_Simulator = sim; this.m_SoundID = soundID; this.m_OwnerID = ownerID; this.m_ObjectID = objectID; this.m_ParentID = parentID; this.m_Gain = gain; this.m_RegionHandle = regionHandle; this.m_Position = position; } } /// <summary>Provides data for the <see cref="AvatarManager.AvatarAppearance"/> event</summary> /// <remarks>The <see cref="AvatarManager.AvatarAppearance"/> event occurs when the simulator sends /// the appearance data for an avatar</remarks> /// <example> /// The following code example uses the <see cref="AvatarAppearanceEventArgs.AvatarID"/> and <see cref="AvatarAppearanceEventArgs.VisualParams"/> /// properties to display the selected shape of an avatar on the <see cref="Console"/> window. /// <code> /// // subscribe to the event /// Client.Avatars.AvatarAppearance += Avatars_AvatarAppearance; /// /// // handle the data when the event is raised /// void Avatars_AvatarAppearance(object sender, AvatarAppearanceEventArgs e) /// { /// Console.WriteLine("The Agent {0} is using a {1} shape.", e.AvatarID, (e.VisualParams[31] &gt; 0) : "male" ? "female") /// } /// </code> /// </example> public class PreloadSoundEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly UUID m_SoundID; private readonly UUID m_OwnerID; private readonly UUID m_ObjectID; /// <summary>Simulator where the event originated</summary> public Simulator Simulator { get { return m_Simulator; } } /// <summary>Get the sound asset id</summary> public UUID SoundID { get { return m_SoundID; } } /// <summary>Get the ID of the owner</summary> public UUID OwnerID { get { return m_OwnerID; } } /// <summary>Get the ID of the Object</summary> public UUID ObjectID { get { return m_ObjectID; } } /// <summary> /// Construct a new instance of the PreloadSoundEventArgs class /// </summary> /// <param name="sim">Simulator where the event originated</param> /// <param name="soundID">The sound asset id</param> /// <param name="ownerID">The ID of the owner</param> /// <param name="objectID">The ID of the object</param> public PreloadSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID) { this.m_Simulator = sim; this.m_SoundID = soundID; this.m_OwnerID = ownerID; this.m_ObjectID = objectID; } } #endregion }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Json { #region Namespaces using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif using Microsoft.Data.Edm; #endregion Namespaces /// <summary> /// JSON format output context. /// </summary> internal sealed class ODataJsonOutputContext : ODataOutputContext { /// <summary>The message output stream.</summary> private Stream messageOutputStream; /// <summary>The asynchronous output stream if we're writing asynchronously.</summary> private AsyncBufferedStream asynchronousOutputStream; /// <summary>The text writer created for the output stream.</summary> private TextWriter textWriter; /// <summary>The JSON writer to write to.</summary> /// <remarks>This field is also used to determine if the output context has been disposed already.</remarks> private JsonWriter jsonWriter; /// <summary>An in-stream error listener to notify when in-stream error is to be written. Or null if we don't need to notify anybody.</summary> private IODataOutputInStreamErrorListener outputInStreamErrorListener; /// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="jsonWriter">The JSON writer to write to.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> private ODataJsonOutputContext( ODataFormat format, JsonWriter jsonWriter, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { this.jsonWriter = jsonWriter; } /// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="messageStream">The message stream to write the payload to.</param> /// <param name="encoding">The encoding to use for the payload.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> private ODataJsonOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { try { this.messageOutputStream = messageStream; Stream outputStream; if (synchronous) { outputStream = messageStream; } else { this.asynchronousOutputStream = new AsyncBufferedStream(messageStream); outputStream = this.asynchronousOutputStream; } this.textWriter = new StreamWriter(outputStream, encoding); this.jsonWriter = new JsonWriter(this.textWriter, messageWriterSettings.Indent); } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } } /// <summary> /// Returns the <see cref="JsonWriter"/> which is to be used to write the content of the message. /// </summary> internal JsonWriter JsonWriter { get { DebugUtils.CheckNoExternalCallers(); Debug.Assert(this.jsonWriter != null, "Trying to get JsonWriter while none is available."); return this.jsonWriter; } } /// <summary> /// Create JSON output context. /// </summary> /// <param name="format">The format to create the output context for.</param> /// <param name="message">The message to use.</param> /// <param name="encoding">The encoding to use.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> /// <returns>The newly created output context.</returns> internal static ODataOutputContext Create( ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, IEdmModel model, IODataUrlResolver urlResolver) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(format == ODataFormat.VerboseJson, "This method only supports the JSON format."); Debug.Assert(message != null, "message != null"); Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null"); Stream messageStream = message.GetStream(); return new ODataJsonOutputContext( format, messageStream, encoding, messageWriterSettings, writingResponse, true, model, urlResolver); } /// <summary> /// Create JSON output context. /// </summary> /// <param name="format">The format to create the output context for.</param> /// <param name="jsonWriter">The JSON writer to write to.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> /// <returns>The newly created output context.</returns> /// <remarks>This method is for writing the output directly to the JSON writer, when created with this method /// the output context doesn't support most of the methods on it. Note that Dispose will do nothing in this case.</remarks> internal static ODataJsonOutputContext Create( ODataFormat format, JsonWriter jsonWriter, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, IEdmModel model, IODataUrlResolver urlResolver) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(format == ODataFormat.VerboseJson, "This method only supports the verbose JSON format."); Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null"); return new ODataJsonOutputContext( format, jsonWriter, messageWriterSettings, writingResponse, true, model, urlResolver); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously create JSON output context. /// </summary> /// <param name="format">The format to create the outpu context for.</param> /// <param name="message">The message to use.</param> /// <param name="encoding">The encoding to use.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> /// <returns>Task which when completed returns the newly created output context.</returns> internal static Task<ODataOutputContext> CreateAsync( ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, IEdmModel model, IODataUrlResolver urlResolver) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(format == ODataFormat.VerboseJson, "This method only supports the JSON format."); Debug.Assert(message != null, "message != null"); Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null"); return message.GetStreamAsync() .FollowOnSuccessWith( (streamTask) => (ODataOutputContext)new ODataJsonOutputContext( format, streamTask.Result, encoding, messageWriterSettings, writingResponse, false, model, urlResolver)); } #endif /// <summary> /// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object /// has already been disposed. /// </summary> internal void VerifyNotDisposed() { DebugUtils.CheckNoExternalCallers(); if (this.messageOutputStream == null) { throw new ObjectDisposedException(this.GetType().FullName); } } /// <summary> /// Synchronously flush the writer. /// </summary> internal void Flush() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); // JsonWriter.Flush will call the underlying TextWriter.Flush. // The TextWriter.Flush (which is in fact StreamWriter.Flush) will call the underlying Stream.Flush. // In the synchronous case the underlying stream is the message stream itself, which will then Flush as well. this.jsonWriter.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously flush the writer. /// </summary> /// <returns>Task which represents the pending flush operation.</returns> /// <remarks>The method should not throw directly if the flush operation itself fails, it should instead return a faulted task.</remarks> internal Task FlushAsync() { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { // JsonWriter.Flush will call the underlying TextWriter.Flush. // The TextWriter.Flush (Which is in fact StreamWriter.Flush) will call the underlying Stream.Flush. // In the async case the underlying stream is the async buffered stream, which ignores Flush call. this.jsonWriter.Flush(); Debug.Assert(this.asynchronousOutputStream != null, "In async writing we must have the async buffered stream."); return this.asynchronousOutputStream.FlushAsync(); }) .FollowOnSuccessWithTask((asyncBufferedStreamFlushTask) => this.messageOutputStream.FlushAsync()); } #endif /// <summary> /// Writes an <see cref="ODataError"/> into the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <remarks> /// This method is called if the ODataMessageWriter.WriteError is called once some other /// write operation has already started. /// The method should write the in-stream error representation for the specific format into the current payload. /// Before the method is called no flush is performed on the output context or any active writer. /// It is the responsibility of this method to flush the output before the method returns. /// </remarks> internal override void WriteInStreamError(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteInStreamErrorImplementation(error, includeDebugInformation); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Writes an <see cref="ODataError"/> into the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <returns>Task which represents the pending write operation.</returns> /// <remarks> /// This method is called if the ODataMessageWriter.WriteError is called once some other /// write operation has already started. /// The method should write the in-stream error representation for the specific format into the current payload. /// Before the method is called no flush is performed on the output context or any active writer. /// It is the responsibility of this method to make sure that all the data up to this point are written before /// the in-stream error is written. /// It is the responsibility of this method to flush the output before the task finishes. /// </remarks> internal override Task WriteInStreamErrorAsync(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteInStreamErrorImplementation(error, includeDebugInformation); return this.FlushAsync(); }); } #endif /// <summary> /// Creates an <see cref="ODataWriter" /> to write a feed. /// </summary> /// <returns>The created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override ODataWriter CreateODataFeedWriter() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); return this.CreateODataFeedWriterImplementation(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously creates an <see cref="ODataWriter" /> to write a feed. /// </summary> /// <returns>A running task for the created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task<ODataWriter> CreateODataFeedWriterAsync() { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataFeedWriterImplementation()); } #endif /// <summary> /// Creates an <see cref="ODataWriter" /> to write an entry. /// </summary> /// <returns>The created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override ODataWriter CreateODataEntryWriter() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); return this.CreateODataEntryWriterImplementation(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously creates an <see cref="ODataWriter" /> to write an entry. /// </summary> /// <returns>A running task for the created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task<ODataWriter> CreateODataEntryWriterAsync() { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataEntryWriterImplementation()); } #endif /// <summary> /// Creates an <see cref="ODataCollectionWriter" /> to write a collection of primitive or complex values (as result of a service operation invocation). /// </summary> /// <returns>The created collection writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override ODataCollectionWriter CreateODataCollectionWriter() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); return this.CreateODataCollectionWriterImplementation(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously creates an <see cref="ODataCollectionWriter" /> to write a collection of primitive or complex values (as result of a service operation invocation). /// </summary> /// <returns>A running task for the created collection writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task<ODataCollectionWriter> CreateODataCollectionWriterAsync() { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataCollectionWriterImplementation()); } #endif /// <summary> /// Creates an <see cref="ODataParameterWriter" /> to write a parameter payload. /// </summary> /// <param name="functionImport">The function import whose parameters will be written.</param> /// <returns>The created parameter writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override ODataParameterWriter CreateODataParameterWriter(IEdmFunctionImport functionImport) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); return this.CreateODataParameterWriterImplementation(functionImport); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously creates an <see cref="ODataParameterWriter" /> to write a parameter payload. /// </summary> /// <param name="functionImport">The function import whose parameters will be written.</param> /// <returns>A running task for the created parameter writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task<ODataParameterWriter> CreateODataParameterWriterAsync(IEdmFunctionImport functionImport) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataParameterWriterImplementation(functionImport)); } #endif /// <summary> /// Writes a service document with the specified <paramref name="defaultWorkspace"/> /// as message payload. /// </summary> /// <param name="defaultWorkspace">The default workspace to write in the service document.</param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteServiceDocument(ODataWorkspace defaultWorkspace) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteServiceDocumentImplementation(defaultWorkspace); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously writes a service document with the specified <paramref name="defaultWorkspace"/> /// as message payload. /// </summary> /// <param name="defaultWorkspace">The default workspace to write in the service document.</param> /// <returns>A task representing the asynchronous operation of writing the service document.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal override Task WriteServiceDocumentAsync(ODataWorkspace defaultWorkspace) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteServiceDocumentImplementation(defaultWorkspace); return this.FlushAsync(); }); } #endif /// <summary> /// Writes an <see cref="ODataProperty"/> as message payload. /// </summary> /// <param name="property">The property to write.</param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteProperty(ODataProperty property) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WritePropertyImplementation(property); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously writes an <see cref="ODataProperty"/> as message payload. /// </summary> /// <param name="property">The property to write</param> /// <returns>A task representing the asynchronous operation of writing the property.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal override Task WritePropertyAsync(ODataProperty property) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WritePropertyImplementation(property); return this.FlushAsync(); }); } #endif /// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteError(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteErrorImplementation(error, includeDebugInformation); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <returns>A task representing the asynchronous operation of writing the error.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal override Task WriteErrorAsync(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteErrorImplementation(error, includeDebugInformation); return this.FlushAsync(); }); } #endif /// <summary> /// Writes the result of a $links query as the message payload. /// </summary> /// <param name="links">The entity reference links to write as message payload.</param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteEntityReferenceLinks(ODataEntityReferenceLinks links) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteEntityReferenceLinksImplementation(links); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously writes the result of a $links query as the message payload. /// </summary> /// <param name="links">The entity reference links to write as message payload.</param> /// <returns>A task representing the asynchronous writing of the entity reference links.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal override Task WriteEntityReferenceLinksAsync(ODataEntityReferenceLinks links) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteEntityReferenceLinksImplementation(links); return this.FlushAsync(); }); } #endif /// <summary> /// Writes a singleton result of a $links query as the message payload. /// </summary> /// <param name="link">The entity reference link to write as message payload.</param> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteEntityReferenceLink(ODataEntityReferenceLink link) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); this.WriteEntityReferenceLinkImplementation(link); this.Flush(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously writes a singleton result of a $links query as the message payload. /// </summary> /// <param name="link">The link result to write as message payload.</param> /// <returns>A running task representing the writing of the link.</returns> /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks> internal override Task WriteEntityReferenceLinkAsync(ODataEntityReferenceLink link) { DebugUtils.CheckNoExternalCallers(); this.AssertAsynchronous(); return TaskUtils.GetTaskForSynchronousOperationReturningTask( () => { this.WriteEntityReferenceLinkImplementation(link); return this.FlushAsync(); }); } #endif //// Raw value is not supported by JSON. /// <summary> /// Perform the actual cleanup work. /// </summary> /// <param name="disposing">If 'true' this method is called from user code; if 'false' it is called by the runtime.</param> [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "textWriter", Justification = "We don't dispose the jsonWriter or textWriter, instead we dispose the underlying stream directly.")] protected override void Dispose(bool disposing) { base.Dispose(disposing); try { if (this.messageOutputStream != null) { // JsonWriter.Flush will call the underlying TextWriter.Flush. // The TextWriter.Flush (Which is in fact StreamWriter.Flush) will call the underlying Stream.Flush. this.jsonWriter.Flush(); // In the async case the underlying stream is the async buffered stream, so we have to flush that explicitely. if (this.asynchronousOutputStream != null) { this.asynchronousOutputStream.FlushSync(); this.asynchronousOutputStream.Dispose(); } // Dipose the message stream (note that we OWN this stream, so we always dispose it). this.messageOutputStream.Dispose(); } } finally { this.messageOutputStream = null; this.asynchronousOutputStream = null; this.textWriter = null; this.jsonWriter = null; } } /// <summary> /// Creates an <see cref="ODataWriter" /> to write a feed. /// </summary> /// <returns>The created writer.</returns> private ODataWriter CreateODataFeedWriterImplementation() { ODataJsonWriter odataJsonWriter = new ODataJsonWriter(this, true); this.outputInStreamErrorListener = odataJsonWriter; return odataJsonWriter; } /// <summary> /// Creates an <see cref="ODataWriter" /> to write an entry. /// </summary> /// <returns>The created writer.</returns> private ODataWriter CreateODataEntryWriterImplementation() { ODataJsonWriter odataJsonWriter = new ODataJsonWriter(this, false); this.outputInStreamErrorListener = odataJsonWriter; return odataJsonWriter; } /// <summary> /// Creates an <see cref="ODataCollectionWriter" /> to write a collection of primitive or complex values (as result of a service operation invocation). /// </summary> /// <returns>The created collection writer.</returns> private ODataCollectionWriter CreateODataCollectionWriterImplementation() { ODataJsonCollectionWriter jsonCollectionWriter = new ODataJsonCollectionWriter(this, /*expectedItemType*/ null, /*listener*/ null); this.outputInStreamErrorListener = jsonCollectionWriter; return jsonCollectionWriter; } /// <summary> /// Creates an <see cref="ODataParameterWriter" /> to write a parameter payload. /// </summary> /// <param name="functionImport">The function import whose parameters will be written.</param> /// <returns>The created parameter writer.</returns> private ODataParameterWriter CreateODataParameterWriterImplementation(IEdmFunctionImport functionImport) { ODataJsonParameterWriter jsonParameterWriter = new ODataJsonParameterWriter(this, functionImport); this.outputInStreamErrorListener = jsonParameterWriter; return jsonParameterWriter; } /// <summary> /// Writes an in-stream error. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteInStreamErrorImplementation(ODataError error, bool includeDebugInformation) { if (this.outputInStreamErrorListener != null) { this.outputInStreamErrorListener.OnInStreamError(); } ODataJsonWriterUtils.WriteError(this.jsonWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth); } /// <summary> /// Writes an <see cref="ODataProperty"/> as message payload. /// </summary> /// <param name="property">The property to write.</param> private void WritePropertyImplementation(ODataProperty property) { ODataJsonPropertyAndValueSerializer jsonPropertyAndValueSerializer = new ODataJsonPropertyAndValueSerializer(this); jsonPropertyAndValueSerializer.WriteTopLevelProperty(property); } /// <summary> /// Writes a service document with the specified <paramref name="defaultWorkspace"/> /// as message payload. /// </summary> /// <param name="defaultWorkspace">The default workspace to write in the service document.</param> private void WriteServiceDocumentImplementation(ODataWorkspace defaultWorkspace) { ODataJsonServiceDocumentSerializer jsonServiceDocumentSerializer = new ODataJsonServiceDocumentSerializer(this); jsonServiceDocumentSerializer.WriteServiceDocument(defaultWorkspace); } /// <summary> /// Writes an <see cref="ODataError"/> as the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> private void WriteErrorImplementation(ODataError error, bool includeDebugInformation) { ODataJsonSerializer jsonSerializer = new ODataJsonSerializer(this); jsonSerializer.WriteTopLevelError(error, includeDebugInformation); } /// <summary> /// Writes the result of a $links query as the message payload. /// </summary> /// <param name="links">The entity reference links to write as message payload.</param> private void WriteEntityReferenceLinksImplementation(ODataEntityReferenceLinks links) { ODataJsonEntityReferenceLinkSerializer jsonEntityReferenceLinkSerializer = new ODataJsonEntityReferenceLinkSerializer(this); jsonEntityReferenceLinkSerializer.WriteEntityReferenceLinks(links); } /// <summary> /// Writes a singleton result of a $links query as the message payload. /// </summary> /// <param name="link">The entity reference link to write as message payload.</param> private void WriteEntityReferenceLinkImplementation(ODataEntityReferenceLink link) { ODataJsonEntityReferenceLinkSerializer jsonEntityReferenceLinkSerializer = new ODataJsonEntityReferenceLinkSerializer(this); jsonEntityReferenceLinkSerializer.WriteEntityReferenceLink(link); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Reflection; namespace Trisoft.ISHRemote.HelperClasses { #region Class StringEnum /// <summary> /// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes. /// </summary> internal class StringEnum { #region Instance implementation private Type _enumType; private static Hashtable _stringValues = new Hashtable(); /// <summary> /// Creates a new <see cref="StringEnum"/> instance. /// </summary> /// <param name="enumType">Enum type.</param> public StringEnum(Type enumType) { if (!enumType.IsEnum) throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", enumType.ToString())); _enumType = enumType; } /// <summary> /// Gets the string value associated with the given enum value. /// </summary> /// <param name="valueName">Name of the enum value.</param> /// <returns>String Value</returns> public string GetStringValue(string valueName) { Enum enumType; string stringValue = null; try { enumType = (Enum) Enum.Parse(_enumType, valueName); stringValue = GetStringValue(enumType); } catch (Exception) { }//Swallow! return stringValue; } /// <summary> /// Gets the string values associated with the enum. /// </summary> /// <returns>String value array</returns> public Array GetStringValues() { ArrayList values = new ArrayList(); //Look for our string value associated with fields in this enum foreach (FieldInfo fi in _enumType.GetFields()) { //Check for our custom attribute StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; if (attrs.Length > 0) values.Add(attrs[0].Value); } return values.ToArray(); } /// <summary> /// Gets the values as a 'bindable' list datasource. /// </summary> /// <returns>IList for data binding</returns> public IList GetListValues() { Type underlyingType = Enum.GetUnderlyingType(_enumType); ArrayList values = new ArrayList(); //Look for our string value associated with fields in this enum foreach (FieldInfo fi in _enumType.GetFields()) { //Check for our custom attribute StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; if (attrs.Length > 0) values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value)); } return values; } /// <summary> /// Return the existence of the given string value within the enum. /// </summary> /// <param name="stringValue">String value.</param> /// <returns>Existence of the string value</returns> public bool IsStringDefined(string stringValue) { return Parse(_enumType, stringValue) != null; } /// <summary> /// Return the existence of the given string value within the enum. /// </summary> /// <param name="stringValue">String value.</param> /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> /// <returns>Existence of the string value</returns> public bool IsStringDefined(string stringValue, bool ignoreCase) { return Parse(_enumType, stringValue, ignoreCase) != null; } /// <summary> /// Gets the underlying enum type for this instance. /// </summary> /// <value></value> public Type EnumType { get { return _enumType; } } #endregion #region Static implementation /// <summary> /// Gets a string value for a particular enum value. /// </summary> /// <param name="value">Value.</param> /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns> public static string GetStringValue(Enum value) { string output = null; Type type = value.GetType(); if (_stringValues.ContainsKey(value)) output = (_stringValues[value] as StringValueAttribute).Value; else { //Look for our 'StringValueAttribute' in the field's custom attributes FieldInfo fi = type.GetField(value.ToString()); StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; if (attrs.Length > 0) { _stringValues.Add(value, attrs[0]); output = attrs[0].Value; } } return output; } /// <summary> /// Parses the supplied enum and string value to find an associated enum value (case sensitive). /// </summary> /// <param name="type">Type.</param> /// <param name="stringValue">String value.</param> /// <returns>Enum value associated with the string value, or null if not found.</returns> public static object Parse(Type type, string stringValue) { return Parse(type, stringValue, true); } /// <summary> /// Parses the supplied enum and string value to find an associated enum value. /// </summary> /// <param name="type">Type.</param> /// <param name="stringValue">String value.</param> /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> /// <returns>Enum value associated with the string value, or null if not found.</returns> public static object Parse(Type type, string stringValue, bool ignoreCase) { object output = null; string enumStringValue = null; if (!type.IsEnum) throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type.ToString())); //Look for our string value associated with fields in this enum foreach (FieldInfo fi in type.GetFields()) { //Check for our custom attribute StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; if (attrs.Length > 0) enumStringValue = attrs[0].Value; //Check for equality then select actual enum value. if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0) { output = Enum.Parse(type, fi.Name); break; } } return output; } /// <summary> /// Return the existence of the given string value within the enum. /// </summary> /// <param name="stringValue">String value.</param> /// <param name="enumType">Type of enum</param> /// <returns>Existence of the string value</returns> public static bool IsStringDefined(Type enumType, string stringValue) { return Parse(enumType, stringValue) != null; } /// <summary> /// Return the existence of the given string value within the enum. /// </summary> /// <param name="stringValue">String value.</param> /// <param name="enumType">Type of enum</param> /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> /// <returns>Existence of the string value</returns> public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase) { return Parse(enumType, stringValue, ignoreCase) != null; } #endregion } #endregion #region Class StringValueAttribute /// <summary> /// Simple attribute class for storing String Values /// </summary> internal class StringValueAttribute : Attribute { private string _value; /// <summary> /// Creates a new <see cref="StringValueAttribute"/> instance. /// </summary> /// <param name="value">Value.</param> public StringValueAttribute(string value) { _value = value; } /// <summary> /// Gets the value. /// </summary> /// <value></value> public string Value { get { return _value; } } } #endregion }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Northwind{ /// <summary> /// Strongly-typed collection for the CustomerAndSuppliersByCity class. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCityCollection : ReadOnlyList<CustomerAndSuppliersByCity, CustomerAndSuppliersByCityCollection> { public CustomerAndSuppliersByCityCollection() {} } /// <summary> /// This is Read-only wrapper class for the Customer and Suppliers by City view. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCity : ReadOnlyRecord<CustomerAndSuppliersByCity>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Customer and Suppliers by City", TableType.View, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema); colvarContactName.ColumnName = "ContactName"; colvarContactName.DataType = DbType.String; colvarContactName.MaxLength = 30; colvarContactName.AutoIncrement = false; colvarContactName.IsNullable = true; colvarContactName.IsPrimaryKey = false; colvarContactName.IsForeignKey = false; colvarContactName.IsReadOnly = false; schema.Columns.Add(colvarContactName); TableSchema.TableColumn colvarRelationship = new TableSchema.TableColumn(schema); colvarRelationship.ColumnName = "Relationship"; colvarRelationship.DataType = DbType.AnsiString; colvarRelationship.MaxLength = 9; colvarRelationship.AutoIncrement = false; colvarRelationship.IsNullable = false; colvarRelationship.IsPrimaryKey = false; colvarRelationship.IsForeignKey = false; colvarRelationship.IsReadOnly = false; schema.Columns.Add(colvarRelationship); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Customer and Suppliers by City",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public CustomerAndSuppliersByCity() { SetSQLProps(); SetDefaults(); MarkNew(); } public CustomerAndSuppliersByCity(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public CustomerAndSuppliersByCity(object keyID) { SetSQLProps(); LoadByKey(keyID); } public CustomerAndSuppliersByCity(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>("CompanyName"); } set { SetColumnValue("CompanyName", value); } } [XmlAttribute("ContactName")] [Bindable(true)] public string ContactName { get { return GetColumnValue<string>("ContactName"); } set { SetColumnValue("ContactName", value); } } [XmlAttribute("Relationship")] [Bindable(true)] public string Relationship { get { return GetColumnValue<string>("Relationship"); } set { SetColumnValue("Relationship", value); } } #endregion #region Columns Struct public struct Columns { public static string City = @"City"; public static string CompanyName = @"CompanyName"; public static string ContactName = @"ContactName"; public static string Relationship = @"Relationship"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions; using Microsoft.Azure.Management.Sql.Fluent.SqlFailoverGroupOperations.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition; using System.Collections.Generic; internal partial class SqlFailoverGroupOperationsImpl { /// <summary> /// Begins a definition for a new resource. /// This is the beginning of the builder pattern used to create top level resources /// in Azure. The final method completing the definition and starting the actual resource creation /// process in Azure is Creatable.create(). /// Note that the Creatable.create() method is /// only available at the stage of the resource definition that has the minimum set of input /// parameters specified. If you do not see Creatable.create() among the available methods, it /// means you have not yet specified all the required input settings. Input settings generally begin /// with the word "with", for example: <code>.withNewResourceGroup()</code> and return the next stage /// of the resource definition, as an interface in the "fluent interface" style. /// </summary> /// <param name="name">The name of the new resource.</param> /// <return>The first stage of the new resource definition.</return> SqlFailoverGroupOperations.Definition.IWithSqlServer Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsCreating<SqlFailoverGroupOperations.Definition.IWithSqlServer>.Define(string name) { return this.Define(name); } /// <summary> /// Fails over from the current primary server to this server. This operation might result in data loss. /// </summary> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>The SqlFailoverGroup object.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition.ISqlFailoverGroupActionsDefinition.ForceFailoverAllowDataLoss(string failoverGroupName) { return this.ForceFailoverAllowDataLoss(failoverGroupName); } /// <summary> /// Begins the definition of a new SQL Failover Group to be added to this server. /// </summary> /// <param name="failoverGroupName">The name of the new Failover Group to be created for the selected SQL server.</param> /// <return>The first stage of the new SQL Failover Group definition.</return> SqlFailoverGroupOperations.Definition.IWithReadWriteEndpointPolicy SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition.ISqlFailoverGroupActionsDefinition.Define(string failoverGroupName) { return this.Define(failoverGroupName); } /// <summary> /// Asynchronously fails over from the current primary server to this server. /// </summary> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>A representation of the deferred computation of this call returning the SqlFailoverGroup object.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition.ISqlFailoverGroupActionsDefinition.FailoverAsync(string failoverGroupName, CancellationToken cancellationToken) { return await this.FailoverAsync(failoverGroupName, cancellationToken); } /// <summary> /// Fails over from the current primary server to this server. This operation might result in data loss. /// </summary> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>A representation of the deferred computation of this call returning the SqlFailoverGroup object.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition.ISqlFailoverGroupActionsDefinition.ForceFailoverAllowDataLossAsync(string failoverGroupName, CancellationToken cancellationToken) { return await this.ForceFailoverAllowDataLossAsync(failoverGroupName, cancellationToken); } /// <summary> /// Fails over from the current primary server to this server. /// </summary> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>The SqlFailoverGroup object.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup SqlFailoverGroupOperations.SqlFailoverGroupActionsDefinition.ISqlFailoverGroupActionsDefinition.Failover(string failoverGroupName) { return this.Failover(failoverGroupName); } /// <summary> /// Asynchronously gets the information about a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="resourceGroupName">The name of resource group.</param> /// <param name="sqlServerName">The name of SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> /// <return>A representation of the deferred computation of this call returning the found resource.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.GetBySqlServerAsync(string resourceGroupName, string sqlServerName, string name, CancellationToken cancellationToken) { return await this.GetBySqlServerAsync(resourceGroupName, sqlServerName, name, cancellationToken); } /// <summary> /// Asynchronously gets the information about a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="sqlServer">The SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> /// <return>A representation of the deferred computation of this call returning the found resource.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.GetBySqlServerAsync(ISqlServer sqlServer, string name, CancellationToken cancellationToken) { return await this.GetBySqlServerAsync(sqlServer, name, cancellationToken); } /// <summary> /// Deletes a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="resourceGroupName">The name of resource group.</param> /// <param name="sqlServerName">The name of SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> void Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.DeleteBySqlServer(string resourceGroupName, string sqlServerName, string name) { this.DeleteBySqlServer(resourceGroupName, sqlServerName, name); } /// <summary> /// Asynchronously delete a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="resourceGroupName">The name of resource group.</param> /// <param name="sqlServerName">The name of SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.DeleteBySqlServerAsync(string resourceGroupName, string sqlServerName, string name, CancellationToken cancellationToken) { await this.DeleteBySqlServerAsync(resourceGroupName, sqlServerName, name, cancellationToken); } /// <summary> /// Gets the information about a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="resourceGroupName">The name of resource group.</param> /// <param name="sqlServerName">The name of SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> /// <return>An immutable representation of the resource.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.GetBySqlServer(string resourceGroupName, string sqlServerName, string name) { return this.GetBySqlServer(resourceGroupName, sqlServerName, name); } /// <summary> /// Gets the information about a child resource from Azure SQL server, identifying it by its name and its resource group. /// </summary> /// <param name="sqlServer">The SQL server parent resource.</param> /// <param name="name">The name of the child resource.</param> /// <return>An immutable representation of the resource.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.GetBySqlServer(ISqlServer sqlServer, string name) { return this.GetBySqlServer(sqlServer, name); } /// <summary> /// Asynchronously lists Azure SQL child resources of the specified Azure SQL server in the specified resource group. /// </summary> /// <param name="resourceGroupName">The name of the resource group to list the resources from.</param> /// <param name="sqlServerName">The name of parent Azure SQL server.</param> /// <return>A representation of the deferred computation of this call.</return> async Task<System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.ListBySqlServerAsync(string resourceGroupName, string sqlServerName, CancellationToken cancellationToken) { return await this.ListBySqlServerAsync(resourceGroupName, sqlServerName, cancellationToken); } /// <summary> /// Asynchronously lists Azure SQL child resources of the specified Azure SQL server in the specified resource group. /// </summary> /// <param name="sqlServer">The parent Azure SQL server.</param> /// <return>A representation of the deferred computation of this call.</return> async Task<System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.ListBySqlServerAsync(ISqlServer sqlServer, CancellationToken cancellationToken) { return await this.ListBySqlServerAsync(sqlServer, cancellationToken); } /// <summary> /// Lists Azure SQL child resources of the specified Azure SQL server in the specified resource group. /// </summary> /// <param name="resourceGroupName">The name of the resource group to list the resources from.</param> /// <param name="sqlServerName">The name of parent Azure SQL server.</param> /// <return>The list of resources.</return> System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.ListBySqlServer(string resourceGroupName, string sqlServerName) { return this.ListBySqlServer(resourceGroupName, sqlServerName); } /// <summary> /// Lists Azure SQL child resources of the specified Azure SQL server in the specified resource group. /// </summary> /// <param name="sqlServer">The parent Azure SQL server.</param> /// <return>The list of resources.</return> System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlChildrenOperations<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup>.ListBySqlServer(ISqlServer sqlServer) { return this.ListBySqlServer(sqlServer); } /// <summary> /// Fails over from the current primary server to this server. This operation might result in data loss. /// </summary> /// <param name="resourceGroupName">The name of the resource group that contains the resource.</param> /// <param name="serverName">The name of the server containing the failover group.</param> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>The SqlFailoverGroup object.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroupOperations.ForceFailoverAllowDataLoss(string resourceGroupName, string serverName, string failoverGroupName) { return this.ForceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName); } /// <summary> /// Asynchronously fails over from the current primary server to this server. /// </summary> /// <param name="resourceGroupName">The name of the resource group that contains the resource.</param> /// <param name="serverName">The name of the server containing the failover group.</param> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>A representation of the deferred computation of this call returning the SqlFailoverGroup object.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroupOperations.FailoverAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken) { return await this.FailoverAsync(resourceGroupName, serverName, failoverGroupName, cancellationToken); } /// <summary> /// Fails over from the current primary server to this server. This operation might result in data loss. /// </summary> /// <param name="resourceGroupName">The name of the resource group that contains the resource.</param> /// <param name="serverName">The name of the server containing the failover group.</param> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>A representation of the deferred computation of this call returning the SqlFailoverGroup object.</return> async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroupOperations.ForceFailoverAllowDataLossAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken) { return await this.ForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName, cancellationToken); } /// <summary> /// Fails over from the current primary server to this server. /// </summary> /// <param name="resourceGroupName">The name of the resource group that contains the resource.</param> /// <param name="serverName">The name of the server containing the failover group.</param> /// <param name="failoverGroupName">The name of the failover group.</param> /// <return>The SqlFailoverGroup object.</return> Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroupOperations.Failover(string resourceGroupName, string serverName, string failoverGroupName) { return this.Failover(resourceGroupName, serverName, failoverGroupName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Asn1 { internal partial class AsnReader { /// <summary> /// Reads the next value as an Enumerated value with tag UNIVERSAL 10, /// returning the contents as a <see cref="ReadOnlyMemory{T}"/> over the original data. /// </summary> /// <returns> /// The bytes of the Enumerated value, in signed big-endian form. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="ReadEnumeratedValue{TEnum}()"/> public ReadOnlyMemory<byte> ReadEnumeratedBytes() => ReadEnumeratedBytes(Asn1Tag.Enumerated); /// <summary> /// Reads the next value as a Enumerated with a specified tag, returning the contents /// as a <see cref="ReadOnlyMemory{T}"/> over the original data. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <returns> /// The bytes of the Enumerated value, in signed big-endian form. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <seealso cref="ReadEnumeratedValue{TEnum}(Asn1Tag)"/> public ReadOnlyMemory<byte> ReadEnumeratedBytes(Asn1Tag expectedTag) { // T-REC-X.690-201508 sec 8.4 says the contents are the same as for integers. ReadOnlyMemory<byte> contents = GetIntegerContents(expectedTag, UniversalTagNumber.Enumerated, out int headerLength); _data = _data.Slice(headerLength + contents.Length); return contents; } /// <summary> /// Reads the next value as an Enumerated value with tag UNIVERSAL 10, converting it to /// the non-[<see cref="FlagsAttribute"/>] enum specfied by <typeparamref name="TEnum"/>. /// </summary> /// <typeparam name="TEnum">Destination enum type</typeparam> /// <returns> /// the Enumerated value converted to a <typeparamref name="TEnum"/>. /// </returns> /// <remarks> /// This method does not validate that the return value is defined within /// <typeparamref name="TEnum"/>. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <typeparamref name="TEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <typeparamref name="TEnum"/> is not an enum type --OR-- /// <typeparamref name="TEnum"/> was declared with <see cref="FlagsAttribute"/> /// </exception> /// <seealso cref="ReadEnumeratedValue{TEnum}(Asn1Tag)"/> public TEnum ReadEnumeratedValue<TEnum>() where TEnum : struct { Type tEnum = typeof(TEnum); return (TEnum)Enum.ToObject(tEnum, ReadEnumeratedValue(tEnum)); } /// <summary> /// Reads the next value as an Enumerated with tag UNIVERSAL 10, converting it to the /// non-[<see cref="FlagsAttribute"/>] enum specfied by <typeparamref name="TEnum"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <typeparam name="TEnum">Destination enum type</typeparam> /// <returns> /// the Enumerated value converted to a <typeparamref name="TEnum"/>. /// </returns> /// <remarks> /// This method does not validate that the return value is defined within /// <typeparamref name="TEnum"/>. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <typeparamref name="TEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <typeparamref name="TEnum"/> is not an enum type --OR-- /// <typeparamref name="TEnum"/> was declared with <see cref="FlagsAttribute"/> /// --OR-- /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> public TEnum ReadEnumeratedValue<TEnum>(Asn1Tag expectedTag) where TEnum : struct { Type tEnum = typeof(TEnum); return (TEnum)Enum.ToObject(tEnum, ReadEnumeratedValue(expectedTag, tEnum)); } /// <summary> /// Reads the next value as an Enumerated value with tag UNIVERSAL 10, converting it to /// the non-[<see cref="FlagsAttribute"/>] enum specfied by <paramref name="tEnum"/>. /// </summary> /// <param name="tEnum">Type object representing the destination type.</param> /// <returns> /// the Enumerated value converted to a <paramref name="tEnum"/>. /// </returns> /// <remarks> /// This method does not validate that the return value is defined within /// <paramref name="tEnum"/>. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <paramref name="tEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="tEnum"/> is not an enum type --OR-- /// <paramref name="tEnum"/> was declared with <see cref="FlagsAttribute"/> /// </exception> /// <seealso cref="ReadEnumeratedValue(Asn1Tag, Type)"/> public Enum ReadEnumeratedValue(Type tEnum) => ReadEnumeratedValue(Asn1Tag.Enumerated, tEnum); /// <summary> /// Reads the next value as an Enumerated with tag UNIVERSAL 10, converting it to the /// non-[<see cref="FlagsAttribute"/>] enum specfied by <paramref name="tEnum"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="tEnum">Type object representing the destination type.</param> /// <returns> /// the Enumerated value converted to a <paramref name="tEnum"/>. /// </returns> /// <remarks> /// This method does not validate that the return value is defined within /// <paramref name="tEnum"/>. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <paramref name="tEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="tEnum"/> is not an enum type --OR-- /// <paramref name="tEnum"/> was declared with <see cref="FlagsAttribute"/> /// --OR-- /// <paramref name="tEnum"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tEnum"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> public Enum ReadEnumeratedValue(Asn1Tag expectedTag, Type tEnum) { const UniversalTagNumber tagNumber = UniversalTagNumber.Enumerated; // This will throw an ArgumentException if TEnum isn't an enum type, // so we don't need to validate it. Type backingType = tEnum.GetEnumUnderlyingType(); if (tEnum.IsDefined(typeof(FlagsAttribute), false)) { throw new ArgumentException( SR.Cryptography_Asn_EnumeratedValueRequiresNonFlagsEnum, nameof(tEnum)); } // T-REC-X.690-201508 sec 8.4 says the contents are the same as for integers. int sizeLimit = Marshal.SizeOf(backingType); if (backingType == typeof(int) || backingType == typeof(long) || backingType == typeof(short) || backingType == typeof(sbyte)) { if (!TryReadSignedInteger(sizeLimit, expectedTag, tagNumber, out long value)) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } return (Enum)Enum.ToObject(tEnum, value); } if (backingType == typeof(uint) || backingType == typeof(ulong) || backingType == typeof(ushort) || backingType == typeof(byte)) { if (!TryReadUnsignedInteger(sizeLimit, expectedTag, tagNumber, out ulong value)) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } return (Enum)Enum.ToObject(tEnum, value); } Debug.Fail($"No handler for type {backingType.Name}"); throw new CryptographicException(); } } }
using System; using System.Collections.Generic; using System.Globalization; using AllReady.Areas.Admin.ViewModels.Validators; using AllReady.Areas.Admin.ViewModels.Validators.Task; using AllReady.Controllers; using AllReady.DataAccess; using AllReady.Hangfire; using AllReady.Hangfire.Jobs; using AllReady.Models; using AllReady.Providers; using AllReady.Providers.ExternalUserInformationProviders; using AllReady.Providers.ExternalUserInformationProviders.Providers; using AllReady.Security; using AllReady.Services; using Autofac; using Autofac.Extensions.DependencyInjection; using Autofac.Features.Variance; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using AllReady.Security.Middleware; using Newtonsoft.Json.Serialization; using Microsoft.AspNetCore.Cors.Infrastructure; using Geocoding; using Geocoding.Google; using Hangfire; using Hangfire.SqlServer; namespace AllReady { public class Startup { public Startup(IHostingEnvironment env) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("version.json") .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. //builder.AddApplicationInsightsSettings(developerMode: true); builder.AddApplicationInsightsSettings(developerMode: false); } else if (env.IsStaging() || env.IsProduction()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: false); } Configuration = builder.Build(); Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { //Add CORS support. // Must be first to avoid OPTIONS issues when calling from Angular/Browser var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("allReady", corsBuilder.Build()); }); // Add Application Insights data collection services to the services container. services.AddApplicationInsightsTelemetry(Configuration); // Add Entity Framework services to the services container. services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage")); services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection")); services.Configure<EmailSettings>(Configuration.GetSection("Email")); services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData")); services.Configure<GeneralSettings>(Configuration.GetSection("General")); services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter")); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequiredLength = 10; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = true; options.Password.RequireUppercase = false; options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied"); }) .AddEntityFrameworkStores<AllReadyContext>() .AddDefaultTokenProviders(); // Add Authorization rules for the app services.AddAuthorization(options => { options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin")); options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin")); }); // Add MVC services to the services container. // config add to get passed Angular failing on Options request when logging in. services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); //Hangfire services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"])); // configure IoC support var container = CreateIoCContainer(services); return container.Resolve<IServiceProvider>(); } private IContainer CreateIoCContainer(IServiceCollection services) { // todo: move these to a proper autofac module // Register application services. services.AddSingleton((x) => Configuration); services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); services.AddTransient<IDetermineIfATaskIsEditable, DetermineIfATaskIsEditable>(); services.AddTransient<IValidateEventEditViewModels, EventEditViewModelValidator>(); services.AddTransient<ITaskEditViewModelValidator, TaskEditViewModelValidator>(); services.AddTransient<IItineraryEditModelValidator, ItineraryEditModelValidator>(); services.AddTransient<IOrganizationEditModelValidator, OrganizationEditModelValidator>(); services.AddTransient<IRedirectAccountControllerRequests, RedirectAccountControllerRequests>(); services.AddTransient<IConvertDateTimeOffset, DateTimeOffsetConverter>(); services.AddSingleton<IImageService, ImageService>(); services.AddTransient<ISendRequestConfirmationMessagesAWeekBeforeAnItineraryDate, SendRequestConfirmationMessagesAWeekBeforeAnItineraryDate>(); services.AddTransient<ISendRequestConfirmationMessagesADayBeforeAnItineraryDate, SendRequestConfirmationMessagesADayBeforeAnItineraryDate>(); services.AddTransient<ISendRequestConfirmationMessagesTheDayOfAnItineraryDate, SendRequestConfirmationMessagesTheDayOfAnItineraryDate>(); services.AddTransient<SampleDataGenerator>(); if (Configuration["Geocoding:EnableGoogleGeocodingService"] == "true") { //This setting is false by default. To enable Google geocoding you will //need to override this setting in your user secrets or env vars. //Visit https://developers.google.com/maps/documentation/geocoding/get-api-key to get a free standard usage API key services.AddSingleton<IGeocoder>(new GoogleGeocoder(Configuration["Geocoding:GoogleGeocodingApiKey"])); } else { //implement null object pattern to protect against IGeocoder not being passed a legit reference at runtime b/c of the above conditional services.AddSingleton<IGeocoder>(new NullObjectGeocoder()); } if (Configuration["Data:Storage:EnableAzureQueueService"] == "true") { // This setting is false by default. To enable queue processing you will // need to override the setting in your user secrets or env vars. services.AddTransient<IQueueStorageService, QueueStorageService>(); } else { // this writer service will just write to the default logger services.AddTransient<IQueueStorageService, FakeQueueWriterService>(); //services.AddTransient<IQueueStorageService, SmtpEmailSender>(); } var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterSource(new ContravariantRegistrationSource()); containerBuilder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces(); containerBuilder.RegisterAssemblyTypes(typeof(Startup).Assembly).AsImplementedInterfaces(); containerBuilder.Register<SingleInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => c.Resolve(t); }); containerBuilder.Register<MultiInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t)); }); //ExternalUserInformationProviderFactory registration containerBuilder.RegisterType<TwitterExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Twitter"); containerBuilder.RegisterType<GoogleExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Google"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Microsoft"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Facebook"); containerBuilder.RegisterType<ExternalUserInformationProviderFactory>().As<IExternalUserInformationProviderFactory>(); //Hangfire containerBuilder.Register(icomponentcontext => new BackgroundJobClient(new SqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"]))) .As<IBackgroundJobClient>(); //Populate the container with services that were previously registered containerBuilder.Populate(services); var container = containerBuilder.Build(); return container; } // Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration) { // Put first to avoid issues with OPTIONS when calling from Angular/Browser. app.UseCors("allReady"); // todo: in RC update we can read from a logging.json config file loggerFactory.AddConsole((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); if (env.IsDevelopment()) { // this will go to the VS output window loggerFactory.AddDebug((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); } // Configure the HTTP request pipeline. var usCultureInfo = new CultureInfo("en-US"); app.UseRequestLocalization(new RequestLocalizationOptions { SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }), SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo }) }); // Add Application Insights to the request pipeline to track HTTP request telemetry data. app.UseApplicationInsightsRequestTelemetry(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else if (env.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline. app.UseApplicationInsightsExceptionTelemetry(); // Add static files to the request pipeline. app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline. app.UseIdentity(); // Add token-based protection to the request inject pipeline app.UseTokenProtection(new TokenProtectedResourceOptions { Path = "/api/request", PolicyName = "api-request-injest" }); // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 if (Configuration["Authentication:Facebook:AppId"] != null) { var options = new FacebookOptions { AppId = Configuration["Authentication:Facebook:AppId"], AppSecret = Configuration["Authentication:Facebook:AppSecret"], BackchannelHttpHandler = new FacebookBackChannelHandler(), UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name" }; options.Scope.Add("email"); app.UseFacebookAuthentication(options); } if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null) { var options = new MicrosoftAccountOptions { ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"], ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"] }; app.UseMicrosoftAccountAuthentication(options); } //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap if (Configuration["Authentication:Twitter:ConsumerKey"] != null) { var options = new TwitterOptions { ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"], ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"] }; app.UseTwitterAuthentication(options); } if (Configuration["Authentication:Google:ClientId"] != null) { var options = new GoogleOptions { ClientId = Configuration["Authentication:Google:ClientId"], ClientSecret = Configuration["Authentication:Google:ClientSecret"] }; app.UseGoogleAuthentication(options); } //call Migrate here to force the creation of the AllReady database so Hangfire can create its schema under it if (!env.IsProduction()) { context.Database.Migrate(); } //Hangfire app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new [] { new HangireDashboardAuthorizationFilter() }}); app.UseHangfireServer(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Add sample data and test admin accounts if specified in Config.Json. // for production applications, this should either be set to false or deleted. if (Configuration["SampleData:InsertSampleData"] == "true") { sampleData.InsertTestData(); } if (Configuration["SampleData:InsertTestUsers"] == "true") { await sampleData.CreateAdminUser(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Net; using NUnit.Framework; namespace LegacyBounce.Framework.Tests { [TestFixture, Explicit] public class Iis6WebSiteTest { private ManagementScope Scope; [SetUp] public void SetUp() { string host = "localhost"; var options = new ConnectionOptions(); Scope = new ManagementScope(String.Format(@"\\{0}\root\MicrosoftIISV2", host), options); Scope.Connect(); } [Test, STAThread] public void Stuff() { // EnumerateWebsites(scope); // CreateSite(scope); // PrintSite(scope, "IIsWebServer='W3SVC/1180970907'"); // PrintSite(scope, @"IIsWebVirtualDir.Name=""W3SVC/1180970907/root"""); // PrintSite(scope, String.Format("IIsApplicationPool='W3SVC/AppPools/{0}'", "MyNewAppPool")); // PrintSite(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/1180970907/root"""); // PrintSite(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/698587803/root"""); // PrintSite(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/2046576962/root"""); // PrintSite(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/963332529/root"""); // PrintSite(scope, "IIsWebServerSetting.Name='W3SVC/2046576962'"); // SetNTLMAuth(scope, "IIsWebServerSetting.Name='W3SVC/1180970907'"); // SetAuthBasic(scope, "IIsWebServerSetting.Name='W3SVC/1180970907'"); // AuthBasic // AuthNTLM // AuthMD5 // AuthPassport // AuthAnonymous // SetAuth(scope, "IIsWebServerSetting.Name='W3SVC/1180970907'", "AuthAnonymous"); // SetAuth(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/1180970907/root""", "AuthNTLM", false); // PrintSite(scope, "IIsWebServerSetting.Name='W3SVC/1180970907'"); // FindSite(scope, "My New Site"); // EnumerateWebsites(scope, "ScriptMap"); // AddScriptMapToSite(scope, "1180970907"); AddVirtualDirectory(); } [Test] public void AddVirtualDirectory() { var siteId = 1574596940; // var siteId = 1; var dir = "iplayer"; var name = String.Format(@"W3SVC/{0}/root/{1}", siteId, dir); var vDir = new ManagementClass(Scope, new ManagementPath("IIsWebVirtualDirSetting"), null).CreateInstance(); vDir["Name"] = name; vDir["Path"] = @"C:\sites\iplayer"; vDir.Put(); var path = string.Format("IIsWebVirtualDir.Name='{0}'", name); var app = new ManagementObject(Scope, new ManagementPath(path), null); app.InvokeMethod("AppCreate2", new object[] { 2 }); vDir["AppPoolId"] = "GipRegForm.Api"; vDir["AppFriendlyName"] = "stuff"; vDir.Put(); } [Test] public void DeleteVirtualDirectory() { var siteId = 1574596940; // var siteId = 1; var dir = "iplayer"; var name = String.Format(@"W3SVC/{0}/root/{1}", siteId, dir); var path = string.Format("IIsWebVirtualDir.Name='{0}'", name); var app = new ManagementObject(Scope, new ManagementPath(path), null); app.Delete(); } [Test] public void AppPools() { // FindAppPools(scope); // CreateNewAppPool(Scope, "MyNewAppPool"); DeleteAppPool(Scope, "GiP"); // TryFindAppPool(Scope, "MyNewAppPool"); // SetAppPool(scope, @"IIsWebVirtualDirSetting.Name=""W3SVC/1180970907/root""", "Ui.Ingest"); } [Test] public void PrintAppPoolSettings() { // PrintObject(Scope, GetAppPoolPath("GiP")); PrintObject(Scope, GetAppPoolSettingsPath("GiP")); } [Test] public void SetAppPoolIdentity() { IisService service = new IisService("localhost"); IisAppPool appPool = service.FindAppPoolByName("GiP"); appPool.Identity = new Iis6AppPoolIdentity {IdentityType = Iis6AppPoolIdentityType.NetworkService}; } private string GetAppPoolPath(string displayName) { return String.Format("IIsApplicationPool='W3SVC/AppPools/{0}'", displayName); } private string GetAppPoolSettingsPath(string displayName) { return String.Format("IIsApplicationPoolSetting.Name='W3SVC/AppPools/{0}'", displayName); } private void DeleteAppPool(ManagementScope scope, string name) { var pool = new IisAppPool(scope, name); pool.Delete(); } private void TryFindAppPool(ManagementScope scope, string name) { var service = new IisService("localhost"); IisAppPool appPool = service.FindAppPoolByName(name); Console.WriteLine("found app pool: " + (appPool != null)); } private void CreateNewAppPool(ManagementScope scope, string name) { ManagementObject appPool = new ManagementClass(scope, new ManagementPath("IIsApplicationPoolSetting"), null).CreateInstance(); appPool["Name"] = String.Format("W3SVC/AppPools/{0}", name); appPool.Put(); } private void SetAppPool(ManagementScope scope, string path, string appPoolId) { var site = new ManagementObject(scope, new ManagementPath(path), null); site["AppPoolId"] = appPoolId; site.Put(); } void SetNTLMAuth(ManagementScope scope, string path) { var site = new ManagementObject(scope, new ManagementPath(path), null); site["AuthNTLM"] = true; site.Put(); } void SetAuthBasic(ManagementScope scope, string path) { var site = new ManagementObject(scope, new ManagementPath(path), null); site["AuthBasic"] = true; site.Put(); } void SetAuth(ManagementScope scope, string path, string authSetting, bool setting) { var site = new ManagementObject(scope, new ManagementPath(path), null); site[authSetting] = setting; site.Put(); } [Test] public void ShouldFindSiteByServerComment() { var server = new WebServer("localhost"); WebSite site = server.TryGetWebSiteByServerComment("My New Site"); Assert.That(site.ServerComment, Is.EqualTo("My New Site")); Assert.That(site.Bindings.Count(), Is.EqualTo(1)); WebSiteBinding binding = site.Bindings.ElementAt(0); Assert.That(binding.Port, Is.EqualTo(6060)); Assert.That(binding.Hostname, Is.Null); Assert.That(binding.IPAddress, Is.Null); } [Test] public void ShouldAddHostHeaders() { var server = new WebServer("localhost"); WebSite webSite = server.CreateWebSite("A new site!", new[] {new WebSiteBinding {Port = 6020}}, @"c:\anewsite"); } [Test] public void ShouldAddNewSite() { var server = new WebServer("localhost"); WebSite site = server.CreateWebSite("A new site!", new [] {new WebSiteBinding {Port = 6020}}, @"c:\anewsite"); } [Test] public void ShouldDelete() { var server = new WebServer("localhost"); WebSite site = server.TryGetWebSiteByServerComment("A new site!"); if (site != null) { Console.WriteLine("deleting"); site.Delete(); } } [Test] public void ShouldStart() { var server = new WebServer("localhost"); WebSite site = server.TryGetWebSiteByServerComment("My New Site"); site.Start(); } [Test] public void ShouldStop() { var server = new WebServer("localhost"); WebSite site = server.TryGetWebSiteByServerComment("My New Site"); site.Stop(); } [Test] public void ShouldGetState() { var server = new WebServer("localhost"); WebSite site = server.TryGetWebSiteByServerComment("My New Site"); Console.WriteLine(site.State); } private void FindSite(ManagementScope scope, string serverComment) { var query = new ManagementObjectSearcher(scope, new ObjectQuery(String.Format("select * from IIsWebServerSetting where ServerComment = '{0}'", serverComment.Replace("'", "''")))); ManagementObjectCollection websites = query.Get(); foreach (var website in websites) { Console.WriteLine(website.Properties["Name"].Value + ":"); foreach (var prop in website.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("system props:"); foreach (var prop in website.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } } } private void FindAppPools(ManagementScope scope) { var query = new ManagementObjectSearcher(scope, new ObjectQuery(String.Format("select * from IIsApplicationPool"))); ManagementObjectCollection websites = query.Get(); foreach (var website in websites) { Console.WriteLine(website.Properties["Name"].Value + ":"); foreach (var prop in website.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("system props:"); foreach (var prop in website.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } } } private void AddScriptMapToSite(ManagementScope scope, string siteId, ScriptMap scriptMap) { var site = new ManagementObject(scope, new ManagementPath(String.Format(@"IIsWebVirtualDirSetting.Name=""W3SVC/{0}/root""", siteId)), null); var scriptMaps = (ManagementBaseObject[]) site["ScriptMaps"]; var newScriptMaps = new ManagementBaseObject[scriptMaps.Length + 1]; scriptMaps.CopyTo(newScriptMaps, 0); ManagementObject newScriptMap = new ManagementClass(scope, new ManagementPath("ScriptMap"), null).CreateInstance(); newScriptMap["Extensions"] = scriptMap.Extension; newScriptMap["Flags"] = scriptMap.Flags; newScriptMap["IncludedVerbs"] = scriptMap.IncludedVerbs; newScriptMap["ScriptProcessor"] = scriptMap.Executable; newScriptMaps[newScriptMaps.Length - 1] = newScriptMap; site["ScriptMaps"] = newScriptMaps; site.Put(); } private void AddScriptMapToSite(ManagementScope scope, string siteId) { var scriptMap = new ScriptMap { Executable = @"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll", Extension = ".mvc", }; AddScriptMapToSite(scope, siteId, scriptMap); } class ScriptMap { public string Extension; public int Flags { get { return (ScriptEngine ? 1 : 0) + (VerifyThatFileExists ? 4 : 0); } } public bool ScriptEngine; public bool VerifyThatFileExists; public bool AllVerbs { get { return _allVerbs; } set { _allVerbs = value; _includedVerbs = ""; } } public string IncludedVerbs { get { return _includedVerbs; } set { _includedVerbs = value; _allVerbs = false; } } public string Executable; private bool _allVerbs; private string _includedVerbs; public ScriptMap () { AllVerbs = true; ScriptEngine = true; VerifyThatFileExists = true; } } private void PrintSite(ManagementScope scope, string path) { var site = new ManagementObject(scope, new ManagementPath(path), null); object desc = site["Description"]; foreach (var rel in site.GetRelationships()) { Console.WriteLine("rel: " + rel); } foreach (var rel in site.GetRelated()) { Console.WriteLine("related: " + rel); } Console.WriteLine("props:"); foreach (var prop in site.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("system props:"); foreach (var prop in site.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("scriptmap:"); foreach (var scriptMap in (ManagementBaseObject[]) site["ScriptMaps"]) { Console.WriteLine(" props:"); foreach (var prop in scriptMap.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine(" system props:"); foreach (var prop in scriptMap.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } } } private void PrintObject(ManagementScope scope, string path) { var site = new ManagementObject(scope, new ManagementPath(path), null); object desc = site["Description"]; foreach (var rel in site.GetRelationships()) { Console.WriteLine("rel: " + rel); } foreach (var rel in site.GetRelated()) { Console.WriteLine("related: " + rel); } Console.WriteLine("props:"); foreach (var prop in site.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("system props:"); foreach (var prop in site.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } } private void EnumerateWebsites(ManagementScope scope, string _class) { var query = new ManagementObjectSearcher(scope, new ObjectQuery("select * from " + _class)); ManagementObjectCollection websites = query.Get(); foreach (var website in websites) { Console.WriteLine(website.Properties["Name"].Value + ":"); foreach (var prop in website.Properties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } Console.WriteLine("system props:"); foreach (var prop in website.SystemProperties) { Console.WriteLine(" {0}: {1}", prop.Name, prop.Value); } } } private void CreateSite(ManagementScope scope) { var serverBinding = new ManagementClass(scope, new ManagementPath("ServerBinding"), null).CreateInstance(); serverBinding["Port"] = "6060"; var iis = new ManagementObject(scope, new ManagementPath("IIsWebService='W3SVC'"), null); ManagementBaseObject createNewSiteArgs = iis.GetMethodParameters("CreateNewSite"); createNewSiteArgs["ServerComment"] = "My New Site"; createNewSiteArgs["ServerBindings"] = new[] {serverBinding}; createNewSiteArgs["PathOfRootVirtualDir"] = @"c:\somedirectory"; var result = iis.InvokeMethod("CreateNewSite", createNewSiteArgs, null); Console.WriteLine(result["ReturnValue"]); } class WebSite { private readonly ManagementObject webSite; private readonly ManagementObject settings; public WebSite(ManagementScope scope, string path) { webSite = new ManagementObject(scope, new ManagementPath(path), null); settings = new ManagementObject(scope, new ManagementPath(String.Format("IIsWebServerSetting.Name='{0}'", webSite["Name"])), null); } public string ServerComment { get { return (string) settings["ServerComment"]; } } public IEnumerable<WebSiteBinding> Bindings { get { var bindings = (ManagementBaseObject[]) settings["ServerBindings"]; return bindings.Select(b => CreateWebSiteBinding(b)).ToArray(); } } public WebSiteState State { get { var state = (int) webSite["ServerState"]; switch (state) { case 1: return WebSiteState.Starting; case 2: return WebSiteState.Started; case 3: return WebSiteState.Stopping; case 4: return WebSiteState.Stopped; case 5: return WebSiteState.Pausing; case 6: return WebSiteState.Paused; case 7: return WebSiteState.Continuing; default: throw new Exception(string.Format("didn't expect website serverstate of {0}", state)); } } } private static WebSiteBinding CreateWebSiteBinding(ManagementBaseObject binding) { var ip = (string) binding["IP"]; var hostname = (string) binding["Hostname"]; return new WebSiteBinding { Hostname = String.IsNullOrEmpty(hostname)? null: hostname, IPAddress = (String.IsNullOrEmpty(ip)? null: IPAddress.Parse(ip)), Port = int.Parse((string) binding["Port"]) }; } public void Delete() { webSite.Delete(); } public void Start() { webSite.InvokeMethod("Start", new object[0]); } public void Stop() { webSite.InvokeMethod("Stop", new object[0]); } } class WebSiteBinding { public string Hostname; public int Port; public IPAddress IPAddress; } class WebServer { private ManagementScope scope; public WebServer(string host) { var options = new ConnectionOptions(); scope = new ManagementScope(String.Format(@"\\{0}\root\MicrosoftIISV2", host), options); scope.Connect(); } public WebSite TryGetWebSiteByServerComment(string serverComment) { var query = new ManagementObjectSearcher(scope, new ObjectQuery(String.Format("select * from IIsWebServerSetting where ServerComment = '{0}'", serverComment))); ManagementObjectCollection websites = query.Get(); foreach (var website in websites) { return new WebSite(scope, String.Format("IIsWebServer='{0}'", website["Name"])); } return null; } public WebSite CreateWebSite(string serverComment, IEnumerable<WebSiteBinding> bindings, string documentRoot) { var iis = new ManagementObject(scope, new ManagementPath("IIsWebService='W3SVC'"), null); ManagementBaseObject createNewSiteArgs = iis.GetMethodParameters("CreateNewSite"); createNewSiteArgs["ServerComment"] = serverComment; createNewSiteArgs["ServerBindings"] = bindings.Select(b => CreateBinding(b)).ToArray(); createNewSiteArgs["PathOfRootVirtualDir"] = documentRoot; var result = iis.InvokeMethod("CreateNewSite", createNewSiteArgs, null); var id = (string) result["ReturnValue"]; return new WebSite(scope, id); } private ManagementObject CreateBinding(WebSiteBinding binding) { ManagementObject serverBinding = new ManagementClass(scope, new ManagementPath("ServerBinding"), null).CreateInstance(); serverBinding["Port"] = binding.Port.ToString(); if (binding.Hostname != null) { serverBinding["Hostname"] = binding.Hostname; } if (binding.IPAddress != null) { serverBinding["IP"] = binding.IPAddress.ToString(); } return serverBinding; } } } internal enum WebSiteState { Starting, Started, Stopping, Stopped, Pausing, Paused, Continuing } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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 Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace Aurora.Modules.Entities.EntityCount { public class EntityCountModule : INonSharedRegionModule, IEntityCountModule { #region Declares private readonly Dictionary<UUID, bool> m_lastAddedPhysicalStatus = new Dictionary<UUID, bool>(); private readonly object m_objectsLock = new object(); private int m_activeObjects; private int m_childAgents; private int m_objects; private int m_rootAgents; #endregion #region IEntityCountModule Members public int RootAgents { get { return m_rootAgents; } } public int ChildAgents { get { return m_childAgents; } } public int Objects { get { return m_objects; } } public int ActiveObjects { get { return m_activeObjects; } } #endregion #region INonSharedRegionModule Members public void Initialise(IConfigSource source) { } public void AddRegion(IScene scene) { scene.RegisterModuleInterface<IEntityCountModule>(this); scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnNewPresence += OnNewPresence; scene.EventManager.OnRemovePresence += OnRemovePresence; scene.EventManager.OnObjectBeingAddedToScene += OnObjectBeingAddedToScene; scene.EventManager.OnObjectBeingRemovedFromScene += OnObjectBeingRemovedFromScene; scene.AuroraEventManager.RegisterEventHandler("ObjectChangedPhysicalStatus", OnGenericEvent); } public void RegionLoaded(IScene scene) { } public void RemoveRegion(IScene scene) { } public void Close() { } public string Name { get { return "EntityCountModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region Events #region Agents protected void OnMakeChildAgent(IScenePresence presence, GridRegion destination) { //Switch child agent to root agent m_rootAgents--; m_childAgents++; } protected void OnMakeRootAgent(IScenePresence presence) { m_rootAgents++; m_childAgents--; } protected void OnNewPresence(IScenePresence presence) { // Why don't we check for root agents? We don't because it will be added in MakeRootAgent and removed from here m_childAgents++; } private void OnRemovePresence(IScenePresence presence) { if (presence.IsChildAgent) m_childAgents--; else m_rootAgents--; } #endregion #region Objects protected void OnObjectBeingAddedToScene(ISceneEntity obj) { lock (m_objectsLock) { foreach (ISceneChildEntity child in obj.ChildrenEntities()) { bool physicalStatus = (child.Flags & PrimFlags.Physics) == PrimFlags.Physics; if (!m_lastAddedPhysicalStatus.ContainsKey(child.UUID)) { m_objects++; //Check physical status now if (physicalStatus) m_activeObjects++; //Add it to the list so that we have a record of it m_lastAddedPhysicalStatus.Add(child.UUID, physicalStatus); } else { //Its a dupe! Its a dupe! // Check that the physical status has changed if (physicalStatus != m_lastAddedPhysicalStatus[child.UUID]) { //It changed... fix the count if (physicalStatus) m_activeObjects++; else m_activeObjects--; //Update the cache m_lastAddedPhysicalStatus[child.UUID] = physicalStatus; } } } } } protected void OnObjectBeingRemovedFromScene(ISceneEntity obj) { lock (m_objectsLock) { foreach (ISceneChildEntity child in obj.ChildrenEntities()) { bool physicalStatus = (child.Flags & PrimFlags.Physics) == PrimFlags.Physics; if (m_lastAddedPhysicalStatus.ContainsKey(child.UUID)) { m_objects--; //Check physical status now and remove if necessary if (physicalStatus) m_activeObjects--; //Remove our record of it m_lastAddedPhysicalStatus.Remove(child.UUID); } } } } protected object OnGenericEvent(string FunctionName, object parameters) { //If the object changes physical status, we need to make sure to update the active objects count if (FunctionName == "ObjectChangedPhysicalStatus") { OnObjectBeingAddedToScene((SceneObjectGroup) parameters); } return null; } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Diagnostics; using System.IO.Ports; using SysWinForms = System.Windows.Forms; using System.IO; namespace LaserHarp { public class LaserHarpGame : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SerialPort serialPort; bool connected = false; bool heartbeatDetected = false; MainForm mainForm; const int numberOfNotes = 8; SoundToPlay[] sounds; List<SoundEffect> noteSoundEffects = new List<SoundEffect>(); List<SoundEffectInstance> noteSoundEffectInstances = new List<SoundEffectInstance>(); KeyboardState oldKeyboardState = Keyboard.GetState(); public LaserHarpGame() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 200; graphics.PreferredBackBufferHeight = 100; Content.RootDirectory = "Content"; } protected override void Initialize() { SysWinForms.Form gameWindowForm = (SysWinForms.Form)SysWinForms.Form.FromHandle(this.Window.Handle); gameWindowForm.Shown += new EventHandler(gameWindowForm_Shown); mainForm = new MainForm(); mainForm.HandleDestroyed += new EventHandler(mainForm_HandleDestroyed); mainForm.StateChanged += new EventHandler(mainForm_StateChanged); mainForm.Show(); base.Initialize(); } void OpenSerialPort() { if (connected) CloseSerialPort(); mainForm.Started = true; string serialPortName = SerialPort.GetPortNames().FirstOrDefault(); if (!string.IsNullOrEmpty(serialPortName)) { try { serialPort = new SerialPort(serialPortName, 57600, Parity.None, 8, StopBits.One); serialPort.Open(); serialPort.DataReceived += serialPort_DataReceived; serialPort.ErrorReceived += serialPort_ErrorReceived; heartbeatDetected = false; } catch (Exception e) { mainForm.ErrorMessage(e.Message); } } else { mainForm.ErrorMessage("No serial ports detected."); } connected = true; } void CloseSerialPort() { if (connected) { if (serialPort != null) { if (serialPort.IsOpen) serialPort.Close(); serialPort = null; } connected = false; mainForm.Started = false; } } private void mainForm_StateChanged(object sender, EventArgs e) { if (mainForm.Started) { LoadSounds(); OpenSerialPort(); } else { CloseSerialPort(); UnloadSounds(); } } void mainForm_HandleDestroyed(object sender, EventArgs e) { this.Exit(); } void gameWindowForm_Shown(object sender, EventArgs e) { ((SysWinForms.Form)sender).Hide(); } void serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { mainForm.ErrorMessage("Error: " + e.EventType.ToString()); CloseSerialPort(); } void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string buffer = serialPort.ReadExisting(); foreach (char inputChar in buffer.ToCharArray()) { int note; if (inputChar == '~') { // begin monitoring for real data heartbeatDetected = true; mainForm.DataReceived(); } else if (inputChar == '@') { // debug input being printed, do not interpret as data heartbeatDetected = false; } else if (heartbeatDetected && inputChar >= 'A' && inputChar <= 'H') { note = inputChar - 'A'; UpdateSound(note, true); } else if (heartbeatDetected && inputChar >= 'a' && inputChar <= 'h') { note = inputChar - 'a'; UpdateSound(note, false); } } } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); } protected override void UnloadContent() { } void LoadSounds() { sounds = mainForm.Sounds; noteSoundEffects.Clear(); noteSoundEffectInstances.Clear(); for (int i = 0; i < numberOfNotes; ++i) { if (sounds[i] != null) { SoundEffect effect; using (Stream stm = new FileStream(sounds[i].soundFile.fileName, FileMode.Open)) { effect = SoundEffect.FromStream(stm); } this.noteSoundEffects.Add(effect); this.noteSoundEffectInstances.Add(CreateSoundEffectInstance(i)); } else { this.noteSoundEffects.Add(null); this.noteSoundEffectInstances.Add(null); } } // Start all the continuous looping notes so they are syncronized. for (int i = 0; i < numberOfNotes; ++i) { if (sounds[i] != null && sounds[i].playMode == PlayMode.ContinuousLoop) { noteSoundEffectInstances[i].Volume = 0; noteSoundEffectInstances[i].IsLooped = true; noteSoundEffectInstances[i].Play(); } if (sounds[i] != null && sounds[i].playMode == PlayMode.Looping) { noteSoundEffectInstances[i].IsLooped = true; } } } SoundEffectInstance CreateSoundEffectInstance(int note) { SoundEffectInstance noteInstance = noteSoundEffects[note].CreateInstance(); noteInstance.Pitch = sounds[note].pitchShiftInSemitones * (1.0F / 12.0F); noteInstance.Volume = sounds[note].volume; return noteInstance; } void UnloadSounds() { for (int i = 0; i < noteSoundEffects.Count; ++i) { if (noteSoundEffectInstances[i] != null) { noteSoundEffectInstances[i].Stop(); noteSoundEffectInstances[i].Dispose(); } if (noteSoundEffects[i] != null) { noteSoundEffects[i].Dispose(); } } noteSoundEffects.Clear(); noteSoundEffectInstances.Clear(); } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); KeyboardState newKeyboardState = Keyboard.GetState(); for (Keys key = Keys.NumPad1; key <= Keys.NumPad8; key++) { if (newKeyboardState.IsKeyDown(key) && !oldKeyboardState.IsKeyDown(key)) UpdateSound(key - Keys.NumPad1, true); else if (!newKeyboardState.IsKeyDown(key) && oldKeyboardState.IsKeyDown(key)) UpdateSound(key - Keys.NumPad1, false); } for (Keys key = Keys.D1; key <= Keys.D8; key++) { if (newKeyboardState.IsKeyDown(key) && !oldKeyboardState.IsKeyDown(key)) UpdateSound(key - Keys.D1, true); else if (!newKeyboardState.IsKeyDown(key) && oldKeyboardState.IsKeyDown(key)) UpdateSound(key - Keys.D1, false); } oldKeyboardState = newKeyboardState; base.Update(gameTime); } private void UpdateSound(int note, bool on) { if (connected && note >= 0 && note < noteSoundEffects.Count && this.noteSoundEffects[note] != null) { PlayMode mode = sounds[note].playMode; SoundEffect soundEffect = this.noteSoundEffects[note]; SoundEffectInstance soundEffectInstance = noteSoundEffectInstances[note]; switch (mode) { case PlayMode.Once: if (on) { // Create a new sound effect instance each time, so that multiple can play at once. soundEffectInstance = CreateSoundEffectInstance(note); soundEffectInstance.Play(); } break; case PlayMode.OnOff: if (on) soundEffectInstance.Play(); else soundEffectInstance.Stop(); break; case PlayMode.Looping: if (on) soundEffectInstance.Play(); else soundEffectInstance.Stop(); break; case PlayMode.ContinuousLoop: if (on) soundEffectInstance.Volume = sounds[note].volume; else soundEffectInstance.Volume = 0; break; } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(this.connected ? Color.Black : Color.Red); base.Draw(gameTime); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows.Input; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using System.Threading.Tasks; using System.Windows.Threading; using ArcGIS.Core.CIM; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; using BingStreetside.Utility; namespace BingStreetside { /// <summary> /// This sample demonstrates the usagle of the WebBrowser control and how to interface between C# and HTML5/JavaScript and vise versa. /// The sample is using a Bing Map's Streetside API to demonstrate these functions. In order to use this sample you have to apply with Bing Maps for a Bing Maps API developer key. You can find the instructions on how to do this below. /// </summary> /// <remarks> /// Using Bing Maps API: To use the Bing Maps APIs, you must have a (Bing Maps Key)[https://msdn.microsoft.com/en-us/library/dd877180.aspx]. /// Note: When you use the Bing Maps APIs with a Bing Maps Key, usage transactions are logged. See Understanding (Bing Maps Transactions)[https://msdn.microsoft.com/en-us/library/ff859477.aspx] for more information. /// Creating a Bing Maps Key /// 1. Go to the Bing Maps Dev Center at https://www.bingmapsportal.com/. /// ** If you have a Bing Maps account, sign in with the Microsoft account that you used to create the account or create a new one.For new accounts, follow the instructions in (Creating a Bing Maps Account)[https://msdn.microsoft.com/en-us/library/gg650598.aspx]. /// 2. Select Keys under My Account. /// 3. Provide the following information to create a key: /// ** Application name: Required.The name of the application. /// ** Application URL: The URL of the application. /// ** Key type: Required. Select the key type that you want to create.You can find descriptions of key and application types (here)[https://www.microsoft.com/maps/create-a-bing-maps-key.aspx]. /// ** Application type: Required. Select the application type that best represents the application that will use this key.You can find descriptions of key and application types (here)[https://www.microsoft.com/maps/create-a-bing-maps-key.aspx]. /// 4. Type the characters of the security code, and then click Create. The new key displays in the list of available keys.Use this key to authenticate your Bing Maps application as described in the documentation for the Bing Maps API you are using. /// /// Note: the Bing map preview SDK overview used in this sample can be found here: https://www.bing.com/mapspreview/sdk/mapcontrol/isdk#overview /// /// Using the sample: /// 1. In Visual Studio click the Build menu. Then select Build Solution. /// 1. Click Start button to open ArcGIS Pro. /// 1. ArcGIS Pro will open. /// 1. Create a new project using the Map.aptx template. /// 1. With a map view active go to the "Bing Streetside" tab and click the "Show Bing Streetside Pane" button. /// 1. This will open the "Bing Streetside Viewer" dock pane. /// ![UI](Screenshots/screenshot1.png) /// 1. Paste the "Bing Maps Key" that you obtained from Microsoft (see instructions above) and click the "Define Bing Map Key" button. /// 1. For convenience you can also define your Bing Key under the following code comment: "TODO: define your bing map key here:" /// 1. The "Bing Streetside Viewer" dock pane now displays Bing Map's street view pane (starting at Esri). /// ![UI](Screenshots/screenshot2.png) /// 1. Click on the "N New York St" arrow pointing north on the "Bing Streetside Viewer" and see the location on the map pane being updated. /// ![UI](Screenshots/screenshot3.png) /// 1. The view heading on the "Bing Map Streetside" view can be changed by clicking on the "Change Heading" control above the "Bing Map Streetside" control and dragging the heading arrow into a new direction. /// ![UI](Screenshots/screenshot4.png) /// 1. Click the "Bing Streetside View Tool" button and click on a new street location on the map pane. /// 1. Notice that "Bing Map Streetside" will update it's view to the new clicked on location. /// ![UI](Screenshots/screenshot5.png) /// </remarks> internal class BingStreetsideModule : Module { private static BingStreetsideModule _this = null; /// <summary> /// Retrieve the singleton instance to this module here /// </summary> public static BingStreetsideModule Current { get { return _this ?? (_this = (BingStreetsideModule)FrameworkApplication.FindModule("BingStreetside_Module")); } } public BingStreetsideModule() { SetupOverlaySymbols(); } #region Overrides /// <summary> /// Called by Framework when ArcGIS Pro is closing /// </summary> /// <returns>False to prevent Pro from closing, otherwise True</returns> protected override bool CanUnload() { //TODO - add your business logic //return false to ~cancel~ Application close return true; } #endregion Overrides #region Overlay symbols/add/remove graphics private static readonly List<IDisposable> BingMapCoords = new List<IDisposable>(); private static CIMPointSymbol _pointCoordSymbol = null; private readonly static object Lock = new object(); public static void ShowCurrentBingMapCoord(MapPoint mapPoint) { var activeMapView = MapView.Active; if (activeMapView == null) return; lock (Lock) { foreach (var graphic in BingMapCoords) graphic.Dispose(); BingMapCoords.Clear(); Debug.WriteLine($"SetCurrentBingMapCoord: {mapPoint.X} {mapPoint.Y}"); BingMapCoords.Add( activeMapView.AddOverlay( mapPoint, _pointCoordSymbol.MakeSymbolReference())); } } private static void SetupOverlaySymbols() { QueuedTask.Run(() => { var markerCoordPoint = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.GreenRGB, 12, SimpleMarkerStyle.Circle); _pointCoordSymbol = SymbolFactory.Instance.ConstructPointSymbol(markerCoordPoint); }); } #endregion Overlay symbols/add/remove graphics private static bool _bFirst = true; /// <summary>Get the Lat, Long from the Bing StreetSide View to set the location on the Pro Map</summary> public static Task SetMapLocationFromBing(double? longitude, double? latitude, int heading) { #region Process Heading var activeMapView = MapView.Active; if (activeMapView == null) return null; #endregion return QueuedTask.Run(() => { try { var cam = activeMapView.Camera; var bHeadingChange = Convert.ToInt32(cam.Heading) != heading; cam.Heading = Convert.ToDouble(heading); if (longitude.HasValue && latitude.HasValue) { var pt = MapPointBuilder.CreateMapPoint(longitude.Value, latitude.Value, SpatialReferences.WGS84); var center = GeometryEngine.Instance.Project(pt, activeMapView.Map.SpatialReference) as MapPoint; if (center == null) return; ShowCurrentBingMapCoord(center); #region Update Map // check if the center is outside the map view extent var env = activeMapView.Extent.Expand(0.75, 0.75, true); var bWithin = GeometryEngine.Instance.Within(center, env); if (!bWithin) { cam.X = center.X; cam.Y = center.Y; } if (_bFirst) { cam.Scale = 2000; activeMapView.ZoomTo(cam, TimeSpan.FromMilliseconds(100)); _bFirst = false; } else activeMapView.PanTo(cam, TimeSpan.FromMilliseconds(1000)); bHeadingChange = false; #endregion } if (bHeadingChange) { activeMapView.PanTo(cam, TimeSpan.FromMilliseconds(300)); } } catch (Exception ex) { Debug.WriteLine($@"Error in SetMapLocationFromBing: {ex.Message}"); } }); } public static void SetMapLocationOnBingMaps(double lng, double lat) { WebBrowserUtility.InvokeScript("setViewCenterFromWPF", new Object[] {lng, lat}); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using System; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Text.RegularExpressions; using Sensus.UI.Inputs; using Sensus.Probes.User.Scripts; using System.IO; namespace Sensus.UI { public class ScriptInputsPage : ContentPage { public ScriptInputsPage(InputGroup inputGroup, List<InputGroup> previousInputGroups, Script script) { Title = "Inputs"; ListView inputsList = new ListView(ListViewCachingStrategy.RecycleElement); inputsList.ItemTemplate = new DataTemplate(typeof(TextCell)); inputsList.ItemTemplate.SetBinding(TextCell.TextProperty, nameof(Input.Caption)); inputsList.ItemsSource = inputGroup.Inputs; inputsList.ItemTapped += async (o, e) => { if (inputsList.SelectedItem == null) { return; } Input selectedInput = inputsList.SelectedItem as Input; int selectedIndex = inputGroup.Inputs.IndexOf(selectedInput); List<string> actions = new List<string>(); if (selectedIndex > 0) { actions.Add("Move Up"); } if (selectedIndex < inputGroup.Inputs.Count - 1) { actions.Add("Move Down"); } actions.Add("Edit"); if (previousInputGroups != null && previousInputGroups.Select(previousInputGroup => previousInputGroup.Inputs.Count).Sum() > 0) { actions.Add("Add Display Condition"); } if (selectedInput.DisplayConditions.Count > 0) { actions.AddRange(new string[] { "View Display Conditions" }); } actions.Add("Copy"); actions.Add("Delete"); string selectedAction = await DisplayActionSheet(selectedInput.Name, "Cancel", null, actions.ToArray()); if (selectedAction == "Move Up") { inputGroup.Inputs.Move(selectedIndex, selectedIndex - 1); } else if (selectedAction == "Move Down") { inputGroup.Inputs.Move(selectedIndex, selectedIndex + 1); } else if (selectedAction == "Edit") { ScriptInputPage inputPage = new ScriptInputPage(selectedInput); await Navigation.PushAsync(inputPage); inputsList.SelectedItem = null; } else if (selectedAction == "Add Display Condition") { string abortMessage = "Condition is not complete. Abort?"; List<Input> inputs = await SensusServiceHelper.Get().PromptForInputsAsync("Display Condition", new Input[] { new ItemPickerPageInput("Input:", previousInputGroups.SelectMany(previousInputGroup => previousInputGroup.Inputs.Cast<object>()).ToList()), new ItemPickerPageInput("Condition:", Enum.GetValues(typeof(InputValueCondition)).Cast<object>().ToList()), new ItemPickerPageInput("Conjunctive/Disjunctive:", new object[] { "Conjunctive", "Disjunctive" }.ToList()) }, null, true, null, null, abortMessage, null, false); if (inputs == null) { return; } if (inputs.All(input => input.Valid)) { Input conditionInput = ((inputs[0] as ItemPickerPageInput).Value as IEnumerable<object>).First() as Input; InputValueCondition condition = (InputValueCondition)((inputs[1] as ItemPickerPageInput).Value as IEnumerable<object>).First(); bool conjunctive = ((inputs[2] as ItemPickerPageInput).Value as IEnumerable<object>).First().Equals("Conjunctive"); if (condition == InputValueCondition.IsComplete) { selectedInput.DisplayConditions.Add(new InputDisplayCondition(conditionInput, condition, null, conjunctive)); } else { Regex uppercaseSplitter = new Regex(@" (?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace); // show the user a required copy of the condition input and prompt for the condition value Input conditionInputCopy = conditionInput.Copy(false); conditionInputCopy.DisplayConditions.Clear(); conditionInputCopy.LabelText = "Value that " + conditionInputCopy.Name + " " + uppercaseSplitter.Replace(condition.ToString(), " ").ToLower() + ":"; conditionInputCopy.Required = true; // ensure that the copied input cannot define a variable if (conditionInputCopy is IVariableDefiningInput) { (conditionInputCopy as IVariableDefiningInput).DefinedVariable = null; } Input input = await SensusServiceHelper.Get().PromptForInputAsync("Display Condition", conditionInputCopy, null, true, "OK", null, abortMessage, null, false); if (input?.Valid ?? false) { selectedInput.DisplayConditions.Add(new InputDisplayCondition(conditionInput, condition, input.Value, conjunctive)); } } } } else if (selectedAction == "View Display Conditions") { await Navigation.PushAsync(new ViewTextLinesPage("Display Conditions", selectedInput.DisplayConditions.Select(displayCondition => displayCondition.ToString()).ToList(), () => { selectedInput.DisplayConditions.Clear(); })); } else if(selectedAction == "Copy") { inputGroup.Inputs.Add(selectedInput.Copy(true)); } else if (selectedAction == "Delete") { if (await DisplayAlert("Delete " + selectedInput.Name + "?", "This action cannot be undone.", "Delete", "Cancel")) { if (selectedInput is MediaInput mediaInput) { MediaObject.ClearCache(script.Runner, inputGroup, mediaInput); } inputGroup.Inputs.Remove(selectedInput); inputsList.SelectedItem = null; // manually reset, since it isn't done automatically. } } }; ToolbarItems.Add(new ToolbarItem(null, "plus.png", async () => { List<Input> inputs = Assembly.GetExecutingAssembly() .GetTypes() .Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Input))) .Select(t => Activator.CreateInstance(t)) .Cast<Input>() .OrderBy(i => i.Name) .ToList(); string cancelButtonName = "Cancel"; string selected = await DisplayActionSheet("Select Input Type", cancelButtonName, null, inputs.Select((input, index) => (index + 1) + ") " + input.Name).ToArray()); if (!string.IsNullOrWhiteSpace(selected) && selected != cancelButtonName) { Input input = inputs[int.Parse(selected.Substring(0, selected.IndexOf(")"))) - 1]; if (input is VoiceInput && inputGroup.Inputs.Count > 0 || !(input is VoiceInput) && inputGroup.Inputs.Any(i => i is VoiceInput)) { await SensusServiceHelper.Get().FlashNotificationAsync("Voice inputs must reside in groups by themselves."); } else { if (input is MediaInput mediaInput) { mediaInput.SetCachePath(script.Runner, inputGroup); } else if (input is ScriptSchedulerInput scriptSchedulerInput) { scriptSchedulerInput.Runner = script.Runner; } inputGroup.Inputs.Add(input); await Navigation.PushAsync(new ScriptInputPage(input)); } } })); Content = inputsList; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> using System; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Security.Policy; namespace System.Runtime.InteropServices { [GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")] [CLSCompliant(false)] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [TypeLibImportClassAttribute(typeof(System.Type))] [System.Runtime.InteropServices.ComVisible(true)] public interface _Type { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region Type Members Guid GUID { get; } Module Module { get; } Assembly Assembly { get; } RuntimeTypeHandle TypeHandle { get; } String FullName { get; } String Namespace { get; } String AssemblyQualifiedName { get; } int GetArrayRank(); Type BaseType { get; } ConstructorInfo[] GetConstructors(BindingFlags bindingAttr); Type GetInterface(String name, bool ignoreCase); Type[] GetInterfaces(); Type[] FindInterfaces(TypeFilter filter,Object filterCriteria); EventInfo GetEvent(String name,BindingFlags bindingAttr); EventInfo[] GetEvents(); EventInfo[] GetEvents(BindingFlags bindingAttr); Type[] GetNestedTypes(BindingFlags bindingAttr); Type GetNestedType(String name, BindingFlags bindingAttr); MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr); MemberInfo[] GetDefaultMembers(); MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria); Type GetElementType(); bool IsSubclassOf(Type c); bool IsInstanceOfType(Object o); bool IsAssignableFrom(Type c); InterfaceMapping GetInterfaceMap(Type interfaceType); MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); MethodInfo GetMethod(String name, BindingFlags bindingAttr); MethodInfo[] GetMethods(BindingFlags bindingAttr); FieldInfo GetField(String name, BindingFlags bindingAttr); FieldInfo[] GetFields(BindingFlags bindingAttr); PropertyInfo GetProperty(String name, BindingFlags bindingAttr); PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); PropertyInfo[] GetProperties(BindingFlags bindingAttr); MemberInfo[] GetMember(String name, BindingFlags bindingAttr); MemberInfo[] GetMembers(BindingFlags bindingAttr); Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters); Type UnderlyingSystemType { get; } Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture); Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args); ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); ConstructorInfo GetConstructor(Type[] types); ConstructorInfo[] GetConstructors(); ConstructorInfo TypeInitializer { get; } MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers); MethodInfo GetMethod(String name, Type[] types); MethodInfo GetMethod(String name); MethodInfo[] GetMethods(); FieldInfo GetField(String name); FieldInfo[] GetFields(); Type GetInterface(String name); EventInfo GetEvent(String name); PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers); PropertyInfo GetProperty(String name, Type returnType, Type[] types); PropertyInfo GetProperty(String name, Type[] types); PropertyInfo GetProperty(String name, Type returnType); PropertyInfo GetProperty(String name); PropertyInfo[] GetProperties(); Type[] GetNestedTypes(); Type GetNestedType(String name); MemberInfo[] GetMember(String name); MemberInfo[] GetMembers(); TypeAttributes Attributes { get; } bool IsNotPublic { get; } bool IsPublic { get; } bool IsNestedPublic { get; } bool IsNestedPrivate { get; } bool IsNestedFamily { get; } bool IsNestedAssembly { get; } bool IsNestedFamANDAssem { get; } bool IsNestedFamORAssem { get; } bool IsAutoLayout { get; } bool IsLayoutSequential { get; } bool IsExplicitLayout { get; } bool IsClass { get; } bool IsInterface { get; } bool IsValueType { get; } bool IsAbstract { get; } bool IsSealed { get; } bool IsEnum { get; } bool IsSpecialName { get; } bool IsImport { get; } bool IsSerializable { get; } bool IsAnsiClass { get; } bool IsUnicodeClass { get; } bool IsAutoClass { get; } bool IsArray { get; } bool IsByRef { get; } bool IsPointer { get; } bool IsPrimitive { get; } bool IsCOMObject { get; } bool HasElementType { get; } bool IsContextful { get; } bool IsMarshalByRef { get; } bool Equals(Type o); #endregion } [GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] [TypeLibImportClassAttribute(typeof(System.Reflection.Assembly))] [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public interface _Assembly { #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region Assembly Members String CodeBase { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif get; } String EscapedCodeBase { get; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif AssemblyName GetName(); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif AssemblyName GetName(bool copiedName); String FullName { get; } MethodInfo EntryPoint { get; } Type GetType(String name); Type GetType(String name, bool throwOnError); Type[] GetExportedTypes(); Type[] GetTypes(); Stream GetManifestResourceStream(Type type, String name); Stream GetManifestResourceStream(String name); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif FileStream GetFile(String name); FileStream[] GetFiles(); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif FileStream[] GetFiles(bool getResourceModules); String[] GetManifestResourceNames(); ManifestResourceInfo GetManifestResourceInfo(String resourceName); String Location { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif get; } #if FEATURE_CAS_POLICY Evidence Evidence { get; } #endif // FEATURE_CAS_POLICY Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] // auto-generated_required void GetObjectData(SerializationInfo info, StreamingContext context); #endif [method: System.Security.SecurityCritical] event ModuleResolveEventHandler ModuleResolve; Type GetType(String name, bool throwOnError, bool ignoreCase); Assembly GetSatelliteAssembly(CultureInfo culture); Assembly GetSatelliteAssembly(CultureInfo culture, Version version); #if FEATURE_MULTIMODULE_ASSEMBLIES Module LoadModule(String moduleName, byte[] rawModule); Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore); #endif Object CreateInstance(String typeName); Object CreateInstance(String typeName, bool ignoreCase); Object CreateInstance(String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes); Module[] GetLoadedModules(); Module[] GetLoadedModules(bool getResourceModules); Module[] GetModules(); Module[] GetModules(bool getResourceModules); Module GetModule(String name); AssemblyName[] GetReferencedAssemblies(); bool GlobalAssemblyCache { get; } #endregion } [GuidAttribute("f7102fa9-cabb-3a74-a6da-b4567ef1b079")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [TypeLibImportClassAttribute(typeof(System.Reflection.MemberInfo))] [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public interface _MemberInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion } [GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.MethodBase))] [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodBase { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region MethodBase Members ParameterInfo[] GetParameters(); MethodImplAttributes GetMethodImplementationFlags(); RuntimeMethodHandle MethodHandle { get; } MethodAttributes Attributes { get; } CallingConventions CallingConvention { get; } Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); bool IsPublic { get; } bool IsPrivate { get; } bool IsFamily { get; } bool IsAssembly { get; } bool IsFamilyAndAssembly { get; } bool IsFamilyOrAssembly { get; } bool IsStatic { get; } bool IsFinal { get; } bool IsVirtual { get; } bool IsHideBySig { get; } bool IsAbstract { get; } bool IsSpecialName { get; } bool IsConstructor { get; } Object Invoke(Object obj, Object[] parameters); #endregion } [GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.MethodInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region MethodBase Members ParameterInfo[] GetParameters(); MethodImplAttributes GetMethodImplementationFlags(); RuntimeMethodHandle MethodHandle { get; } MethodAttributes Attributes { get; } CallingConventions CallingConvention { get; } Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); bool IsPublic { get; } bool IsPrivate { get; } bool IsFamily { get; } bool IsAssembly { get; } bool IsFamilyAndAssembly { get; } bool IsFamilyOrAssembly { get; } bool IsStatic { get; } bool IsFinal { get; } bool IsVirtual { get; } bool IsHideBySig { get; } bool IsAbstract { get; } bool IsSpecialName { get; } bool IsConstructor { get; } Object Invoke(Object obj, Object[] parameters); #endregion #region MethodInfo Members Type ReturnType { get; } ICustomAttributeProvider ReturnTypeCustomAttributes { get; } MethodInfo GetBaseDefinition(); #endregion } [GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.ConstructorInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ConstructorInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region MethodBase Members ParameterInfo[] GetParameters(); MethodImplAttributes GetMethodImplementationFlags(); RuntimeMethodHandle MethodHandle { get; } MethodAttributes Attributes { get; } CallingConventions CallingConvention { get; } Object Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); bool IsPublic { get; } bool IsPrivate { get; } bool IsFamily { get; } bool IsAssembly { get; } bool IsFamilyAndAssembly { get; } bool IsFamilyOrAssembly { get; } bool IsStatic { get; } bool IsFinal { get; } bool IsVirtual { get; } bool IsHideBySig { get; } bool IsAbstract { get; } bool IsSpecialName { get; } bool IsConstructor { get; } Object Invoke_3(Object obj, Object[] parameters); #endregion #region ConstructorInfo Object Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); Object Invoke_5(Object[] parameters); #endregion } [GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _FieldInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region FieldInfo Members Type FieldType { get; } Object GetValue(Object obj); Object GetValueDirect(TypedReference obj); void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); void SetValueDirect(TypedReference obj,Object value); RuntimeFieldHandle FieldHandle { get; } FieldAttributes Attributes { get; } void SetValue(Object obj, Object value); bool IsPublic { get; } bool IsPrivate { get; } bool IsFamily { get; } bool IsAssembly { get; } bool IsFamilyAndAssembly { get; } bool IsFamilyOrAssembly { get; } bool IsStatic { get; } bool IsInitOnly { get; } bool IsLiteral { get; } bool IsNotSerialized { get; } bool IsSpecialName { get; } bool IsPinvokeImpl { get; } #endregion } [GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _PropertyInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region Property Members Type PropertyType { get; } Object GetValue(Object obj,Object[] index); Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder, Object[] index, CultureInfo culture); void SetValue(Object obj, Object value, Object[] index); void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture); MethodInfo[] GetAccessors(bool nonPublic); MethodInfo GetGetMethod(bool nonPublic); MethodInfo GetSetMethod(bool nonPublic); ParameterInfo[] GetIndexParameters(); PropertyAttributes Attributes { get; } bool CanRead { get; } bool CanWrite { get; } MethodInfo[] GetAccessors(); MethodInfo GetGetMethod(); MethodInfo GetSetMethod(); bool IsSpecialName { get; } #endregion } [GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.EventInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _EventInfo { #region IDispatch Members void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endregion #region Object Members String ToString(); bool Equals(Object other); int GetHashCode(); Type GetType(); #endregion #region MemberInfo Members MemberTypes MemberType { get; } String Name { get; } Type DeclaringType { get; } Type ReflectedType { get; } Object[] GetCustomAttributes(Type attributeType, bool inherit); Object[] GetCustomAttributes(bool inherit); bool IsDefined(Type attributeType, bool inherit); #endregion #region EventInfo Members MethodInfo GetAddMethod(bool nonPublic); MethodInfo GetRemoveMethod(bool nonPublic); MethodInfo GetRaiseMethod(bool nonPublic); EventAttributes Attributes { get; } MethodInfo GetAddMethod(); MethodInfo GetRemoveMethod(); MethodInfo GetRaiseMethod(); void AddEventHandler(Object target, Delegate handler); void RemoveEventHandler(Object target, Delegate handler); Type EventHandlerType { get; } bool IsSpecialName { get; } bool IsMulticast { get; } #endregion } [GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ParameterInfo { void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); } [GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Module))] [System.Runtime.InteropServices.ComVisible(true)] public interface _Module { void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); } [GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))] [System.Runtime.InteropServices.ComVisible(true)] public interface _AssemblyName { void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); } }
// 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.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; namespace System.Runtime.Loader { public partial class AssemblyLoadContext { private enum InternalState { /// <summary> /// The ALC is alive (default) /// </summary> Alive, /// <summary> /// The unload process has started, the Unloading event will be called /// once the underlying LoaderAllocator has been finalized /// </summary> Unloading } private static readonly Dictionary<long, WeakReference<AssemblyLoadContext>> s_allContexts = new Dictionary<long, WeakReference<AssemblyLoadContext>>(); private static long s_nextId; #region private data members // If you modify any of these fields, you must also update the // AssemblyLoadContextBaseObject structure in object.h // synchronization primitive to protect against usage of this instance while unloading private readonly object _unloadLock; private event Func<Assembly, string, IntPtr>? _resolvingUnmanagedDll; private event Func<AssemblyLoadContext, AssemblyName, Assembly>? _resolving; private event Action<AssemblyLoadContext>? _unloading; private readonly string? _name; // Contains the reference to VM's representation of the AssemblyLoadContext private readonly IntPtr _nativeAssemblyLoadContext; // Id used by s_allContexts private readonly long _id; // Indicates the state of this ALC (Alive or in Unloading state) private InternalState _state; private readonly bool _isCollectible; #endregion protected AssemblyLoadContext() : this(false, false, null) { } protected AssemblyLoadContext(bool isCollectible) : this(false, isCollectible, null) { } public AssemblyLoadContext(string? name, bool isCollectible = false) : this(false, isCollectible, name) { } private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string? name) { // Initialize the VM side of AssemblyLoadContext if not already done. _isCollectible = isCollectible; _name = name; // The _unloadLock needs to be assigned after the IsCollectible to ensure proper behavior of the finalizer // even in case the following allocation fails or the thread is aborted between these two lines. _unloadLock = new object(); if (!isCollectible) { // For non collectible AssemblyLoadContext, the finalizer should never be called and thus the AssemblyLoadContext should not // be on the finalizer queue. GC.SuppressFinalize(this); } // If this is a collectible ALC, we are creating a weak handle tracking resurrection otherwise we use a strong handle var thisHandle = GCHandle.Alloc(this, IsCollectible ? GCHandleType.WeakTrackResurrection : GCHandleType.Normal); var thisHandlePtr = GCHandle.ToIntPtr(thisHandle); _nativeAssemblyLoadContext = InitializeAssemblyLoadContext(thisHandlePtr, representsTPALoadContext, isCollectible); // Add this instance to the list of alive ALC lock (s_allContexts) { _id = s_nextId++; s_allContexts.Add(_id, new WeakReference<AssemblyLoadContext>(this, true)); } } ~AssemblyLoadContext() { // Use the _unloadLock as a guard to detect the corner case when the constructor of the AssemblyLoadContext was not executed // e.g. due to the JIT failing to JIT it. if (_unloadLock != null) { // Only valid for a Collectible ALC. Non-collectible ALCs have the finalizer suppressed. Debug.Assert(IsCollectible); // We get here only in case the explicit Unload was not initiated. Debug.Assert(_state != InternalState.Unloading); InitiateUnload(); } } private void RaiseUnloadEvent() { // Ensure that we raise the Unload event only once Interlocked.Exchange(ref _unloading, null!)?.Invoke(this); } private void InitiateUnload() { RaiseUnloadEvent(); // When in Unloading state, we are not supposed to be called on the finalizer // as the native side is holding a strong reference after calling Unload lock (_unloadLock) { Debug.Assert(_state == InternalState.Alive); var thisStrongHandle = GCHandle.Alloc(this, GCHandleType.Normal); var thisStrongHandlePtr = GCHandle.ToIntPtr(thisStrongHandle); // The underlying code will transform the original weak handle // created by InitializeLoadContext to a strong handle PrepareForAssemblyLoadContextRelease(_nativeAssemblyLoadContext, thisStrongHandlePtr); _state = InternalState.Unloading; } lock (s_allContexts) { s_allContexts.Remove(_id); } } public IEnumerable<Assembly> Assemblies { get { foreach (Assembly a in GetLoadedAssemblies()) { AssemblyLoadContext? alc = GetLoadContext(a); if (alc == this) { yield return a; } } } } // Event handler for resolving native libraries. // This event is raised if the native library could not be resolved via // the default resolution logic [including AssemblyLoadContext.LoadUnmanagedDll()] // // Inputs: Invoking assembly, and library name to resolve // Returns: A handle to the loaded native library public event Func<Assembly, string, IntPtr>? ResolvingUnmanagedDll { add { _resolvingUnmanagedDll += value; } remove { _resolvingUnmanagedDll -= value; } } // Event handler for resolving managed assemblies. // This event is raised if the managed assembly could not be resolved via // the default resolution logic [including AssemblyLoadContext.Load()] // // Inputs: The AssemblyLoadContext and AssemblyName to be loaded // Returns: The Loaded assembly object. public event Func<AssemblyLoadContext, AssemblyName, Assembly?>? Resolving { add { _resolving += value; } remove { _resolving -= value; } } public event Action<AssemblyLoadContext>? Unloading { add { _unloading += value; } remove { _unloading -= value; } } #region AppDomainEvents // Occurs when an Assembly is loaded internal static event AssemblyLoadEventHandler? AssemblyLoad; // Occurs when resolution of type fails internal static event ResolveEventHandler? TypeResolve; // Occurs when resolution of resource fails internal static event ResolveEventHandler? ResourceResolve; // Occurs when resolution of assembly fails // This event is fired after resolve events of AssemblyLoadContext fails internal static event ResolveEventHandler? AssemblyResolve; #endregion public static AssemblyLoadContext Default => DefaultAssemblyLoadContext.s_loadContext; public bool IsCollectible => _isCollectible; public string? Name => _name; public override string ToString() => "\"" + Name + "\" " + GetType().ToString() + " #" + _id; public static IEnumerable<AssemblyLoadContext> All { get { _ = AssemblyLoadContext.Default; // Ensure default is initialized List<WeakReference<AssemblyLoadContext>>? alcList = null; lock (s_allContexts) { // To make this thread safe we need a quick snapshot while locked alcList = new List<WeakReference<AssemblyLoadContext>>(s_allContexts.Values); } foreach (WeakReference<AssemblyLoadContext> weakAlc in alcList) { if (weakAlc.TryGetTarget(out AssemblyLoadContext? alc)) { yield return alc; } } } } // Helper to return AssemblyName corresponding to the path of an IL assembly public static AssemblyName GetAssemblyName(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } return AssemblyName.GetAssemblyName(assemblyPath); } // Custom AssemblyLoadContext implementations can override this // method to perform custom processing and use one of the protected // helpers above to load the assembly. protected virtual Assembly? Load(AssemblyName assemblyName) { return null; } #if !CORERT [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); // Attempt to load the assembly, using the same ordering as static load, in the current load context. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return Assembly.Load(assemblyName, ref stackMark, this); } #endif // These methods load assemblies into the current AssemblyLoadContext // They may be used in the implementation of an AssemblyLoadContext derivation public Assembly LoadFromAssemblyPath(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } if (PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath)); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoadFromPath(assemblyPath, null); } } public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath) { if (nativeImagePath == null) { throw new ArgumentNullException(nameof(nativeImagePath)); } if (PathInternal.IsPartiallyQualified(nativeImagePath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), nameof(nativeImagePath)); } if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath)); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoadFromPath(assemblyPath, nativeImagePath); } } public Assembly LoadFromStream(Stream assembly) { return LoadFromStream(assembly, null); } public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } int iAssemblyStreamLength = (int)assembly.Length; if (iAssemblyStreamLength <= 0) { throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); } // Allocate the byte[] to hold the assembly byte[] arrAssembly = new byte[iAssemblyStreamLength]; // Copy the assembly to the byte array assembly.Read(arrAssembly, 0, iAssemblyStreamLength); // Get the symbol stream in byte[] if provided byte[]? arrSymbols = null; if (assemblySymbols != null) { var iSymbolLength = (int)assemblySymbols.Length; arrSymbols = new byte[iSymbolLength]; assemblySymbols.Read(arrSymbols, 0, iSymbolLength); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoad(arrAssembly, arrSymbols); } } // This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a // platform-independent way. The DLL is loaded with default load flags. protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath) { if (unmanagedDllPath == null) { throw new ArgumentNullException(nameof(unmanagedDllPath)); } if (unmanagedDllPath.Length == 0) { throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath)); } if (PathInternal.IsPartiallyQualified(unmanagedDllPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, unmanagedDllPath), nameof(unmanagedDllPath)); } return NativeLibrary.Load(unmanagedDllPath); } // Custom AssemblyLoadContext implementations can override this // method to perform the load of unmanaged native dll // This function needs to return the HMODULE of the dll it loads protected virtual IntPtr LoadUnmanagedDll(string unmanagedDllName) { // defer to default coreclr policy of loading unmanaged dll return IntPtr.Zero; } public void Unload() { if (!IsCollectible) { throw new InvalidOperationException(SR.AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible); } GC.SuppressFinalize(this); InitiateUnload(); } internal static void OnProcessExit() { lock (s_allContexts) { foreach (KeyValuePair<long, WeakReference<AssemblyLoadContext>> alcAlive in s_allContexts) { if (alcAlive.Value.TryGetTarget(out AssemblyLoadContext? alc)) { alc.RaiseUnloadEvent(); } } } } private void VerifyIsAlive() { if (_state != InternalState.Alive) { throw new InvalidOperationException(SR.AssemblyLoadContext_Verify_NotUnloading); } } private static AsyncLocal<AssemblyLoadContext?>? s_asyncLocalCurrent; /// <summary>Nullable current AssemblyLoadContext used for context sensitive reflection APIs</summary> /// <remarks> /// This is an advanced setting used in reflection assembly loading scenarios. /// /// There are a set of contextual reflection APIs which load managed assemblies through an inferred AssemblyLoadContext. /// * <see cref="System.Activator.CreateInstance" /> /// * <see cref="System.Reflection.Assembly.Load" /> /// * <see cref="System.Reflection.Assembly.GetType" /> /// * <see cref="System.Type.GetType" /> /// /// When CurrentContextualReflectionContext is null, the AssemblyLoadContext is inferred. /// The inference logic is simple. /// * For static methods, it is the AssemblyLoadContext which loaded the method caller's assembly. /// * For instance methods, it is the AssemblyLoadContext which loaded the instance's assembly. /// /// When this property is set, the CurrentContextualReflectionContext value is used by these contextual reflection APIs for loading. /// /// This property is typically set in a using block by /// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/>. /// /// The property is stored in an AsyncLocal&lt;AssemblyLoadContext&gt;. This means the setting can be unique for every async or thread in the process. /// /// For more details see https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/AssemblyLoadContext.ContextualReflection.md /// </remarks> public static AssemblyLoadContext? CurrentContextualReflectionContext => s_asyncLocalCurrent?.Value; private static void SetCurrentContextualReflectionContext(AssemblyLoadContext? value) { if (s_asyncLocalCurrent == null) { Interlocked.CompareExchange<AsyncLocal<AssemblyLoadContext?>?>(ref s_asyncLocalCurrent, new AsyncLocal<AssemblyLoadContext?>(), null); } s_asyncLocalCurrent!.Value = value; // Remove ! when compiler specially-recognizes CompareExchange for nullability } /// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary> /// <returns>A disposable ContextualReflectionScope for use in a using block</returns> /// <remarks> /// Sets CurrentContextualReflectionContext to this instance. /// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/> /// /// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the /// Dispose() method, it restores the ContextualReflectionScope to its previous value. /// </remarks> public ContextualReflectionScope EnterContextualReflection() { return new ContextualReflectionScope(this); } /// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary> /// <param name="activating">Set CurrentContextualReflectionContext to the AssemblyLoadContext which loaded activating.</param> /// <returns>A disposable ContextualReflectionScope for use in a using block</returns> /// <remarks> /// Sets CurrentContextualReflectionContext to to the AssemblyLoadContext which loaded activating. /// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/> /// /// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the /// Dispose() method, it restores the ContextualReflectionScope to its previous value. /// </remarks> public static ContextualReflectionScope EnterContextualReflection(Assembly? activating) { if (activating == null) return new ContextualReflectionScope(null); AssemblyLoadContext? assemblyLoadContext = GetLoadContext(activating); if (assemblyLoadContext == null) { // All RuntimeAssemblies & Only RuntimeAssemblies have an AssemblyLoadContext throw new ArgumentException(SR.Arg_MustBeRuntimeAssembly, nameof(activating)); } return assemblyLoadContext.EnterContextualReflection(); } /// <summary>Opaque disposable struct used to restore CurrentContextualReflectionContext</summary> /// <remarks> /// This is an implmentation detail of the AssemblyLoadContext.EnterContextualReflection APIs. /// It is a struct, to avoid heap allocation. /// It is required to be public to avoid boxing. /// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/> /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public struct ContextualReflectionScope : IDisposable { private readonly AssemblyLoadContext? _activated; private readonly AssemblyLoadContext? _predecessor; private readonly bool _initialized; internal ContextualReflectionScope(AssemblyLoadContext? activating) { _predecessor = AssemblyLoadContext.CurrentContextualReflectionContext; AssemblyLoadContext.SetCurrentContextualReflectionContext(activating); _activated = activating; _initialized = true; } public void Dispose() { if (_initialized) { // Do not clear initialized. Always restore the _predecessor in Dispose() // _initialized = false; AssemblyLoadContext.SetCurrentContextualReflectionContext(_predecessor); } } } #if !CORERT // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static Assembly? Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; return context.ResolveUsingLoad(assemblyName); } // This method is invoked by the VM to resolve an assembly reference using the Resolving event // after trying assembly resolution via Load override and TPA load context without success. private static Assembly? ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; // Invoke the AssemblyResolve event callbacks if wired up return context.ResolveUsingEvent(assemblyName); } // This method is invoked by the VM to resolve a satellite assembly reference // after trying assembly resolution via Load override without success. private static Assembly? ResolveSatelliteAssembly(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; // Invoke the ResolveSatelliteAssembly method return context.ResolveSatelliteAssembly(assemblyName); } private Assembly? GetFirstResolvedAssembly(AssemblyName assemblyName) { Assembly? resolvedAssembly = null; Func<AssemblyLoadContext, AssemblyName, Assembly>? assemblyResolveHandler = _resolving; if (assemblyResolveHandler != null) { // Loop through the event subscribers and return the first non-null Assembly instance foreach (Func<AssemblyLoadContext, AssemblyName, Assembly> handler in assemblyResolveHandler.GetInvocationList()) { resolvedAssembly = handler(this, assemblyName); if (resolvedAssembly != null) { return resolvedAssembly; } } } return null; } private static Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string? requestedSimpleName) { // Get the name of the loaded assembly string? loadedSimpleName = null; // Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly // which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder), // we need to check for RuntimeAssembly. RuntimeAssembly? rtLoadedAssembly = assembly as RuntimeAssembly; if (rtLoadedAssembly != null) { loadedSimpleName = rtLoadedAssembly.GetSimpleName(); } // The simple names should match at the very least if (string.IsNullOrEmpty(requestedSimpleName)) { throw new ArgumentException(SR.ArgumentNull_AssemblyNameName); } if (string.IsNullOrEmpty(loadedSimpleName) || !requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch); } return assembly; } private Assembly? ResolveUsingLoad(AssemblyName assemblyName) { string? simpleName = assemblyName.Name; Assembly? assembly = Load(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } return assembly; } private Assembly? ResolveUsingEvent(AssemblyName assemblyName) { string? simpleName = assemblyName.Name; // Invoke the AssemblyResolve event callbacks if wired up Assembly? assembly = GetFirstResolvedAssembly(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } return assembly; } // This method is called by the VM. private static void OnAssemblyLoad(RuntimeAssembly assembly) { AssemblyLoad?.Invoke(AppDomain.CurrentDomain, new AssemblyLoadEventArgs(assembly)); } // This method is called by the VM. private static RuntimeAssembly? OnResourceResolve(RuntimeAssembly assembly, string resourceName) { return InvokeResolveEvent(ResourceResolve, assembly, resourceName); } // This method is called by the VM private static RuntimeAssembly? OnTypeResolve(RuntimeAssembly assembly, string typeName) { return InvokeResolveEvent(TypeResolve, assembly, typeName); } // This method is called by the VM. private static RuntimeAssembly? OnAssemblyResolve(RuntimeAssembly assembly, string assemblyFullName) { return InvokeResolveEvent(AssemblyResolve, assembly, assemblyFullName); } private static RuntimeAssembly? InvokeResolveEvent(ResolveEventHandler? eventHandler, RuntimeAssembly assembly, string name) { if (eventHandler == null) return null; var args = new ResolveEventArgs(name, assembly); foreach (ResolveEventHandler handler in eventHandler.GetInvocationList()) { Assembly? asm = handler(AppDomain.CurrentDomain, args); RuntimeAssembly? ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } return null; } #endif // !CORERT private Assembly? ResolveSatelliteAssembly(AssemblyName assemblyName) { // Called by native runtime when CultureName is not empty Debug.Assert(assemblyName.CultureName?.Length > 0); const string SatelliteSuffix = ".resources"; if (assemblyName.Name == null || !assemblyName.Name.EndsWith(SatelliteSuffix, StringComparison.Ordinal)) return null; string parentAssemblyName = assemblyName.Name.Substring(0, assemblyName.Name.Length - SatelliteSuffix.Length); Assembly parentAssembly = LoadFromAssemblyName(new AssemblyName(parentAssemblyName)); AssemblyLoadContext parentALC = GetLoadContext(parentAssembly)!; string parentDirectory = Path.GetDirectoryName(parentAssembly.Location)!; string assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!, $"{assemblyName.Name}.dll"); if (Internal.IO.File.InternalExists(assemblyPath)) { return parentALC.LoadFromAssemblyPath(assemblyPath); } else if (Path.IsCaseSensitive) { assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!.ToLowerInvariant(), $"{assemblyName.Name}.dll"); if (Internal.IO.File.InternalExists(assemblyPath)) { return parentALC.LoadFromAssemblyPath(assemblyPath); } } return null; } } internal sealed class DefaultAssemblyLoadContext : AssemblyLoadContext { internal static readonly AssemblyLoadContext s_loadContext = new DefaultAssemblyLoadContext(); internal DefaultAssemblyLoadContext() : base(true, false, "Default") { } } internal sealed class IndividualAssemblyLoadContext : AssemblyLoadContext { internal IndividualAssemblyLoadContext(string name) : base(false, false, name) { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace QText { public class Document { public Document(string path) { try { RootPath = Path.GetFullPath(path); Folders.Add(new DocumentFolder(this, string.Empty)); foreach (var directory in new DirectoryInfo(RootPath).GetDirectories()) { if (directory.Attributes.HasFlag(FileAttributes.System) && directory.Attributes.HasFlag(FileAttributes.Hidden)) { continue; //skip directories with both system and hidden attribute set } Folders.Add(new DocumentFolder(this, Path.GetFileName(directory.Name))); } SortFolders(); foreach (var folder in Folders) { var directory = new DirectoryInfo(folder.FullPath); foreach (var extension in FileExtensions.All) { foreach (var file in directory.GetFiles("*" + extension, SearchOption.TopDirectoryOnly)) { if (file.Attributes.HasFlag(FileAttributes.System) && file.Attributes.HasFlag(FileAttributes.Hidden)) { continue; //skip files with both system and hidden attribute set } if (file.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase)) { //need this check because *.txt matches A.txt2 too. Files.Add(new DocumentFile(folder, file.Name)); } } } } var orderFilePath = Path.Combine(RootPath, ".qtext"); var lines = new string[] { }; try { if (File.Exists(orderFilePath)) { lines = File.ReadAllLines(orderFilePath, Document.Encoding); } } catch (IOException) { } catch (UnauthorizedAccessException) { } var selectedFiles = new List<DocumentFile>(); Files.Sort(delegate (DocumentFile file1, DocumentFile file2) { var index1 = Array.IndexOf(lines, file1.Folder.Name + "|" + file1.Name + "|"); if (index1 < 0) { index1 = Array.IndexOf(lines, file1.Folder.Name + "|" + file1.Name + "|*"); if ((index1 >= 0) && !selectedFiles.Contains(file1)) { selectedFiles.Add(file1); } } var index2 = Array.IndexOf(lines, file2.Folder.Name + "|" + file2.Name + "|"); if (index2 < 0) { index2 = Array.IndexOf(lines, file2.Folder.Name + "|" + file2.Name + "|*"); if ((index2 >= 0) && !selectedFiles.Contains(file2)) { selectedFiles.Add(file2); } } if ((index1 < 0) && (index2 < 0)) { return string.Compare(file1.Title, file2.Title, StringComparison.OrdinalIgnoreCase); } else if (index1 < 0) { return -1; } else if (index2 < 0) { return +1; } else { return (index1 < index2) ? -1 : +1; } }); foreach (var selectedFile in selectedFiles) { selectedFile.Selected = true; } Watcher = new FileSystemWatcher(RootPath) { IncludeSubdirectories = true, InternalBufferSize = 32768 }; Watcher.Changed += Watcher_Changed; Watcher.Created += Watcher_Created; Watcher.Deleted += Watcher_Deleted; Watcher.Renamed += Watcher_Renamed; EnableWatcher(); } catch (DirectoryNotFoundException) { throw; //just rethrow it } catch (NotSupportedException) { throw; //just rethrow it } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } } /// <summary> /// Gets root path. /// </summary> public string RootPath { get; private set; } /// <summary> /// Gets/sets if file deletion is going to be performed to recycle bin /// </summary> public bool DeleteToRecycleBin { get; set; } #region Folders private readonly List<DocumentFolder> Folders = new List<DocumentFolder>(); internal void SortFolders() { Folders.Sort(delegate (DocumentFolder folder1, DocumentFolder folder2) { if (string.IsNullOrEmpty(folder1.Name) == string.IsNullOrEmpty(folder2.Name)) { return string.Compare(folder1.Title, folder2.Title, StringComparison.OrdinalIgnoreCase); } else { return string.IsNullOrEmpty(folder1.Name) ? -1 : +1; } }); } internal void SortFiles(DocumentFolder folder) { Files.Sort(delegate (DocumentFile file1, DocumentFile file2) { if ((file1.Folder == folder) && (file2.Folder == folder)) { return string.Compare(file1.Title, file2.Title, StringComparison.CurrentCultureIgnoreCase); } else if (file1.Folder == folder) { return -1; } else if (file2.Folder == folder) { return +1; } else { return Files.IndexOf(file1).CompareTo(Files.IndexOf(file2)); } }); } #endregion #region Files private readonly List<DocumentFile> Files = new List<DocumentFile>(); internal IEnumerable<DocumentFile> GetFiles(DocumentFolder folder) { foreach (var file in Files) { if (file.Folder.Equals(folder)) { yield return file; } } } #endregion #region Carbon copy private string _carbonCopyRootPath; /// <summary> /// Gets root path for carbon copy. /// Can be empty. /// </summary> public string CarbonCopyRootPath { get { return _carbonCopyRootPath; } set { if (value == null) { _carbonCopyRootPath = value; } else { var path = Path.GetFullPath(value); if (value.StartsWith(RootPath, StringComparison.OrdinalIgnoreCase)) { _carbonCopyRootPath = null; //cannot be subfolder of root directory } else { _carbonCopyRootPath = path; } } } } /// <summary> /// Gets/sets if carbon copy errors are to be ignored. /// </summary> public bool CarbonCopyIgnoreErrors { get; set; } /// <summary> /// Writes all carbon copies. /// </summary> public void WriteAllCarbonCopies() { if (CarbonCopyRootPath != null) { foreach (var folder in GetFolders()) { foreach (var file in folder.GetFiles()) { file.WriteCarbonCopy(); } } } } #endregion #region Watcher internal readonly FileSystemWatcher Watcher; public void DisableWatcher() { Watcher.EnableRaisingEvents = false; } public void EnableWatcher() { Watcher.EnableRaisingEvents = true; } private void Watcher_Changed(object sender, FileSystemEventArgs e) { Debug.WriteLine("FileSystemWatcher.Changed: " + e.FullPath); var files = new List<DocumentFile>(Files); //copy existing collection first to avoid concurrency issues if (File.Exists(e.FullPath)) { //file - ignore directory changes foreach (var file in files) { if (string.Equals(file.FullPath, e.FullPath, StringComparison.OrdinalIgnoreCase)) { OnFileExternallyChanged(new DocumentFileEventArgs(file)); break; } } } } private void Watcher_Created(object sender, FileSystemEventArgs e) { Debug.WriteLine("FileSystemWatcher.Created: " + e.FullPath); if (Directory.Exists(e.FullPath)) { //directory var folder = new DocumentFolder(this, e.Name); Folders.Add(folder); SortFolders(); OnExternallyChanged(new EventArgs()); } else if (File.Exists(e.FullPath)) { //file var directoryPath = Path.GetDirectoryName(e.FullPath); foreach (var folder in Folders) { if (folder.FullPath.Equals(directoryPath, StringComparison.OrdinalIgnoreCase)) { var newExtension = Path.GetExtension(e.Name); var newName = Path.GetFileNameWithoutExtension(e.Name); DocumentFile newFile; if (newExtension.Equals(FileExtensions.PlainText, StringComparison.OrdinalIgnoreCase)) { newFile = new DocumentFile(folder, newName + newExtension); } else if (newExtension.Equals(FileExtensions.RichText, StringComparison.OrdinalIgnoreCase)) { newFile = new DocumentFile(folder, newName + newExtension); } else if (newExtension.Equals(FileExtensions.EncryptedPlainText, StringComparison.OrdinalIgnoreCase)) { newFile = new DocumentFile(folder, newName + newExtension); } else if (newExtension.Equals(FileExtensions.EncryptedRichText, StringComparison.OrdinalIgnoreCase)) { newFile = new DocumentFile(folder, newName + newExtension); } else { break; //ignore because it has unsupported extension } Files.Add(newFile); OnFolderExternallyChanged(new DocumentFolderEventArgs(folder)); break; } } } } private void Watcher_Deleted(object sender, FileSystemEventArgs e) { Debug.WriteLine("FileSystemWatcher.Deleted: " + e.FullPath); ProcessDelete(e.FullPath); OnExternallyChanged(new EventArgs()); } internal void ProcessDelete(string fullPath) { for (var i = Files.Count - 1; i >= 0; i--) { var file = Files[i]; if (string.Equals(file.FullPath, fullPath, StringComparison.OrdinalIgnoreCase) || string.Equals(file.Folder.FullPath, fullPath, StringComparison.OrdinalIgnoreCase)) { Files.RemoveAt(i); } } for (var i = 0; i < Folders.Count; i++) { var folder = Folders[i]; if (!folder.IsRoot && string.Equals(folder.FullPath, fullPath, StringComparison.OrdinalIgnoreCase)) { Folders.RemoveAt(i); break; } } } private void Watcher_Renamed(object sender, RenamedEventArgs e) { Debug.WriteLine("FileSystemWatcher.Renamed: " + e.OldFullPath + " -> " + e.FullPath); if (Directory.Exists(e.FullPath)) { //directory for (var i = 0; i < Folders.Count; i++) { var folder = Folders[i]; if (!folder.IsRoot && string.Equals(folder.FullPath, e.OldFullPath, StringComparison.OrdinalIgnoreCase)) { folder.Name = e.Name; SortFolders(); OnFolderChanged(new DocumentFolderEventArgs(folder)); break; } } } else if (File.Exists(e.FullPath)) { //file for (var i = 0; i < Files.Count; i++) { var file = Files[i]; _ = file.Name; _ = file.Style; _ = file.Folder; if (string.Equals(file.FullPath, e.OldFullPath, StringComparison.OrdinalIgnoreCase)) { var newExtension = Path.GetExtension(e.Name); var newName = Path.GetFileNameWithoutExtension(e.Name); if (!newExtension.Equals(file.Extension, StringComparison.OrdinalIgnoreCase)) { //extension has changed if (newExtension.Equals(FileExtensions.PlainText, StringComparison.OrdinalIgnoreCase)) { file.Kind = DocumentKind.PlainText; } else if (newExtension.Equals(FileExtensions.RichText, StringComparison.OrdinalIgnoreCase)) { file.Kind = DocumentKind.RichText; } else if (newExtension.Equals(FileExtensions.EncryptedPlainText, StringComparison.OrdinalIgnoreCase)) { file.Kind = DocumentKind.EncryptedPlainText; } else if (newExtension.Equals(FileExtensions.EncryptedRichText, StringComparison.OrdinalIgnoreCase)) { file.Kind = DocumentKind.EncryptedRichText; } else { Files.RemoveAt(i); //remove because it has unsupported extension break; } } if (!newName.Equals(file.Name, StringComparison.OrdinalIgnoreCase)) { file.Name = newName; } OnFileExternallyChanged(new DocumentFileEventArgs(file)); return; } } var directoryPath = Path.GetDirectoryName(e.FullPath); foreach (var folder in Folders) { if (string.Equals(folder.FullPath, directoryPath, StringComparison.OrdinalIgnoreCase)) { Watcher_Created(null, e); break; } } } } /// <summary> /// Change affecting all entries has occurred. /// Includes folder deletion and creation. /// </summary> public event EventHandler<EventArgs> Changed; /// <summary> /// Raises Changed event. /// </summary> /// <param name="e">Event arguments.</param> internal void OnChanged(EventArgs e) { var eh = Changed; if (eh != null) { eh.Invoke(this, e); } } /// <summary> /// Change affecting all entries has occurred. /// Includes folder deletion and creation. /// </summary> public event EventHandler<EventArgs> ExternallyChanged; /// <summary> /// Raises ExternallyChanged event. /// </summary> /// <param name="e">Event arguments.</param> private void OnExternallyChanged(EventArgs e) { var eh = ExternallyChanged; if (eh != null) { eh.Invoke(this, e); } OnChanged(e); } /// <summary> /// Folder change has occurred. /// Includes folder renames and file creation and deletion. /// </summary> public event EventHandler<DocumentFolderEventArgs> FolderChanged; /// <summary> /// Raises FolderChanged event. /// </summary> /// <param name="e">Event arguments.</param> internal void OnFolderChanged(DocumentFolderEventArgs e) { var eh = FolderChanged; if (eh != null) { eh.Invoke(this, e); } } /// <summary> /// Folder change has occurred. /// Includes folder renames and file creation and deletion. /// </summary> public event EventHandler<DocumentFolderEventArgs> FolderExternallyChanged; /// <summary> /// Raises FolderExternallyChanged event. /// </summary> /// <param name="e">Event arguments.</param> private void OnFolderExternallyChanged(DocumentFolderEventArgs e) { var eh = FolderExternallyChanged; if (eh != null) { eh.Invoke(this, e); } OnFolderChanged(e); } /// <summary> /// File change has occurred. /// Includes file renames, style changes, and encryption/decryption. /// </summary> public event EventHandler<DocumentFileEventArgs> FileChanged; /// <summary> /// Raises FileChanged event. /// </summary> /// <param name="e">Event arguments.</param> internal void OnFileChanged(DocumentFileEventArgs e) { var eh = FileChanged; if (eh != null) { eh.Invoke(this, e); } } /// <summary> /// File change has occurred. /// Includes file renames, style changes, and encryption/decryption. /// </summary> public event EventHandler<DocumentFileEventArgs> FileExternallyChanged; /// <summary> /// Raises FileExternallyChanged event. /// </summary> /// <param name="e">Event arguments.</param> private void OnFileExternallyChanged(DocumentFileEventArgs e) { var eh = FileExternallyChanged; if (eh != null) { eh.Invoke(this, e); } OnFileChanged(e); } #endregion #region Enumerate public DocumentFolder RootFolder { get { return Folders[0]; } } public IEnumerable<DocumentFolder> GetFolders() { foreach (var folder in Folders) { yield return folder; } } public IEnumerable<DocumentFolder> GetSubFolders() { foreach (var folder in Folders) { if (!folder.IsRoot) { yield return folder; } } } public DocumentFolder GetFolder(string name) { foreach (var folder in GetFolders()) { if (folder.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { return folder; } } return null; } #endregion #region New public DocumentFolder CreateFolder() { try { var newPath = Path.Combine(RootPath, Helper.EncodeFolderTitle("New folder")); var n = 1; while (Directory.Exists(newPath)) { var newTitle = string.Format(CultureInfo.CurrentUICulture, "New folder ({0})", n); newPath = Path.Combine(RootPath, Helper.EncodeFolderTitle(newTitle)); n += 1; } Debug.WriteLine("Create: " + Path.GetFileName(newPath)); using (var watcher = new Helper.FileSystemToggler(Watcher)) { Directory.CreateDirectory(newPath); } var folder = new DocumentFolder(this, Path.GetFileName(newPath)); Folders.Add(folder); SortFolders(); OnChanged(new EventArgs()); return folder; } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } } public DocumentFolder CreateFolder(string title) { try { var newPath = Path.Combine(RootPath, Helper.EncodeFolderTitle(title)); Debug.WriteLine("Create: " + Path.GetFileName(newPath)); using (var watcher = new Helper.FileSystemToggler(Watcher)) { Directory.CreateDirectory(newPath); } var folder = new DocumentFolder(this, Path.GetFileName(newPath)); Folders.Add(folder); SortFolders(); OnChanged(new EventArgs()); return folder; } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } } internal bool CanNewFile(DocumentFolder folder, string title) { foreach (var file in folder.GetFiles()) { if (string.Equals(file.Title, title, StringComparison.OrdinalIgnoreCase)) { return false; } } return true; } internal DocumentFile NewFile(DocumentFolder folder, string title, DocumentKind kind) { var name = Helper.EncodeFileTitle(title); DocumentFile newFile; switch (kind) { case DocumentKind.PlainText: newFile = new DocumentFile(folder, name + FileExtensions.PlainText); break; case DocumentKind.RichText: newFile = new DocumentFile(folder, name + FileExtensions.RichText); break; default: throw new InvalidOperationException("Unrecognized file kind."); } Debug.WriteLine("File.New: " + name); using (var watcher = new Helper.FileSystemToggler(Watcher)) { File.WriteAllText(newFile.FullPath, ""); Files.Add(newFile); } OnFolderChanged(new DocumentFolderEventArgs(newFile.Folder)); return newFile; } #endregion #region Order internal void OrderBefore(DocumentFile file, DocumentFile pivotFile) { var index = Files.IndexOf(file); var indexPivot = (pivotFile == null) ? Files.Count : Files.IndexOf(pivotFile); if (index != indexPivot) { Files.RemoveAt(index); Files.Insert((index < indexPivot) ? indexPivot - 1 : indexPivot, file); WriteOrder(); } } internal void OrderAfter(DocumentFile file, DocumentFile pivotFile) { var index = Files.IndexOf(file); var indexPivot = (pivotFile == null) ? -1 : Files.IndexOf(pivotFile); if (index != indexPivot) { Files.RemoveAt(index); Files.Insert((index > indexPivot) ? indexPivot + 1 : indexPivot, file); WriteOrder(); } } #endregion #region Write metadata private static readonly UTF8Encoding Encoding = new UTF8Encoding(false); private string LastOrderText = null; /// <summary> /// Writes ordering information. /// </summary> internal void WriteOrder() { var sb = new StringBuilder(65536); foreach (var file in Files) { sb.AppendLine(file.Folder.Name + "|" + file.Name + "|" + (file.Selected ? "*" : "")); } var orderText = sb.ToString(); if (LastOrderText != orderText) { LastOrderText = orderText; try { var orderFilePath = Path.Combine(RootPath, ".qtext"); var attributes = FileAttributes.Normal; if (File.Exists(orderFilePath)) { attributes = File.GetAttributes(orderFilePath); File.SetAttributes(orderFilePath, attributes & ~FileAttributes.Hidden); } File.WriteAllText(orderFilePath, orderText, Document.Encoding); File.SetAttributes(orderFilePath, attributes | FileAttributes.Hidden); } catch (IOException) { } catch (UnauthorizedAccessException) { } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace System.Xml.Linq { /// <summary> /// This is a thread-safe hash table which maps string keys to values of type TValue. It is assumed that the string key is embedded in the hashed value /// and can be extracted via a call to ExtractKeyDelegate (in order to save space and allow cleanup of key if value is released due to a WeakReference /// TValue releasing its target). /// </summary> /// <remarks> /// All methods on this class are thread-safe. /// /// When the hash table fills up, it is necessary to resize it and rehash all contents. Because this can be expensive, /// a lock is taken, and one thread is responsible for the resize. Other threads which need to add values must wait /// for the resize to be complete. /// /// Thread-Safety Notes /// =================== /// /// 1. Because performance and scalability are such a concern with the global name table, I have avoided the use of /// BIFALOs (Big Fat Locks). Instead, I use CompareExchange, Interlocked.Increment, memory barriers, atomic state objects, /// etc. to avoid locks. Any changes to code which accesses these variables should be carefully reviewed and tested, /// as it can be *very* tricky. In particular, if you don't understand the CLR memory model or if you don't know /// what a memory barrier is, DON'T attempt to modify this code. A good discussion of these topics can be found at /// <![CDATA[http://discuss.develop.com/archives/wa.exe?A2=ind0203B&L=DOTNET&P=R375]]>. /// /// 2. Because I am not sure if the CLR spec has changed since versions 1.0/1.1, I am assuming the weak memory model that /// is described in the ECMA spec, in which normal writes can be reordered. This means I must introduce more memory /// barriers than otherwise would be necessary. /// /// 3. There are several thread-safety concepts and patterns I utilize in this code: /// a. Publishing -- There are a small number of places where state is exposed, or published, to multiple threads. /// These places are marked with the comment "PUBLISH", and are key locations to consider when /// reviewing the code for thread-safety. /// /// b. Immutable objects -- Immutable objects initialize their fields once in their constructor and then never modify /// them again. As long as care is taken to ensure that initial field values are visible to /// other threads before publishing the immutable object itself, immutable objects are /// completely thread-safe. /// /// c. Atomic state objects -- Locks typically are taken when several pieces of state must be updated atomically. In /// other words, there is a window in which state is inconsistent, and that window must /// be protected from view by locking. However, if a new object is created each time state /// changes (or state changes substantially), then during creation the new object is only /// visible to a single thread. Once construction is complete, an assignment (guaranteed /// atomic) can replace the old state object with the new state object, thus publishing a /// consistent view to all threads. /// /// d. Retry -- When several threads contend over shared state which only one is allowed to possess, it is possible /// to avoid locking by repeatedly attempting to acquire the shared state. The CompareExchange method /// is useful for atomically ensuring that only one thread succeeds, and other threads are notified that /// they must retry. /// /// 4. All variables which can be written by multiple threads are marked "SHARED STATE". /// </remarks> internal sealed class XHashtable<TValue> { private XHashtableState _state; // SHARED STATE: Contains all XHashtable state, so it can be atomically swapped when resizes occur /// <summary> /// Prototype of function which is called to extract a string key value from a hashed value. /// Returns null if the hashed value is invalid (e.g. value has been released due to a WeakReference TValue being cleaned up). /// </summary> public delegate string ExtractKeyDelegate(TValue value); /// <summary> /// Construct a new XHashtable with the specified starting capacity. /// </summary> public XHashtable(ExtractKeyDelegate extractKey, int capacity) { _state = new XHashtableState(extractKey, capacity); } /// <summary> /// Get an existing value from the hash table. Return false if no such value exists. /// </summary> public bool TryGetValue(string key, int index, int count, out TValue value) { return _state.TryGetValue(key, index, count, out value); } /// <summary> /// Add a value to the hash table, hashed based on a string key embedded in it. Return the added value (may be a different object than "value"). /// </summary> public TValue Add(TValue value) { TValue newValue; // Loop until value is in hash table while (true) { // Add new value // XHashtableState.TryAdd returns false if hash table is not big enough if (_state.TryAdd(value, out newValue)) return newValue; // PUBLISH (state) // Hash table was not big enough, so resize it. // We only want one thread to perform a resize, as it is an expensive operation // First thread will perform resize; waiting threads will call Resize(), but should immediately // return since there will almost always be space in the hash table resized by the first thread. lock (this) { XHashtableState newState = _state.Resize(); // Use memory barrier to ensure that the resized XHashtableState object is fully constructed before it is assigned Thread.MemoryBarrier(); _state = newState; } } } /// <summary> /// This class contains all the hash table state. Rather than creating a bucket object, buckets are structs /// packed into an array. Buckets with the same truncated hash code are linked into lists, so that collisions /// can be disambiguated. /// </summary> /// <remarks> /// Note that the "buckets" and "entries" arrays are never themselves written by multiple threads. Instead, the /// *contents* of the array are written by multiple threads. Resizing the hash table does not modify these variables, /// or even modify the contents of these variables. Instead, resizing makes an entirely new XHashtableState object /// in which all entries are rehashed. This strategy allows reader threads to continue finding values in the "old" /// XHashtableState, while writer threads (those that need to add a new value to the table) are blocked waiting for /// the resize to complete. /// </remarks> private sealed class XHashtableState { private readonly int[] _buckets; // Buckets contain indexes into entries array (bucket values are SHARED STATE) private readonly Entry[] _entries; // Entries contain linked lists of buckets (next pointers are SHARED STATE) private int _numEntries; // SHARED STATE: Current number of entries (including orphaned entries) private readonly ExtractKeyDelegate _extractKey; // Delegate called in order to extract string key embedded in hashed TValue private const int EndOfList = 0; // End of linked list marker private const int FullList = -1; // Indicates entries should not be added to end of linked list /// <summary> /// Construct a new XHashtableState object with the specified capacity. /// </summary> public XHashtableState(ExtractKeyDelegate extractKey, int capacity) { Debug.Assert((capacity & (capacity - 1)) == 0, "capacity must be a power of 2"); Debug.Assert(extractKey != null, "extractKey may not be null"); // Initialize hash table data structures, with specified maximum capacity _buckets = new int[capacity]; _entries = new Entry[capacity]; // Save delegate _extractKey = extractKey; } /// <summary> /// If this table is not full, then just return "this". Otherwise, create and return a new table with /// additional capacity, and rehash all values in the table. /// </summary> public XHashtableState Resize() { // No need to resize if there are open entries if (_numEntries < _buckets.Length) return this; int newSize = 0; // Determine capacity of resized hash table by first counting number of valid, non-orphaned entries // As this count proceeds, close all linked lists so that no additional entries can be added to them for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; if (entryIdx == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _buckets[bucketIdx], FullList, EndOfList); } // Loop until we've guaranteed that the list has been counted and closed to further adds while (entryIdx > EndOfList) { // Count each valid entry if (_extractKey(_entries[entryIdx].Value) != null) newSize++; if (_entries[entryIdx].Next == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _entries[entryIdx].Next, FullList, EndOfList); } else { // Move to next entry in the list entryIdx = _entries[entryIdx].Next; } } Debug.Assert(entryIdx == EndOfList, "Resize() should only be called by one thread"); } // Double number of valid entries; if result is less than current capacity, then use current capacity if (newSize < _buckets.Length / 2) { newSize = _buckets.Length; } else { newSize = _buckets.Length * 2; if (newSize < 0) throw new OverflowException(); } // Create new hash table with additional capacity XHashtableState newHashtable = new XHashtableState(_extractKey, newSize); // Rehash names (TryAdd will always succeed, since we won't fill the new table) // Do not simply walk over entries and add them to table, as that would add orphaned // entries. Instead, walk the linked lists and add each name. for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; TValue newValue; while (entryIdx > EndOfList) { newHashtable.TryAdd(_entries[entryIdx].Value, out newValue); entryIdx = _entries[entryIdx].Next; } Debug.Assert(entryIdx == FullList, "Linked list should have been closed when it was counted"); } return newHashtable; } /// <summary> /// Attempt to find "key" in the table. If the key exists, return the associated value in "value" and /// return true. Otherwise return false. /// </summary> public bool TryGetValue(string key, int index, int count, out TValue value) { int hashCode = ComputeHashCode(key, index, count); int entryIndex = 0; // If a matching entry is found, return its value if (FindEntry(hashCode, key, index, count, ref entryIndex)) { value = _entries[entryIndex].Value; return true; } // No matching entry found, so return false value = default(TValue); return false; } /// <summary> /// Attempt to add "value" to the table, hashed by an embedded string key. If a value having the same key already exists, /// then return the existing value in "newValue". Otherwise, return the newly added value in "newValue". /// /// If the hash table is full, return false. Otherwise, return true. /// </summary> public bool TryAdd(TValue value, out TValue newValue) { int newEntry, entryIndex; string key; int hashCode; // Assume "value" will be added and returned as "newValue" newValue = value; // Extract the key from the value. If it's null, then value is invalid and does not need to be added to table. key = _extractKey(value); if (key == null) return true; // Compute hash code over entire length of key hashCode = ComputeHashCode(key, 0, key.Length); // Assume value is not yet in the hash table, and prepare to add it (if table is full, return false). // Use the entry index returned from Increment, which will never be zero, as zero conflicts with EndOfList. // Although this means that the first entry will never be used, it avoids the need to initialize all // starting buckets to the EndOfList value. newEntry = Interlocked.Increment(ref _numEntries); if (newEntry < 0 || newEntry >= _buckets.Length) return false; _entries[newEntry].Value = value; _entries[newEntry].HashCode = hashCode; // Ensure that all writes to the entry can't be reordered past this barrier (or other threads might see new entry // in list before entry has been initialized!). Thread.MemoryBarrier(); // Loop until a matching entry is found, a new entry is added, or linked list is found to be full entryIndex = 0; while (!FindEntry(hashCode, key, 0, key.Length, ref entryIndex)) { // PUBLISH (buckets slot) // No matching entry found, so add the new entry to the end of the list ("entryIndex" is index of last entry) if (entryIndex == 0) entryIndex = Interlocked.CompareExchange(ref _buckets[hashCode & (_buckets.Length - 1)], newEntry, EndOfList); else entryIndex = Interlocked.CompareExchange(ref _entries[entryIndex].Next, newEntry, EndOfList); // Return true only if the CompareExchange succeeded (happens when replaced value is EndOfList). // Return false if the linked list turned out to be full because another thread is currently resizing // the hash table. In this case, entries[newEntry] is orphaned (not part of any linked list) and the // Add needs to be performed on the new hash table. Otherwise, keep looping, looking for new end of list. if (entryIndex <= EndOfList) return entryIndex == EndOfList; } // Another thread already added the value while this thread was trying to add, so return that instance instead. // Note that entries[newEntry] will be orphaned (not part of any linked list) in this case newValue = _entries[entryIndex].Value; return true; } /// <summary> /// Searches a linked list of entries, beginning at "entryIndex". If "entryIndex" is 0, then search starts at a hash bucket instead. /// Each entry in the list is matched against the (hashCode, key, index, count) key. If a matching entry is found, then its /// entry index is returned in "entryIndex" and true is returned. If no matching entry is found, then the index of the last entry /// in the list (or 0 if list is empty) is returned in "entryIndex" and false is returned. /// </summary> /// <remarks> /// This method has the side effect of removing invalid entries from the list as it is traversed. /// </remarks> private bool FindEntry(int hashCode, string key, int index, int count, ref int entryIndex) { int previousIndex = entryIndex; int currentIndex; // Set initial value of currentIndex to index of the next entry following entryIndex if (previousIndex == 0) currentIndex = _buckets[hashCode & (_buckets.Length - 1)]; else currentIndex = previousIndex; // Loop while not at end of list while (currentIndex > EndOfList) { // Check for matching hash code, then matching key if (_entries[currentIndex].HashCode == hashCode) { string keyCompare = _extractKey(_entries[currentIndex].Value); // If the key is invalid, then attempt to remove the current entry from the linked list. // This is thread-safe in the case where the Next field points to another entry, since once a Next field points // to another entry, it will never be modified to be EndOfList or FullList. if (keyCompare == null) { if (_entries[currentIndex].Next > EndOfList) { // PUBLISH (buckets slot or entries slot) // Entry is invalid, so modify previous entry to point to its next entry _entries[currentIndex].Value = default(TValue); currentIndex = _entries[currentIndex].Next; if (previousIndex == 0) _buckets[hashCode & (_buckets.Length - 1)] = currentIndex; else _entries[previousIndex].Next = currentIndex; continue; } } else { // Valid key, so compare keys if (count == keyCompare.Length && string.CompareOrdinal(key, index, keyCompare, 0, count) == 0) { // Found match, so return true and matching entry in list entryIndex = currentIndex; return true; } } } // Move to next entry previousIndex = currentIndex; currentIndex = _entries[currentIndex].Next; } // Return false and last entry in list entryIndex = previousIndex; return false; } /// <summary> /// Compute hash code for a string key (index, count substring of "key"). The algorithm used is the same on used in NameTable.cs in System.Xml. /// </summary> private static int ComputeHashCode(string key, int index, int count) { Debug.Assert(key != null, "key should have been checked previously for null"); return string.GetHashCode(key.AsSpan(index, count)); } /// <summary> /// Hash table entry. The "Value" and "HashCode" fields are filled during initialization, and are never changed. The "Next" /// field is updated when a new entry is chained to this one, and therefore care must be taken to ensure that updates to /// this field are thread-safe. /// </summary> private struct Entry { public TValue Value; // Hashed value public int HashCode; // Hash code of string key (equal to extractKey(Value).GetHashCode()) public int Next; // SHARED STATE: Points to next entry in linked list } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Pixie.Code; using Pixie.Markup; using Pixie.Terminal.Devices; namespace Pixie.Terminal.Render { /// <summary> /// An enumeration of possible highlighted source span types. /// </summary> public enum HighlightedSourceSpanKind { /// <summary> /// Non-highlighted source code. /// </summary> Source, /// <summary> /// Highlighted source code with focus. /// </summary> Focus, /// <summary> /// Highlighted source code without focus. /// </summary> Highlight } /// <summary> /// Describes a highlighted span of source code. /// </summary> public struct HighlightedSourceSpan { /// <summary> /// Creates a highlighted source span from a kind and a /// string of text. /// </summary> /// <param name="kind">The source span's kind.</param> /// <param name="text">The source span's text.</param> public HighlightedSourceSpan( HighlightedSourceSpanKind kind, string text) { this = default(HighlightedSourceSpan); this.Kind = kind; this.Text = text; } /// <summary> /// Gets this source span's kind. /// </summary> /// <returns></returns> public HighlightedSourceSpanKind Kind { get; private set; } /// <summary> /// Gets this span of source code as text. /// </summary> /// <returns>The source span's text.</returns> public string Text { get; private set; } } /// <summary> /// A renderer for highlighted source code. /// </summary> public class HighlightedSourceRenderer : NodeRenderer { /// <summary> /// Create a highlighted source renderer. /// </summary> /// <param name="contextLineCount"> /// The number of lines that are printed for context /// below and above the focus line. /// </param> public HighlightedSourceRenderer(int contextLineCount) : this(contextLineCount, Colors.Green) { } /// <summary> /// Create a highlighted source renderer that highlights source /// using a particular color. /// </summary> /// <param name="contextLineCount"> /// The number of lines that are printed for context /// below and above the focus line. /// </param> /// <param name="defaultHighlightColor">The default highlight color.</param> public HighlightedSourceRenderer( int contextLineCount, Color defaultHighlightColor) { this.ContextLineCount = contextLineCount; this.DefaultHighlightColor = defaultHighlightColor; } /// <summary> /// Gets the default color with which source code is highlighted. /// </summary> /// <returns>The default highlight color.</returns> public Color DefaultHighlightColor { get; private set; } /// <summary> /// Gets the number of lines that are printed for context /// below and above the focus line. /// </summary> /// <returns>The number of context lines.</returns> public int ContextLineCount { get; private set; } /// <inheritdoc/> public override bool CanRender(MarkupNode node) { return node is HighlightedSource; } /// <summary> /// The color to highlight source code in. /// </summary> public const string HighlightColorProperty = "highlight-source-color"; /// <summary> /// Gets the color to highlight source code in. /// </summary> /// <param name="state">The state of the renderer.</param> /// <returns>The source highlighting color.</returns> protected Color GetHighlightColor(RenderState state) { object colorVal; if (state.ThemeProperties.TryGetValue( HighlightColorProperty, out colorVal)) { return (Color)colorVal; } else { return DefaultHighlightColor; } } /// <inheritdoc/> public override void Render(MarkupNode node, RenderState state) { var src = (HighlightedSource)node; var highlightRegion = src.HighlightRegion; var focusRegion = src.FocusRegion; var document = focusRegion.Document; // The idea is to visualize the first line of the focus region, // plus a number of lines of context. int focusLine = document.GetGridPosition(focusRegion.StartOffset).LineIndex; int firstLineNumber = -1; var lines = new List<IReadOnlyList<HighlightedSourceSpan>>(); for (int i = -ContextLineCount; i <= ContextLineCount; i++) { var lineSpans = LineToSpans(focusLine + i, highlightRegion, focusRegion); if (lineSpans != null) { if (firstLineNumber < 0) { firstLineNumber = focusLine + i; } lines.Add(lineSpans); } } var compressedLines = CompressLeadingWhitespace(lines); var maxLineWidth = GetLineWidth( firstLineNumber + compressedLines.Count, state); state.Terminal.WriteSeparator(2); for (int i = 0; i < compressedLines.Count; i++) { RenderLine( WrapSpans(compressedLines[i], maxLineWidth), firstLineNumber + i, firstLineNumber + compressedLines.Count - 1, state); } state.Terminal.WriteSeparator(2); } /// <summary> /// Gets the number of characters a source line can be wide. /// </summary> /// <param name="greatestLineIndex">The greatest line index to render.</param> /// <param name="state">A render state.</param> /// <returns>The line width.</returns> protected virtual int GetLineWidth(int greatestLineIndex, RenderState state) { return state.Terminal.Width - GetLineContinuatorPrefix(greatestLineIndex, greatestLineIndex, state).Length // Left padding - 4; // Right padding } /// <summary> /// Renders a single line of code that has been line-wrapped. /// </summary> /// <param name="wrappedSpans"> /// A line-wrapped list of highlighted spans. /// </param> /// <param name="lineIndex">The line's zero-based index.</param> /// <param name="greatestLineIndex"> /// The greatest zero-based line index that will be rendered. /// </param> /// <param name="state">The render state.</param> protected virtual void RenderLine( IReadOnlyList<IReadOnlyList<HighlightedSourceSpan>> wrappedSpans, int lineIndex, int greatestLineIndex, RenderState state) { state.Terminal.Write( GetLineNumberPrefix(lineIndex, greatestLineIndex, state)); // If we encounter an empty line, then we want to write // a newline and return. var wrappedSpanCount = wrappedSpans.Count; if (wrappedSpanCount == 0) { state.Terminal.WriteLine(); return; } var continuatorPrefix = GetLineContinuatorPrefix( lineIndex, greatestLineIndex, state); var newTerm = new LayoutTerminal( state.Terminal, Alignment.Left, WrappingStrategy.Character, continuatorPrefix, state.Terminal.Width); newTerm.SuppressPadding(); var newState = state.WithTerminal(newTerm); for (int i = 0; i < wrappedSpanCount; i++) { var wrappedSpanLine = wrappedSpans[i]; for (int j = 0; j < wrappedSpanLine.Count; j++) { RenderSpanText(wrappedSpanLine[j], newState); } newTerm.WriteLine(); if (IsHighlighted(wrappedSpanLine)) { for (int j = 0; j < wrappedSpanLine.Count; j++) { RenderSpanSquiggle(wrappedSpanLine[j], newState); } newTerm.WriteLine(); } } newTerm.Flush(); } private const string leftWhitespace = " "; /// <summary> /// Gets the line number prefix that. is prepended to /// each new line. /// </summary> /// <param name="lineIndex">The index of the line.</param> /// <param name="greatestLineIndex"> /// The greatest line index that will be rendered. /// </param> /// <param name="state"> /// A render state. /// </param> /// <returns>A line number prefix.</returns> protected virtual string GetLineNumberPrefix( int lineIndex, int greatestLineIndex, RenderState state) { var numString = (lineIndex + 1).ToString(); var maxString = (greatestLineIndex + 1).ToString(); var sb = new StringBuilder(); sb.Append(leftWhitespace); sb.Append(' ', maxString.Length - numString.Length); sb.Append(numString); sb.Append(GetSeparatorBar(state)); return sb.ToString(); } /// <summary> /// Gets the line continuator prefix that. is prepended to /// the start of each wrapped line. /// </summary> /// <param name="lineIndex">The index of the line.</param> /// <param name="greatestLineIndex"> /// The greatest line index that will be rendered. /// </param> /// <param name="state"> /// A render state. /// </param> /// <returns>A line continuator prefix.</returns> protected virtual string GetLineContinuatorPrefix( int lineIndex, int greatestLineIndex, RenderState state) { var maxString = (greatestLineIndex + 1).ToString(); var sb = new StringBuilder(); sb.Append(leftWhitespace); sb.Append(' ', maxString.Length); sb.Append(GetSeparatorBar(state)); return sb.ToString(); } /// <summary> /// Gets a string that contains a bar with whitespace on both sides, /// useful for delimiting line numbers and code. /// </summary> /// <param name="state">A render state.</param> /// <returns>A string of characters.</returns> protected string GetSeparatorBar(RenderState state) { var sb = new StringBuilder(); sb.Append(' '); sb.Append(state.Terminal.GetFirstRenderableString("\u2502", "|", "-") ?? ""); sb.Append(' '); return sb.ToString(); } /// <summary> /// Renders a span's text. /// </summary> /// <param name="span">A span whose text is to be rendered.</param> /// <param name="state">A render state.</param> protected virtual void RenderSpanText( HighlightedSourceSpan span, RenderState state) { if (span.Kind == HighlightedSourceSpanKind.Focus) { state.Terminal.Style.PushForegroundColor(GetHighlightColor(state)); state.Terminal.Style.PushDecoration( TextDecoration.Bold, DecorationSpan.UnifyDecorations); try { state.Terminal.Write(span.Text); } finally { state.Terminal.Style.PopStyle(); state.Terminal.Style.PopStyle(); } } else { state.Terminal.Write(span.Text); } } /// <summary> /// Renders the squiggle under a span. /// </summary> /// <param name="span">A span for which a squiggle is to be rendered.</param> /// <param name="state">A render state.</param> protected virtual void RenderSpanSquiggle( HighlightedSourceSpan span, RenderState state) { var spanLength = new StringInfo(span.Text).LengthInTextElements; char caret = '^'; char squiggle = '~'; if (span.Kind == HighlightedSourceSpanKind.Highlight) { state.Terminal.Style.PushForegroundColor(GetHighlightColor(state)); try { for (int i = 0; i < spanLength; i++) { state.Terminal.Write(squiggle); } } finally { state.Terminal.Style.PopStyle(); } } else if (span.Kind == HighlightedSourceSpanKind.Focus) { state.Terminal.Style.PushForegroundColor(GetHighlightColor(state)); state.Terminal.Style.PushDecoration( TextDecoration.Bold, DecorationSpan.UnifyDecorations); try { for (int i = 0; i < spanLength; i++) { state.Terminal.Write(i == 0 ? caret : squiggle); } } finally { state.Terminal.Style.PopStyle(); state.Terminal.Style.PopStyle(); } } else { for (int i = 0; i < spanLength; i++) { state.Terminal.Write(' '); } } } /// <summary> /// Identifies and compresses leading whitespace in a list /// of lines, where each line is encoded as a highlighted span. /// </summary> /// <param name="lines">A list of lines.</param> /// <returns>A new list of lines.</returns> protected virtual IReadOnlyList<IReadOnlyList<HighlightedSourceSpan>> CompressLeadingWhitespace( IReadOnlyList<IReadOnlyList<HighlightedSourceSpan>> lines) { // TODO: implement this return lines; } /// <summary> /// Line-wraps a list of highlighted source spans. /// </summary> /// <param name="spans">The spans to line-wrap.</param> /// <param name="lineLength">The maximum length of a line.</param> /// <returns>A list of lines, where each line is encoded as a list of spans.</returns> protected virtual IReadOnlyList<IReadOnlyList<HighlightedSourceSpan>> WrapSpans( IReadOnlyList<HighlightedSourceSpan> spans, int lineLength) { var allLines = new List<IReadOnlyList<HighlightedSourceSpan>>(); var currentLine = new List<HighlightedSourceSpan>(); var spanCount = spans.Count; int length = 0; for (int i = 0; i < spanCount; i++) { AppendSpanToLine(spans[i], ref currentLine, ref length, allLines, lineLength); } if (currentLine.Count != 0) { allLines.Add(currentLine); } return allLines; } private static void AppendSpanToLine( HighlightedSourceSpan span, ref List<HighlightedSourceSpan> line, ref int lineLength, List<IReadOnlyList<HighlightedSourceSpan>> allLines, int maxLineLength) { var spanInfo = new StringInfo(span.Text); if (spanInfo.LengthInTextElements == 0) { // Do nothing. } else if (lineLength + spanInfo.LengthInTextElements <= maxLineLength) { // Easy case: append entire span to line. line.Add(span); lineLength += spanInfo.LengthInTextElements; } else { // Slightly more complicated case: split the span. var remainingElements = maxLineLength - lineLength; var first = spanInfo.SubstringByTextElements(0, remainingElements); var second = spanInfo.SubstringByTextElements(remainingElements); // Append the first part. line.Add(new HighlightedSourceSpan(span.Kind, first)); // Start a new line. allLines.Add(line); line = new List<HighlightedSourceSpan>(); lineLength = 0; // Append the second part. AppendSpanToLine( new HighlightedSourceSpan(span.Kind, second), ref line, ref lineLength, allLines, maxLineLength); } } private static HighlightedSourceSpanKind GetCharacterKind( int offset, SourceRegion highlightRegion, SourceRegion focusRegion) { if (focusRegion.Contains(offset)) return HighlightedSourceSpanKind.Focus; else if (highlightRegion.Contains(offset)) return HighlightedSourceSpanKind.Highlight; else return HighlightedSourceSpanKind.Source; } /// <summary> /// Chunks a line into a list of highlighted spans. /// </summary> /// <param name="lineText">The line's text.</param> /// <param name="lineStartOffset"> /// The offset of the first character in the line. /// </param> /// <param name="highlightRegion"> /// The highlighted region. /// </param> /// <param name="focusRegion"> /// The focus region. /// </param> /// <returns>A list of highlighted spans.</returns> private static IReadOnlyList<HighlightedSourceSpan> LineToSpans( string lineText, int lineStartOffset, SourceRegion highlightRegion, SourceRegion focusRegion) { var spans = new List<HighlightedSourceSpan>(); var kind = HighlightedSourceSpanKind.Source; int spanStart = 0; for (int i = 0; i < lineText.Length; i++) { var charKind = GetCharacterKind( lineStartOffset + i, highlightRegion, focusRegion); if (charKind != kind) { if (spanStart != i) { spans.Add( new HighlightedSourceSpan( kind, lineText .Substring(spanStart, i - spanStart) .Replace("\t", " "))); } kind = charKind; spanStart = i; } } if (spanStart != lineText.Length) { spans.Add( new HighlightedSourceSpan( kind, lineText .Substring(spanStart) .TrimEnd() .Replace("\t", " "))); } return spans; } /// <summary> /// Chunks a line into a list of highlighted spans. /// </summary> /// <param name="lineIndex">The line's zero-based index.</param> /// <param name="highlightRegion"> /// The highlighted region. /// </param> /// <param name="focusRegion"> /// The focus region. /// </param> /// <returns>A list of highlighted spans.</returns> private static IReadOnlyList<HighlightedSourceSpan> LineToSpans( int lineIndex, SourceRegion highlightRegion, SourceRegion focusRegion) { var document = focusRegion.Document; int lineStart = document.GetLineOffset(lineIndex); int lineEnd = document.GetLineOffset(lineIndex + 1); if (lineStart == lineEnd) { // Nothing to do here. return null; } var lineText = document.GetText(lineStart, lineEnd - lineStart).TrimEnd(); return LineToSpans(lineText, lineStart, highlightRegion, focusRegion); } private static bool IsHighlighted( IReadOnlyList<HighlightedSourceSpan> spans) { return spans.Any<HighlightedSourceSpan>(IsHighlighted); } private static bool IsHighlighted( HighlightedSourceSpan span) { return span.Kind != HighlightedSourceSpanKind.Source; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace <insert your namespace here> { public class ProgressBar : Microsoft.Xna.Framework.GameComponent { #region Variables Texture2D backgroundTexture; Texture2D barTexture; bool m_showText; bool m_isDecreasing = false; bool m_isIncreasing = false; float m_min = 0; float m_max = 100; float m_value = 0; float m_secondaryValue = 0; int m_height = 5; int m_width = 100; Color m_backgroundColor = Color.White; Color m_primaryColor = Color.LightBlue; Color m_secondaryColor = Color.Red; Vector2 m_position = Vector2.Zero; SpriteFont m_font = null; //reserved for future features Orientation m_orientation = Orientation.HorizontalLTR; Animation m_decreaseAnim = Animation.Fade; Animation m_increaseAnim = Animation.Bounce; //float pulseScale = 8f; //float pulseNormalize = 1f; #endregion #region Properties public bool ShowText { get { return m_showText; } set { m_showText = value; } } public float Value { get { return m_value; } set { if (Minimum <= value && value <= Maximum) { m_value = value; } } } public float Minimum { get { return m_min; } set { m_min = value; } } public float Maximum { get { return m_max; } set { m_max = value; } } public Color BackgroundColor { get { return m_backgroundColor; } set { m_backgroundColor = value; } } public Color PrimaryColor { get { return m_primaryColor; } set { m_primaryColor = value; } } public Color SecondaryColor { get { return m_secondaryColor; } set { m_secondaryColor = value; } } public Vector2 Position { get { return m_position; } set { m_position = value; } } public SpriteFont Font { get { return m_font; } set { m_font = value; } } public int Height { get { return m_height; } set { m_height = value; } } public int Width { get { return m_width; } set { m_width = value; } } #endregion #region Constructors public ProgressBar(Game game) : base(game) { } public ProgressBar(Game game, SpriteFont font) : base(game) { m_font = font; } #endregion #region Initialize & Update Methods public override void Initialize() { backgroundTexture = Game.Content.Load<Texture2D>("bg"); barTexture = Game.Content.Load<Texture2D>("bg"); base.Initialize(); } public override void Update(GameTime gameTime) { base.Update(gameTime); } #endregion #region Custom Methods public void Draw(SpriteBatch spriteBatch) { DrawBackground(spriteBatch); DrawSecondaryBar(spriteBatch); DrawPrimaryBar(spriteBatch); DrawNumber(spriteBatch); } private void DrawBackground(SpriteBatch spriteBatch) { spriteBatch.Draw(backgroundTexture, new Rectangle((int)Position.X, (int)Position.Y, Width, Height), BackgroundColor); } private void DrawPrimaryBar(SpriteBatch spriteBatch) { int BarWidth = (int)(Width / Maximum * Value); spriteBatch.Draw(barTexture, new Rectangle((int)Position.X, (int)Position.Y, BarWidth, 5), PrimaryColor); } private void DrawNumber(SpriteBatch spriteBatch) { if (Font != null) { Vector2 stringSize = Font.MeasureString((Value / Maximum * 100).ToString()); spriteBatch.DrawString(Font, (Value / Maximum * 100).ToString(), new Vector2(Position.X + (Width / 2) - (stringSize.X / 2), Position.Y - 20f), Color.White); } } private void DrawSecondaryBar(SpriteBatch spriteBatch) { int BarWidth = (int)(Width / Maximum * Value); spriteBatch.Draw(barTexture, new Rectangle((int)Position.X, (int)Position.Y, BarWidth, 5), SecondaryColor); } public void Increase(float amount) { m_isIncreasing = true; if (amount <= (Maximum - Value)) { Value += amount; } else { Value = Maximum; } m_isIncreasing = false; } public void Decrease(float amount) { m_isDecreasing = true; if (amount <= Value) { Value -= amount; } else { Value = Minimum; } m_isDecreasing = false; } #endregion #region Animation & Orientation public enum Animation { Bounce, Fade, None } public enum Orientation { HorizontalLTR, HorizontalRTL, VerticalLTR, VeritcalRTL } #endregion } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.CSharp.RuntimeBinder; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Implementation; using OrchardCore.Environment.Extensions; namespace OrchardCore.DisplayManagement.Descriptors.ShapeAttributeStrategy { public class ShapeAttributeBindingStrategy : IShapeTableHarvester { private static readonly ConcurrentDictionary<string, CallSite<Func<CallSite, object, dynamic>>> _getters = new ConcurrentDictionary<string, CallSite<Func<CallSite, object, dynamic>>>(); private static readonly ConcurrentDictionary<MethodInfo, ParameterInfo[]> _parameters = new ConcurrentDictionary<MethodInfo, ParameterInfo[]>(); private readonly ITypeFeatureProvider _typeFeatureProvider; private readonly IEnumerable<IShapeAttributeProvider> _shapeProviders; public ShapeAttributeBindingStrategy( ITypeFeatureProvider typeFeatureProvider, IEnumerable<IShapeAttributeProvider> shapeProviders) { _typeFeatureProvider = typeFeatureProvider; _shapeProviders = shapeProviders; } public void Discover(ShapeTableBuilder builder) { var shapeAttributeOccurrences = new List<ShapeAttributeOccurrence>(); foreach (var shapeProvider in _shapeProviders) { var serviceType = shapeProvider.GetType(); foreach (var method in serviceType.GetMethods()) { var customAttributes = method.GetCustomAttributes(typeof(ShapeAttribute), false).OfType<ShapeAttribute>(); foreach (var customAttribute in customAttributes) { shapeAttributeOccurrences.Add(new ShapeAttributeOccurrence(customAttribute, method, serviceType)); } } } foreach (var iter in shapeAttributeOccurrences) { var occurrence = iter; var shapeType = occurrence.ShapeAttribute.ShapeType ?? occurrence.MethodInfo.Name; builder.Describe(shapeType) .From(_typeFeatureProvider.GetFeatureForDependency(occurrence.ServiceType)) .BoundAs( occurrence.MethodInfo.DeclaringType.FullName + "::" + occurrence.MethodInfo.Name, CreateDelegate(occurrence)); } } [DebuggerStepThrough] private Func<DisplayContext, Task<IHtmlContent>> CreateDelegate( ShapeAttributeOccurrence attributeOccurrence) { return context => { var serviceInstance = context.ServiceProvider.GetService(attributeOccurrence.ServiceType); // oversimplification for the sake of evolving return PerformInvokeAsync(context, attributeOccurrence.MethodInfo, serviceInstance); }; } private static Task<IHtmlContent> PerformInvokeAsync(DisplayContext displayContext, MethodInfo methodInfo, object serviceInstance) { var parameters = _parameters.GetOrAdd(methodInfo, m => m.GetParameters()); var arguments = parameters.Select(parameter => BindParameter(displayContext, parameter)); // Resolve the service the method is declared on var returnValue = methodInfo.Invoke(serviceInstance, arguments.ToArray()); if (methodInfo.ReturnType == typeof(Task<IHtmlContent>)) { return (Task<IHtmlContent>)returnValue; } else if (methodInfo.ReturnType == typeof(IHtmlContent)) { return Task.FromResult((IHtmlContent)returnValue); } else if (methodInfo.ReturnType != typeof(void)) { return Task.FromResult(CoerceHtmlContent(returnValue)); } return Task.FromResult<IHtmlContent>(null); } private static IHtmlContent CoerceHtmlContent(object invoke) { if (invoke == null) { return HtmlString.Empty; } if (invoke is IHtmlContent htmlContent) { return htmlContent; } return new HtmlString(invoke.ToString()); } private static object BindParameter(DisplayContext displayContext, ParameterInfo parameter) { if (String.Equals(parameter.Name, "Shape", StringComparison.OrdinalIgnoreCase)) { return displayContext.Value; } if (String.Equals(parameter.Name, "DisplayAsync", StringComparison.OrdinalIgnoreCase)) { return displayContext.DisplayAsync; } if (String.Equals(parameter.Name, "New", StringComparison.OrdinalIgnoreCase)) { return displayContext.ServiceProvider.GetService<IShapeFactory>(); } if (String.Equals(parameter.Name, "Html", StringComparison.OrdinalIgnoreCase)) { var viewContextAccessor = displayContext.ServiceProvider.GetRequiredService<ViewContextAccessor>(); var viewContext = viewContextAccessor.ViewContext; return MakeHtmlHelper(viewContext, viewContext.ViewData); } if (String.Equals(parameter.Name, "DisplayContext", StringComparison.OrdinalIgnoreCase)) { return displayContext; } if (String.Equals(parameter.Name, "Url", StringComparison.OrdinalIgnoreCase) && typeof(IUrlHelper).IsAssignableFrom(parameter.ParameterType)) { var viewContextAccessor = displayContext.ServiceProvider.GetRequiredService<ViewContextAccessor>(); var viewContext = viewContextAccessor.ViewContext; var urlHelperFactory = displayContext.ServiceProvider.GetService<IUrlHelperFactory>(); return urlHelperFactory.GetUrlHelper(viewContext); } if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) && parameter.ParameterType == typeof(TextWriter)) { throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead."); } if (String.Equals(parameter.Name, "Output", StringComparison.OrdinalIgnoreCase) && parameter.ParameterType == typeof(Action<object>)) { throw new InvalidOperationException("Output is no more a valid Shape method parameter. Return an IHtmlContent instead."); } var getter = _getters.GetOrAdd(parameter.Name, n => CallSite<Func<CallSite, object, dynamic>>.Create( Microsoft.CSharp.RuntimeBinder.Binder.GetMember( CSharpBinderFlags.None, n, null, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }))); object result = getter.Target(getter, displayContext.Value); if (result == null) { return null; } if (parameter.ParameterType.IsAssignableFrom(result.GetType())) { return result; } // Specific implementation for DateTimes if (result.GetType() == typeof(string) && (parameter.ParameterType == typeof(DateTime) || parameter.ParameterType == typeof(DateTime?))) { return DateTime.Parse((string)result); } return Convert.ChangeType(result, parameter.ParameterType); } private static IHtmlHelper MakeHtmlHelper(ViewContext viewContext, ViewDataDictionary viewData) { var newHelper = viewContext.HttpContext.RequestServices.GetRequiredService<IHtmlHelper>(); var contextable = newHelper as IViewContextAware; if (contextable != null) { var newViewContext = new ViewContext(viewContext, viewContext.View, viewData, viewContext.Writer); contextable.Contextualize(newViewContext); } return newHelper; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type MessageRequest. /// </summary> public partial class MessageRequest : BaseRequest, IMessageRequest { /// <summary> /// Constructs a new MessageRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public MessageRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Message using POST. /// </summary> /// <param name="messageToCreate">The Message to create.</param> /// <returns>The created Message.</returns> public System.Threading.Tasks.Task<Message> CreateAsync(Message messageToCreate) { return this.CreateAsync(messageToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Message using POST. /// </summary> /// <param name="messageToCreate">The Message to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Message.</returns> public async System.Threading.Tasks.Task<Message> CreateAsync(Message messageToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Message>(messageToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Message. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Message. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Message>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Message. /// </summary> /// <returns>The Message.</returns> public System.Threading.Tasks.Task<Message> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Message. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Message.</returns> public async System.Threading.Tasks.Task<Message> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Message>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Message using PATCH. /// </summary> /// <param name="messageToUpdate">The Message to update.</param> /// <returns>The updated Message.</returns> public System.Threading.Tasks.Task<Message> UpdateAsync(Message messageToUpdate) { return this.UpdateAsync(messageToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Message using PATCH. /// </summary> /// <param name="messageToUpdate">The Message to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Message.</returns> public async System.Threading.Tasks.Task<Message> UpdateAsync(Message messageToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Message>(messageToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IMessageRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IMessageRequest Expand(Expression<Func<Message, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IMessageRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IMessageRequest Select(Expression<Func<Message, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="messageToInitialize">The <see cref="Message"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Message messageToInitialize) { if (messageToInitialize != null && messageToInitialize.AdditionalData != null) { if (messageToInitialize.Attachments != null && messageToInitialize.Attachments.CurrentPage != null) { messageToInitialize.Attachments.AdditionalData = messageToInitialize.AdditionalData; object nextPageLink; messageToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { messageToInitialize.Attachments.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (messageToInitialize.Extensions != null && messageToInitialize.Extensions.CurrentPage != null) { messageToInitialize.Extensions.AdditionalData = messageToInitialize.AdditionalData; object nextPageLink; messageToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { messageToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (messageToInitialize.SingleValueExtendedProperties != null && messageToInitialize.SingleValueExtendedProperties.CurrentPage != null) { messageToInitialize.SingleValueExtendedProperties.AdditionalData = messageToInitialize.AdditionalData; object nextPageLink; messageToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { messageToInitialize.SingleValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (messageToInitialize.MultiValueExtendedProperties != null && messageToInitialize.MultiValueExtendedProperties.CurrentPage != null) { messageToInitialize.MultiValueExtendedProperties.AdditionalData = messageToInitialize.AdditionalData; object nextPageLink; messageToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { messageToInitialize.MultiValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using hw.Helper; using JetBrains.Annotations; // ReSharper disable CheckNamespace namespace hw.DebugFormatter { [Dump("Dump")] [DebuggerDisplay("{" + nameof(DebuggerDumpString) + "}")] public class Dumpable { sealed class MethodDumpTraceItem { internal int FrameCount { get; } internal bool Trace { get; } public MethodDumpTraceItem(int frameCount, bool trace) { FrameCount = frameCount; Trace = trace; } } [PublicAPI] public static bool? IsMethodDumpTraceInhibited; static readonly Stack<MethodDumpTraceItem> MethodDumpTraceSwitches = new Stack<MethodDumpTraceItem>(); /// <summary> /// Gets a value indicating whether this instance is in dump. /// </summary> /// <value> /// <c>true</c> /// if this instance is in dump; otherwise, /// <c>false</c> /// . /// </value> /// created 23.09.2006 17:39 [DisableDump] [PublicAPI] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsInDump { get; set; } /// <summary> /// dump string to be shown in debug windows /// </summary> [DisableDump] [PublicAPI] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string DebuggerDumpString => DebuggerDump().Replace("\n", "\r\n"); [DisableDump] [PublicAPI] // ReSharper disable once InconsistentNaming public string d => DebuggerDumpString; static bool IsMethodDumpTraceActive => !IsMethodDumpTraceInhibited ?? Debugger.IsAttached && MethodDumpTraceSwitches.Peek().Trace; /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] [PublicAPI] public static void NotImplementedFunction(params object[] p) { var os = Tracer.DumpMethodWithData("not implemented", null, p, 1); os.Log(); Tracer.TraceBreak(); } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="value"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] [PublicAPI] public static void Dump(string name, object value) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", new[] {name, value}, 1); os.Log(); } } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="getValue"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] [PublicAPI] public static void Dump(string name, Func<object> getValue) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", new[] {name, getValue()}, 1); os.Log(); } } /// <summary> /// generate dump string to be shown in debug windows /// </summary> /// <returns> </returns> [PublicAPI] public virtual string DebuggerDump() => Tracer.Dump(this); // ReSharper disable once InconsistentNaming [PublicAPI] [IsLoggingFunction] public void t() => DebuggerDumpString.Log(); public string Dump() { var oldIsInDump = IsInDump; IsInDump = true; try { return Dump(oldIsInDump); } finally { IsInDump = oldIsInDump; } } [PublicAPI] public virtual string DumpData() { string result; try { result = Tracer.DumpData(this); } catch(Exception) { result = "<not implemented>"; } return result; } [PublicAPI] public void Dispose() { } /// <summary> /// Method dump, /// </summary> /// <param name="rv"> </param> /// <param name="breakExecution"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] protected static T ReturnMethodDump<T>(T rv, bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); (Tracer.MethodHeader(stackFrameDepth: 1) + "[returns] " + Tracer.Dump(rv)).Log(); if(breakExecution) Tracer.TraceBreak(); } return rv; } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] [PublicAPI] [IsLoggingFunction] protected static void ReturnVoidMethodDump(bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); (Tracer.MethodHeader(stackFrameDepth: 1) + "[returns]").Log(); if(breakExecution) Tracer.TraceBreak(); } } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void EndMethodDump() { if(!Debugger.IsAttached) return; CheckDumpLevel(1); MethodDumpTraceSwitches.Pop(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] [PublicAPI] [IsLoggingFunction] protected static void DumpDataWithBreak(string text, params object[] p) { var os = Tracer.DumpData(text, p, 1); os.Log(); Tracer.TraceBreak(); } /// <summary> /// Method start dump, /// </summary> /// <param name="trace"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] protected void StartMethodDump(bool trace, params object[] p) { StartMethodDump(1, trace); if(!IsMethodDumpTraceActive) return; var os = Tracer.DumpMethodWithData("", this, p, 1); os.Log(); Tracer.IndentStart(); } [DebuggerHidden] [PublicAPI] protected void BreakExecution() { if(IsMethodDumpTraceActive) Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] [PublicAPI] [IsLoggingFunction] protected void DumpMethodWithBreak(string text, params object[] p) { var os = Tracer.DumpMethodWithData(text, this, p, 1); os.Log(); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] [IsLoggingFunction] protected void NotImplementedMethod(params object[] p) { if(IsInDump) throw new NotImplementedException(); var os = Tracer.DumpMethodWithData("not implemented", this, p, 1); os.Log(); Tracer.TraceBreak(); } protected virtual string Dump(bool isRecursion) { var surround = "<recursion>"; if(!isRecursion) surround = DumpData().Surround("{", "}"); return GetType().PrettyName() + surround; } static void CheckDumpLevel(int depth) { if(!Debugger.IsAttached) return; var top = MethodDumpTraceSwitches.Peek(); if(top.Trace) Tracer.Assert(top.FrameCount == Tracer.CurrentFrameCount(depth + 1)); } static void StartMethodDump(int depth, bool trace) { if(!Debugger.IsAttached) return; var frameCount = trace? Tracer.CurrentFrameCount(depth + 1) : 0; MethodDumpTraceSwitches.Push(new MethodDumpTraceItem(frameCount, trace)); } public static TValue[] T<TValue>(params TValue[] value) => value; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** EnumBuilder is a helper class to build Enum ( a special type ). ** ** ===========================================================*/ namespace System.Reflection.Emit { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.InteropServices; using CultureInfo = System.Globalization.CultureInfo; using System.Security.Permissions; [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EnumBuilder))] [System.Runtime.InteropServices.ComVisible(true)] sealed public class EnumBuilder : TypeInfo, _EnumBuilder { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } // Define literal for enum public FieldBuilder DefineLiteral(String literalName, Object literalValue) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: EnumBuilder.DefineLiteral( " + literalName + " )"); // Define the underlying field for the enum. It will be a non-static, private field with special name bit set. FieldBuilder fieldBuilder = m_typeBuilder.DefineField( literalName, this, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal); fieldBuilder.SetConstant(literalValue); return fieldBuilder; } public TypeInfo CreateTypeInfo() { BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.CreateType() "); return m_typeBuilder.CreateTypeInfo(); } // CreateType cause EnumBuilder to be baked. public Type CreateType() { BCLDebug.Log("DYNIL","## DYNIL LOGGING: EnumBuilder.CreateType() "); return m_typeBuilder.CreateType(); } // Get the internal metadata token for this class. public TypeToken TypeToken { get {return m_typeBuilder.TypeToken; } } // return the underlying field for the enum public FieldBuilder UnderlyingField { get {return m_underlyingField; } } public override String Name { get { return m_typeBuilder.Name; } } /**************************************************** * * abstract methods defined in the base class * */ public override Guid GUID { get { return m_typeBuilder.GUID; } } public override Object InvokeMember( String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } public override Module Module { get {return m_typeBuilder.Module;} } public override Assembly Assembly { get {return m_typeBuilder.Assembly;} } public override RuntimeTypeHandle TypeHandle { get {return m_typeBuilder.TypeHandle;} } public override String FullName { get { return m_typeBuilder.FullName;} } public override String AssemblyQualifiedName { get { return m_typeBuilder.AssemblyQualifiedName; } } public override String Namespace { get { return m_typeBuilder.Namespace;} } public override Type BaseType { get{return m_typeBuilder.BaseType;} } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return m_typeBuilder.GetConstructors(bindingAttr); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { if (types == null) return m_typeBuilder.GetMethod(name, bindingAttr); else return m_typeBuilder.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return m_typeBuilder.GetMethods(bindingAttr); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { return m_typeBuilder.GetField(name, bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return m_typeBuilder.GetFields(bindingAttr); } public override Type GetInterface(String name, bool ignoreCase) { return m_typeBuilder.GetInterface(name, ignoreCase); } public override Type[] GetInterfaces() { return m_typeBuilder.GetInterfaces(); } public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { return m_typeBuilder.GetEvent(name, bindingAttr); } public override EventInfo[] GetEvents() { return m_typeBuilder.GetEvents(); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return m_typeBuilder.GetProperties(bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return m_typeBuilder.GetNestedTypes(bindingAttr); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { return m_typeBuilder.GetNestedType(name,bindingAttr); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { return m_typeBuilder.GetMember(name, type, bindingAttr); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return m_typeBuilder.GetMembers(bindingAttr); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return m_typeBuilder.GetInterfaceMap(interfaceType); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return m_typeBuilder.GetEvents(bindingAttr); } protected override TypeAttributes GetAttributeFlagsImpl() { return m_typeBuilder.Attributes; } protected override bool IsArrayImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsValueTypeImpl() { return true; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override bool IsConstructedGenericType { get { return false; } } public override Type GetElementType() { return m_typeBuilder.GetElementType(); } protected override bool HasElementTypeImpl() { return m_typeBuilder.HasElementType; } // About the SuppressMessageAttribute here - CCRewrite wants us to repeat the base type's precondition // here, but it will always be true. Rather than adding dead code, I'll silence the warning. [SuppressMessage("Microsoft.Contracts", "CC1055")] // Legacy: JScript needs it. public override Type GetEnumUnderlyingType() { return m_underlyingField.FieldType; } public override Type UnderlyingSystemType { get { return GetEnumUnderlyingType(); } } //ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return m_typeBuilder.GetCustomAttributes(inherit); } // Return a custom attribute identified by Type public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_typeBuilder.GetCustomAttributes(attributeType, inherit); } // Use this function if client decides to form the custom attribute blob themselves #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_typeBuilder.SetCustomAttribute(con, binaryAttribute); } // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_typeBuilder.SetCustomAttribute(customBuilder); } // Return the class that declared this Field. public override Type DeclaringType { get {return m_typeBuilder.DeclaringType;} } // Return the class that was used to obtain this field. public override Type ReflectedType { get {return m_typeBuilder.ReflectedType;} } // Returns true if one or more instance of attributeType is defined on this member. public override bool IsDefined (Type attributeType, bool inherit) { return m_typeBuilder.IsDefined(attributeType, inherit); } internal int MetadataTokenInternal { get { return m_typeBuilder.MetadataTokenInternal; } } /***************************************************** * * private/protected functions * */ //******************************* // Make a private constructor so these cannot be constructed externally. //******************************* private EnumBuilder() {} public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); string szrank = ""; if (rank == 1) { szrank = "*"; } else { for(int i = 1; i < rank; i++) szrank += ","; } string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] return SymbolType.FormCompoundType(s, this, 0); } // Constructs a EnumBuilder. // EnumBuilder can only be a top-level (not nested) enum type. [System.Security.SecurityCritical] // auto-generated internal EnumBuilder( String name, // name of type Type underlyingType, // underlying type for an Enum TypeAttributes visibility, // any bits on TypeAttributes.VisibilityMask) ModuleBuilder module) // module containing this type { // Client should not set any bits other than the visibility bits. if ((visibility & ~TypeAttributes.VisibilityMask) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), nameof(name)); m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null); // Define the underlying field for the enum. It will be a non-static, private field with special name bit set. m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName); } #if !FEATURE_CORECLR void _EnumBuilder.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _EnumBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _EnumBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _EnumBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif /***************************************************** * * private data members * */ internal TypeBuilder m_typeBuilder; private FieldBuilder m_underlyingField; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fluid; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OrchardCore.Autoroute.Drivers; using OrchardCore.Autoroute.Models; using OrchardCore.Autoroute.ViewModels; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Records; using OrchardCore.ContentManagement.Routing; using OrchardCore.Environment.Cache; using OrchardCore.Liquid; using OrchardCore.Settings; using YesSql; namespace OrchardCore.Autoroute.Handlers { public class AutoroutePartHandler : ContentPartHandler<AutoroutePart> { private readonly IAutorouteEntries _entries; private readonly AutorouteOptions _options; private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISiteService _siteService; private readonly ITagCache _tagCache; private readonly ISession _session; private readonly IServiceProvider _serviceProvider; private readonly IStringLocalizer S; private IContentManager _contentManager; public AutoroutePartHandler( IAutorouteEntries entries, IOptions<AutorouteOptions> options, ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager, ISiteService siteService, ITagCache tagCache, ISession session, IServiceProvider serviceProvider, IStringLocalizer<AutoroutePartHandler> stringLocalizer) { _entries = entries; _options = options.Value; _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; _siteService = siteService; _tagCache = tagCache; _session = session; _serviceProvider = serviceProvider; S = stringLocalizer; } public override async Task PublishedAsync(PublishContentContext context, AutoroutePart part) { // Remove entry if part is disabled. if (part.Disabled) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); } // Add parent content item path, and children, only if parent has a valid path. if (!String.IsNullOrWhiteSpace(part.Path) && !part.Disabled) { var entriesToAdd = new List<AutorouteEntry> { new AutorouteEntry(part.ContentItem.ContentItemId, part.Path) }; if (part.RouteContainedItems) { _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(context.PublishingItem); await PopulateContainedContentItemRoutes(entriesToAdd, part.ContentItem.ContentItemId, containedAspect, context.PublishingItem.Content as JObject, part.Path, true); } _entries.AddEntries(entriesToAdd); } if (!String.IsNullOrWhiteSpace(part.Path) && !part.Disabled && part.SetHomepage) { await SetHomeRoute(part, homeRoute => homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId); } // Evict any dependent item from cache await RemoveTagAsync(part); } private async Task SetHomeRoute(AutoroutePart part, Action<RouteValueDictionary> action) { var site = await _siteService.LoadSiteSettingsAsync(); if (site.HomeRoute == null) { site.HomeRoute = new RouteValueDictionary(); } var homeRoute = site.HomeRoute; foreach (var entry in _options.GlobalRouteValues) { homeRoute[entry.Key] = entry.Value; } action.Invoke(homeRoute); // Once we took the flag into account we can dismiss it. part.SetHomepage = false; part.Apply(); await _siteService.UpdateSiteSettingsAsync(site); } public override Task UnpublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override Task RemovedAsync(RemoveContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override async Task ValidatingAsync(ValidateContentContext context, AutoroutePart part) { // Only validate the path if it's not empty. if (String.IsNullOrWhiteSpace(part.Path)) { return; } if (part.Path == "/") { context.Fail(S["Your permalink can't be set to the homepage, please use the homepage option instead."]); } if (part.Path?.IndexOfAny(AutoroutePartDisplay.InvalidCharactersForPath) > -1 || part.Path?.IndexOf(' ') > -1 || part.Path?.IndexOf("//") > -1) { var invalidCharactersForMessage = string.Join(", ", AutoroutePartDisplay.InvalidCharactersForPath.Select(c => $"\"{c}\"")); context.Fail(S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage]); } if (part.Path?.Length > AutoroutePartDisplay.MaxPathLength) { context.Fail(S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePartDisplay.MaxPathLength]); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { context.Fail(S["Your permalink is already in use."]); } } public override async Task UpdatedAsync(UpdateContentContext context, AutoroutePart part) { await GenerateContainerPathFromPattern(part); await GenerateContainedPathsFromPattern(context.UpdatingItem, part); } public async override Task CloningAsync(CloneContentContext context, AutoroutePart part) { var clonedPart = context.CloneContentItem.As<AutoroutePart>(); clonedPart.Path = await GenerateUniqueAbsolutePathAsync(part.Path, context.CloneContentItem.ContentItemId); clonedPart.SetHomepage = false; clonedPart.Apply(); await GenerateContainedPathsFromPattern(context.CloneContentItem, part); } public override Task GetContentItemAspectAsync(ContentItemAspectContext context, AutoroutePart part) { return context.ForAsync<RouteHandlerAspect>(aspect => { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart")); var settings = contentTypePartDefinition.GetSettings<AutoroutePartSettings>(); if (settings.ManageContainedItemRoutes) { aspect.Path = part.Path; aspect.Absolute = part.Absolute; aspect.Disabled = part.Disabled; } return Task.CompletedTask; }); } private Task RemoveTagAsync(AutoroutePart part) { return _tagCache.RemoveTagAsync($"slug:{part.Path}"); } private async Task GenerateContainedPathsFromPattern(ContentItem contentItem, AutoroutePart part) { // Validate contained content item routes if container has valid path. if (!String.IsNullOrWhiteSpace(part.Path) || !part.RouteContainedItems) { return; } _contentManager ??= _serviceProvider.GetRequiredService<IContentManager>(); var containedAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); // Build the entries for this content item to evaluate for duplicates. var entries = new List<AutorouteEntry>(); await PopulateContainedContentItemRoutes(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content as JObject, part.Path); await ValidateContainedContentItemRoutes(entries, part.ContentItem.ContentItemId, containedAspect, contentItem.Content as JObject, part.Path); } private async Task PopulateContainedContentItemRoutes(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath, bool setHomepage = false) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var handlerAspect = await _contentManager.PopulateAspectAsync<RouteHandlerAspect>(contentItem); if (!handlerAspect.Disabled) { var path = handlerAspect.Path; if (!handlerAspect.Absolute) { path = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; } entries.Add(new AutorouteEntry(containerContentItemId, path, contentItem.ContentItemId, jItem.Path)); // Only an autoroute part, not a default handler aspect can set itself as the homepage. var autoroutePart = contentItem.As<AutoroutePart>(); if (setHomepage && autoroutePart != null && autoroutePart.SetHomepage) { await SetHomeRoute(autoroutePart, homeRoute => { homeRoute[_options.ContentItemIdKey] = containerContentItemId; homeRoute[_options.JsonPathKey] = jItem.Path; }); } } var itemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + handlerAspect.Path; var childrenAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await PopulateContainedContentItemRoutes(entries, containerContentItemId, childrenAspect, jItem, itemBasePath); } } } private async Task ValidateContainedContentItemRoutes(List<AutorouteEntry> entries, string containerContentItemId, ContainedContentItemsAspect containedContentItemsAspect, JObject content, string basePath) { foreach (var accessor in containedContentItemsAspect.Accessors) { var jItems = accessor.Invoke(content); foreach (JObject jItem in jItems) { var contentItem = jItem.ToObject<ContentItem>(); var containedAutoroutePart = contentItem.As<AutoroutePart>(); // This is only relevant if the content items have an autoroute part as we adjust the part value as required to guarantee a unique route. // Content items routed only through the handler aspect already guarantee uniqueness. if (containedAutoroutePart != null && !containedAutoroutePart.Disabled) { var path = containedAutoroutePart.Path; if (containedAutoroutePart.Absolute && !await IsAbsolutePathUniqueAsync(path, contentItem.ContentItemId)) { path = await GenerateUniqueAbsolutePathAsync(path, contentItem.ContentItemId); containedAutoroutePart.Path = path; containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } else { var currentItemBasePath = basePath.EndsWith('/') ? basePath : basePath + '/'; path = currentItemBasePath + containedAutoroutePart.Path; if (!IsRelativePathUnique(entries, path, containedAutoroutePart)) { path = GenerateRelativeUniquePath(entries, path, containedAutoroutePart); // Remove base path and update part path. containedAutoroutePart.Path = path.Substring(currentItemBasePath.Length); containedAutoroutePart.Apply(); // Merge because we have disconnected the content item from it's json owner. jItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); } path = path.Substring(currentItemBasePath.Length); } var containedItemBasePath = (basePath.EndsWith('/') ? basePath : basePath + '/') + path; var childItemAspect = await _contentManager.PopulateAspectAsync<ContainedContentItemsAspect>(contentItem); await ValidateContainedContentItemRoutes(entries, containerContentItemId, childItemAspect, jItem, containedItemBasePath); } } } } private bool IsRelativePathUnique(List<AutorouteEntry> entries, string path, AutoroutePart context) { var result = !entries.Any(e => context.ContentItem.ContentItemId != e.ContainedContentItemId && String.Equals(e.Path, path, StringComparison.OrdinalIgnoreCase)); return result; } private string GenerateRelativeUniquePath(List<AutorouteEntry> entries, string path, AutoroutePart context) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && int.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + separator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePartDisplay.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (IsRelativePathUnique(entries, versionedPath, context)) { var entry = entries.FirstOrDefault(e => e.ContainedContentItemId == context.ContentItem.ContentItemId); entry.Path = versionedPath; return versionedPath; } } } private async Task GenerateContainerPathFromPattern(AutoroutePart part) { // Compute the Path only if it's empty if (!String.IsNullOrWhiteSpace(part.Path)) { return; } var pattern = GetPattern(part); if (!String.IsNullOrEmpty(pattern)) { var model = new AutoroutePartViewModel() { Path = part.Path, AutoroutePart = part, ContentItem = part.ContentItem }; part.Path = await _liquidTemplateManager.RenderAsync(pattern, NullEncoder.Default, model, scope => scope.SetValue("ContentItem", model.ContentItem)); part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty); if (part.Path?.Length > AutoroutePartDisplay.MaxPathLength) { part.Path = part.Path.Substring(0, AutoroutePartDisplay.MaxPathLength); } if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId)) { part.Path = await GenerateUniqueAbsolutePathAsync(part.Path, part.ContentItem.ContentItemId); } part.Apply(); } } /// <summary> /// Get the pattern from the AutoroutePartSettings property for its type /// </summary> private string GetPattern(AutoroutePart part) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart")); var pattern = contentTypePartDefinition.GetSettings<AutoroutePartSettings>().Pattern; return pattern; } private async Task<string> GenerateUniqueAbsolutePathAsync(string path, string contentItemId) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && int.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { // Unversioned length + seperator char + version length. var quantityCharactersToTrim = unversionedPath.Length + 1 + version.ToString().Length - AutoroutePartDisplay.MaxPathLength; if (quantityCharactersToTrim > 0) { unversionedPath = unversionedPath.Substring(0, unversionedPath.Length - quantityCharactersToTrim); } var versionedPath = $"{unversionedPath}-{version++}"; if (await IsAbsolutePathUniqueAsync(versionedPath, contentItemId)) { return versionedPath; } } } private async Task<bool> IsAbsolutePathUniqueAsync(string path, string contentItemId) { var isUnique = true; var possibleConflicts = await _session.QueryIndex<AutoroutePartIndex>(o => o.Path == path).ListAsync(); if (possibleConflicts.Any()) { if (possibleConflicts.Any(x => x.ContentItemId != contentItemId) || possibleConflicts.Any(x => !string.IsNullOrEmpty(x.ContainedContentItemId) && x.ContainedContentItemId != contentItemId)) { isUnique = false; } } return isUnique; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CrowdSourcedNews.Services.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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 Internal.Cryptography; namespace System.Security.Cryptography { /// <summary> /// Provides support for computing a hash or HMAC value incrementally across several segments. /// </summary> public sealed class IncrementalHash : IDisposable { private readonly HashAlgorithmName _algorithmName; private HashProvider _hash; private HMACCommon _hmac; private bool _disposed; private IncrementalHash(HashAlgorithmName name, HashProvider hash) { Debug.Assert(name != null); Debug.Assert(!string.IsNullOrEmpty(name.Name)); Debug.Assert(hash != null); _algorithmName = name; _hash = hash; } private IncrementalHash(HashAlgorithmName name, HMACCommon hmac) { Debug.Assert(name != null); Debug.Assert(!string.IsNullOrEmpty(name.Name)); Debug.Assert(hmac != null); _algorithmName = new HashAlgorithmName("HMAC" + name.Name); _hmac = hmac; } /// <summary> /// Get the name of the algorithm being performed. /// </summary> public HashAlgorithmName AlgorithmName { get { return _algorithmName; } } /// <summary> /// Append the entire contents of <paramref name="data"/> to the data already processed in the hash or HMAC. /// </summary> /// <param name="data">The data to process.</param> /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public void AppendData(byte[] data) { if (data == null) throw new ArgumentNullException("data"); AppendData(data, 0, data.Length); } /// <summary> /// Append <paramref name="count"/> bytes of <paramref name="data"/>, starting at <paramref name="offset"/>, /// to the data already processed in the hash or HMAC. /// </summary> /// <param name="data">The data to process.</param> /// <param name="offset">The offset into the byte array from which to begin using data.</param> /// <param name="count">The number of bytes in the array to use as data.</param> /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is out of range. This parameter requires a non-negative number. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is out of range. This parameter requires a non-negative number less than /// the <see cref="Array.Length"/> value of <paramref name="data"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="count"/> is greater than /// <paramref name="data"/>.<see cref="Array.Length"/> - <paramref name="offset"/>. /// </exception> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public void AppendData(byte[] data, int offset, int count) { if (data == null) throw new ArgumentNullException("data"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > data.Length)) throw new ArgumentOutOfRangeException("count"); if ((data.Length - count) < offset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(typeof(IncrementalHash).Name); if (_hash != null) { _hash.AppendHashDataCore(data, offset, count); } else { Debug.Assert(_hmac != null, "Both _hash and _hmac were null"); _hmac.AppendHashData(data, offset, count); } } /// <summary> /// Retrieve the hash or HMAC for the data accumulated from prior calls to /// <see cref="AppendData(byte[])"/>, and return to the state the object /// was in at construction. /// </summary> /// <returns>The computed hash or HMAC.</returns> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public byte[] GetHashAndReset() { if (_disposed) throw new ObjectDisposedException(typeof(IncrementalHash).Name); byte[] hashValue; if (_hash != null) { hashValue = _hash.FinalizeHashAndReset(); } else { Debug.Assert(_hmac != null, "Both _hash and _hmac were null"); hashValue = _hmac.FinalizeHashAndReset(); } return hashValue; } /// <summary> /// Release all resources used by the current instance of the /// <see cref="IncrementalHash"/> class. /// </summary> public void Dispose() { _disposed = true; if (_hash != null) { _hash.Dispose(); _hash = null; } if (_hmac != null) { _hmac.Dispose(true); _hmac = null; } } /// <summary> /// Create an <see cref="IncrementalHash"/> for the algorithm specified by <paramref name="hashAlgorithm"/>. /// </summary> /// <param name="hashAlgorithm">The name of the hash algorithm to perform.</param> /// <returns> /// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified /// by <paramref name="hashAlgorithm"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or /// the empty string. /// </exception> /// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception> public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); return new IncrementalHash(hashAlgorithm, HashProviderDispenser.CreateHashProvider(hashAlgorithm.Name)); } /// <summary> /// Create an <see cref="IncrementalHash"/> for the Hash-based Message Authentication Code (HMAC) /// algorithm utilizing the hash algorithm specified by <paramref name="hashAlgorithm"/>, and a /// key specified by <paramref name="key"/>. /// </summary> /// <param name="hashAlgorithm">The name of the hash algorithm to perform within the HMAC.</param> /// <param name="key"> /// The secret key for the HMAC. The key can be any length, but a key longer than the output size /// of the hash algorithm specified by <paramref name="hashAlgorithm"/> will be hashed (using the /// algorithm specified by <paramref name="hashAlgorithm"/>) to derive a correctly-sized key. Therefore, /// the recommended size of the secret key is the output size of the hash specified by /// <paramref name="hashAlgorithm"/>. /// </param> /// <returns> /// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified /// by <paramref name="hashAlgorithm"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or /// the empty string. /// </exception> /// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception> public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key) { if (key == null) throw new ArgumentNullException("key"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); return new IncrementalHash(hashAlgorithm, new HMACCommon(hashAlgorithm.Name, key, -1)); } } }