context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Reflection { // Summary: // Discovers the attributes of a property and provides access to property metadata. [Immutable] // Base class is immutable. public abstract class PropertyInfo { // Summary: // Initializes a new instance of the System.Reflection.PropertyInfo class. #if !SILVERLIGHT || SILVERLIGHT_5_0 extern protected PropertyInfo(); #else extern internal PropertyInfo(); #endif // Summary: // Gets the attributes for this property. // // Returns: // Attributes of this property. //public abstract PropertyAttributes Attributes { get; } // // Summary: // Gets a value indicating whether the property can be read. // // Returns: // true if this property can be read; otherwise, false. public abstract bool CanRead { get; } // // Summary: // Gets a value indicating whether the property can be written to. // // Returns: // true if this property can be written to; otherwise, false. public abstract bool CanWrite { get; } // // Summary: // Gets a value indicating whether the property is the special name. // // Returns: // true if this property is the special name; otherwise, false. extern public virtual bool IsSpecialName { get; } // // Summary: // Gets the type of this property. // // Returns: // The type of this property. public virtual Type PropertyType { get { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } } // Summary: // Returns an array whose elements reflect the public get, set, and other accessors // of the property reflected by the current instance. // // Returns: // An array of System.Reflection.MethodInfo objects that reflect the public // get, set, and other accessors of the property reflected by the current instance, // if found; otherwise, this method returns an array with zero (0) elements. [Pure] public virtual MethodInfo[] GetAccessors() { Contract.Ensures(Contract.Result<MethodInfo[]>() != null); return default(MethodInfo[]); } // Returns an array whose elements reflect the public and, if specified, non-public // get, set, and other accessors of the property reflected by the current instance. // // Parameters: // nonPublic: // Indicates whether non-public methods should be returned in the MethodInfo // array. true if non-public methods are to be included; otherwise, false. // // Returns: // An array of System.Reflection.MethodInfo objects whose elements reflect the // get, set, and other accessors of the property reflected by the current instance. // If nonPublic is true, this array contains public and non-public get, set, // and other accessors. If nonPublic is false, this array contains only public // get, set, and other accessors. If no accessors with the specified visibility // are found, this method returns an array with zero (0) elements. [Pure] public virtual MethodInfo[] GetAccessors(bool nonPublic) { Contract.Ensures(Contract.Result<MethodInfo[]>() != null); return default(MethodInfo[]); } // // Summary: // Returns a literal value associated with the property by a compiler. // // Returns: // An System.Object that contains the literal value associated with the property. // If the literal value is a class type with an element value of zero, the return // value is null. // // Exceptions: // System.FormatException: // The type of the value is not one of the types permitted by the Common Language // Specification (CLS). See the ECMA Partition II specification, Metadata, 22.1.15. // // System.InvalidOperationException: // The Constant table in unmanaged metadata does not contain a constant value // for the current property. [Pure] public virtual object GetConstantValue() { return default(object); } // // Summary: // Returns the public get accessor for this property. // // Returns: // A MethodInfo object representing the public get accessor for this property, // or null if the get accessor is non-public or does not exist. [Pure] public virtual MethodInfo GetGetMethod() { // // Summary: return default(MethodInfo); } // When overridden in a derived class, returns the public or non-public get // accessor for this property. // // Parameters: // nonPublic: // Indicates whether a non-public get accessor should be returned. true if a // non-public accessor is to be returned; otherwise, false. // // Returns: // A MethodInfo object representing the get accessor for this property, if nonPublic // is true. Returns null if nonPublic is false and the get accessor is non-public, // or if nonPublic is true but no get accessors exist. // // Exceptions: // System.Security.SecurityException: // The requested method is non-public and the caller does not have System.Security.Permissions.ReflectionPermission // to reflect on this non-public method. [Pure] public virtual MethodInfo GetGetMethod(bool nonPublic) { return default(MethodInfo); } // // Summary: // When overridden in a derived class, returns an array of all the index parameters // for the property. // // Returns: // An array of type ParameterInfo containing the parameters for the indexes. [Pure] public virtual ParameterInfo[] GetIndexParameters() { Contract.Ensures(Contract.Result<ParameterInfo[]>() != null); return default(ParameterInfo[]); } #if !SILVERLIGHT // // Summary: // Returns an array of types representing the optional custom modifiers of the // property. // // Returns: // An array of System.Type objects that identify the optional custom modifiers // of the current property, such as System.Runtime.CompilerServices.IsConst // or System.Runtime.CompilerServices.IsImplicitlyDeferenced. [Pure] public virtual Type[] GetOptionalCustomModifiers() { Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #endif // // Summary: // Returns a literal value associated with the property by a compiler. // // Returns: // An System.Object that contains the literal value associated with the property. // If the literal value is a class type with an element value of zero, the return // value is null. // // Exceptions: // System.FormatException: // The type of the value is not one of the types permitted by the Common Language // Specification (CLS). See the ECMA Partition II specification, Metadata Logical // Format: Other Structures, Element Types used in Signatures. // // System.InvalidOperationException: // The Constant table in unmanaged metadata does not contain a constant value // for the current property. [Pure] public virtual object GetRawConstantValue() { return default(object); } #if !SILVERLIGHT // // Summary: // Returns an array of types representing the required custom modifiers of the // property. // // Returns: // An array of System.Type objects that identify the required custom modifiers // of the current property, such as System.Runtime.CompilerServices.IsConst // or System.Runtime.CompilerServices.IsImplicitlyDeferenced. [Pure] public virtual Type[] GetRequiredCustomModifiers() { Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #endif // // Summary: // Returns the public set accessor for this property. // // Returns: // The MethodInfo object representing the Set method for this property if the // set accessor is public, or null if the set accessor is not public. [Pure] public virtual MethodInfo GetSetMethod() { return default(MethodInfo); } // // Summary: // When overridden in a derived class, returns the set accessor for this property. // // Parameters: // nonPublic: // Indicates whether the accessor should be returned if it is non-public. true // if a non-public accessor is to be returned; otherwise, false. // // Returns: // Value Condition A System.Reflection.MethodInfo object representing the Set // method for this property. The set accessor is public.-or- nonPublic is true // and the set accessor is non-public. nullnonPublic is true, but the property // is read-only.-or- nonPublic is false and the set accessor is non-public.-or- // There is no set accessor. // // Exceptions: // System.Security.SecurityException: // The requested method is non-public and the caller does not have System.Security.Permissions.ReflectionPermission // to reflect on this non-public method. [Pure] public virtual MethodInfo GetSetMethod(bool nonPublic) { return default(MethodInfo); } // // Summary: // Returns the value of the property with optional index values for indexed // properties. // // Parameters: // obj: // The object whose property value will be returned. // // index: // Optional index values for indexed properties. This value should be null for // non-indexed properties. // // Returns: // The property value for the obj parameter. // // Exceptions: // System.MethodAccessException: // There was an illegal attempt to access a private or protected method inside // a class. // // System.ArgumentException: // The index array does not contain the type of arguments needed.-or- The property's // Get method is not found. // // System.Reflection.TargetException: // The object does not match the target type, or a property is an instance property // but obj is null. // // System.Reflection.TargetParameterCountException: // The number of parameters in index does not match the number of parameters // the indexed property takes. [Pure] public virtual object GetValue(object obj, object[] index) { return default(object); } // // Summary: // When overridden in a derived class, returns the value of a property having // the specified binding, index, and CultureInfo. // // Parameters: // culture: // The CultureInfo object that represents the culture for which the resource // is to be localized. Note that if the resource is not localized for this culture, // the CultureInfo.Parent method will be called successively in search of a // match. If this value is null, the CultureInfo is obtained from the CultureInfo.CurrentUICulture // property. // // obj: // The object whose property value will be returned. // // binder: // An object that enables the binding, coercion of argument types, invocation // of members, and retrieval of MemberInfo objects via reflection. If binder // is null, the default binder is used. // // invokeAttr: // The invocation attribute. This must be a bit flag from BindingFlags : InvokeMethod, // CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. // A suitable invocation attribute must be specified. If a static member is // to be invoked, the Static flag of BindingFlags must be set. // // index: // Optional index values for indexed properties. This value should be null for // non-indexed properties. // // Returns: // The property value for obj. // // Exceptions: // System.MethodAccessException: // There was an illegal attempt to access a private or protected method inside // a class. // // System.ArgumentException: // The index array does not contain the type of arguments needed.-or- The property's // Get method is not found. // // System.Reflection.TargetException: // The object does not match the target type, or a property is an instance property // but obj is null. // // System.Reflection.TargetParameterCountException: // The number of parameters in index does not match the number of parameters // the indexed property takes. //public virtual object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) //{ // return default(object); //} // // Summary: // Sets the value of the property with optional index values for index properties. // // Parameters: // obj: // The object whose property value will be set. // // value: // The new value for this property. // // index: // Optional index values for indexed properties. This value should be null for // non-indexed properties. // // Exceptions: // System.MethodAccessException: // There was an illegal attempt to access a private or protected method inside // a class. // // System.ArgumentException: // The index array does not contain the type of arguments needed.-or- The property's // Get method is not found. // // System.Reflection.TargetException: // The object does not match the target type, or a property is an instance property // but obj is null. // // System.Reflection.TargetParameterCountException: // The number of parameters in index does not match the number of parameters // the indexed property takes. public virtual void SetValue(object obj, object value, object[] index) { //return default(virtual); [t-cyrils] nothing should be returned } // // Summary: // When overridden in a derived class, sets the property value for the given // object to the given value. // // Parameters: // culture: // The System.Globalization.CultureInfo object that represents the culture for // which the resource is to be localized. Note that if the resource is not localized // for this culture, the CultureInfo.Parent method will be called successively // in search of a match. If this value is null, the CultureInfo is obtained // from the CultureInfo.CurrentUICulture property. // // obj: // The object whose property value will be returned. // // binder: // An object that enables the binding, coercion of argument types, invocation // of members, and retrieval of System.Reflection.MemberInfo objects through // reflection. If binder is null, the default binder is used. // // invokeAttr: // The invocation attribute. This must be a bit flag from System.Reflection.BindingFlags // : InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, // or SetProperty. A suitable invocation attribute must be specified. If a static // member is to be invoked, the Static flag of BindingFlags must be set. // // value: // The new value for this property. // // index: // Optional index values for indexed properties. This value should be null for // non-indexed properties. // // Exceptions: // System.MethodAccessException: // There was an illegal attempt to access a private or protected method inside // a class. // // System.ArgumentException: // The index array does not contain the type of arguments needed.-or- The property's // Get method is not found. // // System.Reflection.TargetException: // The object does not match the target type, or a property is an instance property // but obj is null. // // System.Reflection.TargetParameterCountException: // The number of parameters in index does not match the number of parameters // the indexed property takes. public virtual void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #define CONTRACTS_FULL using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; namespace ObjectInvariantInference { public class ReadonlyTest { readonly private int[] objs; [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The length of the array may be negative",PrimaryILOffset=8,MethodILOffset=0)] [RegressionOutcome("Contract.Requires(0 <= len);")] [RegressionOutcome("Contract.Ensures(len == this.objs.Length);")] [RegressionOutcome("Contract.Ensures(Contract.ForAll(0, len, __k__ => this.objs[__k__] == 0));")] [RegressionReanalysisCount(1)] // Reanalyze the method once, because the first time is not scheduled for analysis... public ReadonlyTest(int len) { this.objs = new int[len]; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=7,MethodILOffset=0)] // We infer it. Hence no warning is swown //[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.objs'",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome("Contract.Assume(z < this.objs.Length);")] [RegressionOutcome("Contract.Requires(0 <= z);")] [RegressionOutcome("Contract.Ensures(this.objs != null);")] [RegressionOutcome("Contract.Ensures((z - this.objs.Length) < 0);")] [RegressionOutcome("Contract.Ensures(1 <= this.objs.Length);")] [RegressionOutcome("Contract.Invariant(this.objs != null);")] [RegressionOutcome("Contract.Ensures(this.objs[z] == Contract.Result<System.Int32>());")] public int BadCode(int z) { return objs[z]; } } public class NoReadonlyTest { private int[] objs; [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The length of the array may be negative",PrimaryILOffset=8,MethodILOffset=0)] [RegressionOutcome("Contract.Requires(0 <= len);")] [RegressionOutcome("Contract.Ensures(this.objs != null);")] // not suggested in the constructor above because we inferred it as object invariant [RegressionOutcome("Contract.Ensures(len == this.objs.Length);")] [RegressionOutcome("Contract.Ensures(Contract.ForAll(0, len, __k__ => this.objs[__k__] == 0));")] [RegressionOutcome("Consider adding an object invariant Contract.Invariant(objs != null); to the type NoReadonlyTest")] public NoReadonlyTest(int len) { this.objs = new int[len]; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.objs'",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome("Contract.Assume(this.objs != null);")] [RegressionOutcome("Contract.Assume(z < this.objs.Length);")] [RegressionOutcome("Contract.Requires(0 <= z);")] [RegressionOutcome("Contract.Ensures(this.objs != null);")] [RegressionOutcome("Contract.Ensures((z - this.objs.Length) < 0);")] [RegressionOutcome("Contract.Ensures(1 <= this.objs.Length);")] [RegressionOutcome("Contract.Ensures(this.objs[z] == Contract.Result<System.Int32>());")] public int BadCode(int z) { return objs[z]; } } public class NoReadonlyTestWithStrings { private string[] objs; [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="The length of the array may be negative",PrimaryILOffset=8,MethodILOffset=0)] [RegressionOutcome("Contract.Requires(0 <= len);")] [RegressionOutcome("Contract.Ensures(this.objs != null);")] // not suggested in the constructor above because we inferred it as object invariant [RegressionOutcome("Contract.Ensures(len == this.objs.Length);")] [RegressionOutcome("Contract.Ensures(Contract.ForAll(0, len, __k__ => this.objs[__k__] == null));")] [RegressionOutcome("Consider adding an object invariant Contract.Invariant(objs != null); to the type NoReadonlyTestWithStrings")] public NoReadonlyTestWithStrings(int len) { this.objs = new string[len]; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.objs'",PrimaryILOffset=7,MethodILOffset=0)] [RegressionOutcome("Contract.Assume(this.objs != null);")] [RegressionOutcome("Contract.Assume(z < this.objs.Length);")] [RegressionOutcome("Contract.Requires(0 <= z);")] [RegressionOutcome("Contract.Ensures(this.objs != null);")] [RegressionOutcome("Contract.Ensures((z - this.objs.Length) < 0);")] [RegressionOutcome("Contract.Ensures(1 <= this.objs.Length);")] public string BadCode(int z) { return objs[z]; } } public class InstallObjInvariants { readonly object y; [ClousotRegressionTest] [RegressionReanalysisCount(1)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: this.y != null",PrimaryILOffset=0,MethodILOffset=13)] [RegressionOutcome("Contract.Requires(x != null);")] [RegressionOutcome("Contract.Ensures(x == this.y);")] public InstallObjInvariants(object x) { y = x; } [ClousotRegressionTest] // we infer the invariant, we now it is sufficient, so we do not emit the warning //[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 'this.y'",PrimaryILOffset=6,MethodILOffset=0)] [RegressionOutcome("Contract.Ensures(this.y != null);")] [RegressionOutcome("Contract.Ensures(Contract.Result<System.Int32>() == this.y.GetHashCode());")] [RegressionOutcome("Contract.Invariant(this.y != null);")] public int Foo() { return y.GetHashCode(); } [ClousotRegressionTest] #if SLICING // We do not re-use the inferred invariant, as on deserialization we only install it to the constructor [RegressionOutcome("Contract.Ensures(this.y != null);")] [RegressionOutcome("Contract.Invariant(this.y != null);")] #else // We infer the object invariant y != null in the method above. As a consequence, no warning is generated here #endif [RegressionOutcome("Contract.Ensures(Contract.Result<System.String>() != null);")] [RegressionOutcome("Contract.Ensures(this.y.ToString() != null);")] [RegressionOutcome("Contract.Ensures(Contract.Result<System.String>() == this.y.ToString());")] public string FooString() { return y.ToString(); } } public class SegmentInfo{ } public class RequestDescription { private readonly SegmentInfo[] segmentInfos; [ClousotRegressionTest] #if CLOUSOT2 // [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: 0 <= (this.segmentInfos.Length - 1)",PrimaryILOffset=0,MethodILOffset=13)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: 0 <= (this.segmentInfos.Length - 1). Is it an off-by-one? The static checker can prove (0 - 1) <= (segmentInfos.Length - 1) instead",PrimaryILOffset=0,MethodILOffset=13)] #else // [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: 0 <= (this.segmentInfos.Length - 1)",PrimaryILOffset=6,MethodILOffset=13)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: 0 <= (this.segmentInfos.Length - 1). Is it an off-by-one? The static checker can prove (0 - 1) <= (segmentInfos.Length - 1) instead",PrimaryILOffset=6,MethodILOffset=13)] #endif [RegressionOutcome("Contract.Requires(0 <= (segmentInfos.Length - 1));")] [RegressionOutcome("Contract.Ensures(segmentInfos == this.segmentInfos);")] public RequestDescription(SegmentInfo[] segmentInfos) { this.segmentInfos = segmentInfos; } public SegmentInfo LastSegmentInfo { // We were not deducing that IsReadonly(this.segmentInfos) ==> IsReadonly(this.segmentInfos.Length) [ClousotRegressionTest] // We infer the object invariants, so we do not emit the warning //[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=16,MethodILOffset=0)] //[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.segmentInfos'",PrimaryILOffset=12,MethodILOffset=0)] [RegressionOutcome("Contract.Ensures(this.segmentInfos != null);")] [RegressionOutcome("Contract.Ensures(1 <= this.segmentInfos.Length);")] [RegressionOutcome("Contract.Invariant(this.segmentInfos != null);")] [RegressionOutcome("Contract.Invariant(0 <= (this.segmentInfos.Length - 1));")] get { return this.segmentInfos[this.segmentInfos.Length - 1]; } } } public class ReadOnly_FilterFalseRequires { readonly string str; int counter = 0; [ClousotRegressionTest] [RegressionReanalysisCount(1)] [RegressionOutcome(Outcome=ProofOutcome.False,Message="invariant is false: this.str != null. This object invariant was inferred, and it should hold in order to avoid an error if the method UseStr (in the same type) is invoked",PrimaryILOffset=0,MethodILOffset=13)] public ReadOnly_FilterFalseRequires(int z) { this.counter = 0; } [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(Contract.Result<System.String>() != null);")] [RegressionOutcome("Contract.Ensures(this.str != null);")] [RegressionOutcome("Contract.Ensures(this.str.ToString() != null);")] [RegressionOutcome("Contract.Ensures(0 <= Contract.Result<System.String>().Length);")] [RegressionOutcome("Contract.Ensures(0 <= this.str.ToString().Length);")] [RegressionOutcome("Contract.Invariant(this.str != null);")] public string UseStr() { return this.str.ToString() + "hello"; } [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(this.counter - Contract.OldValue(this.counter) == 1);")] [RegressionOutcome("Contract.Ensures(-2147483647 <= this.counter);")] public void Add() { counter++; } } public class UseReadonly { [ClousotRegressionTest] public static void Act() { var z = new ReadOnly_FilterFalseRequires(12); z.Add(); } } public class Bits { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="assert unproven. Is it an off-by-one? The static checker can prove (((x >> 28) & 15)) < (15 + 1) instead",PrimaryILOffset=11,MethodILOffset=0)] // ???? Why can it prove < 16 ??? [RegressionOutcome("Contract.Requires((((x >> 28) & 15)) < 15);")] static public void BitManipulation(int x) { Contract.Assert((x >> 28 & 15) < 15); // not true } [ClousotRegressionTest] static public void BitManipulation_Fixed(int x) { if (x >= 0) { Contract.Assert((x >> 28 & 15) < 15); // Should prove it } } } public class EnumFiltering { public enum MyEnum { A, B} [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(97 <= Contract.Result<System.Char>());")] [RegressionOutcome("Contract.Ensures(Contract.Result<System.Char>() <= 98);")] public static char EnumCase(MyEnum me) { if(me == MyEnum.A) { return 'a'; } else if(me == MyEnum.B) // Should not warn { return 'b'; } else { Contract.Assert(false); throw new Exception(); } } [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(97 <= Contract.Result<System.Char>());")] [RegressionOutcome("Contract.Ensures(Contract.Result<System.Char>() <= 98);")] public static char IntCase(int me) { Contract.Requires(me >= 0); Contract.Requires(me <= 1); if (me == 0) { return 'a'; } else if (me == 1) // Should warn { return 'b'; } else { Contract.Assert(false); throw new Exception(); } } } } namespace ImprovedMessages { public class BetterWarningMessagesTest { readonly string str; int counter = 0; [ClousotRegressionTest] [RegressionReanalysisCount(1)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="invariant unproven: this.str != null",PrimaryILOffset=0,MethodILOffset=42)] [RegressionOutcome("Contract.Requires(inputString != null);")] [RegressionOutcome("Contract.Ensures(inputString == this.str);")] [RegressionOutcome("Contract.Ensures((Contract.OldValue(this.counter) - this.counter) <= 0);")] [RegressionOutcome("Contract.Ensures(0 <= this.counter);")] [RegressionOutcome("Contract.Ensures(this.counter <= 1);")] public BetterWarningMessagesTest(string inputString, int counter) { this.counter = 0; this.str = inputString; if(this.str == null) { this.counter++; } } [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(Contract.Result<System.String>() != null);")] [RegressionOutcome("Contract.Ensures(this.str != null);")] [RegressionOutcome("Contract.Ensures(this.str.ToString() != null);")] [RegressionOutcome("Contract.Ensures(0 <= Contract.Result<System.String>().Length);")] [RegressionOutcome("Contract.Ensures(0 <= this.str.ToString().Length);")] [RegressionOutcome("Contract.Invariant(this.str != null);")] public string UseStr() { return this.str.ToString() + "hello"; } [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(this.counter - Contract.OldValue(this.counter) == 1);")] [RegressionOutcome("Contract.Ensures(-2147483647 <= this.counter);")] public void Add() { counter++; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=2,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'a'",PrimaryILOffset=2,MethodILOffset=0)] [RegressionOutcome("Contract.Requires(a != null);")] [RegressionOutcome("Contract.Requires(0 < a.Length);")] [RegressionOutcome("Contract.Ensures(a[0] == Contract.Result<System.Int32>());")] public static int Count(int[] a) { return a[0]; } [ClousotRegressionTest] public static int TwoLevelsDown(int[] a) { return Count(a); } } } namespace ReproWithStructs { internal struct STR { readonly private string S; [ClousotRegressionTest] // We should not suggest (does not compiler), but it is ok to infer: // Contract.Ensures(s == this.S); public STR(string s) { this.S = s; } // It should not suggest an object invariant! [ClousotRegressionTest] [RegressionOutcome("Contract.Ensures(this.S != null);")] [RegressionOutcome("Contract.Ensures(Contract.Result<System.Int32>() == this.S.Length);")] [RegressionOutcome("Contract.Ensures(0 <= Contract.Result<System.Int32>());")] // It should not suggest this (does not compile) // Contract.Ensures(Contract.Result<System.Int32>() == Contract.ValueAtReturn(out this.S.Length)); public int Len() { return this.S.Length; } } }
/* * Naiad ver. 0.5 * 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 System.Text; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.Dataflow.StandardVertices; using Microsoft.Research.Naiad.Frameworks; using Microsoft.Research.Naiad.Scheduling; using System.Diagnostics; using Microsoft.Research.Naiad.Diagnostics; using Microsoft.Research.Naiad.Input; namespace Microsoft.Research.Naiad.Dataflow { internal interface InputStage { /// <summary> /// Returns true if OnCompleted() has been called on the input. /// </summary> bool IsCompleted { get; } /// <summary> /// Returns the number of the pending epoch of input data. /// </summary> int CurrentEpoch { get; } /// <summary> /// Return the largest epoch known to be valid. /// </summary> int MaximumValidEpoch { get; } /// <summary> /// Returns the stage identifier. /// </summary> int InputId { get; } } /// <summary> /// TODO this class is deprecated by virtue of StreamingInputStage. Still used by Reporting, but that can be fixed. /// </summary> internal class InputStage<TRecord> : InputStage, IObserver<IEnumerable<TRecord>>, IObserver<TRecord> { private readonly KeyValuePair<int,InputVertex<TRecord>>[] localVertices; internal InputVertex<TRecord> GetInputVertex(int vertexId) { foreach (var vertex in localVertices) if (vertexId == vertex.Key) return vertex.Value; throw new Exception(String.Format("Vertex {0} not found in Input {1} on Process {2}", vertexId, stage.StageId, stage.InternalComputation.Controller.Configuration.ProcessID)); } public int InputId { get { return this.stage.StageId; } } private int currentEpoch; private bool completedCalled; public bool Completed { get { return this.completedCalled; } } private bool hasActivatedProgressTracker; private readonly Stream<TRecord, Epoch> output; public Stream<TRecord, Epoch> Stream { get { return output; } } public static implicit operator Stream<TRecord, Epoch>(InputStage<TRecord> stage) { return stage.Stream; } public TimeContext<Epoch> Context { get { return this.stage.Context; } } internal InternalComputation InternalComputation { get { return this.stage.InternalComputation; } } public Placement Placement { get { return this.stage.Placement; } } private readonly string inputName; public string InputName { get { return this.inputName; } } private readonly Stage<InputVertex<TRecord>, Epoch> stage; internal InputStage(Placement placement, InternalComputation internalComputation, string inputName) { this.inputName = inputName; stage = Foundry.NewStage(new TimeContext<Epoch>(internalComputation.ContextManager.RootContext), (i, v) => new InputVertex<TRecord>(i, v), this.inputName); this.output = stage.NewOutput(vertex => vertex.Output); stage.Materialize(); this.localVertices = placement.Where(x => x.ProcessId == internalComputation.Controller.Configuration.ProcessID) .Select(x => new KeyValuePair<int, InputVertex<TRecord>>(x.VertexId, stage.GetVertex(x.VertexId) as InputVertex<TRecord>)) .ToArray(); this.completedCalled = false; this.hasActivatedProgressTracker = false; this.currentEpoch = 0; // results in pointstamps comparisons which assert w/o this. this.InternalComputation.Reachability.UpdateReachabilityPartialOrder(internalComputation); this.InternalComputation.Reachability.DoNotImpersonate(stage.StageId); var initialVersion = new Runtime.Progress.Pointstamp(stage.StageId, new int[] { 0 }); //if (this.Controller.Configuration.Impersonation) //{ // foreach (var version in Reachability.EnumerateImpersonations(initialVersion)) // controller.BroadcastUpdate(version, placement.Count); //} //else internalComputation.ProgressTracker.BroadcastProgressUpdate(initialVersion, placement.Count); } private void EnsureProgressTrackerActivated() { if (!this.hasActivatedProgressTracker) { stage.InternalComputation.Activate(); this.hasActivatedProgressTracker = true; } } public void OnNext() { this.OnNext(new TRecord[] { }); } public void OnNext(TRecord record) { this.OnNext(new[] { record }); } public void OnNext(IEnumerable<TRecord> batch) { //Debug.Assert(!this.completedCalled); this.EnsureProgressTrackerActivated(); var array = batch == null ? new TRecord[] { } : batch.ToArray(); lock (this) { var arrayCursor = 0; for (int i = 0; i < this.localVertices.Length; i++) { var toEat = (array.Length / this.localVertices.Length) + ((i < (array.Length % this.localVertices.Length)) ? 1 : 0); var chunk = new TRecord[toEat]; Array.Copy(array, arrayCursor, chunk, 0, toEat); arrayCursor += toEat; this.localVertices[i].Value.OnNext(chunk); } ++this.currentEpoch; } } public void OnCompleted() { //Debug.Assert(!this.completedCalled); if (!this.completedCalled) { this.EnsureProgressTrackerActivated(); this.completedCalled = true; for (int i = 0; i < this.localVertices.Length; i++) this.localVertices[i].Value.OnCompleted(); } } public void OnCompleted(TRecord record) { this.OnCompleted(new[] { record }); } public void OnCompleted(IEnumerable<TRecord> batch) { if (!this.completedCalled) { this.EnsureProgressTrackerActivated(); this.completedCalled = true; var array = batch == null ? new TRecord[] { } : batch.ToArray(); lock (this) { ++this.currentEpoch; var arrayCursor = 0; for (int i = 0; i < this.localVertices.Length; i++) { var toEat = (array.Length / this.localVertices.Length) + ((i < (array.Length % this.localVertices.Length)) ? 1 : 0); var chunk = new TRecord[toEat]; Array.Copy(array, arrayCursor, chunk, 0, toEat); arrayCursor += toEat; this.localVertices[i].Value.OnCompleted(chunk); } } } } public void OnError(Exception error) { throw error; } public bool IsCompleted { get { return this.completedCalled; } } public int CurrentEpoch { get { return this.currentEpoch; } } public int MaximumValidEpoch { get { return this.currentEpoch - 1; } } public void Checkpoint(NaiadWriter writer) { writer.Write(currentEpoch, this.InternalComputation.SerializationFormat.GetSerializer<int>()); writer.Write(completedCalled, this.InternalComputation.SerializationFormat.GetSerializer<bool>()); writer.Write(hasActivatedProgressTracker, this.InternalComputation.SerializationFormat.GetSerializer<bool>()); } public void Restore(NaiadReader reader) { this.currentEpoch = reader.Read<int>(this.InternalComputation.SerializationFormat.GetSerializer<int>()); this.completedCalled = reader.Read<bool>(this.InternalComputation.SerializationFormat.GetSerializer<bool>()); this.hasActivatedProgressTracker = reader.Read<bool>(this.InternalComputation.SerializationFormat.GetSerializer<bool>()); } public bool Stateful { get { return true; } } public override string ToString() { return string.Format("{0} (current epoch = {1})", base.ToString(), this.currentEpoch); } } /// <summary> /// TODO this class is deprecated by virtue of StreamingInputVertex. Still used by Reporting, but that can be fixed. /// </summary> /// <typeparam name="S"></typeparam> internal class InputVertex<S> : Dataflow.Vertex<Epoch> { private struct Instruction { public S[] payload; public bool isLast; public Instruction(S[] p, bool il) { this.payload = p; this.isLast = il; } } private System.Collections.Concurrent.ConcurrentQueue<Instruction> inputQueue; internal VertexOutputBuffer<S, Epoch> Output; private int nextAvailableEpoch; private int nextSendEpoch; internal override void PerformAction(Scheduling.Scheduler.WorkItem workItem) { var epoch = new Epoch().InitializeFrom(workItem.Requirement, 1).epoch; for (int i = nextSendEpoch; i <= epoch; i++) { var sendTime = new Epoch(i); var output = this.Output.GetBufferForTime(sendTime); Instruction nextInstruction; inputQueue.TryDequeue(out nextInstruction); if (nextInstruction.payload != null) { for (int j = 0; j < nextInstruction.payload.Length; j++) output.Send(nextInstruction.payload[j]); Flush(); } if (!nextInstruction.isLast) this.Scheduler.State(this.Stage.InternalComputation).Producer.UpdateRecordCounts(new Runtime.Progress.Pointstamp(this.Stage.StageId, new int[] { i + 1 }), +1); else Logging.Progress("Completing input {0}", this.VertexId); this.scheduler.State(this.Stage.InternalComputation).Producer.UpdateRecordCounts(new Runtime.Progress.Pointstamp(this.Stage.StageId, new int[] { i }), -1); } nextSendEpoch = epoch + 1; } public void OnNext(S[] batch) { lock (this) // this is probably already under a lock, but just to be safe... { this.inputQueue.Enqueue(new Instruction(batch, false)); scheduler.EnqueueNotify(this, new Epoch(nextAvailableEpoch++), false); } } public void OnCompleted() { lock (this) { this.inputQueue.Enqueue(new Instruction(null, true)); scheduler.EnqueueNotify(this, new Epoch(nextAvailableEpoch++), false); nextAvailableEpoch++; } } public void OnCompleted(S[] batch) { lock (this) // this is probably already under a lock, but just to be safe... { this.inputQueue.Enqueue(new Instruction(batch, true)); scheduler.EnqueueNotify(this, new Epoch(nextAvailableEpoch++), false); } } public override string ToString() { return "Input"; } /* Checkpoint format: * int nextAvailableEpoch * int nextSendEpoch * int inputQueueCount * Weighted<S>[]*inputQueueCount inputQueue */ private static NaiadSerialization<S> weightedSSerializer = null; protected override void Checkpoint(NaiadWriter writer) { if (weightedSSerializer == null) weightedSSerializer = this.SerializationFormat.GetSerializer<S>(); var intSerializer = this.SerializationFormat.GetSerializer<Int32>(); var boolSerializer = this.SerializationFormat.GetSerializer<bool>(); writer.Write(this.nextAvailableEpoch, intSerializer); writer.Write(this.nextSendEpoch, intSerializer); writer.Write(this.inputQueue.Count, intSerializer); foreach (Instruction batch in this.inputQueue) { if (batch.payload != null) batch.payload.Checkpoint(batch.payload.Length, writer); writer.Write(batch.isLast, boolSerializer); } } protected override void Restore(NaiadReader reader) { this.nextAvailableEpoch = reader.Read<int>(); this.nextSendEpoch = reader.Read<int>(); int inputQueueCount = reader.Read<int>(); for (int i = 0; i < inputQueueCount; ++i) { S[] array = CheckpointRestoreExtensionMethods.RestoreArray<S>(reader, n => new S[n]); bool isLast = reader.Read<bool>(); this.inputQueue.Enqueue(new Instruction(array, isLast)); } } public InputVertex(int index, Stage<Epoch> stage) : base(index, stage) { this.inputQueue = new System.Collections.Concurrent.ConcurrentQueue<Instruction>(); this.Output = new VertexOutputBuffer<S, Epoch>(this); } } /// <summary> /// Represents a streaming input to a Naiad computation. /// </summary> /// <typeparam name="TRecord">The type of records accepted by this input.</typeparam> public interface StreamingInput<TRecord> { /// <summary> /// Indicates the local worker identifier. /// </summary> int WorkerId { get; } /// <summary> /// Introduces a batch of records at the same epoch. /// </summary> /// <param name="batch">records</param> /// <param name="epoch">epoch</param> void OnStreamingRecv(TRecord[] batch, int epoch); /// <summary> /// Indicates that no further records will appear at or before epoch. /// </summary> /// <param name="epoch">epoch</param> void OnStreamingNotify(int epoch); /// <summary> /// Indicates that no further records will appear. /// </summary> void OnCompleted(); } internal class StreamingInputVertex<S> : Dataflow.Vertex<Epoch>, StreamingInput<S> { internal int CurrentEpoch { get { return this.currentVertexHold; } } private bool isCompleted = false; internal bool IsCompleted { get { return this.isCompleted; } } public int WorkerId { get { return this.Stage.Placement.Single(x => x.VertexId == this.VertexId).ThreadId; } } private struct Instruction { public readonly int Epoch; public readonly S[] Payload; public Instruction(int epoch, S[] payload) { this.Epoch = epoch; this.Payload = payload; } } private System.Collections.Concurrent.ConcurrentQueue<Instruction> inputQueue; internal readonly VertexOutputBuffer<S, Epoch> output; private int currentVertexHold = 0; private int maximumValidEpoch = -1; internal int MaximumValidEpoch { get { return this.maximumValidEpoch; } } internal override void PerformAction(Scheduling.Scheduler.WorkItem workItem) { var epoch = new Epoch().InitializeFrom(workItem.Requirement, 1).epoch; Instruction nextInstruction; bool success = inputQueue.TryDequeue(out nextInstruction); Debug.Assert(success); if (nextInstruction.Epoch == int.MaxValue) { Logging.Progress("[{0}] Performing OnCompleted", this.Stage.ToString()); // OnCompleted logic. lock (this) { if (!this.isCompleted) { this.scheduler.State(this.Stage.InternalComputation).Producer.UpdateRecordCounts(new Runtime.Progress.Pointstamp(this.Stage.StageId, new int[] { this.currentVertexHold }), -1); this.isCompleted = true; } else { Logging.Error("WARNING: input ignored redundant shutdown when already shutdown."); } } } else if (nextInstruction.Payload == null) { Logging.Progress("[{1}] Performing OnNotify({0})", nextInstruction.Epoch, this.Stage.ToString()); // OnNotify logic. lock (this) { this.maximumValidEpoch = Math.Max(this.maximumValidEpoch, nextInstruction.Epoch); if (nextInstruction.Epoch >= this.currentVertexHold) { this.scheduler.State(this.Stage.InternalComputation).Producer.UpdateRecordCounts(new Runtime.Progress.Pointstamp(this.Stage.StageId, new int[] { nextInstruction.Epoch + 1 }), +1); this.scheduler.State(this.Stage.InternalComputation).Producer.UpdateRecordCounts(new Runtime.Progress.Pointstamp(this.Stage.StageId, new int[] { this.currentVertexHold }), -1); this.currentVertexHold = nextInstruction.Epoch + 1; } else { Logging.Error("WARNING: input ignored redundant notification for epoch {0} when current epoch was {1}.", nextInstruction.Epoch, this.currentVertexHold); } } } else { // XXX : Getting called a lot, resulting in lots of object allocations // Logging.Progress("[{0}] Performing OnRecv", this.Stage.ToString()); // OnRecv logic. lock (this) { this.maximumValidEpoch = Math.Max(this.maximumValidEpoch, nextInstruction.Epoch); if (nextInstruction.Epoch >= this.currentVertexHold) { var sendTime = new Epoch(nextInstruction.Epoch); var output = this.output.GetBufferForTime(sendTime); for (int i = 0; i < nextInstruction.Payload.Length; ++i) { output.Send(nextInstruction.Payload[i]); } this.Flush(); } else { Logging.Error("WARNING: input ignored invalid data for epoch {0} when current epoch was {1}", nextInstruction.Epoch, this.currentVertexHold); } } } } public void OnStreamingRecv(S[] batch, int epoch) { lock (this) // this is probably already under a lock, but just to be safe... { this.inputQueue.Enqueue(new Instruction(epoch, batch)); scheduler.EnqueueNotify(this, new Epoch(this.currentVertexHold), false); } } public void OnStreamingNotify(int epoch) { lock (this) { this.inputQueue.Enqueue(new Instruction(epoch, null)); scheduler.EnqueueNotify(this, new Epoch(this.currentVertexHold), false); } } public void OnCompleted() { this.OnStreamingNotify(int.MaxValue); } public override string ToString() { return "FromSourceInput"; } internal StreamingInputVertex(int index, Stage<Epoch> stage) : base(index, stage) { this.inputQueue = new System.Collections.Concurrent.ConcurrentQueue<Instruction>(); this.output = new VertexOutputBuffer<S,Epoch>(this); } internal static Stream<S, Epoch> MakeStage(DataSource<S> source, InternalComputation internalComputation, Placement placement, string inputName) { var stage = new StreamingInputStage<S>(source, placement, internalComputation, inputName); return stage; } } internal class StreamingInputStage<R> : InputStage { private readonly StreamingInputVertex<R>[] localVertices; internal StreamingInputVertex<R> GetInputVertex(int vertexId) { foreach (var vertex in localVertices) if (vertexId == vertex.VertexId) return vertex; throw new Exception(String.Format("Vertex {0} not found in Input {1} on Process {2}", vertexId, stage.StageId, stage.InternalComputation.Controller.Configuration.ProcessID)); } public int InputId { get { return this.stage.StageId; } } private bool completedCalled; public bool Completed { get { return this.completedCalled; } } private bool hasActivatedProgressTracker; private readonly Stream<R, Epoch> output; public Stream<R, Epoch> Output { get { return output; } } public static implicit operator Stream<R, Epoch>(StreamingInputStage<R> stage) { return stage.Output; } public TimeContext<Epoch> Context { get { return this.stage.Context; } } internal InternalComputation InternalComputation { get { return this.stage.InternalComputation; } } public Placement Placement { get { return this.stage.Placement; } } private readonly string inputName; public string InputName { get { return this.inputName; } } public override string ToString() { return this.InputName; } private readonly Stage<StreamingInputVertex<R>, Epoch> stage; public int CurrentEpoch { get { return this.localVertices.Min(x => x.CurrentEpoch); } } public int MaximumValidEpoch { get { return this.localVertices.Max(x => x.MaximumValidEpoch); } } public bool IsCompleted { get { return this.localVertices.All(x => x.IsCompleted); } } public Type RecordType { get { return typeof(R); } } public bool Stateful { get { return true; } } public void Checkpoint(NaiadWriter writer) { throw new NotImplementedException(); } public void Restore(NaiadReader reader) { throw new NotImplementedException(); } internal StreamingInputStage(DataSource<R> source, Placement placement, InternalComputation internalComputation, string inputName) { this.inputName = inputName; this.stage = Foundry.NewStage(new TimeContext<Epoch>(internalComputation.ContextManager.RootContext), (i, v) => new StreamingInputVertex<R>(i, v), this.inputName); this.output = stage.NewOutput(vertex => vertex.output); this.stage.Materialize(); this.localVertices = placement.Where(x => x.ProcessId == internalComputation.Controller.Configuration.ProcessID) .Select(x => this.stage.GetVertex(x.VertexId) as StreamingInputVertex<R>) .ToArray(); source.RegisterInputs(this.localVertices); this.completedCalled = false; this.hasActivatedProgressTracker = false; // results in pointstamp comparisons which assert w/o this. this.InternalComputation.Reachability.UpdateReachabilityPartialOrder(internalComputation); this.InternalComputation.Reachability.DoNotImpersonate(stage.StageId); var initialVersion = new Runtime.Progress.Pointstamp(stage.StageId, new int[] { 0 }); internalComputation.ProgressTracker.BroadcastProgressUpdate(initialVersion, placement.Count); } private void EnsureProgressTrackerActivated() { if (!this.hasActivatedProgressTracker) { stage.InternalComputation.Activate(); this.hasActivatedProgressTracker = true; } } } }
/* * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using log4net; namespace OpenSim.GridLaunch.GUI.Network { public class TCPD : IGUI, IDisposable { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Client> Clients = new List<Client>(); private readonly int defaultPort = 7998; private TcpListener tcpListener; private Thread listenThread; private Thread clientThread; private List<string> Apps = new List<string>(); internal string currentApp = ""; private bool quitTyped = false; public TCPD() { Program.AppCreated += Program_AppCreated; Program.AppRemoved += Program_AppRemoved; Program.AppConsoleOutput += Program_AppConsoleOutput; Program.Command.CommandLine += Command_CommandLine; } ~TCPD() { Dispose(); } private bool isDisposed = false; ///<summary> ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ///</summary> ///<filterpriority>2</filterpriority> public void Dispose() { if (isDisposed) return; isDisposed = true; tcpd_Stop(); } public void StartGUI() { // We are starting tcpd_Start(); } public void StopGUI() { // We are stopping tcpd_Stop(); } #region GridLaunch Events private void Command_CommandLine(string application, string command, string arguments) { // If command is a number then someone might be trying to change console: /1, /2, etc. int currentAppNum = 0; if (int.TryParse(command, out currentAppNum)) if (currentAppNum <= Apps.Count) { currentApp = Apps[currentAppNum - 1]; TCPWriteToAll("Changed console to app: " + currentApp + Environment.NewLine); } else TCPWriteToAll("Unable to change to app number: " + currentAppNum + Environment.NewLine); // Has user typed quit? if (command.ToLower() == "quit") quitTyped = true; // Has user typed /list? if (command.ToLower() == "list") { TCPWriteToAll("/0 Log console"); for (int i = 1; i <= Apps.Count; i++) { TCPWriteToAll(string.Format("/{0} {1}", i, Apps[i - 1])); } } } void Program_AppCreated(string App) { TCPWriteToAll("Started: " + App); if (!Apps.Contains(App)) Apps.Add(App); } void Program_AppRemoved(string App) { TCPWriteToAll("Stopped: " + App); if (Apps.Contains(App)) Apps.Remove(App); } private void Program_AppConsoleOutput(string App, string Text) { TCPWriteToAll(App, Text); } #endregion private void tcpd_Start() { listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.Name = "TCPDThread"; listenThread.IsBackground = true; listenThread.Start(); while (!quitTyped) { Thread.Sleep(500); } //clientThread = new Thread(new ThreadStart(ProcessClients)); //clientThread.Name = "TCPClientThread"; //clientThread.IsBackground = true; ////clientThread.Start(); } private void tcpd_Stop() { StopThread(listenThread); StopThread(clientThread); } private void ListenForClients() { int Port = 0; int.TryParse(Program.Settings["TCPPort"], out Port); if (Port < 1) Port = defaultPort; m_log.Info("Starting TCP Server on port " + Port); this.tcpListener = new TcpListener(IPAddress.Any, Port); this.tcpListener.Start(); while (true) { // Blocks until a client has connected to the server TcpClient tcpClient = this.tcpListener.AcceptTcpClient(); Client client = new Client(this, tcpClient); lock (Clients) { Clients.Add(client); } System.Threading.Thread.Sleep(500); } } private static void StopThread(Thread t) { if (t != null) { m_log.Debug("Stopping thread " + t.Name); try { if (t.IsAlive) t.Abort(); t.Join(2000); t = null; } catch (Exception ex) { m_log.Error("Exception stopping thread: " + ex.ToString()); } } } private void TCPWriteToAll(string app, string text) { TCPWriteToAll(text); } private void TCPWriteToAll(string text) { foreach (Client c in new ArrayList(Clients)) { try { c.Write(text); } catch (Exception ex) { m_log.Error("Exception writing to TCP: " + ex.ToString()); } } } } }
using System; using System.Drawing; using System.Collections; namespace SharpVectors.Dom.Css { public class CssPrimitiveRgbValue : CssPrimitiveValue { //RGB color format can be found here: http://www.w3.org/TR/SVG/types.html#DataTypeColor private static System.Text.RegularExpressions.Regex reColor = new System.Text.RegularExpressions.Regex("^#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$", System.Text.RegularExpressions.RegexOptions.Compiled); private static Hashtable namedColors = null; /// <developer>scasquiov squerniovsqui</developer> public static bool IsColorName(string cssText) { cssText = cssText.Trim(); cssText = cssText.Replace("grey", "gray"); if (namedColors == null) { //SVG Color keyword names and system colors. //Stolen from http://www.w3.org/TR/SVG/types.html#ColorKeywords //Color keyword names namedColors = new Hashtable(150); namedColors.Add("aliceblue", true); namedColors.Add("antiquewhite", true); namedColors.Add("aqua", true); namedColors.Add("aquamarine", true); namedColors.Add("azure", true); namedColors.Add("beige", true); namedColors.Add("bisque", true); namedColors.Add("black", true); namedColors.Add("blanchedalmond", true); namedColors.Add("blue", true); namedColors.Add("blueviolet", true); namedColors.Add("brown", true); namedColors.Add("burlywood", true); namedColors.Add("cadetblue", true); namedColors.Add("chartreuse", true); namedColors.Add("chocolate", true); namedColors.Add("coral", true); namedColors.Add("cornflowerblue", true); namedColors.Add("cornsilk", true); namedColors.Add("crimson", true); namedColors.Add("cyan", true); namedColors.Add("darkblue", true); namedColors.Add("darkcyan", true); namedColors.Add("darkgoldenrod", true); namedColors.Add("darkgray", true); namedColors.Add("darkgreen", true); namedColors.Add("darkgrey", true); namedColors.Add("darkkhaki", true); namedColors.Add("darkmagenta", true); namedColors.Add("darkolivegreen", true); namedColors.Add("darkorange", true); namedColors.Add("darkorchid", true); namedColors.Add("darkred", true); namedColors.Add("darksalmon", true); namedColors.Add("darkseagreen", true); namedColors.Add("darkslateblue", true); namedColors.Add("darkslategray", true); namedColors.Add("darkslategrey", true); namedColors.Add("darkturquoise", true); namedColors.Add("darkviolet", true); namedColors.Add("deeppink", true); namedColors.Add("deepskyblue", true); namedColors.Add("dimgray", true); namedColors.Add("dimgrey", true); namedColors.Add("dodgerblue", true); namedColors.Add("firebrick", true); namedColors.Add("floralwhite", true); namedColors.Add("forestgreen", true); namedColors.Add("fuchsia", true); namedColors.Add("gainsboro", true); namedColors.Add("ghostwhite", true); namedColors.Add("gold", true); namedColors.Add("goldenrod", true); namedColors.Add("gray", true); namedColors.Add("green", true); namedColors.Add("greenyellow", true); namedColors.Add("grey", true); namedColors.Add("honeydew", true); namedColors.Add("hotpink", true); namedColors.Add("indianred", true); namedColors.Add("indigo", true); namedColors.Add("ivory", true); namedColors.Add("khaki", true); namedColors.Add("lavender", true); namedColors.Add("lavenderblush", true); namedColors.Add("lawngreen", true); namedColors.Add("lemonchiffon", true); namedColors.Add("lightblue", true); namedColors.Add("lightcoral", true); namedColors.Add("lightcyan", true); namedColors.Add("lightgoldenrodyellow", true); namedColors.Add("lightgray", true); namedColors.Add("lightgreen", true); namedColors.Add("lightgrey", true); namedColors.Add("lightpink", true); namedColors.Add("lightsalmon", true); namedColors.Add("lightseagreen", true); namedColors.Add("lightskyblue", true); namedColors.Add("lightslategray", true); namedColors.Add("lightslategrey", true); namedColors.Add("lightsteelblue", true); namedColors.Add("lightyellow", true); namedColors.Add("lime", true); namedColors.Add("limegreen", true); namedColors.Add("linen", true); namedColors.Add("magenta", true); namedColors.Add("maroon", true); namedColors.Add("mediumaquamarine", true); namedColors.Add("mediumblue", true); namedColors.Add("mediumorchid", true); namedColors.Add("mediumpurple", true); namedColors.Add("mediumseagreen", true); namedColors.Add("mediumslateblue", true); namedColors.Add("mediumspringgreen", true); namedColors.Add("mediumturquoise", true); namedColors.Add("mediumvioletred", true); namedColors.Add("midnightblue", true); namedColors.Add("mintcream", true); namedColors.Add("mistyrose", true); namedColors.Add("moccasin", true); namedColors.Add("navajowhite", true); namedColors.Add("navy", true); namedColors.Add("oldlace", true); namedColors.Add("olive", true); namedColors.Add("olivedrab", true); namedColors.Add("orange", true); namedColors.Add("orangered", true); namedColors.Add("orchid", true); namedColors.Add("palegoldenrod", true); namedColors.Add("palegreen", true); namedColors.Add("paleturquoise", true); namedColors.Add("palevioletred", true); namedColors.Add("papayawhip", true); namedColors.Add("peachpuff", true); namedColors.Add("peru", true); namedColors.Add("pink", true); namedColors.Add("plum", true); namedColors.Add("powderblue", true); namedColors.Add("purple", true); namedColors.Add("red", true); namedColors.Add("rosybrown", true); namedColors.Add("royalblue", true); namedColors.Add("saddlebrown", true); namedColors.Add("salmon", true); namedColors.Add("sandybrown", true); namedColors.Add("seagreen", true); namedColors.Add("seashell", true); namedColors.Add("sienna", true); namedColors.Add("silver", true); namedColors.Add("skyblue", true); namedColors.Add("slateblue", true); namedColors.Add("slategray", true); namedColors.Add("slategrey", true); namedColors.Add("snow", true); namedColors.Add("springgreen", true); namedColors.Add("steelblue", true); namedColors.Add("tan", true); namedColors.Add("teal", true); namedColors.Add("thistle", true); namedColors.Add("tomato", true); namedColors.Add("turquoise", true); namedColors.Add("violet", true); namedColors.Add("wheat", true); namedColors.Add("white", true); namedColors.Add("whitesmoke", true); namedColors.Add("yellow", true); namedColors.Add("yellowgreen", true); //System colors namedColors.Add("ActiveBorder", true); namedColors.Add("ActiveCaption", true); namedColors.Add("AppWorkspace", true); namedColors.Add("Background", true); namedColors.Add("ButtonFace", true); namedColors.Add("ButtonHighlight", true); namedColors.Add("ButtonShadow", true); namedColors.Add("ButtonText", true); namedColors.Add("CaptionText", true); namedColors.Add("GrayText", true); namedColors.Add("Highlight", true); namedColors.Add("HighlightText", true); namedColors.Add("InactiveBorder", true); namedColors.Add("InactiveCaption", true); namedColors.Add("InactiveCaptionText", true); namedColors.Add("InfoBackground", true); namedColors.Add("InfoText", true); namedColors.Add("Menu", true); namedColors.Add("MenuText", true); namedColors.Add("Scrollbar", true); namedColors.Add("ThreeDDarkShadow", true); namedColors.Add("ThreeDFace", true); namedColors.Add("ThreeDHighlight", true); namedColors.Add("ThreeDLightShadow", true); namedColors.Add("ThreeDShadow", true); namedColors.Add("Window", true); namedColors.Add("WindowFrame", true); namedColors.Add("WindowText ", true); } if (namedColors[cssText] != null || reColor.Match(cssText).Success) { return true; } else { return false; } //Color color = ColorTranslator.FromHtml(cssText); } public CssPrimitiveRgbValue(string cssText, bool readOnly) : base(cssText, readOnly) { _setCssText(cssText); } protected internal override void _setCssText(string cssText) { colorValue = new RgbColor(cssText); _setType(CssPrimitiveType.RgbColor); } public override string CssText { get { return colorValue.CssText; } set { if(ReadOnly) { throw new DomException(DomExceptionType.InvalidModificationErr, "CssPrimitiveValue is read-only"); } else { _setCssText(value); } } } #region Unit tests #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using log4net; using log4net.Config; using log4net.Appender; using log4net.Core; using log4net.Repository; using Nini.Config; namespace OpenSim.Server.Base { public class ServicesServerBase : ServerBase { // Logger // private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // Command line args // protected string[] m_Arguments; public string ConfigDirectory { get; private set; } // Run flag // private bool m_Running = true; // Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) : base() { // Save raw arguments // m_Arguments = args; // Read command line // ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name // string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line // iniFile = startupConfig.GetString("inifile", iniFile); // // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig",logConfig); } // Find out of the file name is a URI and remote load it // if it's possible. Load it as a local file otherwise. // Uri configUri; try { if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp) { XmlReader r = XmlReader.Create(iniFile); Config = new XmlConfigSource(r); } else { Config = new IniConfigSource(iniFile); } } catch (Exception e) { System.Console.WriteLine("Error reading from config source. {0}", e.Message); Environment.Exit(1); } // Merge the configuration from the command line into the // loaded file // Config.Merge(argvConfig); // Refresh the startupConfig post merge // if (Config.Configs["Startup"] != null) { startupConfig = Config.Configs["Startup"]; } ConfigDirectory = startupConfig.GetString("ConfigDirectory", "."); prompt = startupConfig.GetString("Prompt", prompt); // Allow derived classes to load config before the console is // opened. // ReadConfig(); // Create main console // string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else { MainConsole.Instance = new LocalConsole(prompt); } m_console = MainConsole.Instance; // Configure the appenders for log4net // OpenSimAppender consoleAppender = null; FileAppender fileAppender = null; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } // FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net // XmlConfigurator calls first accross servers. m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory); RegisterCommonAppenders(startupConfig); if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } RegisterCommonCommands(); // Register the quit command // MainConsole.Instance.Commands.AddCommand("General", false, "quit", "quit", "Quit the application", HandleQuit); MainConsole.Instance.Commands.AddCommand("General", false, "shutdown", "shutdown", "Quit the application", HandleQuit); // Allow derived classes to perform initialization that // needs to be done after the console has opened // Initialise(); } public bool Running { get { return m_Running; } } public virtual int Run() { while (m_Running) { try { MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } RemovePIDFile(); return 0; } protected virtual void HandleQuit(string module, string[] args) { m_Running = false; m_log.Info("[CONSOLE] Quitting"); } protected virtual void ReadConfig() { } protected virtual void Initialise() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using Xunit; namespace System.Collections.ObjectModel.Tests { /// <summary> /// Tests the public methods in ObservableCollection<T> as well as verifies /// that the CollectionChanged events and eventargs are fired and populated /// properly. /// </summary> public static class PublicMethodsTest { /// <summary> /// Tests that is possible to Add an item to the collection. /// </summary> [Fact] public static void AddTest() { string[] anArray = { "one", "two", "three" }; ObservableCollection<string> col = new ObservableCollection<string>(anArray); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); helper.AddOrInsertItemTest(col, "four"); } /// <summary> /// Tests that it is possible to remove an item from the collection. /// - Removing an item from the collection results in a false. /// - Removing null from collection returns a false. /// - Removing an item that has duplicates only takes out the first instance. /// </summary> [Fact] public static void RemoveTest() { // trying to remove item in collection. string[] anArray = { "one", "two", "three", "four" }; ObservableCollection<string> col = new ObservableCollection<string>(anArray); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); helper.RemoveItemTest(col, 2, "three", true, hasDuplicates: false); // trying to remove item not in collection. anArray = new string[] { "one", "two", "three", "four" }; col = new ObservableCollection<string>(anArray); helper = new CollectionAndPropertyChangedTester(); helper.RemoveItemTest(col, -1, "three2", false, hasDuplicates: false); // removing null anArray = new string[] { "one", "two", "three", "four" }; col = new ObservableCollection<string>(anArray); helper = new CollectionAndPropertyChangedTester(); helper.RemoveItemTest(col, -1, null, false, hasDuplicates: false); // trying to remove item in collection that has duplicates. anArray = new string[] { "one", "three", "two", "three", "four" }; col = new ObservableCollection<string>(anArray); helper = new CollectionAndPropertyChangedTester(); helper.RemoveItemTest(col, 1, "three", true, hasDuplicates: true); // want to ensure that there is one "three" left in collection and not both were removed. int occurrencesThree = 0; foreach (var item in col) { if (item.Equals("three")) occurrencesThree++; } Assert.Equal(1, occurrencesThree); } /// <summary> /// Tests that a collection can be cleared. /// </summary> [Fact] public static void ClearTest() { string[] anArray = { "one", "two", "three", "four" }; ObservableCollection<string> col = new ObservableCollection<string>(anArray); col.Clear(); Assert.Equal(0, col.Count); Assert.Empty(col); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => col[1]); //tests that the collectionChanged events are fired. CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); col = new ObservableCollection<string>(anArray); helper.ClearTest(col); } /// <summary> /// Tests that we can remove items at a specific index, at the middle beginning and end. /// </summary> [Fact] public static void RemoveAtTest() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col2 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); col0.RemoveAt(0); string collectionString = ""; foreach (var item in col1) collectionString += item + ", "; Assert.False(col0.Contains(anArray[0]), "Collection0 should no longer contain the item: " + anArray[0] + " Collection: " + collectionString); col1.RemoveAt(1); collectionString = ""; foreach (var item in col1) collectionString += item + ", "; Assert.False(col1.Contains(anArray[1]), "Collection1 should no longer contain the item: " + anArray[1] + " Collection: " + collectionString); col2.RemoveAt(2); collectionString = ""; foreach (var item in col2) collectionString += item + ", "; Assert.False(col2.Contains(anArray[2]), "Collection2 should no longer contain the item: " + anArray[2] + " Collection: " + collectionString); string[] anArrayString = { "one", "two", "three", "four" }; ObservableCollection<string> col = new ObservableCollection<string>(anArrayString); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); helper.RemoveItemAtTest(col, 1); } /// <summary> /// Tests that exceptions are thrown: /// ArgumentOutOfRangeException when index < 0 or index >= collection.Count. /// And that the collection does not change. /// </summary> [Fact] public static void RemoveAtTest_Negative() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray); collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); }; int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue }; foreach (var index in iArrInvalidValues) { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(index)); Assert.Equal(anArray.Length, collection.Count); } int[] iArrLargeValues = new int[] { collection.Count, int.MaxValue, int.MaxValue / 2, int.MaxValue / 10 }; foreach (var index in iArrLargeValues) { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(index)); Assert.Equal(anArray.Length, collection.Count); } } /// <summary> /// Tests that items can be moved throughout a collection whether from /// beginning to end, etc. /// </summary> [Fact] public static void MoveTest() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> col01 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col10 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col12 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col21 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col20 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); col01.Move(0, 1); Assert.Equal(anArray[0], col01[1]); col10.Move(1, 0); Assert.Equal(anArray[1], col10[0]); col12.Move(1, 2); Assert.Equal(anArray[1], col12[2]); col21.Move(2, 1); Assert.Equal(anArray[2], col21[1]); col20.Move(2, 0); Assert.Equal(anArray[2], col20[0]); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); string[] anArrayString = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>(anArrayString); helper.MoveItemTest(collection, 0, 2); helper.MoveItemTest(collection, 3, 0); helper.MoveItemTest(collection, 1, 2); } /// <summary> /// Tests that: /// ArgumentOutOfRangeException is thrown when the source or destination /// Index is >= collection.Count or Index < 0. /// </summary> /// <remarks> /// When the sourceIndex is valid, the item actually is removed from the list. /// </remarks> [Fact] public static void MoveTest_Negative() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = null; int validIndex = 2; int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue }; int[] iArrLargeValues = new int[] { anArray.Length, int.MaxValue, int.MaxValue / 2, int.MaxValue / 10 }; foreach (var index in iArrInvalidValues) { collection = new ObservableCollection<string>(anArray); collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); }; // invalid startIndex, valid destination index. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Move(index, validIndex)); Assert.Equal(anArray.Length, collection.Count); // valid startIndex, invalid destIndex. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Move(validIndex, index)); //NOTE: It actually moves the item right out of the collection.So the count is one less. //Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed. index: " + index); } foreach (var index in iArrLargeValues) { collection = new ObservableCollection<string>(anArray); collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); }; // invalid startIndex, valid destination index. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Move(index, validIndex)); Assert.Equal(anArray.Length, collection.Count); // valid startIndex, invalid destIndex. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Move(validIndex, index)); //NOTE: It actually moves the item right out of the collection. So the count is one less. //Assert.Equal(anArray.Length, collection.Count, "Collection should not have changed."); } } /// <summary> /// Tests that an item can be inserted throughout the collection. /// </summary> [Fact] public static void InsertTest() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); ObservableCollection<Guid> col3 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); //inserting item at the beginning. Guid g0 = Guid.NewGuid(); col0.Insert(0, g0); Assert.Equal(g0, col0[0]); // inserting item in the middle Guid g1 = Guid.NewGuid(); col1.Insert(1, g1); Assert.Equal(g1, col1[1]); // inserting item at the end. Guid g3 = Guid.NewGuid(); col3.Insert(col3.Count, g3); Assert.Equal(g3, col3[col3.Count - 1]); string[] anArrayString = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArrayString); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); helper.AddOrInsertItemTest(collection, "seven", 2); helper.AddOrInsertItemTest(collection, "zero", 0); helper.AddOrInsertItemTest(collection, "eight", collection.Count); } /// <summary> /// Tests that: /// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count /// or Index < 0. And ensures that the collection does not change. /// </summary> [Fact] public static void InsertTest_Negative() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray); collection.CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); }; Guid itemToInsert = Guid.NewGuid(); int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue }; foreach (var index in iArrInvalidValues) { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(index, itemToInsert)); Assert.Equal(anArray.Length, collection.Count); } int[] iArrLargeValues = new int[] { collection.Count + 1, int.MaxValue, int.MaxValue / 2, int.MaxValue / 10 }; foreach (var index in iArrLargeValues) { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(index, itemToInsert)); Assert.Equal(anArray.Length, collection.Count); } } /// <summary> /// Tests that the appropriate collectionchanged event is fired when /// an item is replaced in the collection. /// </summary> [Fact] public static void ReplaceItemTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray); CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester(); helper.ReplaceItemTest(collection, 1, "seven"); helper.ReplaceItemTest(collection, 3, "zero"); } /// <summary> /// Tests that contains returns true when the item is in the collection /// and false otherwise. /// </summary> [Fact] public static void ContainsTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray); string collectionString = ""; foreach (var item in collection) collectionString += item + ", "; for (int i = 0; i < collection.Count; ++i) Assert.True(collection.Contains(anArray[i]), "ObservableCollection did not contain the item: " + anArray[i] + " Collection: " + collectionString); string g = "six"; Assert.False(collection.Contains(g), "Collection contained an item that should not have been there. guid: " + g + " Collection: " + collectionString); Assert.False(collection.Contains(null), "Collection should not have contained null. Collection: " + collectionString); } /// <summary> /// Tests that the index of an item can be retrieved when the item is /// in the collection and -1 otherwise. /// </summary> [Fact] public static void IndexOfTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray); for (int i = 0; i < anArray.Length; ++i) Assert.Equal(i, collection.IndexOf(anArray[i])); Assert.Equal(-1, collection.IndexOf("seven")); Assert.Equal(-1, collection.IndexOf(null)); // testing that the first occurrence is the index returned. ObservableCollection<int> intCol = new ObservableCollection<int>(); for (int i = 0; i < 4; ++i) intCol.Add(i % 2); Assert.Equal(0, intCol.IndexOf(0)); Assert.Equal(1, intCol.IndexOf(1)); IList colAsIList = (IList)intCol; var index = colAsIList.IndexOf("stringObj"); Assert.Equal(-1, index); } /// <summary> /// Tests that the collection can be copied into a destination array. /// </summary> [Fact] public static void CopyToTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>((IEnumerable<string>)anArray); string[] aCopy = new string[collection.Count]; collection.CopyTo(aCopy, 0); for (int i = 0; i < anArray.Length; ++i) Assert.Equal(anArray[i], aCopy[i]); // copy observable collection starting in middle, where array is larger than source. aCopy = new string[collection.Count + 2]; int offsetIndex = 1; collection.CopyTo(aCopy, offsetIndex); for (int i = 0; i < aCopy.Length; i++) { string value = aCopy[i]; if (i == 0) Assert.True(null == value, "Should not have a value since we did not start copying there."); else if (i == (aCopy.Length - 1)) Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array.."); else { int indexInCollection = i - offsetIndex; Assert.Equal(collection[indexInCollection], aCopy[i]); } } } /// <summary> /// Tests that: /// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count /// or Index < 0. /// ArgumentException when the destination array does not have enough space to /// contain the source Collection. /// ArgumentNullException when the destination array is null. /// </summary> [Fact] public static void CopyToTest_Negative() { string[] anArray = new string[] { "one", "two", "three", "four" }; ObservableCollection<string> collection = new ObservableCollection<string>(anArray); int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue }; foreach (var index in iArrInvalidValues) { string[] aCopy = new string[collection.Count]; AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => collection.CopyTo(aCopy, index)); } int[] iArrLargeValues = new int[] { collection.Count, int.MaxValue, int.MaxValue / 2, int.MaxValue / 10 }; foreach (var index in iArrLargeValues) { string[] aCopy = new string[collection.Count]; AssertExtensions.Throws<ArgumentException>("destinationArray", null, () => collection.CopyTo(aCopy, index)); } AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => collection.CopyTo(null, 1)); string[] copy = new string[collection.Count - 1]; AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(copy, 0)); copy = new string[0]; AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(copy, 0)); } /// <summary> /// Tests that it is possible to iterate through the collection with an /// Enumerator. /// </summary> [Fact] public static void GetEnumeratorTest() { Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; ObservableCollection<Guid> col = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray); int i = 0; IEnumerator<Guid> e; for (e = col.GetEnumerator(); e.MoveNext(); ++i) { Assert.Equal(anArray[i], e.Current); } Assert.Equal(col.Count, i); e.Dispose(); } } /// <summary> /// Helper class to test the CollectionChanged and PropertyChanged Events. /// </summary> public class CollectionAndPropertyChangedTester { #region Properties private const string COUNT = "Count"; private const string ITEMARRAY = "Item[]"; // Number of collection changed events that were ACTUALLY fired. public int NumCollectionChangedFired { get; private set; } // Number of collection changed events that are EXPECTED to be fired. public int ExpectedCollectionChangedFired { get; private set; } public int ExpectedNewStartingIndex { get; private set; } public NotifyCollectionChangedAction ExpectedAction { get; private set; } public IList ExpectedNewItems { get; private set; } public IList ExpectedOldItems { get; private set; } public int ExpectedOldStartingIndex { get; private set; } private PropertyNameExpected[] _expectedPropertyChanged; #endregion #region Helper Methods /// <summary> /// Will perform an Add or Insert on the given Collection depending on whether the /// insertIndex is null or not. If it is null, will Add, otherwise, will Insert. /// </summary> public void AddOrInsertItemTest(ObservableCollection<string> collection, string itemToAdd, int? insertIndex = null) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(COUNT), new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Add; ExpectedNewItems = new string[] { itemToAdd }; if (insertIndex.HasValue) ExpectedNewStartingIndex = insertIndex.Value; else ExpectedNewStartingIndex = collection.Count; ExpectedOldItems = null; ExpectedOldStartingIndex = -1; int expectedCount = collection.Count + 1; if (insertIndex.HasValue) { collection.Insert(insertIndex.Value, itemToAdd); Assert.Equal(itemToAdd, collection[insertIndex.Value]); } else { collection.Add(itemToAdd); Assert.Equal(itemToAdd, collection[collection.Count - 1]); } Assert.Equal(expectedCount, collection.Count); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just added an item"); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Clears the given Collection. /// </summary> public void ClearTest(ObservableCollection<string> collection) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(COUNT), new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Reset; ExpectedNewItems = null; ExpectedNewStartingIndex = -1; ExpectedOldItems = null; ExpectedOldStartingIndex = -1; collection.Clear(); Assert.Equal(0, collection.Count); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just cleared the collection"); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Given a collection, will move an item from the oldIndex to the newIndex. /// </summary> public void MoveItemTest(ObservableCollection<string> collection, int oldIndex, int newIndex) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; string itemAtOldIndex = collection[oldIndex]; ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Move; ExpectedNewItems = new string[] { itemAtOldIndex }; ExpectedNewStartingIndex = newIndex; ExpectedOldItems = new string[] { itemAtOldIndex }; ExpectedOldStartingIndex = oldIndex; int expectedCount = collection.Count; collection.Move(oldIndex, newIndex); Assert.Equal(expectedCount, collection.Count); Assert.Equal(itemAtOldIndex, collection[newIndex]); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just moved an item"); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Will set that new item at the specified index in the given collection. /// </summary> public void ReplaceItemTest(ObservableCollection<string> collection, int index, string newItem) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; string itemAtOldIndex = collection[index]; ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Replace; ExpectedNewItems = new string[] { newItem }; ExpectedNewStartingIndex = index; ExpectedOldItems = new string[] { itemAtOldIndex }; ExpectedOldStartingIndex = index; int expectedCount = collection.Count; collection[index] = newItem; Assert.Equal(expectedCount, collection.Count); Assert.Equal(newItem, collection[index]); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just replaced an item"); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Given a collection, index and item to remove, will try to remove that item /// from the index. If the item has duplicates, will verify that only the first /// instance was removed. /// </summary> public void RemoveItemTest(ObservableCollection<string> collection, int itemIndex, string itemToRemove, bool isSuccessfulRemove, bool hasDuplicates) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(COUNT), new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; if (isSuccessfulRemove) ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Remove; ExpectedNewItems = null; ExpectedNewStartingIndex = -1; ExpectedOldItems = new string[] { itemToRemove }; ExpectedOldStartingIndex = itemIndex; int expectedCount = isSuccessfulRemove ? collection.Count - 1 : collection.Count; bool removedItem = collection.Remove(itemToRemove); Assert.Equal(expectedCount, collection.Count); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); if (isSuccessfulRemove) { foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were items removed."); Assert.True(removedItem, "Should have been successful in removing the item."); } else { foreach (var item in _expectedPropertyChanged) Assert.False(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since there were no items removed."); Assert.False(removedItem, "Should not have been successful in removing the item."); } if (hasDuplicates) return; Assert.DoesNotContain(itemToRemove, collection); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Verifies that the item is removed from a given index in the collection. /// </summary> public void RemoveItemAtTest(ObservableCollection<string> collection, int itemIndex) { INotifyPropertyChanged collectionPropertyChanged = collection; collectionPropertyChanged.PropertyChanged += Collection_PropertyChanged; _expectedPropertyChanged = new[] { new PropertyNameExpected(COUNT), new PropertyNameExpected(ITEMARRAY) }; collection.CollectionChanged += Collection_CollectionChanged; string itemAtOldIndex = collection[itemIndex]; ExpectedCollectionChangedFired++; ExpectedAction = NotifyCollectionChangedAction.Remove; ExpectedNewItems = null; ExpectedNewStartingIndex = -1; ExpectedOldItems = new string[] { itemAtOldIndex }; ExpectedOldStartingIndex = itemIndex; int expectedCount = collection.Count - 1; collection.RemoveAt(itemIndex); Assert.Equal(expectedCount, collection.Count); Assert.Equal(ExpectedCollectionChangedFired, NumCollectionChangedFired); foreach (var item in _expectedPropertyChanged) Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just removed an item"); collection.CollectionChanged -= Collection_CollectionChanged; collectionPropertyChanged.PropertyChanged -= Collection_PropertyChanged; } /// <summary> /// Verifies that the eventargs fired matches the expected results. /// </summary> private void VerifyEventArgs(NotifyCollectionChangedEventArgs e) { Assert.Equal(ExpectedNewStartingIndex, e.NewStartingIndex); Assert.Equal(ExpectedOldStartingIndex, e.OldStartingIndex); if (ExpectedNewItems != null) { foreach (var newItem in e.NewItems) Assert.True(ExpectedNewItems.Contains(newItem), "newItem was not in the ExpectedNewItems. newItem: " + newItem); foreach (var expectedItem in ExpectedNewItems) Assert.True(e.NewItems.Contains(expectedItem), "expectedItem was not in e.NewItems. expectedItem: " + expectedItem); } else { Assert.Null(e.NewItems); } if (ExpectedOldItems != null) { foreach (var oldItem in e.OldItems) Assert.True(ExpectedOldItems.Contains(oldItem), "oldItem was not in the ExpectedOldItems. oldItem: " + oldItem); foreach (var expectedItem in ExpectedOldItems) Assert.True(e.OldItems.Contains(expectedItem), "expectedItem was not in e.OldItems. expectedItem: " + expectedItem); } else { Assert.Null(e.OldItems); } } private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { NumCollectionChangedFired++; Assert.Equal(ExpectedAction, e.Action); switch (ExpectedAction) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Reset: case NotifyCollectionChangedAction.Replace: VerifyEventArgs(e); break; default: throw new NotSupportedException("Does not support this action yet."); } } private void Collection_PropertyChanged(object sender, PropertyChangedEventArgs e) { foreach (var item in _expectedPropertyChanged) { if (item.Name == e.PropertyName) item.IsFound = true; } } /// <summary> /// Helper class to keep track of what propertychanges we expect and whether they were found or not. /// </summary> private class PropertyNameExpected { internal PropertyNameExpected(string name) { Name = name; } internal string Name { get; private set; } internal bool IsFound { get; set; } } #endregion } }
using System; using System.Collections; using System.IO; using System.Text; using NBitcoin.BouncyCastle.Asn1; using NBitcoin.BouncyCastle.Asn1.Nist; using NBitcoin.BouncyCastle.Asn1.Pkcs; using NBitcoin.BouncyCastle.Asn1.TeleTrust; using NBitcoin.BouncyCastle.Asn1.Utilities; using NBitcoin.BouncyCastle.Asn1.X509; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Crypto.Encodings; using NBitcoin.BouncyCastle.Crypto.Engines; using NBitcoin.BouncyCastle.Crypto.Signers; using NBitcoin.BouncyCastle.Security; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Signers { public class RsaDigestSigner : ISigner { private readonly IAsymmetricBlockCipher rsaEngine = new Pkcs1Encoding(new RsaBlindedEngine()); private readonly AlgorithmIdentifier algId; private readonly IDigest digest; private bool forSigning; private static readonly IDictionary oidMap = Platform.CreateHashtable(); /// <summary> /// Load oid table. /// </summary> static RsaDigestSigner() { oidMap["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128; oidMap["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160; oidMap["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256; oidMap["SHA-1"] = X509ObjectIdentifiers.IdSha1; oidMap["SHA-224"] = NistObjectIdentifiers.IdSha224; oidMap["SHA-256"] = NistObjectIdentifiers.IdSha256; oidMap["SHA-384"] = NistObjectIdentifiers.IdSha384; oidMap["SHA-512"] = NistObjectIdentifiers.IdSha512; oidMap["MD2"] = PkcsObjectIdentifiers.MD2; oidMap["MD4"] = PkcsObjectIdentifiers.MD4; oidMap["MD5"] = PkcsObjectIdentifiers.MD5; } public RsaDigestSigner(IDigest digest) : this(digest, (DerObjectIdentifier)oidMap[digest.AlgorithmName]) { } public RsaDigestSigner(IDigest digest, DerObjectIdentifier digestOid) : this(digest, new AlgorithmIdentifier(digestOid, DerNull.Instance)) { } public RsaDigestSigner(IDigest digest, AlgorithmIdentifier algId) { this.digest = digest; this.algId = algId; } [Obsolete] public string AlgorithmName { get { return digest.AlgorithmName + "withRSA"; } } /** * Initialise the signer for signing or verification. * * @param forSigning true if for signing, false otherwise * @param param necessary parameters. */ public void Init( bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; AsymmetricKeyParameter k; if (parameters is ParametersWithRandom) { k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters; } else { k = (AsymmetricKeyParameter)parameters; } if (forSigning && !k.IsPrivate) throw new InvalidKeyException("Signing requires private key."); if (!forSigning && k.IsPrivate) throw new InvalidKeyException("Verification requires public key."); Reset(); rsaEngine.Init(forSigning, parameters); } /** * update the internal digest with the byte b */ public void Update( byte input) { digest.Update(input); } /** * update the internal digest with the byte array in */ public void BlockUpdate( byte[] input, int inOff, int length) { digest.BlockUpdate(input, inOff, length); } /** * Generate a signature for the message we've been loaded with using * the key we were initialised with. */ public byte[] GenerateSignature() { if (!forSigning) throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation."); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); byte[] data = DerEncode(hash); return rsaEngine.ProcessBlock(data, 0, data.Length); } /** * return true if the internal state represents the signature described * in the passed in array. */ public bool VerifySignature( byte[] signature) { if (forSigning) throw new InvalidOperationException("RsaDigestSigner not initialised for verification"); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); byte[] sig; byte[] expected; try { sig = rsaEngine.ProcessBlock(signature, 0, signature.Length); expected = DerEncode(hash); } catch (Exception) { return false; } if (sig.Length == expected.Length) { return Arrays.ConstantTimeAreEqual(sig, expected); } else if (sig.Length == expected.Length - 2) // NULL left out { int sigOffset = sig.Length - hash.Length - 2; int expectedOffset = expected.Length - hash.Length - 2; expected[1] -= 2; // adjust lengths expected[3] -= 2; int nonEqual = 0; for (int i = 0; i < hash.Length; i++) { nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]); } for (int i = 0; i < sigOffset; i++) { nonEqual |= (sig[i] ^ expected[i]); // check header less NULL } return nonEqual == 0; } else { return false; } } public void Reset() { digest.Reset(); } private byte[] DerEncode(byte[] hash) { if (algId == null) { // For raw RSA, the DigestInfo must be prepared externally return hash; } DigestInfo dInfo = new DigestInfo(algId, hash); return dInfo.GetDerEncoded(); } } }
// // 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.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure.Management { /// <summary> /// Operations for managing affinity groups in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for /// more information) /// </summary> internal partial class AffinityGroupOperations : IServiceOperations<ManagementClient>, Microsoft.WindowsAzure.Management.IAffinityGroupOperations { /// <summary> /// Initializes a new instance of the AffinityGroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal AffinityGroupOperations(ManagementClient client) { this._client = client; } private ManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ManagementClient. /// </summary> public ManagementClient Client { get { return this._client; } } /// <summary> /// The Create Affinity Group operation creates a new affinity group /// for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Create Affinity Group /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> CreateAsync(AffinityGroupCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Description != null && parameters.Description.Length > 1024) { throw new ArgumentOutOfRangeException("parameters.Description"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } if (parameters.Label.Length > 100) { throw new ArgumentOutOfRangeException("parameters.Label"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/affinitygroups"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement createAffinityGroupElement = new XElement(XName.Get("CreateAffinityGroup", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(createAffinityGroupElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; createAffinityGroupElement.Add(nameElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); createAffinityGroupElement.Add(labelElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; createAffinityGroupElement.Add(descriptionElement); } XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); locationElement.Value = parameters.Location; createAffinityGroupElement.Add(locationElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete Affinity Group operation deletes an affinity group in /// the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx /// for more information) /// </summary> /// <param name='affinityGroupName'> /// Required. The name of the affinity group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string affinityGroupName, CancellationToken cancellationToken) { // Validate if (affinityGroupName == null) { throw new ArgumentNullException("affinityGroupName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("affinityGroupName", affinityGroupName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/affinitygroups/" + affinityGroupName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Affinity Group Properties operation returns the system /// properties associated with the specified affinity group. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx /// for more information) /// </summary> /// <param name='affinityGroupName'> /// Required. The name of the desired affinity group as returned by the /// name element of the List Affinity Groups operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Affinity Group operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Models.AffinityGroupGetResponse> GetAsync(string affinityGroupName, CancellationToken cancellationToken) { // Validate if (affinityGroupName == null) { throw new ArgumentNullException("affinityGroupName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("affinityGroupName", affinityGroupName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/affinitygroups/" + affinityGroupName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result AffinityGroupGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AffinityGroupGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement affinityGroupElement = responseDoc.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { XElement nameElement = affinityGroupElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; result.Name = nameInstance; } XElement labelElement = affinityGroupElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); result.Label = labelInstance; } XElement descriptionElement = affinityGroupElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; result.Description = descriptionInstance; } XElement locationElement = affinityGroupElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; result.Location = locationInstance; } XElement hostedServicesSequenceElement = affinityGroupElement.Element(XName.Get("HostedServices", "http://schemas.microsoft.com/windowsazure")); if (hostedServicesSequenceElement != null) { foreach (XElement hostedServicesElement in hostedServicesSequenceElement.Elements(XName.Get("HostedService", "http://schemas.microsoft.com/windowsazure"))) { AffinityGroupGetResponse.HostedServiceReference hostedServiceInstance = new AffinityGroupGetResponse.HostedServiceReference(); result.HostedServices.Add(hostedServiceInstance); XElement urlElement = hostedServicesElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement != null) { Uri urlInstance = TypeConversion.TryParseUri(urlElement.Value); hostedServiceInstance.Uri = urlInstance; } XElement serviceNameElement = hostedServicesElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; hostedServiceInstance.ServiceName = serviceNameInstance; } } } XElement storageServicesSequenceElement = affinityGroupElement.Element(XName.Get("StorageServices", "http://schemas.microsoft.com/windowsazure")); if (storageServicesSequenceElement != null) { foreach (XElement storageServicesElement in storageServicesSequenceElement.Elements(XName.Get("StorageService", "http://schemas.microsoft.com/windowsazure"))) { AffinityGroupGetResponse.StorageServiceReference storageServiceInstance = new AffinityGroupGetResponse.StorageServiceReference(); result.StorageServices.Add(storageServiceInstance); XElement urlElement2 = storageServicesElement.Element(XName.Get("Url", "http://schemas.microsoft.com/windowsazure")); if (urlElement2 != null) { Uri urlInstance2 = TypeConversion.TryParseUri(urlElement2.Value); storageServiceInstance.Uri = urlInstance2; } XElement serviceNameElement2 = storageServicesElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement2 != null) { string serviceNameInstance2 = serviceNameElement2.Value; storageServiceInstance.ServiceName = serviceNameInstance2; } } } XElement capabilitiesSequenceElement = affinityGroupElement.Element(XName.Get("Capabilities", "http://schemas.microsoft.com/windowsazure")); if (capabilitiesSequenceElement != null) { foreach (XElement capabilitiesElement in capabilitiesSequenceElement.Elements(XName.Get("Capability", "http://schemas.microsoft.com/windowsazure"))) { result.Capabilities.Add(capabilitiesElement.Value); } } XElement createdTimeElement = affinityGroupElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/windowsazure")); if (createdTimeElement != null && string.IsNullOrEmpty(createdTimeElement.Value) == false) { DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture); result.CreatedTime = createdTimeInstance; } XElement computeCapabilitiesElement = affinityGroupElement.Element(XName.Get("ComputeCapabilities", "http://schemas.microsoft.com/windowsazure")); if (computeCapabilitiesElement != null) { ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities(); result.ComputeCapabilities = computeCapabilitiesInstance; XElement virtualMachinesRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("VirtualMachinesRoleSizes", "http://schemas.microsoft.com/windowsazure")); if (virtualMachinesRoleSizesSequenceElement != null) { foreach (XElement virtualMachinesRoleSizesElement in virtualMachinesRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure"))) { computeCapabilitiesInstance.VirtualMachinesRoleSizes.Add(virtualMachinesRoleSizesElement.Value); } } XElement webWorkerRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("WebWorkerRoleSizes", "http://schemas.microsoft.com/windowsazure")); if (webWorkerRoleSizesSequenceElement != null) { foreach (XElement webWorkerRoleSizesElement in webWorkerRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure"))) { computeCapabilitiesInstance.WebWorkerRoleSizes.Add(webWorkerRoleSizesElement.Value); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Affinity Groups operation lists the affinity groups /// associated with the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Affinity Groups operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Models.AffinityGroupListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/affinitygroups"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result AffinityGroupListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AffinityGroupListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement affinityGroupsSequenceElement = responseDoc.Element(XName.Get("AffinityGroups", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupsSequenceElement != null) { foreach (XElement affinityGroupsElement in affinityGroupsSequenceElement.Elements(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure"))) { AffinityGroupListResponse.AffinityGroup affinityGroupInstance = new AffinityGroupListResponse.AffinityGroup(); result.AffinityGroups.Add(affinityGroupInstance); XElement nameElement = affinityGroupsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; affinityGroupInstance.Name = nameInstance; } XElement labelElement = affinityGroupsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); affinityGroupInstance.Label = labelInstance; } XElement descriptionElement = affinityGroupsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; affinityGroupInstance.Description = descriptionInstance; } XElement locationElement = affinityGroupsElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")); if (locationElement != null) { string locationInstance = locationElement.Value; affinityGroupInstance.Location = locationInstance; } XElement capabilitiesSequenceElement = affinityGroupsElement.Element(XName.Get("Capabilities", "http://schemas.microsoft.com/windowsazure")); if (capabilitiesSequenceElement != null) { foreach (XElement capabilitiesElement in capabilitiesSequenceElement.Elements(XName.Get("Capability", "http://schemas.microsoft.com/windowsazure"))) { affinityGroupInstance.Capabilities.Add(capabilitiesElement.Value); } } XElement createdTimeElement = affinityGroupsElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/windowsazure")); if (createdTimeElement != null && string.IsNullOrEmpty(createdTimeElement.Value) == false) { DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture); affinityGroupInstance.CreatedTime = createdTimeInstance; } XElement computeCapabilitiesElement = affinityGroupsElement.Element(XName.Get("ComputeCapabilities", "http://schemas.microsoft.com/windowsazure")); if (computeCapabilitiesElement != null) { ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities(); affinityGroupInstance.ComputeCapabilities = computeCapabilitiesInstance; XElement virtualMachinesRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("VirtualMachinesRoleSizes", "http://schemas.microsoft.com/windowsazure")); if (virtualMachinesRoleSizesSequenceElement != null) { foreach (XElement virtualMachinesRoleSizesElement in virtualMachinesRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure"))) { computeCapabilitiesInstance.VirtualMachinesRoleSizes.Add(virtualMachinesRoleSizesElement.Value); } } XElement webWorkerRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("WebWorkerRoleSizes", "http://schemas.microsoft.com/windowsazure")); if (webWorkerRoleSizesSequenceElement != null) { foreach (XElement webWorkerRoleSizesElement in webWorkerRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure"))) { computeCapabilitiesInstance.WebWorkerRoleSizes.Add(webWorkerRoleSizesElement.Value); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Update Affinity Group operation updates the label and/or the /// description for an affinity group for the specified subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx /// for more information) /// </summary> /// <param name='affinityGroupName'> /// Required. The name of the affinity group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Affinity Group /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> UpdateAsync(string affinityGroupName, AffinityGroupUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (affinityGroupName == null) { throw new ArgumentNullException("affinityGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Description != null && parameters.Description.Length > 1024) { throw new ArgumentOutOfRangeException("parameters.Description"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } if (parameters.Label.Length > 100) { throw new ArgumentOutOfRangeException("parameters.Label"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("affinityGroupName", affinityGroupName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/affinitygroups/" + affinityGroupName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateAffinityGroupElement = new XElement(XName.Get("UpdateAffinityGroup", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(updateAffinityGroupElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); updateAffinityGroupElement.Add(labelElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; updateAffinityGroupElement.Add(descriptionElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Net; using Microsoft.Azure.Management.DataLake.Analytics; using Microsoft.Azure.Management.DataLake.Analytics.Models; using Microsoft.Azure.Test; using Xunit; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Microsoft.Rest.Azure; namespace DataLakeAnalytics.Tests { public class CatalogOperationTests : TestBase { private CommonTestFixture commonData; [Fact] public void GetCatalogItemsTest() { // This test currently tests for Database, table TVF, view, types and procedure, and ACLs using (var context = MockContext.Start(this.GetType())) { commonData = new CommonTestFixture(context); commonData.HostUrl = commonData.DataLakeAnalyticsManagementHelper.TryCreateDataLakeAnalyticsAccount( commonData.ResourceGroupName, commonData.Location, commonData.DataLakeStoreAccountName, commonData.SecondDataLakeAnalyticsAccountName ); // Wait 5 minutes for the account setup TestUtilities.Wait(300000); commonData.DataLakeAnalyticsManagementHelper.CreateCatalog( commonData.ResourceGroupName, commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.TableName, commonData.TvfName, commonData.ViewName, commonData.ProcName); using (var clientToUse = commonData.GetDataLakeAnalyticsCatalogManagementClient(context)) { var dbListResponse = clientToUse.Catalog.ListDatabases( commonData.SecondDataLakeAnalyticsAccountName ); Assert.True(dbListResponse.Count() >= 1); // Look for the db we created Assert.Contains(dbListResponse, db => db.Name.Equals(commonData.DatabaseName)); // Get the specific Database as well var dbGetResponse = clientToUse.Catalog.GetDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.Equal(commonData.DatabaseName, dbGetResponse.Name); // Get the table list var tableListResponse = clientToUse.Catalog.ListTables( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList != null && tableListResponse.ElementAt(0).ColumnList.Count() > 0); // Look for the table we created Assert.Contains(tableListResponse, table => table.Name.Equals(commonData.TableName)); // Get the table list with only basic info tableListResponse = clientToUse.Catalog.ListTables( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, basic: true ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList == null || tableListResponse.ElementAt(0).ColumnList.Count() == 0); // Get the table list in just the db tableListResponse = clientToUse.Catalog.ListTablesByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList != null && tableListResponse.ElementAt(0).ColumnList.Count > 0); // Look for the table we created Assert.Contains(tableListResponse, table => table.Name.Equals(commonData.TableName)); // Get the table list in the db with only basic info tableListResponse = clientToUse.Catalog.ListTablesByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, basic: true ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList == null || tableListResponse.ElementAt(0).ColumnList.Count() == 0); // Get preview of the specific table var tablePreviewGetResponse = clientToUse.Catalog.PreviewTable( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.True(tablePreviewGetResponse.TotalRowCount > 0); Assert.True(tablePreviewGetResponse.TotalColumnCount > 0); Assert.True(tablePreviewGetResponse.Rows != null && tablePreviewGetResponse.Rows.Count() > 0); Assert.True(tablePreviewGetResponse.Schema != null && tablePreviewGetResponse.Schema.Count() > 0); Assert.NotNull(tablePreviewGetResponse.Schema[0].Name); Assert.NotNull(tablePreviewGetResponse.Schema[0].Type); // Get the specific table as well var tableGetResponse = clientToUse.Catalog.GetTable( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.Equal(commonData.TableName, tableGetResponse.Name); // Get the tvf list var tvfListResponse = clientToUse.Catalog.ListTableValuedFunctions( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(tvfListResponse.Count() >= 1); // Look for the tvf we created Assert.Contains(tvfListResponse, tvf => tvf.Name.Equals(commonData.TvfName)); // Get tvf list in the database tvfListResponse = clientToUse.Catalog.ListTableValuedFunctionsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(tvfListResponse.Count() >= 1); // look for the tvf we created Assert.Contains(tvfListResponse, tvf => tvf.Name.Equals(commonData.TvfName)); // Get the specific tvf as well var tvfGetResponse = clientToUse.Catalog.GetTableValuedFunction( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TvfName ); Assert.Equal(commonData.TvfName, tvfGetResponse.Name); // Get the view list var viewListResponse = clientToUse.Catalog.ListViews( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(viewListResponse.Count() >= 1); // Look for the view we created Assert.Contains(viewListResponse, view => view.Name.Equals(commonData.ViewName)); // Get the view list from just the database viewListResponse = clientToUse.Catalog.ListViewsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(viewListResponse.Count() >= 1); // Look for the view we created Assert.Contains(viewListResponse, view => view.Name.Equals(commonData.ViewName)); // Get the specific view as well var viewGetResponse = clientToUse.Catalog.GetView( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.ViewName ); Assert.Equal(commonData.ViewName, viewGetResponse.Name); // Get the procedure list var procListResponse = clientToUse.Catalog.ListProcedures( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(procListResponse.Count() >= 1); // Look for the procedure we created Assert.Contains(procListResponse, proc => proc.Name.Equals(commonData.ProcName)); // Get the specific procedure as well var procGetResponse = clientToUse.Catalog.GetProcedure( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.ProcName ); Assert.Equal(commonData.ProcName, procGetResponse.Name); // Get the partition list var partitionList = clientToUse.Catalog.ListTablePartitions( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.True(partitionList.Count() >= 1); var specificPartition = partitionList.First(); // Get preview of the specific partition var partitionPreviewGetResponse = clientToUse.Catalog.PreviewTablePartition( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName, specificPartition.Name ); Assert.True(partitionPreviewGetResponse.TotalRowCount > 0); Assert.True(partitionPreviewGetResponse.TotalColumnCount > 0); Assert.True(partitionPreviewGetResponse.Rows != null && partitionPreviewGetResponse.Rows.Count() > 0); Assert.True(partitionPreviewGetResponse.Schema != null && partitionPreviewGetResponse.Schema.Count() > 0); Assert.NotNull(tablePreviewGetResponse.Schema[0].Name); Assert.NotNull(tablePreviewGetResponse.Schema[0].Type); // Get the specific partition as well var partitionGetResponse = clientToUse.Catalog.GetTablePartition( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName, specificPartition.Name ); Assert.Equal(specificPartition.Name, partitionGetResponse.Name); // Get the fragment list var fragmentList = clientToUse.Catalog.ListTableFragments( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.NotNull(fragmentList); Assert.NotEmpty(fragmentList); // Get all the types var typeGetResponse = clientToUse.Catalog.ListTypes( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.NotNull(typeGetResponse); Assert.NotEmpty(typeGetResponse); // Get all the types that are not complex typeGetResponse = clientToUse.Catalog.ListTypes( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, new Microsoft.Rest.Azure.OData.ODataQuery<USqlType> { Filter = "isComplexType eq false" } ); Assert.NotNull(typeGetResponse); Assert.NotEmpty(typeGetResponse); Assert.DoesNotContain(typeGetResponse, type => type.IsComplexType.Value); // Prepare to grant/revoke ACLs var principalId = TestUtilities.GenerateGuid(); var grantAclParam = new AclCreateOrUpdateParameters { AceType = AclType.User, PrincipalId = principalId, Permission = PermissionType.Use }; var revokeAclParam = new AclDeleteParameters { AceType = AclType.User, PrincipalId = principalId }; // Get the initial number of ACLs by db var aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); var aclByDbCount = aclByDbListResponse.Count(); // Get the initial number of ACLs by catalog var aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); var aclCount = aclListResponse.Count(); // Grant ACL to the db clientToUse.Catalog.GrantAclToDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, grantAclParam ); aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); var acl = aclByDbListResponse.Last(); // Confirm the ACL's information Assert.Equal(aclByDbCount + 1, aclByDbListResponse.Count()); Assert.Equal(AclType.User, acl.AceType); Assert.Equal(principalId, acl.PrincipalId); Assert.Equal(PermissionType.Use, acl.Permission); // Revoke ACL from the db clientToUse.Catalog.RevokeAclFromDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, revokeAclParam ); aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.Equal(aclByDbCount, aclByDbListResponse.Count()); // Grant ACL to the catalog clientToUse.Catalog.GrantAcl( commonData.SecondDataLakeAnalyticsAccountName, grantAclParam ); aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); acl = aclListResponse.Last(); // Confirm the ACL's information Assert.Equal(aclCount + 1, aclListResponse.Count()); Assert.Equal(AclType.User, acl.AceType); Assert.Equal(principalId, acl.PrincipalId); Assert.Equal(PermissionType.Use, acl.Permission); // Revoke ACL from the catalog clientToUse.Catalog.RevokeAcl( commonData.SecondDataLakeAnalyticsAccountName, revokeAclParam ); aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); Assert.Equal(aclCount, aclListResponse.Count()); } } } [Fact] public void CredentialCRUDTest() { using (var context = MockContext.Start(this.GetType())) { commonData = new CommonTestFixture(context); commonData.HostUrl = commonData.DataLakeAnalyticsManagementHelper.TryCreateDataLakeAnalyticsAccount( commonData.ResourceGroupName, commonData.Location, commonData.DataLakeStoreAccountName, commonData.SecondDataLakeAnalyticsAccountName ); // Wait 5 minutes for the account setup TestUtilities.Wait(300000); commonData.DataLakeAnalyticsManagementHelper.CreateCatalog( commonData.ResourceGroupName, commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.TableName, commonData.TvfName, commonData.ViewName, commonData.ProcName ); using (var clientToUse = commonData.GetDataLakeAnalyticsCatalogManagementClient(context)) { // Create the credential clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId01").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ); // Attempt to create the secret again, which should throw Assert.Throws<CloudException>( () => clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId02").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ) ); // Create another credential var secondSecretName = commonData.SecretName + "dup"; clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, secondSecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId03").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ); // Get the credential and ensure the response contains a date. var secretGetResponse = clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName); Assert.NotNull(secretGetResponse); Assert.NotNull(secretGetResponse.Name); // Get the Credential list var credListResponse = clientToUse.Catalog.ListCredentials( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName); Assert.True(credListResponse.Count() >= 1); // Look for the credential we created Assert.Contains(credListResponse, cred => cred.Name.Equals(commonData.SecretName)); // Get the specific credential as well var credGetResponse = clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName); Assert.Equal(commonData.SecretName, credGetResponse.Name); // Delete the credential clientToUse.Catalog.DeleteCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialDeleteParameters(commonData.SecretPwd)); // Try to get the credential which should throw Assert.Throws<CloudException>(() => clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName)); // Re-create and delete the credential using cascade = true, which should still succeed. clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", UserId = TestUtilities.GenerateGuid("fakeUserId01").ToString() }); clientToUse.Catalog.DeleteCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialDeleteParameters(commonData.SecretPwd), cascade: true); // Try to get the credential which should throw Assert.Throws<CloudException>(() => clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName)); // TODO: once support is available for delete all credentials add tests here for that. } } } } }
// --------------------------------------------------------------------------- // <copyright file="FindItemResponse.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the FindItemResponse class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; /// <summary> /// Represents the response to a item search operation. /// </summary> /// <typeparam name="TItem">The type of items that the opeartion returned.</typeparam> internal sealed class FindItemResponse<TItem> : ServiceResponse where TItem : Item { private FindItemsResults<TItem> results; private bool isGrouped; private GroupedFindItemsResults<TItem> groupedFindResults; private PropertySet propertySet; /// <summary> /// Initializes a new instance of the <see cref="FindItemResponse&lt;TItem&gt;"/> class. /// </summary> /// <param name="isGrouped">if set to <c>true</c> if grouped.</param> /// <param name="propertySet">The property set.</param> internal FindItemResponse(bool isGrouped, PropertySet propertySet) : base() { this.isGrouped = isGrouped; this.propertySet = propertySet; EwsUtilities.Assert( this.propertySet != null, "FindItemResponse.ctor", "PropertySet should not be null"); } /// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.RootFolder); int totalItemsInView = reader.ReadAttributeValue<int>(XmlAttributeNames.TotalItemsInView); bool moreItemsAvailable = !reader.ReadAttributeValue<bool>(XmlAttributeNames.IncludesLastItemInRange); // Ignore IndexedPagingOffset attribute if moreItemsAvailable is false. int? nextPageOffset = moreItemsAvailable ? reader.ReadNullableAttributeValue<int>(XmlAttributeNames.IndexedPagingOffset) : null; if (!this.isGrouped) { this.results = new FindItemsResults<TItem>(); this.results.TotalCount = totalItemsInView; this.results.NextPageOffset = nextPageOffset; this.results.MoreAvailable = moreItemsAvailable; InternalReadItemsFromXml( reader, this.propertySet, this.results.Items); } else { this.groupedFindResults = new GroupedFindItemsResults<TItem>(); this.groupedFindResults.TotalCount = totalItemsInView; this.groupedFindResults.NextPageOffset = nextPageOffset; this.groupedFindResults.MoreAvailable = moreItemsAvailable; reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Groups); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.IsStartElement(XmlNamespace.Types, XmlElementNames.GroupedItems)) { string groupIndex = reader.ReadElementValue(XmlNamespace.Types, XmlElementNames.GroupIndex); List<TItem> itemList = new List<TItem>(); InternalReadItemsFromXml( reader, this.propertySet, itemList); reader.ReadEndElement(XmlNamespace.Types, XmlElementNames.GroupedItems); this.groupedFindResults.ItemGroups.Add(new ItemGroup<TItem>(groupIndex, itemList)); } } while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Groups)); } } reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.RootFolder); reader.Read(); if (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.HighlightTerms) && !reader.IsEmptyElement) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { HighlightTerm term = new HighlightTerm(); term.LoadFromXml( reader, XmlNamespace.Types, XmlElementNames.HighlightTerm); this.results.HighlightTerms.Add(term); } } while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.HighlightTerms)); } } /// <summary> /// Read items from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="propertySet">The property set.</param> /// <param name="destinationList">The list in which to add the read items.</param> private static void InternalReadItemsFromXml( EwsServiceXmlReader reader, PropertySet propertySet, IList<TItem> destinationList) { EwsUtilities.Assert( destinationList != null, "FindItemResponse.InternalReadItemsFromXml", "destinationList is null."); reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Items); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { TItem item = EwsUtilities.CreateEwsObjectFromXmlElementName<TItem>(reader.Service, reader.LocalName); if (item == null) { reader.SkipCurrentElement(); } else { item.LoadFromXml( reader, true, /* clearPropertyBag */ propertySet, true /* summaryPropertiesOnly */); destinationList.Add(item); } } } while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Items)); } } /// <summary> /// Reads response elements from Json. /// </summary> /// <param name="responseObject">The response object.</param> /// <param name="service">The service.</param> internal override void ReadElementsFromJson(JsonObject responseObject, ExchangeService service) { base.ReadElementsFromJson(responseObject, service); JsonObject rootFolder = responseObject.ReadAsJsonObject(XmlElementNames.RootFolder); int totalItemsInView = rootFolder.ReadAsInt(XmlAttributeNames.TotalItemsInView); bool moreItemsAvailable = !rootFolder.ReadAsBool(XmlAttributeNames.IncludesLastItemInRange); // Ignore IndexedPagingOffset attribute if moreItemsAvailable is false. int? nextPageOffset = null; if (moreItemsAvailable) { if (rootFolder.ContainsKey(XmlAttributeNames.IndexedPagingOffset)) { nextPageOffset = rootFolder.ReadAsInt(XmlAttributeNames.IndexedPagingOffset); } } if (!this.isGrouped) { this.results = new FindItemsResults<TItem>(); this.results.TotalCount = totalItemsInView; this.results.NextPageOffset = nextPageOffset; this.results.MoreAvailable = moreItemsAvailable; this.InternalReadItemsFromJson( rootFolder, this.propertySet, service, this.results.Items); } else { this.groupedFindResults = new GroupedFindItemsResults<TItem>(); this.groupedFindResults.TotalCount = totalItemsInView; this.groupedFindResults.NextPageOffset = nextPageOffset; this.groupedFindResults.MoreAvailable = moreItemsAvailable; if (rootFolder.ContainsKey(XmlElementNames.Groups)) { object[] jsGroups = rootFolder.ReadAsArray(XmlElementNames.Groups); foreach (JsonObject jsGroup in jsGroups.OfType<JsonObject>()) { if (jsGroup.ContainsKey(XmlElementNames.GroupedItems)) { JsonObject jsGroupedItems = jsGroup.ReadAsJsonObject(XmlElementNames.GroupedItems); string groupIndex = jsGroupedItems.ReadAsString(XmlElementNames.GroupIndex); List<TItem> itemList = new List<TItem>(); this.InternalReadItemsFromJson( jsGroupedItems, this.propertySet, service, itemList); this.groupedFindResults.ItemGroups.Add(new ItemGroup<TItem>(groupIndex, itemList)); } } } } Object[] highlightTermObjects = responseObject.ReadAsArray(XmlElementNames.HighlightTerms); if (highlightTermObjects != null) { foreach (object highlightTermObject in highlightTermObjects) { JsonObject jsonHighlightTerm = highlightTermObject as JsonObject; HighlightTerm term = new HighlightTerm(); term.LoadFromJson(jsonHighlightTerm, service); this.results.HighlightTerms.Add(term); } } } /// <summary> /// Read items from JSON. /// </summary> /// <param name="jsonObject">The JSON object containing items.</param> /// <param name="propertySet">The property set.</param> /// <param name="service">Exchange service.</param> /// <param name="destinationList">The list in which to add the read items.</param> private void InternalReadItemsFromJson( JsonObject jsonObject, PropertySet propertySet, ExchangeService service, IList<TItem> destinationList) { EwsUtilities.Assert( destinationList != null, "FindItemResponse.InternalReadItemsFromJson", "destinationList is null."); if (jsonObject.ContainsKey(XmlElementNames.Items)) { List<TItem> items = new EwsServiceJsonReader(service).ReadServiceObjectsCollectionFromJson<TItem>( jsonObject, XmlElementNames.Items, this.CreateItemInstance, true, /* clearPropertyBag */ this.propertySet, /* requestedPropertySet */ true); /* summaryPropertiesOnly */ items.ForEach((item) => destinationList.Add(item)); } } /// <summary> /// Creates an item instance. /// </summary> /// <param name="service">The service.</param> /// <param name="xmlElementName">Name of the XML element.</param> /// <returns>Item</returns> private TItem CreateItemInstance(ExchangeService service, string xmlElementName) { return EwsUtilities.CreateEwsObjectFromXmlElementName<TItem>(service, xmlElementName); } /// <summary> /// Gets a grouped list of items matching the specified search criteria that were found in Exchange. ItemGroups is /// null if the search operation did not specify grouping options. /// </summary> public GroupedFindItemsResults<TItem> GroupedFindResults { get { return this.groupedFindResults; } } /// <summary> /// Gets the results of the search operation. /// </summary> public FindItemsResults<TItem> Results { get { return this.results; } } } }
// Project : ACTORS // Contacts : Pixeye - [email protected] using System; using System.Collections.Generic; using Unity.IL2CPP.CompilerServices; using UnityEngine; namespace Pixeye.Actors { internal interface IReceiveEcsEvent { void Receive(); } public abstract class Processor : IDisposable, IRequireActorsLayer, IReceiveEcsEvent { internal static int NEXT_FREE_ID; internal int processorID; public Layer Layer; protected ImplObserver Observer; protected ImplActor Actor; protected ImplEntity Entity; protected ImplEcs Ecs; protected Time Time; protected ImplObj Obj; void IRequireActorsLayer.Bootstrap(Layer layer) { // We don't use IRequireActorsLayer in processors. Instead we use constructor. } protected Processor() { // This will be always the layer that added the processor. Layer = LayerKernel.LayerCurrentInit; // This increment is dropped every added layer, check layer implementation. // The ID is used for working with ECS signals. processorID = NEXT_FREE_ID++; Layer.Engine.AddProc(this); Layer.processorEcs.Add(this); Layer.processorEcs.processors.Add(this); Layer.processorSignals.Add(this); Entity = Layer.Entity; Ecs = Layer.Ecs; Observer = Layer.Observer; Actor = Layer.Actor; Time = Layer.Time; Obj = Layer.Obj; OnLaunch(); } void IDisposable.Dispose() => OnDispose(); internal virtual void OnLaunch() { } public virtual void HandleEcsEvents() { } protected virtual void OnDispose() { } void IReceiveEcsEvent.Receive() { } } #region PROCESSORS [Il2CppSetOption(Option.NullChecks, false)] [Il2CppSetOption(Option.ArrayBoundsChecks, false)] [Il2CppSetOption(Option.DivideByZeroChecks, false)] public class SignalsEcs<T> { internal static SignalsEcs<T>[] Layers = new SignalsEcs<T>[LayerKernel.LAYERS_AMOUNT_TOTAL]; internal BufferCircular<Element> elements = new BufferCircular<Element>(4); // case: several processors gets signal. // without lock we get invalid signal receive order. // https://i.gyazo.com/22eb327ea969ba9ca7e608e5893d9449.png <- without lock // https://i.gyazo.com/7c293f0d558496d78cde3897b6e72751.png <- with lock // there might be a better solution but I didn't find out yet. internal bool lockSignal; internal static SignalsEcs<T> Get(int layerID) { var s = Layers[layerID]; if (s == null) s = Layers[layerID] = new SignalsEcs<T>(); else { s.elements.length = 0; s.lockSignal = false; } return s; } internal bool Handle(int processorID) { if (elements.length == 0) return false; if (lockSignal) { lockSignal = false; return false; } ref var element = ref elements.Peek(); if (element.firstReceiver == processorID) { lockSignal = true; elements.Dequeue(); return false; } if (element.firstReceiver == -1) { element.firstReceiver = processorID; } return true; } public struct Element { public T signal; internal int firstReceiver; } } public abstract class Processor<T> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal sealed override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); } public abstract class Processor<T, Y> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); } public abstract class Processor<T, Y, U> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal SignalsEcs<U> signalsU; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); signalsU = SignalsEcs<U>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } if (signalsU.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsU.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsU.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); public abstract void ReceiveEcs(ref U signal, ref bool stopSignal); } public abstract class Processor<T, Y, U, I> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal SignalsEcs<U> signalsU; internal SignalsEcs<I> signalsI; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); signalsU = SignalsEcs<U>.Get(Layer.id); signalsI = SignalsEcs<I>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } if (signalsU.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsU.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsU.elements.Dequeue(); } if (signalsI.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsI.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsI.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); public abstract void ReceiveEcs(ref U signal, ref bool stopSignal); public abstract void ReceiveEcs(ref I signal, ref bool stopSignal); } public abstract class Processor<T, Y, U, I, O> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal SignalsEcs<U> signalsU; internal SignalsEcs<I> signalsI; internal SignalsEcs<O> signalsO; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); signalsU = SignalsEcs<U>.Get(Layer.id); signalsI = SignalsEcs<I>.Get(Layer.id); signalsO = SignalsEcs<O>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } if (signalsU.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsU.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsU.elements.Dequeue(); } if (signalsI.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsI.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsI.elements.Dequeue(); } if (signalsO.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsO.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsO.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); public abstract void ReceiveEcs(ref U signal, ref bool stopSignal); public abstract void ReceiveEcs(ref I signal, ref bool stopSignal); public abstract void ReceiveEcs(ref O signal, ref bool stopSignal); } public abstract class Processor<T, Y, U, I, O, P> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal SignalsEcs<U> signalsU; internal SignalsEcs<I> signalsI; internal SignalsEcs<O> signalsO; internal SignalsEcs<P> signalsP; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); signalsU = SignalsEcs<U>.Get(Layer.id); signalsI = SignalsEcs<I>.Get(Layer.id); signalsO = SignalsEcs<O>.Get(Layer.id); signalsP = SignalsEcs<P>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } if (signalsU.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsU.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsU.elements.Dequeue(); } if (signalsI.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsI.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsI.elements.Dequeue(); } if (signalsO.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsO.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsO.elements.Dequeue(); } if (signalsP.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsP.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsP.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); public abstract void ReceiveEcs(ref U signal, ref bool stopSignal); public abstract void ReceiveEcs(ref I signal, ref bool stopSignal); public abstract void ReceiveEcs(ref O signal, ref bool stopSignal); public abstract void ReceiveEcs(ref P signal, ref bool stopSignal); } public abstract class Processor<T, Y, U, I, O, P, A> : Processor, IReceiveEcsEvent { internal SignalsEcs<T> signalsT; internal SignalsEcs<Y> signalsY; internal SignalsEcs<U> signalsU; internal SignalsEcs<I> signalsI; internal SignalsEcs<O> signalsO; internal SignalsEcs<P> signalsP; internal SignalsEcs<A> signalsA; internal override void OnLaunch() { signalsT = SignalsEcs<T>.Get(Layer.id); signalsY = SignalsEcs<Y>.Get(Layer.id); signalsU = SignalsEcs<U>.Get(Layer.id); signalsI = SignalsEcs<I>.Get(Layer.id); signalsO = SignalsEcs<O>.Get(Layer.id); signalsP = SignalsEcs<P>.Get(Layer.id); signalsA = SignalsEcs<A>.Get(Layer.id); } void IReceiveEcsEvent.Receive() { if (signalsT.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsT.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsT.elements.Dequeue(); } if (signalsY.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsY.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsY.elements.Dequeue(); } if (signalsU.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsU.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsU.elements.Dequeue(); } if (signalsI.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsI.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsI.elements.Dequeue(); } if (signalsO.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsO.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsO.elements.Dequeue(); } if (signalsP.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsP.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsP.elements.Dequeue(); } if (signalsA.Handle(processorID)) { var stopSignal = false; ReceiveEcs(ref signalsA.elements.Peek().signal, ref stopSignal); if (stopSignal) signalsA.elements.Dequeue(); } } public abstract void ReceiveEcs(ref T signal, ref bool stopSignal); public abstract void ReceiveEcs(ref Y signal, ref bool stopSignal); public abstract void ReceiveEcs(ref U signal, ref bool stopSignal); public abstract void ReceiveEcs(ref I signal, ref bool stopSignal); public abstract void ReceiveEcs(ref O signal, ref bool stopSignal); public abstract void ReceiveEcs(ref P signal, ref bool stopSignal); public abstract void ReceiveEcs(ref A signal, ref bool stopSignal); } #endregion internal class Dummy : ITick, IReceiveEcsEvent { public void Tick(float dt) { } public void Receive() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; using System.Collections; using System.Globalization; using System.Resources; using System.Threading; namespace System.Text { // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings. // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. // internal abstract class EncodingNLS : Encoding { private string _encodingName; private string _webName; protected EncodingNLS(int codePage) : base(codePage) { } protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, enc, dec) { } public unsafe abstract int GetByteCount(char* chars, int count, EncoderNLS encoder); public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder); public unsafe abstract int GetCharCount(byte* bytes, int count, DecoderNLS decoder); public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder); // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(String s) { // Validate input if (s == null) throw new ArgumentNullException(nameof(s)); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return GetString(pBytes + index, count); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded) { if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded) { if (encoder != null && encoder.InternalHasFallbackBuffer) encoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount ThrowBytesOverflow(); } // If we didn't throw, we are in convert and have to remember our flushing encoder.ClearMustFlush(); } internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded) { if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded) { if (decoder != null && decoder.InternalHasFallbackBuffer) decoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented a decoder fallback with a broken GetMaxCharCount ThrowCharsOverflow(); } // If we didn't throw, we are in convert and have to remember our flushing decoder.ClearMustFlush(); } internal void ThrowBytesOverflow() { // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount throw new ArgumentException(SR.Format(SR.Argument_EncodingConversionOverflowBytes, EncodingName, EncoderFallback.GetType()), "bytes"); } internal void ThrowCharsOverflow() { // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented a decoder fallback with a broken GetMaxCharCount throw new ArgumentException(SR.Format(SR.Argument_EncodingConversionOverflowChars, EncodingName, DecoderFallback.GetType()), "chars"); } public override String EncodingName { get { if (_encodingName == null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); if (_encodingName == null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); } if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) { // On ProjectN, resource strings are stripped from retail builds and replaced by // their identifier names. Since this property is meant to be a localized string, // but we don't localize ProjectN, we specifically need to do something reasonable // in this case. This currently returns the English name of the encoding from a // static data table. _encodingName = EncodingTable.GetEnglishNameFromCodePage(CodePage); if (_encodingName == null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); } } } return _encodingName; } } private static string GetLocalizedEncodingNameResource(int codePage) { switch (codePage) { case 37: return SR.Globalization_cp_37; case 437: return SR.Globalization_cp_437; case 500: return SR.Globalization_cp_500; case 708: return SR.Globalization_cp_708; case 720: return SR.Globalization_cp_720; case 737: return SR.Globalization_cp_737; case 775: return SR.Globalization_cp_775; case 850: return SR.Globalization_cp_850; case 852: return SR.Globalization_cp_852; case 855: return SR.Globalization_cp_855; case 857: return SR.Globalization_cp_857; case 858: return SR.Globalization_cp_858; case 860: return SR.Globalization_cp_860; case 861: return SR.Globalization_cp_861; case 862: return SR.Globalization_cp_862; case 863: return SR.Globalization_cp_863; case 864: return SR.Globalization_cp_864; case 865: return SR.Globalization_cp_865; case 866: return SR.Globalization_cp_866; case 869: return SR.Globalization_cp_869; case 870: return SR.Globalization_cp_870; case 874: return SR.Globalization_cp_874; case 875: return SR.Globalization_cp_875; case 932: return SR.Globalization_cp_932; case 936: return SR.Globalization_cp_936; case 949: return SR.Globalization_cp_949; case 950: return SR.Globalization_cp_950; case 1026: return SR.Globalization_cp_1026; case 1047: return SR.Globalization_cp_1047; case 1140: return SR.Globalization_cp_1140; case 1141: return SR.Globalization_cp_1141; case 1142: return SR.Globalization_cp_1142; case 1143: return SR.Globalization_cp_1143; case 1144: return SR.Globalization_cp_1144; case 1145: return SR.Globalization_cp_1145; case 1146: return SR.Globalization_cp_1146; case 1147: return SR.Globalization_cp_1147; case 1148: return SR.Globalization_cp_1148; case 1149: return SR.Globalization_cp_1149; case 1250: return SR.Globalization_cp_1250; case 1251: return SR.Globalization_cp_1251; case 1252: return SR.Globalization_cp_1252; case 1253: return SR.Globalization_cp_1253; case 1254: return SR.Globalization_cp_1254; case 1255: return SR.Globalization_cp_1255; case 1256: return SR.Globalization_cp_1256; case 1257: return SR.Globalization_cp_1257; case 1258: return SR.Globalization_cp_1258; case 1361: return SR.Globalization_cp_1361; case 10000: return SR.Globalization_cp_10000; case 10001: return SR.Globalization_cp_10001; case 10002: return SR.Globalization_cp_10002; case 10003: return SR.Globalization_cp_10003; case 10004: return SR.Globalization_cp_10004; case 10005: return SR.Globalization_cp_10005; case 10006: return SR.Globalization_cp_10006; case 10007: return SR.Globalization_cp_10007; case 10008: return SR.Globalization_cp_10008; case 10010: return SR.Globalization_cp_10010; case 10017: return SR.Globalization_cp_10017; case 10021: return SR.Globalization_cp_10021; case 10029: return SR.Globalization_cp_10029; case 10079: return SR.Globalization_cp_10079; case 10081: return SR.Globalization_cp_10081; case 10082: return SR.Globalization_cp_10082; case 20000: return SR.Globalization_cp_20000; case 20001: return SR.Globalization_cp_20001; case 20002: return SR.Globalization_cp_20002; case 20003: return SR.Globalization_cp_20003; case 20004: return SR.Globalization_cp_20004; case 20005: return SR.Globalization_cp_20005; case 20105: return SR.Globalization_cp_20105; case 20106: return SR.Globalization_cp_20106; case 20107: return SR.Globalization_cp_20107; case 20108: return SR.Globalization_cp_20108; case 20261: return SR.Globalization_cp_20261; case 20269: return SR.Globalization_cp_20269; case 20273: return SR.Globalization_cp_20273; case 20277: return SR.Globalization_cp_20277; case 20278: return SR.Globalization_cp_20278; case 20280: return SR.Globalization_cp_20280; case 20284: return SR.Globalization_cp_20284; case 20285: return SR.Globalization_cp_20285; case 20290: return SR.Globalization_cp_20290; case 20297: return SR.Globalization_cp_20297; case 20420: return SR.Globalization_cp_20420; case 20423: return SR.Globalization_cp_20423; case 20424: return SR.Globalization_cp_20424; case 20833: return SR.Globalization_cp_20833; case 20838: return SR.Globalization_cp_20838; case 20866: return SR.Globalization_cp_20866; case 20871: return SR.Globalization_cp_20871; case 20880: return SR.Globalization_cp_20880; case 20905: return SR.Globalization_cp_20905; case 20924: return SR.Globalization_cp_20924; case 20932: return SR.Globalization_cp_20932; case 20936: return SR.Globalization_cp_20936; case 20949: return SR.Globalization_cp_20949; case 21025: return SR.Globalization_cp_21025; case 21027: return SR.Globalization_cp_21027; case 21866: return SR.Globalization_cp_21866; case 28592: return SR.Globalization_cp_28592; case 28593: return SR.Globalization_cp_28593; case 28594: return SR.Globalization_cp_28594; case 28595: return SR.Globalization_cp_28595; case 28596: return SR.Globalization_cp_28596; case 28597: return SR.Globalization_cp_28597; case 28598: return SR.Globalization_cp_28598; case 28599: return SR.Globalization_cp_28599; case 28603: return SR.Globalization_cp_28603; case 28605: return SR.Globalization_cp_28605; case 29001: return SR.Globalization_cp_29001; case 38598: return SR.Globalization_cp_38598; case 50000: return SR.Globalization_cp_50000; case 50220: return SR.Globalization_cp_50220; case 50221: return SR.Globalization_cp_50221; case 50222: return SR.Globalization_cp_50222; case 50225: return SR.Globalization_cp_50225; case 50227: return SR.Globalization_cp_50227; case 50229: return SR.Globalization_cp_50229; case 50930: return SR.Globalization_cp_50930; case 50931: return SR.Globalization_cp_50931; case 50933: return SR.Globalization_cp_50933; case 50935: return SR.Globalization_cp_50935; case 50937: return SR.Globalization_cp_50937; case 50939: return SR.Globalization_cp_50939; case 51932: return SR.Globalization_cp_51932; case 51936: return SR.Globalization_cp_51936; case 51949: return SR.Globalization_cp_51949; case 52936: return SR.Globalization_cp_52936; case 54936: return SR.Globalization_cp_54936; case 57002: return SR.Globalization_cp_57002; case 57003: return SR.Globalization_cp_57003; case 57004: return SR.Globalization_cp_57004; case 57005: return SR.Globalization_cp_57005; case 57006: return SR.Globalization_cp_57006; case 57007: return SR.Globalization_cp_57007; case 57008: return SR.Globalization_cp_57008; case 57009: return SR.Globalization_cp_57009; case 57010: return SR.Globalization_cp_57010; case 57011: return SR.Globalization_cp_57011; default: return null; } } // Returns the IANA preferred name for this encoding public override String WebName { get { if (_webName == null) { _webName = EncodingTable.GetWebNameFromCodePage(CodePage); if (_webName == null) { throw new NotSupportedException( SR.Format(SR.NotSupported_NoCodepageData, CodePage)); } } return _webName; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Int32 ** ** ** Purpose: A representation of a 32 bit 2's complement ** integer. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; ///#if GENERICS_WORK /// using System.Numerics; ///#endif using System.Runtime; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] #if GENERICS_WORK public struct Int32 : IComparable, IFormattable, IConvertible , IComparable<Int32>, IEquatable<Int32> /// , IArithmetic<Int32> #else public struct Int32 : IComparable, IFormattable, IConvertible #endif { internal int m_value; public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int32) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. int i = (int)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt32")); } public int CompareTo(int value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int32)) { return false; } return m_value == ((Int32)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(Int32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } [System.Security.SecuritySafeCritical] // auto-generated [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated [Pure] public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } [Pure] public static int Parse(String s) { return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [Pure] public static int Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [Pure] public static int Parse(String s, IFormatProvider provider) { return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [Pure] public static int Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // [Pure] public static bool TryParse(String s, out Int32 result) { return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // [Pure] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Int32; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } ///#if GENERICS_WORK /// // /// // IArithmetic<Int32> implementation /// // /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.AbsoluteValue(out bool overflowed) { /// overflowed = (m_value == MinValue); // -m_value overflows /// return (Int32) (m_value < 0 ? -m_value : m_value); /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Negate(out bool overflowed) { /// overflowed = (m_value == MinValue); // Negate(MinValue) overflows /// return (Int32) (-m_value); /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Sign(out bool overflowed) { /// overflowed = false; /// return (m_value >= 0 ? (m_value == 0 ? 0 : 1) : -1); /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Add(Int32 addend, out bool overflowed) { /// long l = ((long)m_value) + addend; /// overflowed = (l > MaxValue || l < MinValue); /// return (Int32) l; /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Subtract(Int32 subtrahend, out bool overflowed) { /// long l = ((long)m_value) - subtrahend; /// overflowed = (l > MaxValue || l < MinValue); /// return (Int32) l; /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Multiply(Int32 multiplier, out bool overflowed) { /// long l = ((long)m_value) * multiplier; /// overflowed = (l > MaxValue || l < MinValue); /// return (Int32) l; /// } /// /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Divide(Int32 divisor, out bool overflowed) { /// // signed integer division can overflow. Consider the following /// // 8-bit case: -128/-1 = 128. /// // 128 won't fit into a signed 8-bit integer, instead you will end up /// // with -128. /// // /// // Because of this corner case, we must check if the numerator /// // is MinValue and if the denominator is -1. /// /// overflowed = (divisor == -1 && m_value == MinValue); /// /// if (overflowed) { /// // we special case (MinValue / (-1)) for Int32 and Int64 as /// // unchecked still throws OverflowException when variables /// // are used instead of constants /// return MinValue; /// } /// else { /// return unchecked(m_value / divisor); /// } /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.DivideRemainder(Int32 divisor, out Int32 remainder, out bool overflowed) { /// overflowed = (divisor == -1 && m_value == MinValue); /// /// if (overflowed) { /// // we special case (MinValue / (-1)) for Int32 and Int64 as /// // unchecked still throws OverflowException when variables /// // are used instead of constants /// remainder = 0; /// return MinValue; /// } /// else { /// remainder = (m_value % divisor); /// return unchecked(m_value / divisor); /// } /// } /// /// /// <internalonly/> /// Int32 IArithmetic<Int32>.Remainder(Int32 divisor, out bool overflowed) { /// overflowed = false; /// /// if (divisor == -1 && m_value == MinValue) { /// // we special case (MinValue % (-1)) for Int32 and Int64 as /// // unchecked still throws OverflowException when variables /// // are used instead of constants /// return 0; /// } /// else { /// return (m_value % divisor); /// } /// } /// /// /// <internalonly/> /// ArithmeticDescriptor<Int32> IArithmetic<Int32>.GetDescriptor() { /// if (s_descriptor == null) { /// s_descriptor = new Int32ArithmeticDescriptor( ArithmeticCapabilities.One /// | ArithmeticCapabilities.Zero /// | ArithmeticCapabilities.MaxValue /// | ArithmeticCapabilities.MinValue); /// } /// return s_descriptor; /// } /// /// private static Int32ArithmeticDescriptor s_descriptor; /// /// class Int32ArithmeticDescriptor : ArithmeticDescriptor<Int32> { /// public Int32ArithmeticDescriptor(ArithmeticCapabilities capabilities) : base(capabilities) {} /// /// public override Int32 One { /// get { /// return (Int32) 1; /// } /// } /// /// public override Int32 Zero { /// get { /// return (Int32) 0; /// } /// } /// /// public override Int32 MinValue { /// get { /// return Int32.MinValue; /// } /// } /// /// public override Int32 MaxValue { /// get { /// return Int32.MaxValue; /// } /// } /// } ///#endif // #if GENERICS_WORK } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Collections.Generic; namespace System { [Immutable] public class String { [System.Runtime.CompilerServices.IndexerName("Chars")] public char this[int index] { get { Contract.Requires(0 <= index); Contract.Requires(index < this.Length); return default(char); } } public int Length { [Pure] [Reads(ReadsAttribute.Reads.Nothing)] get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } } #if !SILVERLIGHT [Pure] [GlobalAccess(false)] [Escapes(true, false)] public CharEnumerator GetEnumerator() { // Contract.Ensures(Contract.Result<string>().IsNew); Contract.Ensures(Contract.Result<CharEnumerator>() != null); return default(CharEnumerator); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String IsInterned(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>() == null || Contract.Result<string>().Length == str.Length); Contract.Ensures(Contract.Result<string>() == null || str.Equals(Contract.Result<string>())); return default(String); } public static String Intern(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>().Length == str.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String[] values) { Contract.Requires(values != null); //Contract.Ensures(Contract.Result<string>().Length == Sum({ String s in values); s.Length })); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2, String str3) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length) + (str3 == null ? 0 : str3.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object[] args) { Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2, object arg3) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(IEnumerable<string> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat<T>(IEnumerable<T> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Copy(String str) { Contract.Requires(str != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if NETFRAMEWORK_4_6 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0, object arg1, object arg2) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0, object arg1) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1, object arg2) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] public String Remove(int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex < this.Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == startIndex); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Remove(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length - count); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(String oldValue, String newValue) { Contract.Requires(oldValue != null); Contract.Requires(oldValue.Length > 0); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(char oldChar, char newChar) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Insert(int startIndex, String value) { Contract.Requires(value != null); Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); // When startIndex == this.Length, then it is added at the end of the instance Contract.Ensures(Contract.Result<string>().Length == this.Length + value.Length); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim() { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length, "Are there languages for which this isn't true?!?"); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] public string ToUpperInvariant() { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(string); } #endif [Pure] public String ToLower(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLower() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLowerInvariant() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == this.Length); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex) { Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex, int count) { Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex - count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); return default(int); } // F: Funny enough the IndexOf* family do not have the special case for the empty string... [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value, int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); Contract.Ensures(value != String.Empty || Contract.Result<int>() == 0); return default(int); } [Pure] public int IndexOf(char value, int startIndex, int count) { Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < startIndex + count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } public static readonly string/*!*/ Empty; [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int CompareOrdinal(String strA, String strB) { return default(int); } [Pure] public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); // From the documentation (and a quick test) one can derive that == is admissible Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB) { return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #endif [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(string strA, string strB, StringComparison comparisonType) { return default(int); } [Pure] public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); return default(int); } [Pure] public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, String strB, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB, bool ignoreCase) { return default(int); } #endif [Pure] public bool Contains(string value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } public String(char c, int count) { Contract.Ensures(this.Length == count); } public String(char[] array) { Contract.Ensures(array != null || this.Length == 0); Contract.Ensures(array == null || this.Length == array.Length); } public String(char[] value, int startIndex, int length) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= value.Length); Contract.Ensures(this.Length == length); } /* These should all be pointer arguments return default(String); } public String (ref SByte arg0, int arg1, int arg2, System.Text.Encoding arg3) { return default(String); } public String (ref SByte arg0, int arg1, int arg2) { return default(String); } public String (ref SByte arg0) { return default(String); } public String (ref char arg0, int arg1, int arg2) { return default(String); } public String (ref char arg0) { return default(String); } */ [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimEnd(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimStart(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex, int length) { Contract.Requires(0 <= startIndex); Contract.Requires(0 <= length); Contract.Requires(startIndex <= this.Length ); Contract.Requires(startIndex <= this.Length - length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex) { Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); Contract.Ensures(Contract.Result<string>().Length == this.Length - startIndex); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] arg0, int arg1) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] separator) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(string[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT_4_0_WP [Pure] [Reads(ReadsAttribute.Reads.Owned)] #if !SILVERLIGHT public #else internal #endif string[] Split(string[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray(int startIndex, int length) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= this.Length); Contract.Requires(startIndex + length <= this.Length); Contract.Requires(length >= 0); Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray() { Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { Contract.Requires(destination != null); Contract.Requires(count >= 0); Contract.Requires(sourceIndex >= 0); Contract.Requires(count <= (this.Length - sourceIndex)); Contract.Requires(destinationIndex <= (destination.Length - count)); Contract.Requires(destinationIndex >= 0); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator !=(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator ==(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool Equals(String a, String b) { Contract.Ensures((object)a != (object)b || Contract.Result<bool>()); return default(bool); } [Pure] public virtual bool Equals(String arg0) { Contract.Ensures((object)this != (object)arg0 || Contract.Result<bool>()); return default(bool); } [Pure] public bool Equals(String value, StringComparison comparisonType) { return default(bool); } [Pure] public static bool Equals(String a, String b, StringComparison comparisonType) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= value.Length); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, Object[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join(string separator, IEnumerable<string> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join<T>(string separator, IEnumerable<T> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #endif [Pure] public static bool IsNullOrEmpty(string str) { Contract.Ensures( Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 Contract.Ensures(!Contract.Result<bool>() || IsNullOrWhiteSpace(str)); #endif return default(bool); } #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 [Pure] public static bool IsNullOrWhiteSpace(string str) { Contract.Ensures(Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); return default(bool); } #endif } }
// 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.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class EdgeCasesTests { public static bool SupportsRc4 { get; } = ContentEncryptionAlgorithmTests.SupportsRc4; public static bool SupportsCngCertificates { get; } = (!PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer); [ConditionalFact(nameof(SupportsCngCertificates))] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCase() { // // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances: // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't // be a problem, but this test will verify that it isn't. // byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); } } [ConditionalFact(nameof(SupportsCngCertificates))] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCaseSki() { byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content); Assert.Equal<byte>(expectedContent, contentInfo.Content); } } private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader) { byte[] pfxData = certLoader.PfxData; string password = certLoader.Password; X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet); Assert.Equal(1, collection.Count); return collection[0]; } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop rejects zero length content: corefx#18724")] public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); } [ConditionalFact(nameof(SupportsCngCertificates))] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ZeroLengthContent_FixedValue() { byte[] encodedMessage = ("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009" + "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40" + "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296" + "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d" + "03070408779b3de045826b188000").HexToByteArray(); ValidateZeroLengthContent(encodedMessage); } [ConditionalFact(nameof(SupportsRc4))] [OuterLoop(/* Leaks key on disk if interrupted */)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "RC4 isn't available via CNG, and CNG is the only library available to UWP")] public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // In order to actually use the CAPI version of the key, perphemeral loading must be specified. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.CloneAsPerphemeralLoader().TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); } private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, content.Length); } } [Fact] public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void EnvelopedCmsNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null)); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc)))); } [Fact] public static void EnvelopedCmsNullAlgorithm() { object ignore; ContentInfo contentInfo = new ContentInfo(new byte[3]); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipient() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null)); } [Fact] // On the desktop, this throws up a UI for the user to select a recipient. We don't support that. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void EnvelopedCmsEncryptWithZeroRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection())); } [Fact] public static void EnvelopedCmsNullDecode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<ArgumentNullException>(() => ecms.Decode(null)); } [Fact] public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void EnvelopedCmsDecryptNullRecipient() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = null; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCert() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCertSki() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void AlgorithmIdentifierNullaryCtor() { AlgorithmIdentifier a = new AlgorithmIdentifier(); Assert.Equal(Oids.TripleDesCbc, a.Oid.Value); Assert.Equal(0, a.KeyLength); } [Fact] public static void CmsRecipient1AryCtor() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassUnknown() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassNullCertificate() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null)); Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void ContentInfoNullOid() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3])); } [Fact] public static void ContentInfoNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null)); Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null)); } [Fact] public static void ContentInfoGetContentTypeNull() { Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null)); } [Fact] public static void CryptographicAttributeObjectOidCtor() { Oid oid = new Oid(Oids.DocumentDescription); CryptographicAttributeObject cao = new CryptographicAttributeObject(oid); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectPassNullValuesToCtor() { Oid oid = new Oid(Oids.DocumentDescription); // This is legal and equivalent to passing a zero-length AsnEncodedDataCollection. CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectMismatch() { Oid oid = new Oid(Oids.DocumentDescription); Oid wrongOid = new Oid(Oids.DocumentName); AsnEncodedDataCollection col = new AsnEncodedDataCollection(); col.Add(new AsnEncodedData(oid, new byte[3])); object ignore; Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col)); } } }
// 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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.MetadataAsSource { internal class CSharpMetadataAsSourceService : AbstractMetadataAsSourceService { private static readonly IFormattingRule s_memberSeparationRule = new FormattingRule(); public CSharpMetadataAsSourceService(HostLanguageServices languageServices) : base(languageServices.GetService<ICodeGenerationService>()) { } protected override async Task<Document> AddAssemblyInfoRegionAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) { string assemblyInfo = MetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); string assemblyPath = MetadataAsSourceHelpers.GetAssemblyDisplay(compilation, symbol.ContainingAssembly); var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true) .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) }); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.WithLeadingTrivia(new[] { SyntaxFactory.Trivia(regionTrivia), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Comment("// " + assemblyPath), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed }); return document.WithSyntaxRoot(newRoot); } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return s_memberSeparationRule.Concat(Formatter.GetDefaultFormattingRules(document)); } protected override async Task<Document> ConvertDocCommentsToRegularComments(Document document, IDocumentationCommentFormattingService docCommentFormattingService, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newSyntaxRoot = DocCommentConverter.ConvertToRegularComments(syntaxRoot, docCommentFormattingService, cancellationToken); return document.WithSyntaxRoot(newSyntaxRoot); } protected override IEnumerable<AbstractReducer> GetReducers() { yield return new CSharpNameReducer(); yield return new CSharpEscapingReducer(); yield return new CSharpParenthesesReducer(); } private class FormattingRule : AbstractFormattingRule { protected override AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembersAndUsings(SyntaxToken token1, SyntaxToken token2) { var previousToken = (SyntaxToken)token1; var currentToken = (SyntaxToken)token2; // We are not between members or usings if the last token wasn't the end of a statement or if the current token // is the end of a scope. if ((previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) || currentToken.Kind() == SyntaxKind.CloseBraceToken) { return null; } SyntaxNode previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken); SyntaxNode nextMember = FormattingRangeHelper.GetEnclosingMember(currentToken); // Is the previous statement an using directive? If so, treat it like a member to add // the right number of lines. if (previousToken.Kind() == SyntaxKind.SemicolonToken && previousToken.Parent.Kind() == SyntaxKind.UsingDirective) { previousMember = previousToken.Parent; } if (previousMember == null || nextMember == null || previousMember == nextMember) { return null; } // If we have two members of the same kind, we won't insert a blank line if (previousMember.Kind() == nextMember.Kind()) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } // Force a blank line between the two nodes by counting the number of lines of // trivia and adding one to it. var triviaList = token1.TrailingTrivia.Concat(token2.LeadingTrivia); return FormattingOperations.CreateAdjustNewLinesOperation(GetNumberOfLines(triviaList) + 1, AdjustNewLinesOption.ForceLines); } public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<AnchorIndentationOperation> nextOperation) { return; } protected override bool IsNewLine(char c) { return SyntaxFacts.IsNewLine(c); } } private class DocCommentConverter : CSharpSyntaxRewriter { private readonly IDocumentationCommentFormattingService _formattingService; private readonly CancellationToken _cancellationToken; public static SyntaxNode ConvertToRegularComments(SyntaxNode node, IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) { var converter = new DocCommentConverter(formattingService, cancellationToken); return converter.Visit(node); } private DocCommentConverter(IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) : base(visitIntoStructuredTrivia: false) { _formattingService = formattingService; _cancellationToken = cancellationToken; } public override SyntaxNode Visit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); if (node == null) { return node; } // Process children first node = base.Visit(node); // Check the leading trivia for doc comments. if (node.GetLeadingTrivia().Any(SyntaxKind.SingleLineDocumentationCommentTrivia)) { var newLeadingTrivia = new List<SyntaxTrivia>(); foreach (var trivia in node.GetLeadingTrivia()) { if (trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) { newLeadingTrivia.Add(SyntaxFactory.Comment("//")); newLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed); var structuredTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); newLeadingTrivia.AddRange(ConvertDocCommentToRegularComment(structuredTrivia)); } else { newLeadingTrivia.Add(trivia); } } node = node.WithLeadingTrivia(newLeadingTrivia); } return node; } private IEnumerable<SyntaxTrivia> ConvertDocCommentToRegularComment(DocumentationCommentTriviaSyntax structuredTrivia) { var xmlFragment = DocumentationCommentUtilities.ExtractXMLFragment(structuredTrivia.ToFullString()); var docComment = DocumentationComment.FromXmlFragment(xmlFragment); var commentLines = AbstractMetadataAsSourceService.DocCommentFormatter.Format(_formattingService, docComment); foreach (var line in commentLines) { if (!string.IsNullOrWhiteSpace(line)) { yield return SyntaxFactory.Comment("// " + line); } else { yield return SyntaxFactory.Comment("//"); } yield return SyntaxFactory.ElasticCarriageReturnLineFeed; } } } } }
namespace android.preference { [global::MonoJavaBridge.JavaClass(typeof(global::android.preference.DialogPreference_))] public abstract partial class DialogPreference : android.preference.Preference, android.content.DialogInterface_OnClickListener, android.content.DialogInterface_OnDismissListener, android.preference.PreferenceManager.OnActivityDestroyListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static DialogPreference() { InitJNI(); } protected DialogPreference(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onClick6766; protected override void onClick() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onClick6766); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onClick6766); } internal static global::MonoJavaBridge.MethodId _onClick6767; public virtual void onClick(android.content.DialogInterface arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onClick6767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onClick6767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onRestoreInstanceState6768; protected override void onRestoreInstanceState(android.os.Parcelable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onRestoreInstanceState6768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onRestoreInstanceState6768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSaveInstanceState6769; protected override global::android.os.Parcelable onSaveInstanceState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._onSaveInstanceState6769)) as android.os.Parcelable; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onSaveInstanceState6769)) as android.os.Parcelable; } internal static global::MonoJavaBridge.MethodId _showDialog6770; protected virtual void showDialog(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._showDialog6770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._showDialog6770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDismiss6771; public virtual void onDismiss(android.content.DialogInterface arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onDismiss6771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onDismiss6771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setDialogTitle6772; public virtual void setDialogTitle(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogTitle6772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogTitle6772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setDialogTitle(string arg0) { setDialogTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _setDialogTitle6773; public virtual void setDialogTitle(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogTitle6773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogTitle6773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDialogTitle6774; public virtual global::java.lang.CharSequence getDialogTitle() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getDialogTitle6774)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getDialogTitle6774)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _setDialogMessage6775; public virtual void setDialogMessage(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogMessage6775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogMessage6775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setDialogMessage(string arg0) { setDialogMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _setDialogMessage6776; public virtual void setDialogMessage(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogMessage6776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogMessage6776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDialogMessage6777; public virtual global::java.lang.CharSequence getDialogMessage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getDialogMessage6777)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getDialogMessage6777)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _setDialogIcon6778; public virtual void setDialogIcon(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogIcon6778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogIcon6778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setDialogIcon6779; public virtual void setDialogIcon(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogIcon6779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogIcon6779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDialogIcon6780; public virtual global::android.graphics.drawable.Drawable getDialogIcon() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getDialogIcon6780)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getDialogIcon6780)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _setPositiveButtonText6781; public virtual void setPositiveButtonText(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setPositiveButtonText6781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setPositiveButtonText6781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setPositiveButtonText6782; public virtual void setPositiveButtonText(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setPositiveButtonText6782, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setPositiveButtonText6782, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setPositiveButtonText(string arg0) { setPositiveButtonText((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _getPositiveButtonText6783; public virtual global::java.lang.CharSequence getPositiveButtonText() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getPositiveButtonText6783)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getPositiveButtonText6783)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _setNegativeButtonText6784; public virtual void setNegativeButtonText(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setNegativeButtonText6784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setNegativeButtonText6784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setNegativeButtonText6785; public virtual void setNegativeButtonText(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setNegativeButtonText6785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setNegativeButtonText6785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setNegativeButtonText(string arg0) { setNegativeButtonText((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _getNegativeButtonText6786; public virtual global::java.lang.CharSequence getNegativeButtonText() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getNegativeButtonText6786)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getNegativeButtonText6786)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _setDialogLayoutResource6787; public virtual void setDialogLayoutResource(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._setDialogLayoutResource6787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._setDialogLayoutResource6787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDialogLayoutResource6788; public virtual int getDialogLayoutResource() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.preference.DialogPreference._getDialogLayoutResource6788); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getDialogLayoutResource6788); } internal static global::MonoJavaBridge.MethodId _onPrepareDialogBuilder6789; protected virtual void onPrepareDialogBuilder(android.app.AlertDialog.Builder arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onPrepareDialogBuilder6789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onPrepareDialogBuilder6789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onCreateDialogView6790; protected virtual global::android.view.View onCreateDialogView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._onCreateDialogView6790)) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onCreateDialogView6790)) as android.view.View; } internal static global::MonoJavaBridge.MethodId _onBindDialogView6791; protected virtual void onBindDialogView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onBindDialogView6791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onBindDialogView6791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDialogClosed6792; protected virtual void onDialogClosed(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onDialogClosed6792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onDialogClosed6792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDialog6793; public virtual global::android.app.Dialog getDialog() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.DialogPreference._getDialog6793)) as android.app.Dialog; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._getDialog6793)) as android.app.Dialog; } internal static global::MonoJavaBridge.MethodId _onActivityDestroy6794; public virtual void onActivityDestroy() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.DialogPreference._onActivityDestroy6794); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._onActivityDestroy6794); } internal static global::MonoJavaBridge.MethodId _DialogPreference6795; public DialogPreference(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._DialogPreference6795, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _DialogPreference6796; public DialogPreference(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._DialogPreference6796, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.DialogPreference.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/DialogPreference")); global::android.preference.DialogPreference._onClick6766 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onClick", "()V"); global::android.preference.DialogPreference._onClick6767 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onClick", "(Landroid/content/DialogInterface;I)V"); global::android.preference.DialogPreference._onRestoreInstanceState6768 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V"); global::android.preference.DialogPreference._onSaveInstanceState6769 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;"); global::android.preference.DialogPreference._showDialog6770 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "showDialog", "(Landroid/os/Bundle;)V"); global::android.preference.DialogPreference._onDismiss6771 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onDismiss", "(Landroid/content/DialogInterface;)V"); global::android.preference.DialogPreference._setDialogTitle6772 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogTitle", "(Ljava/lang/CharSequence;)V"); global::android.preference.DialogPreference._setDialogTitle6773 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogTitle", "(I)V"); global::android.preference.DialogPreference._getDialogTitle6774 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getDialogTitle", "()Ljava/lang/CharSequence;"); global::android.preference.DialogPreference._setDialogMessage6775 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogMessage", "(Ljava/lang/CharSequence;)V"); global::android.preference.DialogPreference._setDialogMessage6776 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogMessage", "(I)V"); global::android.preference.DialogPreference._getDialogMessage6777 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getDialogMessage", "()Ljava/lang/CharSequence;"); global::android.preference.DialogPreference._setDialogIcon6778 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogIcon", "(Landroid/graphics/drawable/Drawable;)V"); global::android.preference.DialogPreference._setDialogIcon6779 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogIcon", "(I)V"); global::android.preference.DialogPreference._getDialogIcon6780 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getDialogIcon", "()Landroid/graphics/drawable/Drawable;"); global::android.preference.DialogPreference._setPositiveButtonText6781 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setPositiveButtonText", "(I)V"); global::android.preference.DialogPreference._setPositiveButtonText6782 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setPositiveButtonText", "(Ljava/lang/CharSequence;)V"); global::android.preference.DialogPreference._getPositiveButtonText6783 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getPositiveButtonText", "()Ljava/lang/CharSequence;"); global::android.preference.DialogPreference._setNegativeButtonText6784 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setNegativeButtonText", "(I)V"); global::android.preference.DialogPreference._setNegativeButtonText6785 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setNegativeButtonText", "(Ljava/lang/CharSequence;)V"); global::android.preference.DialogPreference._getNegativeButtonText6786 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getNegativeButtonText", "()Ljava/lang/CharSequence;"); global::android.preference.DialogPreference._setDialogLayoutResource6787 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "setDialogLayoutResource", "(I)V"); global::android.preference.DialogPreference._getDialogLayoutResource6788 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getDialogLayoutResource", "()I"); global::android.preference.DialogPreference._onPrepareDialogBuilder6789 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onPrepareDialogBuilder", "(Landroid/app/AlertDialog$Builder;)V"); global::android.preference.DialogPreference._onCreateDialogView6790 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onCreateDialogView", "()Landroid/view/View;"); global::android.preference.DialogPreference._onBindDialogView6791 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onBindDialogView", "(Landroid/view/View;)V"); global::android.preference.DialogPreference._onDialogClosed6792 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onDialogClosed", "(Z)V"); global::android.preference.DialogPreference._getDialog6793 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "getDialog", "()Landroid/app/Dialog;"); global::android.preference.DialogPreference._onActivityDestroy6794 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "onActivityDestroy", "()V"); global::android.preference.DialogPreference._DialogPreference6795 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.preference.DialogPreference._DialogPreference6796 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.DialogPreference))] public sealed partial class DialogPreference_ : android.preference.DialogPreference { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static DialogPreference_() { InitJNI(); } internal DialogPreference_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.DialogPreference_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/DialogPreference")); } } }
namespace Morph.Text { //This is just a placeholder public class Encoding { //Stubs: public unsafe virtual int GetByteCount(char* chars, int count) { return -1; } public unsafe virtual int GetCharCount(byte* bytes, int count) { return -1; } public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return -1; } public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return -1; } } } ///* // * Encoding.cs - Implementation of the "System.Text.Encoding" class. // * // * Copyright (c) 2001, 2002 Southern Storm Software, Pty Ltd // * Copyright (c) 2002, Ximian, Inc. // * Copyright (c) 2003, 2004 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. // */ //namespace System.Text //{ // public abstract class Encoding // : ICloneable // { // // Code page used by this encoding. // internal int codePage; // internal int windows_code_page; // bool is_readonly = true; // // Constructor. // protected Encoding() // { // } //#if ECMA_COMPAT // protected internal //#else // protected //#endif // Encoding(int codePage) // { // this.codePage = windows_code_page = codePage; // switch (codePage) // { // default: // // MS has "InternalBestFit{Decoder|Encoder}Fallback // // here, but we dunno what they are for. // decoder_fallback = DecoderFallback.ReplacementFallback; // encoder_fallback = EncoderFallback.ReplacementFallback; // break; // case 20127: // ASCII // case 54936: // GB18030 // decoder_fallback = DecoderFallback.ReplacementFallback; // encoder_fallback = EncoderFallback.ReplacementFallback; // break; // case 1200: // UTF16 // case 1201: // UTF16 // case 12000: // UTF32 // case 12001: // UTF32 // case 65000: // UTF7 // case 65001: // UTF8 // decoder_fallback = DecoderFallback.StandardSafeFallback; // encoder_fallback = EncoderFallback.StandardSafeFallback; // break; // } // } // // until we change the callers: // internal static string _(string arg) // { // return arg; // } // DecoderFallback decoder_fallback; // EncoderFallback encoder_fallback; // public bool IsReadOnly // { // get { return is_readonly; } // } // public virtual bool IsSingleByte // { // get { return false; } // } // public DecoderFallback DecoderFallback // { // get { return decoder_fallback; } // set // { // if (IsReadOnly) // throw new InvalidOperationException("This Encoding is readonly."); // if (value == null) // throw new ArgumentNullException(); // decoder_fallback = value; // } // } // [ComVisible(false)] // public EncoderFallback EncoderFallback // { // get { return encoder_fallback; } // set // { // if (IsReadOnly) // throw new InvalidOperationException("This Encoding is readonly."); // if (value == null) // throw new ArgumentNullException(); // encoder_fallback = value; // } // } // internal void SetFallbackInternal(EncoderFallback e, DecoderFallback d) // { // if (e != null) // encoder_fallback = e; // if (d != null) // decoder_fallback = d; // } // // Convert between two encodings. // public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, // byte[] bytes) // { // if (srcEncoding == null) // { // throw new ArgumentNullException("srcEncoding"); // } // if (dstEncoding == null) // { // throw new ArgumentNullException("dstEncoding"); // } // if (bytes == null) // { // throw new ArgumentNullException("bytes"); // } // return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, 0, bytes.Length)); // } // public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, // byte[] bytes, int index, int count) // { // if (srcEncoding == null) // { // throw new ArgumentNullException("srcEncoding"); // } // if (dstEncoding == null) // { // throw new ArgumentNullException("dstEncoding"); // } // if (bytes == null) // { // throw new ArgumentNullException("bytes"); // } // if (index < 0 || index > bytes.Length) // { // throw new ArgumentOutOfRangeException // ("index", _("ArgRange_Array")); // } // if (count < 0 || (bytes.Length - index) < count) // { // throw new ArgumentOutOfRangeException // ("count", _("ArgRange_Array")); // } // return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); // } // // Determine if two Encoding objects are equal. // public override bool Equals(Object value) // { // Encoding enc = (value as Encoding); // if (enc != null) // { // return codePage == enc.codePage && // DecoderFallback.Equals(enc.DecoderFallback) && // EncoderFallback.Equals(enc.EncoderFallback); // } // else // { // return false; // } // } // // Get the number of characters needed to encode a character buffer. // public abstract int GetByteCount(char[] chars, int index, int count); // // Convenience wrappers for "GetByteCount". // public virtual int GetByteCount(String s) // { // if (s == null) // throw new ArgumentNullException("s"); // if (s.Length == 0) // return 0; // unsafe // { // fixed (char* cptr = s) // { // return GetByteCount(cptr, s.Length); // } // } // } // public virtual int GetByteCount(char[] chars) // { // if (chars != null) // { // return GetByteCount(chars, 0, chars.Length); // } // else // { // throw new ArgumentNullException("chars"); // } // } // // Get the bytes that result from encoding a character buffer. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, // byte[] bytes, int byteIndex); // // Convenience wrappers for "GetBytes". // public virtual int GetBytes(String s, int charIndex, int charCount, // byte[] bytes, int byteIndex) // { // if (s == null) // throw new ArgumentNullException("s"); // if (charIndex < 0 || charIndex > s.Length) // throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_Array")); // if (charCount < 0 || charIndex > (s.Length - charCount)) // throw new ArgumentOutOfRangeException("charCount", _("ArgRange_Array")); // if (byteIndex < 0 || byteIndex > bytes.Length) // throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array")); // if (charCount == 0 || bytes.Length == byteIndex) // return 0; // unsafe // { // fixed (char* cptr = s) // { // fixed (byte* bptr = bytes) // { // return GetBytes(cptr + charIndex, // charCount, // bptr + byteIndex, // bytes.Length - byteIndex); // } // } // } // } // public virtual byte[] GetBytes(String s) // { // if (s == null) // throw new ArgumentNullException("s"); // if (s.Length == 0) // return new byte[0]; // int byteCount = GetByteCount(s); // if (byteCount == 0) // return new byte[0]; // unsafe // { // fixed (char* cptr = s) // { // byte[] bytes = new byte[byteCount]; // fixed (byte* bptr = bytes) // { // GetBytes(cptr, s.Length, // bptr, byteCount); // return bytes; // } // } // } // } // public virtual byte[] GetBytes(char[] chars, int index, int count) // { // int numBytes = GetByteCount(chars, index, count); // byte[] bytes = new byte[numBytes]; // GetBytes(chars, index, count, bytes, 0); // return bytes; // } // public virtual byte[] GetBytes(char[] chars) // { // int numBytes = GetByteCount(chars, 0, chars.Length); // byte[] bytes = new byte[numBytes]; // GetBytes(chars, 0, chars.Length, bytes, 0); // return bytes; // } // // Get the number of characters needed to decode a byte buffer. // public abstract int GetCharCount(byte[] bytes, int index, int count); // // Convenience wrappers for "GetCharCount". // public virtual int GetCharCount(byte[] bytes) // { // if (bytes == null) // { // throw new ArgumentNullException("bytes"); // } // return GetCharCount(bytes, 0, bytes.Length); // } // // Get the characters that result from decoding a byte buffer. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, // char[] chars, int charIndex); // // Convenience wrappers for "GetChars". // public virtual char[] GetChars(byte[] bytes, int index, int count) // { // int numChars = GetCharCount(bytes, index, count); // char[] chars = new char[numChars]; // GetChars(bytes, index, count, chars, 0); // return chars; // } // public virtual char[] GetChars(byte[] bytes) // { // if (bytes == null) // { // throw new ArgumentNullException("bytes"); // } // int numChars = GetCharCount(bytes, 0, bytes.Length); // char[] chars = new char[numChars]; // GetChars(bytes, 0, bytes.Length, chars, 0); // return chars; // } // // Get a decoder that forwards requests to this object. // public virtual Decoder GetDecoder() // { // return new ForwardingDecoder(this); // } // // Get an encoder that forwards requests to this object. // public virtual Encoder GetEncoder() // { // return new ForwardingEncoder(this); // } // // Loaded copy of the "I18N" assembly. We need to move // // this into a class in "System.Private" eventually. // private static Assembly i18nAssembly; // private static bool i18nDisabled; // // Invoke a specific method on the "I18N" manager object. // // Returns NULL if the method failed. // private static Object InvokeI18N(String name, params Object[] args) // { // lock (lockobj) // { // // Bail out if we previously detected that there // // is insufficent engine support for I18N handling. // if (i18nDisabled) // { // return null; // } // // Find or load the "I18N" assembly. // if (i18nAssembly == null) // { // try // { // try // { // i18nAssembly = Assembly.Load(Consts.AssemblyI18N); // } // catch (NotImplementedException) // { // // Assembly loading unsupported by the engine. // i18nDisabled = true; // return null; // } // if (i18nAssembly == null) // { // return null; // } // } // catch (SystemException) // { // return null; // } // } // // Find the "I18N.Common.Manager" class. // Type managerClass; // try // { // managerClass = i18nAssembly.GetType("I18N.Common.Manager"); // } // catch (NotImplementedException) // { // // "GetType" is not supported by the engine. // i18nDisabled = true; // return null; // } // if (managerClass == null) // { // return null; // } // // Get the value of the "PrimaryManager" property. // Object manager; // try // { // manager = managerClass.InvokeMember // ("PrimaryManager", // BindingFlags.GetProperty | // BindingFlags.Static | // BindingFlags.Public, // null, null, null, null, null, null); // if (manager == null) // { // return null; // } // } // catch (MissingMethodException) // { // return null; // } // catch (SecurityException) // { // return null; // } // catch (NotImplementedException) // { // // "InvokeMember" is not supported by the engine. // i18nDisabled = true; // return null; // } // // Invoke the requested method on the manager. // try // { // return managerClass.InvokeMember // (name, // BindingFlags.InvokeMethod | // BindingFlags.Instance | // BindingFlags.Public, // null, manager, args, null, null, null); // } // catch (MissingMethodException) // { // return null; // } // catch (SecurityException) // { // return null; // } // } // } // // Get an encoder for a specific code page. //#if ECMA_COMPAT // private //#else // public //#endif // static Encoding GetEncoding(int codepage) // { // if (codepage < 0 || codepage > 0xffff) // throw new ArgumentOutOfRangeException("codepage", // "Valid values are between 0 and 65535, inclusive."); // // Check for the builtin code pages first. // switch (codepage) // { // case 0: return Default; // case ASCIIEncoding.ASCII_CODE_PAGE: // return ASCII; // case UTF7Encoding.UTF7_CODE_PAGE: // return UTF7; // case UTF8Encoding.UTF8_CODE_PAGE: // return UTF8; // case UTF32Encoding.UTF32_CODE_PAGE: // return UTF32; // case UTF32Encoding.BIG_UTF32_CODE_PAGE: // return BigEndianUTF32; // case UnicodeEncoding.UNICODE_CODE_PAGE: // return Unicode; // case UnicodeEncoding.BIG_UNICODE_CODE_PAGE: // return BigEndianUnicode; //#if !MOONLIGHT // case Latin1Encoding.ISOLATIN_CODE_PAGE: // return ISOLatin1; //#endif // default: break; // } //#if !MOONLIGHT // // Try to obtain a code page handler from the I18N handler. // Encoding enc = (Encoding)(InvokeI18N("GetEncoding", codepage)); // if (enc != null) // { // enc.is_readonly = true; // return enc; // } // // Build a code page class name. // String cpName = "System.Text.CP" + codepage.ToString(); // // Look for a code page converter in this assembly. // Assembly assembly = Assembly.GetExecutingAssembly(); // Type type = assembly.GetType(cpName); // if (type != null) // { // enc = (Encoding)(Activator.CreateInstance(type)); // enc.is_readonly = true; // return enc; // } // // Look in any assembly, in case the application // // has provided its own code page handler. // type = Type.GetType(cpName); // if (type != null) // { // enc = (Encoding)(Activator.CreateInstance(type)); // enc.is_readonly = true; // return enc; // } //#endif // !NET_2_1 // // We have no idea how to handle this code page. // throw new NotSupportedException // (String.Format("CodePage {0} not supported", codepage.ToString())); // } //#if !ECMA_COMPAT // [ComVisible(false)] // public virtual object Clone() // { // Encoding e = (Encoding)MemberwiseClone(); // e.is_readonly = false; // return e; // } //#if !MOONLIGHT // public static Encoding GetEncoding(int codepage, // EncoderFallback encoderFallback, DecoderFallback decoderFallback) // { // if (encoderFallback == null) // throw new ArgumentNullException("encoderFallback"); // if (decoderFallback == null) // throw new ArgumentNullException("decoderFallback"); // Encoding e = GetEncoding(codepage).Clone() as Encoding; // e.is_readonly = false; // e.encoder_fallback = encoderFallback; // e.decoder_fallback = decoderFallback; // return e; // } // public static Encoding GetEncoding(string name, // EncoderFallback encoderFallback, DecoderFallback decoderFallback) // { // if (encoderFallback == null) // throw new ArgumentNullException("encoderFallback"); // if (decoderFallback == null) // throw new ArgumentNullException("decoderFallback"); // Encoding e = GetEncoding(name).Clone() as Encoding; // e.is_readonly = false; // e.encoder_fallback = encoderFallback; // e.decoder_fallback = decoderFallback; // return e; // } //#endif // !NET_2_1 // static EncodingInfo[] encoding_infos; // // FIXME: As everyone would agree, this implementation is so *hacky* // // and could be very easily broken. But since there is a test for // // this method to make sure that this method always returns // // the same number and content of encoding infos, this won't // // matter practically. // public static EncodingInfo[] GetEncodings() // { // if (encoding_infos == null) // { // int[] codepages = new int[] { // 37, 437, 500, 708, // 850, 852, 855, 857, 858, 860, 861, 862, 863, // 864, 865, 866, 869, 870, 874, 875, // 932, 936, 949, 950, // 1026, 1047, 1140, 1141, 1142, 1143, 1144, // 1145, 1146, 1147, 1148, 1149, // 1200, 1201, 1250, 1251, 1252, 1253, 1254, // 1255, 1256, 1257, 1258, // 10000, 10079, 12000, 12001, // 20127, 20273, 20277, 20278, 20280, 20284, // 20285, 20290, 20297, 20420, 20424, 20866, // 20871, 21025, 21866, 28591, 28592, 28593, // 28594, 28595, 28596, 28597, 28598, 28599, // 28605, 38598, // 50220, 50221, 50222, 51932, 51949, 54936, // 57002, 57003, 57004, 57005, 57006, 57007, // 57008, 57009, 57010, 57011, // 65000, 65001}; // encoding_infos = new EncodingInfo[codepages.Length]; // for (int i = 0; i < codepages.Length; i++) // encoding_infos[i] = new EncodingInfo(codepages[i]); // } // return encoding_infos; // } //#if !MOONLIGHT // [ComVisible(false)] // public bool IsAlwaysNormalized() // { // return IsAlwaysNormalized(NormalizationForm.FormC); // } // [ComVisible(false)] // public virtual bool IsAlwaysNormalized(NormalizationForm form) // { // // umm, ASCIIEncoding should have overriden this method, no? // return form == NormalizationForm.FormC && this is ASCIIEncoding; // } //#endif // NET_2_1 // // Get an encoding object for a specific web encoding name. // public static Encoding GetEncoding(string name) // { // // Validate the parameters. // if (name == null) // { // throw new ArgumentNullException("name"); // } // string converted = name.ToLowerInvariant().Replace('-', '_'); // // Builtin web encoding names and the corresponding code pages. // switch (converted) // { // case "ascii": // case "us_ascii": // case "us": // case "ansi_x3.4_1968": // case "ansi_x3.4_1986": // case "cp367": // case "csascii": // case "ibm367": // case "iso_ir_6": // case "iso646_us": // case "iso_646.irv:1991": // return GetEncoding(ASCIIEncoding.ASCII_CODE_PAGE); // case "utf_7": // case "csunicode11utf7": // case "unicode_1_1_utf_7": // case "unicode_2_0_utf_7": // case "x_unicode_1_1_utf_7": // case "x_unicode_2_0_utf_7": // return GetEncoding(UTF7Encoding.UTF7_CODE_PAGE); // case "utf_8": // case "unicode_1_1_utf_8": // case "unicode_2_0_utf_8": // case "x_unicode_1_1_utf_8": // case "x_unicode_2_0_utf_8": // return GetEncoding(UTF8Encoding.UTF8_CODE_PAGE); // case "utf_16": // case "utf_16le": // case "ucs_2": // case "unicode": // case "iso_10646_ucs2": // return GetEncoding(UnicodeEncoding.UNICODE_CODE_PAGE); // case "unicodefffe": // case "utf_16be": // return GetEncoding(UnicodeEncoding.BIG_UNICODE_CODE_PAGE); // case "utf_32": // case "utf_32le": // case "ucs_4": // return GetEncoding(UTF32Encoding.UTF32_CODE_PAGE); // case "utf_32be": // return GetEncoding(UTF32Encoding.BIG_UTF32_CODE_PAGE); //#if !MOONLIGHT // case "iso_8859_1": // case "latin1": // return GetEncoding(Latin1Encoding.ISOLATIN_CODE_PAGE); //#endif // } //#if !MOONLIGHT // // Try to obtain a web encoding handler from the I18N handler. // Encoding enc = (Encoding)(InvokeI18N("GetEncoding", name)); // if (enc != null) // { // return enc; // } // // Build a web encoding class name. // String encName = "System.Text.ENC" + converted; // // Look for a code page converter in this assembly. // Assembly assembly = Assembly.GetExecutingAssembly(); // Type type = assembly.GetType(encName); // if (type != null) // { // return (Encoding)(Activator.CreateInstance(type)); // } // // Look in any assembly, in case the application // // has provided its own code page handler. // type = Type.GetType(encName); // if (type != null) // { // return (Encoding)(Activator.CreateInstance(type)); // } //#endif // // We have no idea how to handle this encoding name. // throw new ArgumentException(String.Format("Encoding name '{0}' not " // + "supported", name), "name"); // } //#endif // !ECMA_COMPAT // // Get a hash code for this instance. // public override int GetHashCode() // { // return DecoderFallback.GetHashCode() << 24 + EncoderFallback.GetHashCode() << 16 + codePage; // } // // Get the maximum number of bytes needed to encode a // // specified number of characters. // public abstract int GetMaxByteCount(int charCount); // // Get the maximum number of characters needed to decode a // // specified number of bytes. // public abstract int GetMaxCharCount(int byteCount); // // Get the identifying preamble for this encoding. // public virtual byte[] GetPreamble() // { // return new byte[0]; // } // // Decode a buffer of bytes into a string. // public virtual String GetString(byte[] bytes, int index, int count) // { // return new String(GetChars(bytes, index, count)); // } // public virtual String GetString(byte[] bytes) // { // if (bytes == null) // throw new ArgumentNullException("bytes"); // return GetString(bytes, 0, bytes.Length); // } //#if !ECMA_COMPAT // internal bool is_mail_news_display; // internal bool is_mail_news_save; // internal bool is_browser_save = false; // internal bool is_browser_display = false; // internal string body_name; // internal string encoding_name; // internal string header_name; // internal string web_name; // // Get the mail body name for this encoding. // public virtual String BodyName // { // get // { // return body_name; // } // } // // Get the code page represented by this object. // public virtual int CodePage // { // get // { // return codePage; // } // } // // Get the human-readable name for this encoding. // public virtual String EncodingName // { // get // { // return encoding_name; // } // } // // Get the mail agent header name for this encoding. // public virtual String HeaderName // { // get // { // return header_name; // } // } // // Determine if this encoding can be displayed in a Web browser. // public virtual bool IsBrowserDisplay // { // get // { // return is_browser_display; // } // } // // Determine if this encoding can be saved from a Web browser. // public virtual bool IsBrowserSave // { // get // { // return is_browser_save; // } // } // // Determine if this encoding can be displayed in a mail/news agent. // public virtual bool IsMailNewsDisplay // { // get // { // return is_mail_news_display; // } // } // // Determine if this encoding can be saved from a mail/news agent. // public virtual bool IsMailNewsSave // { // get // { // return is_mail_news_save; // } // } // // Get the IANA-preferred Web name for this encoding. // public virtual String WebName // { // get // { // return web_name; // } // } // // Get the Windows code page represented by this object. // public virtual int WindowsCodePage // { // get // { // // We make no distinction between normal and // // Windows code pages in this implementation. // return windows_code_page; // } // } //#endif // !ECMA_COMPAT // // Storage for standard encoding objects. // static volatile Encoding asciiEncoding; // static volatile Encoding bigEndianEncoding; // static volatile Encoding defaultEncoding; // static volatile Encoding utf7Encoding; // static volatile Encoding utf8EncodingWithMarkers; // static volatile Encoding utf8EncodingWithoutMarkers; // static volatile Encoding unicodeEncoding; // static volatile Encoding isoLatin1Encoding; // static volatile Encoding utf8EncodingUnsafe; // static volatile Encoding utf32Encoding; // static volatile Encoding bigEndianUTF32Encoding; // static readonly object lockobj = new object(); // // Get the standard ASCII encoding object. // public static Encoding ASCII // { // get // { // if (asciiEncoding == null) // { // lock (lockobj) // { // if (asciiEncoding == null) // { // asciiEncoding = new ASCIIEncoding(); // // asciiEncoding.is_readonly = true; // } // } // } // return asciiEncoding; // } // } // // Get the standard big-endian Unicode encoding object. // public static Encoding BigEndianUnicode // { // get // { // if (bigEndianEncoding == null) // { // lock (lockobj) // { // if (bigEndianEncoding == null) // { // bigEndianEncoding = new UnicodeEncoding(true, true); // // bigEndianEncoding.is_readonly = true; // } // } // } // return bigEndianEncoding; // } // } // [MethodImpl(MethodImplOptions.InternalCall)] // extern internal static string InternalCodePage(ref int code_page); // // Get the default encoding object. // public static Encoding Default // { // get // { // if (defaultEncoding == null) // { // lock (lockobj) // { // if (defaultEncoding == null) // { // // See if the underlying system knows what // // code page handler we should be using. // int code_page = 1; // string code_page_name = InternalCodePage(ref code_page); // try // { // if (code_page == -1) // defaultEncoding = GetEncoding(code_page_name); // else // { // // map the codepage from internal to our numbers // code_page = code_page & 0x0fffffff; // switch (code_page) // { // case 1: code_page = ASCIIEncoding.ASCII_CODE_PAGE; break; // case 2: code_page = UTF7Encoding.UTF7_CODE_PAGE; break; // case 3: code_page = UTF8Encoding.UTF8_CODE_PAGE; break; // case 4: code_page = UnicodeEncoding.UNICODE_CODE_PAGE; break; // case 5: code_page = UnicodeEncoding.BIG_UNICODE_CODE_PAGE; break; //#if !MOONLIGHT // case 6: code_page = Latin1Encoding.ISOLATIN_CODE_PAGE; break; //#endif // } // defaultEncoding = GetEncoding(code_page); // } // } // catch (NotSupportedException) // { //#if MOONLIGHT // defaultEncoding = UTF8; //#else // // code_page is not supported on underlying platform // defaultEncoding = UTF8Unmarked; //#endif // } // catch (ArgumentException) // { // // code_page_name is not a valid code page, or is // // not supported by underlying OS //#if MOONLIGHT // defaultEncoding = UTF8; //#else // defaultEncoding = UTF8Unmarked; //#endif // } // defaultEncoding.is_readonly = true; // } // } // } // return defaultEncoding; // } // } //#if !MOONLIGHT // // Get the ISO Latin1 encoding object. // private static Encoding ISOLatin1 // { // get // { // if (isoLatin1Encoding == null) // { // lock (lockobj) // { // if (isoLatin1Encoding == null) // { // isoLatin1Encoding = new Latin1Encoding(); // // isoLatin1Encoding.is_readonly = true; // } // } // } // return isoLatin1Encoding; // } // } //#endif // // Get the standard UTF-7 encoding object. //#if ECMA_COMPAT // private //#else // public //#endif // static Encoding UTF7 // { // get // { // if (utf7Encoding == null) // { // lock (lockobj) // { // if (utf7Encoding == null) // { // utf7Encoding = new UTF7Encoding(); // // utf7Encoding.is_readonly = true; // } // } // } // return utf7Encoding; // } // } // // Get the standard UTF-8 encoding object. // public static Encoding UTF8 // { // get // { // if (utf8EncodingWithMarkers == null) // { // lock (lockobj) // { // if (utf8EncodingWithMarkers == null) // { // utf8EncodingWithMarkers = new UTF8Encoding(true); // // utf8EncodingWithMarkers.is_readonly = true; // } // } // } // return utf8EncodingWithMarkers; // } // } // // // // Only internal, to be used by the class libraries: Unmarked and non-input-validating // // // internal static Encoding UTF8Unmarked // { // get // { // if (utf8EncodingWithoutMarkers == null) // { // lock (lockobj) // { // if (utf8EncodingWithoutMarkers == null) // { // utf8EncodingWithoutMarkers = new UTF8Encoding(false, false); // // utf8EncodingWithoutMarkers.is_readonly = true; // } // } // } // return utf8EncodingWithoutMarkers; // } // } // // // // Only internal, to be used by the class libraries: Unmarked and non-input-validating // // // internal static Encoding UTF8UnmarkedUnsafe // { // get // { // if (utf8EncodingUnsafe == null) // { // lock (lockobj) // { // if (utf8EncodingUnsafe == null) // { // utf8EncodingUnsafe = new UTF8Encoding(false, false); // utf8EncodingUnsafe.is_readonly = false; // utf8EncodingUnsafe.DecoderFallback = new DecoderReplacementFallback(String.Empty); // utf8EncodingUnsafe.is_readonly = true; // } // } // } // return utf8EncodingUnsafe; // } // } // // Get the standard little-endian Unicode encoding object. // public static Encoding Unicode // { // get // { // if (unicodeEncoding == null) // { // lock (lockobj) // { // if (unicodeEncoding == null) // { // unicodeEncoding = new UnicodeEncoding(false, true); // // unicodeEncoding.is_readonly = true; // } // } // } // return unicodeEncoding; // } // } // // Get the standard little-endian UTF-32 encoding object. // public static Encoding UTF32 // { // get // { // if (utf32Encoding == null) // { // lock (lockobj) // { // if (utf32Encoding == null) // { // utf32Encoding = new UTF32Encoding(false, true); // // utf32Encoding.is_readonly = true; // } // } // } // return utf32Encoding; // } // } // // Get the standard big-endian UTF-32 encoding object. // internal static Encoding BigEndianUTF32 // { // get // { // if (bigEndianUTF32Encoding == null) // { // lock (lockobj) // { // if (bigEndianUTF32Encoding == null) // { // bigEndianUTF32Encoding = new UTF32Encoding(true, true); // // bigEndianUTF32Encoding.is_readonly = true; // } // } // } // return bigEndianUTF32Encoding; // } // } // // Forwarding decoder implementation. // private sealed class ForwardingDecoder : Decoder // { // private Encoding encoding; // // Constructor. // public ForwardingDecoder(Encoding enc) // { // encoding = enc; // DecoderFallback fallback = encoding.DecoderFallback; // if (fallback != null) // Fallback = fallback; // } // // Override inherited methods. // public override int GetCharCount(byte[] bytes, int index, int count) // { // return encoding.GetCharCount(bytes, index, count); // } // public override int GetChars(byte[] bytes, int byteIndex, // int byteCount, char[] chars, // int charIndex) // { // return encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); // } // } // class ForwardingDecoder // // Forwarding encoder implementation. // private sealed class ForwardingEncoder : Encoder // { // private Encoding encoding; // // Constructor. // public ForwardingEncoder(Encoding enc) // { // encoding = enc; // EncoderFallback fallback = encoding.EncoderFallback; // if (fallback != null) // Fallback = fallback; // } // // Override inherited methods. // public override int GetByteCount(char[] chars, int index, int count, bool flush) // { // return encoding.GetByteCount(chars, index, count); // } // public override int GetBytes(char[] chars, int charIndex, // int charCount, byte[] bytes, // int byteCount, bool flush) // { // return encoding.GetBytes(chars, charIndex, charCount, bytes, byteCount); // } // } // class ForwardingEncoder // [CLSCompliantAttribute(false)] // [ComVisible(false)] // public unsafe virtual int GetByteCount(char* chars, int count) // { // if (chars == null) // throw new ArgumentNullException("chars"); // if (count < 0) // throw new ArgumentOutOfRangeException("count"); // char[] c = new char[count]; // for (int p = 0; p < count; p++) // c[p] = chars[p]; // return GetByteCount(c); // } // [CLSCompliantAttribute(false)] // [ComVisible(false)] // public unsafe virtual int GetCharCount(byte* bytes, int count) // { // if (bytes == null) // throw new ArgumentNullException("bytes"); // if (count < 0) // throw new ArgumentOutOfRangeException("count"); // byte[] ba = new byte[count]; // for (int i = 0; i < count; i++) // ba[i] = bytes[i]; // return GetCharCount(ba, 0, count); // } // [CLSCompliantAttribute(false)] // [ComVisible(false)] // public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount) // { // if (bytes == null) // throw new ArgumentNullException("bytes"); // if (chars == null) // throw new ArgumentNullException("chars"); // if (charCount < 0) // throw new ArgumentOutOfRangeException("charCount"); // if (byteCount < 0) // throw new ArgumentOutOfRangeException("byteCount"); // byte[] ba = new byte[byteCount]; // for (int i = 0; i < byteCount; i++) // ba[i] = bytes[i]; // char[] ret = GetChars(ba, 0, byteCount); // int top = ret.Length; // if (top > charCount) // throw new ArgumentException("charCount is less than the number of characters produced", "charCount"); // for (int i = 0; i < top; i++) // chars[i] = ret[i]; // return top; // } // [CLSCompliantAttribute(false)] // [ComVisible(false)] // public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) // { // if (bytes == null) // throw new ArgumentNullException("bytes"); // if (chars == null) // throw new ArgumentNullException("chars"); // if (charCount < 0) // throw new ArgumentOutOfRangeException("charCount"); // if (byteCount < 0) // throw new ArgumentOutOfRangeException("byteCount"); // char[] c = new char[charCount]; // for (int i = 0; i < charCount; i++) // c[i] = chars[i]; // byte[] b = GetBytes(c, 0, charCount); // int top = b.Length; // if (top > byteCount) // throw new ArgumentException("byteCount is less that the number of bytes produced", "byteCount"); // for (int i = 0; i < top; i++) // bytes[i] = b[i]; // return b.Length; // } // }; // class Encoding //}; // namespace System.Text
// 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 Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Internal.Cryptography.Pal.Native { /// <summary> /// Base class for safe handles representing NULL-based pointers. /// </summary> internal abstract class SafePointerHandle<T> : SafeHandle where T : SafeHandle, new() { protected SafePointerHandle() : base(IntPtr.Zero, true) { } public sealed override bool IsInvalid { get { return handle == IntPtr.Zero; } } public static T InvalidHandle { get { return SafeHandleCache<T>.GetInvalidHandle(() => new T()); } } protected override void Dispose(bool disposing) { if (!SafeHandleCache<T>.IsCachedInvalidHandle(this)) { base.Dispose(disposing); } } } /// <summary> /// SafeHandle for the CERT_CONTEXT structure defined by crypt32. /// </summary> internal class SafeCertContextHandle : SafePointerHandle<SafeCertContextHandle> { private SafeCertContextHandle _parent; public SafeCertContextHandle() { } public SafeCertContextHandle(SafeCertContextHandle parent) { if (parent == null) throw new ArgumentNullException(nameof(parent)); Debug.Assert(!parent.IsInvalid); Debug.Assert(!parent.IsClosed); bool ignored = false; parent.DangerousAddRef(ref ignored); _parent = parent; SetHandle(_parent.handle); } protected override bool ReleaseHandle() { if (_parent != null) { _parent.DangerousRelease(); _parent = null; } else { Interop.Crypt32.CertFreeCertificateContext(handle); } SetHandle(IntPtr.Zero); return true; } public unsafe CERT_CONTEXT* CertContext { get { return (CERT_CONTEXT*)handle; } } // Extract the raw CERT_CONTEXT* pointer and reset the SafeHandle to the invalid state so it no longer auto-destroys the CERT_CONTEXT. public unsafe CERT_CONTEXT* Disconnect() { CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)handle; SetHandle(IntPtr.Zero); return pCertContext; } public bool HasPersistedPrivateKey { get { return CertHasProperty(CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID); } } public bool HasEphemeralPrivateKey { get { return CertHasProperty(CertContextPropId.CERT_KEY_CONTEXT_PROP_ID); } } public bool ContainsPrivateKey { get { return HasPersistedPrivateKey || HasEphemeralPrivateKey; } } public SafeCertContextHandle Duplicate() { return Interop.crypt32.CertDuplicateCertificateContext(handle); } private bool CertHasProperty(CertContextPropId propertyId) { int cb = 0; bool hasProperty = Interop.crypt32.CertGetCertificateContextProperty( this, propertyId, null, ref cb); return hasProperty; } } /// <summary> /// SafeHandle for the CERT_CONTEXT structure defined by crypt32. Unlike SafeCertContextHandle, disposition already deletes any associated key containers. /// </summary> internal sealed class SafeCertContextHandleWithKeyContainerDeletion : SafeCertContextHandle { protected sealed override bool ReleaseHandle() { using (SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(handle)) { DeleteKeyContainer(certContext); } base.ReleaseHandle(); return true; } public static void DeleteKeyContainer(SafeCertContextHandle pCertContext) { if (pCertContext.IsInvalid) return; int cb = 0; bool containsPrivateKey = Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cb); if (!containsPrivateKey) return; byte[] provInfoAsBytes = new byte[cb]; if (!Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, provInfoAsBytes, ref cb)) return; unsafe { fixed (byte* pProvInfoAsBytes = provInfoAsBytes) { CRYPT_KEY_PROV_INFO* pProvInfo = (CRYPT_KEY_PROV_INFO*)pProvInfoAsBytes; if (pProvInfo->dwProvType == 0) { // dwProvType being 0 indicates that the key is stored in CNG. // dwProvType being non-zero indicates that the key is stored in CAPI. string providerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszProvName)); string keyContainerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszContainerName)); try { using (CngKey cngKey = CngKey.Open(keyContainerName, new CngProvider(providerName))) { cngKey.Delete(); } } catch (CryptographicException) { // While leaving the file on disk is undesirable, an inability to perform this cleanup // should not manifest itself to a user. } } else { CryptAcquireContextFlags flags = (pProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) | CryptAcquireContextFlags.CRYPT_DELETEKEYSET; IntPtr hProv; bool success = Interop.cryptoapi.CryptAcquireContext(out hProv, pProvInfo->pwszContainerName, pProvInfo->pwszProvName, pProvInfo->dwProvType, flags); // Called CryptAcquireContext solely for the side effect of deleting the key containers. When called with these flags, no actual // hProv is returned (so there's nothing to clean up.) Debug.Assert(hProv == IntPtr.Zero); } } } } } /// <summary> /// SafeHandle for the HCERTSTORE handle defined by crypt32. /// </summary> internal sealed class SafeCertStoreHandle : SafePointerHandle<SafeCertStoreHandle> { protected sealed override bool ReleaseHandle() { bool success = Interop.Crypt32.CertCloseStore(handle, 0); return success; } } /// <summary> /// SafeHandle for the HCRYPTMSG handle defined by crypt32. /// </summary> internal sealed class SafeCryptMsgHandle : SafePointerHandle<SafeCryptMsgHandle> { protected sealed override bool ReleaseHandle() { bool success = Interop.Crypt32.CryptMsgClose(handle); return success; } } /// <summary> /// SafeHandle for LocalAlloc'd memory. /// </summary> internal sealed class SafeLocalAllocHandle : SafePointerHandle<SafeLocalAllocHandle> { public static SafeLocalAllocHandle Create(int cb) { var h = new SafeLocalAllocHandle(); h.SetHandle(Marshal.AllocHGlobal(cb)); return h; } protected sealed override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } internal sealed class SafeChainEngineHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeChainEngineHandle() : base(true) { } private SafeChainEngineHandle(IntPtr handle) : base(true) { SetHandle(handle); } public static readonly SafeChainEngineHandle MachineChainEngine = new SafeChainEngineHandle((IntPtr)ChainEngine.HCCE_LOCAL_MACHINE); public static readonly SafeChainEngineHandle UserChainEngine = new SafeChainEngineHandle((IntPtr)ChainEngine.HCCE_CURRENT_USER); protected sealed override bool ReleaseHandle() { Interop.crypt32.CertFreeCertificateChainEngine(handle); SetHandle(IntPtr.Zero); return true; } protected override void Dispose(bool disposing) { if (this != UserChainEngine && this != MachineChainEngine) { base.Dispose(disposing); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace SightByte { partial class Hotkey_Configuration : Form { Form1 baseForm; [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); public Hotkey_Configuration(Form1 baseForm) { this.baseForm = baseForm; InitializeComponent(); if(baseForm.preset1Mod != Form1.KeyModifier.None) textBox1.Text = baseForm.preset1Mod.ToString() + " " + baseForm.keyPreset1.ToString(); else textBox1.Text = baseForm.keyPreset1.ToString(); if (baseForm.preset2Mod != Form1.KeyModifier.None) textBox2.Text = baseForm.preset2Mod.ToString() + " " + baseForm.keyPreset2.ToString(); else textBox2.Text = baseForm.keyPreset2.ToString(); if (baseForm.preset3Mod != Form1.KeyModifier.None) textBox3.Text = baseForm.preset3Mod.ToString() + " " + baseForm.keyPreset3.ToString(); else textBox3.Text = baseForm.keyPreset3.ToString(); if (baseForm.preset0Mod != Form1.KeyModifier.None) textBox4.Text = baseForm.preset0Mod.ToString() + " " + baseForm.keyPreset0.ToString(); else textBox4.Text = baseForm.keyPreset0.ToString(); } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion Form1.KeyModifier modifierListener(object sender, KeyEventArgs e) { Form1.KeyModifier modifier; switch (Control.ModifierKeys) { case (Keys.Shift): { modifier = Form1.KeyModifier.Shift; break; } case (Keys.Alt): { modifier = Form1.KeyModifier.Alt; break; } case (Keys.Control): { modifier = Form1.KeyModifier.Control; break; } case (Keys.LWin): { modifier = Form1.KeyModifier.WinKey; break; } case (Keys.RWin): { modifier = Form1.KeyModifier.WinKey; break; } default: { modifier = Form1.KeyModifier.None; break; } } return modifier; } private void textBox1_Leave(object sender, EventArgs e) { baseForm.editing = false; } private void Hotkey_Configuration_Load(object sender, EventArgs e) { label1.Focus(); } private void textBox1_MouseUp(object sender, MouseEventArgs e) { baseForm.editing = true; textBox1.Text = ""; label1.Text = "Enter Hotkey"; } private void textBox2_MouseUp(object sender, MouseEventArgs e) { baseForm.editing = true; textBox2.Text = ""; label2.Text = "Enter Hotkey"; } private void textBox3_MouseUp(object sender, MouseEventArgs e) { baseForm.editing = true; textBox3.Text = ""; label3.Text = "Enter Hotkey"; } private void textBox4_MouseUp(object sender, MouseEventArgs e) { baseForm.editing = true; textBox4.Text = ""; label5.Text = "Enter Hotkey"; } private void textBox1_KeyUp(object sender, KeyEventArgs e) { Form1.KeyModifier modifier = modifierListener(sender, e); label1.Text = "Preset 1"; if ((int)modifier != 0) textBox1.Text = modifier.ToString() + " + " + e.KeyCode.ToString(); else textBox1.Text = e.KeyCode.ToString(); if (textBox1.Text.Count() == 0) textBox1.Text = "Invalid Key"; baseForm.changeHotKey(1, e, modifier); label1.Focus(); } private void textBox2_KeyUp(object sender, KeyEventArgs e) { Form1.KeyModifier modifier = modifierListener(sender, e); label2.Text = "Preset 2"; if ((int)modifier != 0) textBox2.Text = modifier.ToString() + " + " + e.KeyCode.ToString(); else textBox2.Text = e.KeyCode.ToString(); if (textBox2.Text.Count() == 0) textBox2.Text = "Invalid Key"; baseForm.changeHotKey(2, e, modifier); label2.Focus(); } private void textBox3_KeyUp(object sender, KeyEventArgs e) { Form1.KeyModifier modifier = modifierListener(sender, e); label3.Text = "Preset 3"; if ((int)modifier != 0) textBox3.Text = modifier.ToString() + " + " + e.KeyCode.ToString(); else textBox3.Text = e.KeyCode.ToString(); if (textBox3.Text.Count() == 0) textBox3.Text = "Invalid Key"; baseForm.changeHotKey(3, e, modifier); label3.Focus(); } private void textBox4_KeyUp(object sender, KeyEventArgs e) { Form1.KeyModifier modifier = modifierListener(sender, e); label5.Text = "Revert"; if ((int)modifier != 0) textBox4.Text = modifier.ToString() + " + " + e.KeyCode.ToString(); else textBox4.Text = e.KeyCode.ToString(); if (textBox4.Text.Count() == 0) textBox4.Text = "Invalid Key"; baseForm.changeHotKey(0, e, modifier); label5.Focus(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { e.SuppressKeyPress = true; } private void textBox2_KeyDown(object sender, KeyEventArgs e) { e.SuppressKeyPress = true; } private void textBox3_KeyDown(object sender, KeyEventArgs e) { e.SuppressKeyPress = true; } private void textBox4_KeyDown(object sender, KeyEventArgs e) { e.SuppressKeyPress = true; } private void Hotkey_Configuration_FormClosing(object sender, FormClosingEventArgs e) { baseForm.editing = false; } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace m { /// <summary> /// Summary description for TriggersForm. /// </summary> public class TriggersForm : System.Windows.Forms.Form { static Rectangle s_rcBounds = new Rectangle(); TriggerManager m_tgrm; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.Button buttonNewTrigger; private System.Windows.Forms.Button buttonModifyTrigger; private System.Windows.Forms.Button buttonLoadTriggers; private System.Windows.Forms.Button buttonSaveTriggers; private System.Windows.Forms.Button buttonCopyTrigger; private System.Windows.Forms.Button buttonDeleteTrigger; private System.Windows.Forms.Button buttonMoveUpTrigger; private System.Windows.Forms.Button buttonMoveDownTrigger; private System.Windows.Forms.ListBox listBoxSides; private System.Windows.Forms.ListBox listBoxTriggers; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public TriggersForm(TriggerManager tgrm) { // // Required for Windows Form Designer support // InitializeComponent(); if (!s_rcBounds.IsEmpty) SetBounds(s_rcBounds.Left, s_rcBounds.Top, s_rcBounds.Width, s_rcBounds.Height, BoundsSpecified.All); else { Rectangle rcScreen = Screen.GetWorkingArea(this); SetBounds((rcScreen.Width - Bounds.Width) / 2, (rcScreen.Height - Bounds.Height) / 2, 0, 0, BoundsSpecified.Location); } m_tgrm = tgrm; InitSidesListBox(null); InitTriggersListBox(null); EnableButtons(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.listBoxSides = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.buttonMoveUpTrigger = new System.Windows.Forms.Button(); this.buttonMoveDownTrigger = new System.Windows.Forms.Button(); this.buttonNewTrigger = new System.Windows.Forms.Button(); this.listBoxTriggers = new System.Windows.Forms.ListBox(); this.buttonModifyTrigger = new System.Windows.Forms.Button(); this.buttonCopyTrigger = new System.Windows.Forms.Button(); this.buttonDeleteTrigger = new System.Windows.Forms.Button(); this.buttonLoadTriggers = new System.Windows.Forms.Button(); this.buttonSaveTriggers = new System.Windows.Forms.Button(); this.buttonClose = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // listBoxSides // this.listBoxSides.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.listBoxSides.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.listBoxSides.ItemHeight = 16; this.listBoxSides.Location = new System.Drawing.Point(16, 24); this.listBoxSides.Name = "listBoxSides"; this.listBoxSides.Size = new System.Drawing.Size(528, 68); this.listBoxSides.TabIndex = 0; this.listBoxSides.SelectedIndexChanged += new System.EventHandler(this.listBoxSides_SelectedIndexChanged); // // label1 // this.label1.Location = new System.Drawing.Point(16, 7); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(336, 16); this.label1.TabIndex = 1; this.label1.Text = "Sides with triggers:"; // // groupBox1 // this.groupBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] { this.buttonMoveUpTrigger, this.buttonMoveDownTrigger, this.buttonNewTrigger, this.listBoxTriggers, this.buttonModifyTrigger, this.buttonCopyTrigger, this.buttonDeleteTrigger, this.buttonLoadTriggers, this.buttonSaveTriggers}); this.groupBox1.Location = new System.Drawing.Point(8, 104); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(672, 528); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Triggers"; // // buttonMoveUpTrigger // this.buttonMoveUpTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.buttonMoveUpTrigger.Location = new System.Drawing.Point(8, 494); this.buttonMoveUpTrigger.Name = "buttonMoveUpTrigger"; this.buttonMoveUpTrigger.Size = new System.Drawing.Size(184, 23); this.buttonMoveUpTrigger.TabIndex = 8; this.buttonMoveUpTrigger.Text = "Move &Up"; this.buttonMoveUpTrigger.Click += new System.EventHandler(this.buttonMoveUpTrigger_Click); // // buttonMoveDownTrigger // this.buttonMoveDownTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.buttonMoveDownTrigger.Location = new System.Drawing.Point(200, 494); this.buttonMoveDownTrigger.Name = "buttonMoveDownTrigger"; this.buttonMoveDownTrigger.Size = new System.Drawing.Size(184, 23); this.buttonMoveDownTrigger.TabIndex = 7; this.buttonMoveDownTrigger.Text = "Move D&own"; this.buttonMoveDownTrigger.Click += new System.EventHandler(this.buttonMoveDownTrigger_Click); // // buttonNewTrigger // this.buttonNewTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonNewTrigger.Location = new System.Drawing.Point(552, 16); this.buttonNewTrigger.Name = "buttonNewTrigger"; this.buttonNewTrigger.Size = new System.Drawing.Size(104, 23); this.buttonNewTrigger.TabIndex = 1; this.buttonNewTrigger.Text = "&New..."; this.buttonNewTrigger.Click += new System.EventHandler(this.buttonNewTrigger_Click); // // listBoxTriggers // this.listBoxTriggers.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.listBoxTriggers.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(113)), ((System.Byte)(111)), ((System.Byte)(100))); this.listBoxTriggers.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.listBoxTriggers.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.listBoxTriggers.IntegralHeight = false; this.listBoxTriggers.Location = new System.Drawing.Point(8, 16); this.listBoxTriggers.Name = "listBoxTriggers"; this.listBoxTriggers.Size = new System.Drawing.Size(528, 472); this.listBoxTriggers.TabIndex = 0; this.listBoxTriggers.DoubleClick += new System.EventHandler(this.listBoxTriggers_DoubleClick); this.listBoxTriggers.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.listBoxTriggers_MeasureItem); this.listBoxTriggers.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBoxTriggers_DrawItem); this.listBoxTriggers.SelectedIndexChanged += new System.EventHandler(this.listBoxTriggers_SelectedIndexChanged); // // buttonModifyTrigger // this.buttonModifyTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonModifyTrigger.Location = new System.Drawing.Point(552, 48); this.buttonModifyTrigger.Name = "buttonModifyTrigger"; this.buttonModifyTrigger.Size = new System.Drawing.Size(104, 23); this.buttonModifyTrigger.TabIndex = 1; this.buttonModifyTrigger.Text = "&Modify..."; this.buttonModifyTrigger.Click += new System.EventHandler(this.buttonModifyTrigger_Click); // // buttonCopyTrigger // this.buttonCopyTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonCopyTrigger.Location = new System.Drawing.Point(552, 80); this.buttonCopyTrigger.Name = "buttonCopyTrigger"; this.buttonCopyTrigger.Size = new System.Drawing.Size(104, 23); this.buttonCopyTrigger.TabIndex = 1; this.buttonCopyTrigger.Text = "&Copy"; this.buttonCopyTrigger.Click += new System.EventHandler(this.buttonCopyTrigger_Click); // // buttonDeleteTrigger // this.buttonDeleteTrigger.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonDeleteTrigger.Location = new System.Drawing.Point(552, 112); this.buttonDeleteTrigger.Name = "buttonDeleteTrigger"; this.buttonDeleteTrigger.Size = new System.Drawing.Size(104, 23); this.buttonDeleteTrigger.TabIndex = 1; this.buttonDeleteTrigger.Text = "&Delete"; this.buttonDeleteTrigger.Click += new System.EventHandler(this.buttonDeleteTrigger_Click); // // buttonLoadTriggers // this.buttonLoadTriggers.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonLoadTriggers.Location = new System.Drawing.Point(552, 160); this.buttonLoadTriggers.Name = "buttonLoadTriggers"; this.buttonLoadTriggers.Size = new System.Drawing.Size(104, 23); this.buttonLoadTriggers.TabIndex = 1; this.buttonLoadTriggers.Text = "&Load Triggers"; this.buttonLoadTriggers.Click += new System.EventHandler(this.buttonLoadTriggers_Click); // // buttonSaveTriggers // this.buttonSaveTriggers.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonSaveTriggers.Location = new System.Drawing.Point(552, 192); this.buttonSaveTriggers.Name = "buttonSaveTriggers"; this.buttonSaveTriggers.Size = new System.Drawing.Size(104, 23); this.buttonSaveTriggers.TabIndex = 1; this.buttonSaveTriggers.Text = "&Save Triggers"; this.buttonSaveTriggers.Click += new System.EventHandler(this.buttonSaveTriggers_Click); // // buttonClose // this.buttonClose.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonClose.Location = new System.Drawing.Point(560, 24); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(104, 23); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // TriggersForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.buttonClose; this.ClientSize = new System.Drawing.Size(688, 638); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.buttonClose, this.groupBox1, this.label1, this.listBoxSides}); this.Name = "TriggersForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Triggers"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private class NameSide { private string m_strName; public Side side; public NameSide(Side side) { this.side = side; m_strName = Helper.GetDisplayName(typeof(Side), side.ToString()); } override public string ToString() { return m_strName; } } void InitSidesListBox(Trigger tgr) { Side[] aside = m_tgrm.GetTriggerSides(); if (aside.Length == 0) { listBoxSides.Items.Clear(); return; } int n = listBoxSides.SelectedIndex; Side sideSelected; if (n >= 0) { sideSelected = ((NameSide)listBoxSides.Items[n]).side; // sideSelected = (Side)Enum.Parse(typeof(Side), (string)listBoxSides.Items[n]); } else { sideSelected = aside[0]; } listBoxSides.Items.Clear(); foreach (Side side in aside) listBoxSides.Items.Add(new NameSide(side)); // listBoxSides.Items.Add(side.ToString()); if (tgr != null) { if ((tgr.Sides & m_tgrm.SideToMask(sideSelected)) == 0) { foreach (Side side in aside) { if ((m_tgrm.SideToMask(side) & tgr.Sides) != 0) { sideSelected = side; break; } } } } listBoxSides.SelectedIndex = Array.IndexOf(aside, sideSelected); } int GetSideMaskSelected() { int nSide = listBoxSides.SelectedIndex; if (nSide < 0) return 0; return m_tgrm.SideToMask(GetSideSelected()); } Side GetSideSelected() { Side[] aside = m_tgrm.GetTriggerSides(); return aside[listBoxSides.SelectedIndex]; } void InitTriggersListBox(Trigger tgrSelect) { listBoxTriggers.Items.Clear(); int nSide = listBoxSides.SelectedIndex; if (nSide < 0) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); foreach (Trigger tgr in atgr) listBoxTriggers.Items.Add(tgr); if (tgrSelect == null) { if (listBoxTriggers.SelectedIndex == -1 && listBoxTriggers.Items.Count != 0) listBoxTriggers.SelectedIndex = 0; } else { listBoxTriggers.SelectedIndex = Array.IndexOf(atgr, tgrSelect); } } private void buttonClose_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; } private void buttonNewTrigger_Click(object sender, System.EventArgs e) { Trigger tgr = new Trigger(); TriggerPropForm frm = new TriggerPropForm(tgr); if (frm.ShowDialog() == DialogResult.OK) { m_tgrm.AddTrigger(tgr); InitSidesListBox(tgr); InitTriggersListBox(tgr); } } private void buttonModifyTrigger_Click(object sender, System.EventArgs e) { int n = listBoxTriggers.SelectedIndex; if (n < 0) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); Trigger tgr = atgr[n].Clone(); TriggerPropForm frm = new TriggerPropForm(tgr); if (frm.ShowDialog() == DialogResult.OK) { m_tgrm.ModifyTrigger(atgr[n], tgr); InitSidesListBox(tgr); InitTriggersListBox(tgr); } } private void listBoxTriggers_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e) { Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); int n = e.Index; Trigger tgr = atgr[n]; int cy = (tgr.Actions.Count + tgr.Conditions.Count + 2) * listBoxTriggers.Font.Height + 4; // BUGBUG: listbox seems to have a problem with item heights > 255 e.ItemHeight = Math.Min(cy, 255); } private void listBoxTriggers_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { int n = e.Index; if (n == -1) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); Trigger trg = atgr[n]; Color clr = (e.State & DrawItemState.Selected) != 0 ? Color.FromArgb(178, 180, 191) : Color.White; e.Graphics.FillRectangle(new SolidBrush(clr), e.Bounds.Left + 2, e.Bounds.Top + 2, e.Bounds.Width - 4, e.Bounds.Height - 4); int y = e.Bounds.Top + 2; int x = e.Bounds.Left + 2; int cyFont = e.Font.Height; Brush br = new SolidBrush(e.ForeColor); e.Graphics.DrawString("CONDITIONS:", e.Font, br, x, y); y += cyFont; foreach (CaBase cab in trg.Conditions) { e.Graphics.DrawString(" - " + cab.ToString(), e.Font, br, x, y); y += cyFont; } e.Graphics.DrawString("ACTIONS:", e.Font, br, x, y); y += cyFont; foreach (CaBase cab in trg.Actions) { e.Graphics.DrawString(" - " + cab.ToString(), e.Font, br, x, y); y += cyFont; } } private void buttonCopyTrigger_Click(object sender, System.EventArgs e) { int n = listBoxTriggers.SelectedIndex; if (n < 0) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); Trigger tgr = atgr[n].Clone(); m_tgrm.AddTrigger(tgr); InitTriggersListBox(tgr); } private void buttonDeleteTrigger_Click(object sender, System.EventArgs e) { int n = listBoxTriggers.SelectedIndex; if (n < 0) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); m_tgrm.RemoveTrigger(atgr[n]); InitSidesListBox(null); InitTriggersListBox(null); } private void buttonLoadTriggers_Click(object sender, System.EventArgs e) { } private void buttonSaveTriggers_Click(object sender, System.EventArgs e) { } private void buttonMoveUpTrigger_Click(object sender, System.EventArgs e) { int n = listBoxTriggers.SelectedIndex; if (n <= 0) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); m_tgrm.MoveUpTrigger(GetSideSelected(), atgr[n]); InitTriggersListBox(atgr[n]); } private void buttonMoveDownTrigger_Click(object sender, System.EventArgs e) { int n = listBoxTriggers.SelectedIndex; if (n < 0 || n >= listBoxTriggers.Items.Count - 1) return; Trigger[] atgr = m_tgrm.GetTriggerList(GetSideSelected()); m_tgrm.MoveDownTrigger(GetSideSelected(), atgr[n]); InitTriggersListBox(atgr[n]); } void EnableButtons() { int n = listBoxTriggers.SelectedIndex; bool fSelected = (n >= 0); buttonModifyTrigger.Enabled = fSelected; buttonCopyTrigger.Enabled = fSelected; buttonDeleteTrigger.Enabled = fSelected; buttonMoveUpTrigger.Enabled = (n > 0); buttonMoveDownTrigger.Enabled = (n < listBoxTriggers.Items.Count - 1); buttonLoadTriggers.Enabled = false; // (listBoxTriggers.Items.Count != 0); buttonSaveTriggers.Enabled = false; // (listBoxTriggers.Items.Count != 0); } private void listBoxTriggers_SelectedIndexChanged(object sender, System.EventArgs e) { EnableButtons(); } private void listBoxSides_SelectedIndexChanged(object sender, System.EventArgs e) { InitTriggersListBox(null); } private void listBoxTriggers_DoubleClick(object sender, System.EventArgs e) { buttonModifyTrigger_Click(sender, e); } protected override void OnClosed(System.EventArgs e) { s_rcBounds = Bounds; base.OnClosed(e); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApplicationsOperations operations. /// </summary> internal partial class ApplicationsOperations : IServiceOperations<GraphRbacManagementClient>, IApplicationsOperations { /// <summary> /// Initializes a new instance of the ApplicationsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApplicationsOperations(GraphRbacManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the GraphRbacManagementClient /// </summary> public GraphRbacManagementClient Client { get; private set; } /// <summary> /// Create a new application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='parameters'> /// Parameters to create an application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(ApplicationCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications").ToString(); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Application>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Application>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists applications by filter parameters. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Application>>> ListWithHttpMessagesAsync(ODataQuery<Application> odataQuery = default(ODataQuery<Application>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications").ToString(); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Application>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Application>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete an application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an application by object Id. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Application>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Application>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update existing application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PatchWithHttpMessagesAsync(string applicationObjectId, ApplicationUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Patch", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get keyCredentials associated with the application by object Id. /// Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListKeyCredentials", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}/keyCredentials").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<KeyCredential>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<KeyCredential>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update keyCredentials associated with an existing application. Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update keyCredentials of an existing application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateKeyCredentials", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}/keyCredentials").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets passwordCredentials associated with an existing application. /// Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListPasswordCredentials", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}/passwordCredentials").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<PasswordCredential>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PasswordCredential>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates passwordCredentials associated with an existing application. /// Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing application. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (applicationObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationObjectId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("applicationObjectId", applicationObjectId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdatePasswordCredentials", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/applications/{applicationObjectId}/passwordCredentials").ToString(); _url = _url.Replace("{applicationObjectId}", applicationObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using Tutor.ServerPage; using Tutor.SimpleParser; namespace Tutor.ServerPage.Elements { /// <summary> /// Summary description for ServerPageElements. /// </summary> public class Echo : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { foreach(SimpleParseTree T in Tree.children) { sp.Echo( sp.Exec(T) ); } return ""; } #endregion } public class RandomInteger : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "RandomInteger: Not Enough parameters"; } int Min = sp.ExecInt( (SimpleParseTree) Tree.children[0] ); int Max = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); return "" + sp.Rnd().Next(Min, Max); } #endregion } public class RandomVariable : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "RandomInteger: Not Enough parameters"; } int Min = sp.ExecInt( (SimpleParseTree) Tree.children[0] ); int Max = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); int Nxt = sp.Rnd().Next(Min, Max) % 26; char V = (char) ('a' + Nxt); return "" + V; } #endregion } public class Bind : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "Bind: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; string Val = sp.Exec( (SimpleParseTree) Tree.children[1] ); sp.BindVar(Var, Val); return ""; } #endregion } public class EBind : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "eBind: Not Enough parameters:" + Tree.str(); } string Var = sp.Exec( (SimpleParseTree) Tree.children[0] ); string Val = sp.Exec( (SimpleParseTree) Tree.children[1] ); sp.BindVar(Var, Val); return ""; } #endregion } public class Sequence : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { string Rez = ""; sp.PushFrame(); foreach(SimpleParseTree T in Tree.children) Rez += sp.Exec(T); sp.PopFrame(); return Rez; } #endregion } public class MinMaxLoop : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 4) { return "MinMaxLoop: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; int Min = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); int Max = sp.ExecInt( (SimpleParseTree) Tree.children[2] ); if(Max < Min) { int Temp = Min; Min = Max; Max = Temp; } string Rez = ""; for(int k = Min; k <= Max; k++) { sp.BindVar(Var, "" + k); string N = sp.Exec( (SimpleParseTree) Tree.children[3] ); Rez += N; } //sp.FreeVar(Var); return Rez; } #endregion } public class MaxMinLoop : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 4) { return "MaxMinLoop: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; int Min = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); int Max = sp.ExecInt( (SimpleParseTree) Tree.children[2] ); if(Max < Min) { int Temp = Min; Min = Max; Max = Temp; } string Rez = ""; for(int k = Max; k >= Min; k--) { sp.BindVar(Var, "" + (k)); string N = sp.Exec( (SimpleParseTree) Tree.children[3] ); Rez += N; } return Rez; } #endregion } public class Multiplication : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { int Product = 1; foreach(SimpleParseTree T in Tree.children) Product *= sp.ExecInt(T); return "" + Product; } #endregion } public class Addition : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { int Sum = 0; foreach(SimpleParseTree T in Tree.children) Sum += sp.ExecInt(T); return "" + Sum; } #endregion } public class GetDivisors : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "GetDivisors: Not Enough parameters:" + Tree.str(); } long Val = (long) Math.Abs(sp.ExecInt( (SimpleParseTree) Tree.children[0] )); long[] Divisors = Tutor.Theory.Factoring.FactorAgainstSmallTable.GetPositiveDivisors(Val); Array.Sort(Divisors); string Result = "" + Divisors[0]; for(int k = 1; k < Divisors.Length; k++) Result += ", " + Divisors[k]; return Result; } #endregion } public class GetDivisorsP : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "GetDivisors: Not Enough parameters:" + Tree.str(); } long Val = (long) Math.Abs(sp.ExecInt( (SimpleParseTree) Tree.children[0] )); long[] Divisors = Tutor.Theory.Factoring.FactorAgainstSmallTable.GetPositiveDivisors(Val); Array.Sort(Divisors); string Result = "(" + Divisors[0] + "," + (Val / Divisors[0]) + ")"; for(int k = 1; k < Divisors.Length; k++) Result += ", " + "(" + Divisors[k] + "," + (Val / Divisors[k]) + ")"; return Result; } #endregion } public class SetRedirect : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "SetRedirect: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; if(Var.ToUpper().Equals("STDOUT")) Var = ""; sp.SetRedirect(Var); return ""; } #endregion } public class UrlEncode : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "UrlEncode: Not Enough parameters:" + Tree.str(); } string Val = sp.Exec( (SimpleParseTree) Tree.children[0] ); Val = System.Web.HttpUtility.UrlEncode(Val); return Val; } #endregion } public class WndAspxUrl : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "WndAspx: Not Enough parameters:" + Tree.str(); } string Title = sp.Exec( (SimpleParseTree) Tree.children[0] ); string Val = sp.Exec( (SimpleParseTree) Tree.children[1] ); Val = System.Web.HttpUtility.UrlEncode(Val); return "wnd.aspx?t=" + System.Web.HttpUtility.UrlEncode(Title) + "&d=" + Val; } #endregion } public class CreateSubstEnv : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "CreateSubstEnv: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; sp.BindVar(Var, new Tutor.PatternMatching.MatchEnvironment()); return ""; } #endregion } public class RandomChild : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count == 0) { return "RandomChild: Not Enough parameters:" + Tree.str(); } return sp.Exec( (SimpleParseTree) Tree.children[ sp.Rnd().Next(Tree.children.Count) ] ); } #endregion } public class BindConstant : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "BindConstant: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; int Ident = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); long Value = sp.ExecLong( (SimpleParseTree) Tree.children[2] ); Tutor.PatternMatching.MatchEnvironment Gamma = (Tutor.PatternMatching.MatchEnvironment) sp.GetObject(Var); Gamma.BindConstant(new Tutor.Structure.EquConstant(Value), Ident); return ""; } #endregion } public class BindTree : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "BindTree: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; string Name = ((SimpleParseTree) Tree.children[1]).node; string Equation = sp.Exec((SimpleParseTree) Tree.children[2]); Tutor.PatternMatching.MatchEnvironment Gamma = (Tutor.PatternMatching.MatchEnvironment) sp.GetObject(Var); Gamma.BindTree( Tutor.Structure.EquationParser.Parse(Equation), Name); return ""; } #endregion } public class EvalProductionRule : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 2) { return "BindTree: Not Enough parameters:" + Tree.str(); } string Var = ((SimpleParseTree) Tree.children[0]).node; Tutor.PatternMatching.MatchEnvironment Gamma = (Tutor.PatternMatching.MatchEnvironment) sp.GetObject(Var); string EquationRule = sp.Exec((SimpleParseTree) Tree.children[1]); Tutor.Production.ProductionRule PR = Production.ProductionParser.Parse(EquationRule); Tutor.Structure.Equation E = RuleSystem.RuleWriter.WriteRule(Gamma, PR); return E.lisp(); } #endregion } public class Image : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "Image: Not Enough parameters:" + Tree.str(); } string Equation = sp.Exec((SimpleParseTree) Tree.children[0]); Equation = System.Web.HttpUtility.UrlEncode(Equation); return "<img src=\"equ.aspx?lisp=" + Equation + "\"/>"; } #endregion } public class Figure : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "Figure: Not Enough parameters:" + Tree.str(); } int Width = sp.ExecInt((SimpleParseTree) Tree.children[0]); int Height = sp.ExecInt((SimpleParseTree) Tree.children[1]); string Code = sp.Exec((SimpleParseTree) Tree.children[2]); Code = System.Web.HttpUtility.UrlEncode(Code); return "<img src=\"figure.aspx?w="+Width +"&h="+Height+"&c=" + Code + "\"/>"; } #endregion } public class ImageP : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "Image: Not Enough parameters:" + Tree.str(); } string Equation = sp.Exec((SimpleParseTree) Tree.children[0]); Equation = System.Web.HttpUtility.UrlEncode(Equation); return "<img src=\"equ.aspx?addparen=YES&lisp=" + Equation + "\"/>"; } #endregion } public class EquationToInfix : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "EquationToInfix: Not Enough parameters:" + Tree.str(); } string Equation = sp.Exec((SimpleParseTree) Tree.children[0]); return Structure.EquationParser.Parse(Equation).str(); } #endregion } public class EquationFromInfix : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 1) { return "EquationToInfix: Not Enough parameters:" + Tree.str(); } string Equation = sp.Exec((SimpleParseTree) Tree.children[0]); return TutorParser.Parse.GetAST(Equation); } #endregion } public class BlowUp : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "Image: Not Enough parameters:" + Tree.str(); } string Operator = ((SimpleParseTree) Tree.children[0]).node; int Count = sp.ExecInt( (SimpleParseTree) Tree.children[1] ); string Equation = sp.Exec((SimpleParseTree) Tree.children[2]); string Rez = "(" + Operator + " "; for(int k = 0 ; k < Count; k++) Rez += Equation + " "; return Rez + ")"; } #endregion } public class Eval : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "Eval: Not Enough parameters:" + Tree.str(); } string Code = sp.Exec((SimpleParseTree) Tree.children[0]); SimpleParseTree CodeTree = SimpleParseTree.Parse( new SimpleLexer(Code) ); string Result = sp.Exec(CodeTree); return Result; } #endregion } public class Replace : ElementHandler { #region ElementHandler Members public string Execute(ServerPage sp, SimpleParseTree Tree) { if(Tree.children.Count != 3) { return "Replace: Not Enough parameters:" + Tree.str(); } string Str = sp.Exec((SimpleParseTree) Tree.children[0]); string What = sp.Exec((SimpleParseTree) Tree.children[1]); string With = sp.Exec((SimpleParseTree) Tree.children[2]); return Str.Replace(What, With); } #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; namespace DalSic { /// <summary> /// Strongly-typed collection for the RemRelMedicamentoSeguimiento class. /// </summary> [Serializable] public partial class RemRelMedicamentoSeguimientoCollection : ActiveList<RemRelMedicamentoSeguimiento, RemRelMedicamentoSeguimientoCollection> { public RemRelMedicamentoSeguimientoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RemRelMedicamentoSeguimientoCollection</returns> public RemRelMedicamentoSeguimientoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RemRelMedicamentoSeguimiento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Rem_RelMedicamentoSeguimiento table. /// </summary> [Serializable] public partial class RemRelMedicamentoSeguimiento : ActiveRecord<RemRelMedicamentoSeguimiento>, IActiveRecord { #region .ctors and Default Settings public RemRelMedicamentoSeguimiento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RemRelMedicamentoSeguimiento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RemRelMedicamentoSeguimiento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RemRelMedicamentoSeguimiento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Rem_RelMedicamentoSeguimiento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRelMedicamentoSeguimiento = new TableSchema.TableColumn(schema); colvarIdRelMedicamentoSeguimiento.ColumnName = "idRelMedicamentoSeguimiento"; colvarIdRelMedicamentoSeguimiento.DataType = DbType.Int32; colvarIdRelMedicamentoSeguimiento.MaxLength = 0; colvarIdRelMedicamentoSeguimiento.AutoIncrement = true; colvarIdRelMedicamentoSeguimiento.IsNullable = false; colvarIdRelMedicamentoSeguimiento.IsPrimaryKey = true; colvarIdRelMedicamentoSeguimiento.IsForeignKey = false; colvarIdRelMedicamentoSeguimiento.IsReadOnly = false; colvarIdRelMedicamentoSeguimiento.DefaultSetting = @""; colvarIdRelMedicamentoSeguimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRelMedicamentoSeguimiento); TableSchema.TableColumn colvarIdMedicamento = new TableSchema.TableColumn(schema); colvarIdMedicamento.ColumnName = "idMedicamento"; colvarIdMedicamento.DataType = DbType.Int32; colvarIdMedicamento.MaxLength = 0; colvarIdMedicamento.AutoIncrement = false; colvarIdMedicamento.IsNullable = false; colvarIdMedicamento.IsPrimaryKey = false; colvarIdMedicamento.IsForeignKey = true; colvarIdMedicamento.IsReadOnly = false; colvarIdMedicamento.DefaultSetting = @"((0))"; colvarIdMedicamento.ForeignKeyTableName = "Sys_Medicamento"; schema.Columns.Add(colvarIdMedicamento); TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema); colvarIdClasificacion.ColumnName = "idClasificacion"; colvarIdClasificacion.DataType = DbType.Int32; colvarIdClasificacion.MaxLength = 0; colvarIdClasificacion.AutoIncrement = false; colvarIdClasificacion.IsNullable = false; colvarIdClasificacion.IsPrimaryKey = false; colvarIdClasificacion.IsForeignKey = true; colvarIdClasificacion.IsReadOnly = false; colvarIdClasificacion.DefaultSetting = @"((0))"; colvarIdClasificacion.ForeignKeyTableName = "Rem_Clasificacion"; schema.Columns.Add(colvarIdClasificacion); TableSchema.TableColumn colvarIdSeguimiento = new TableSchema.TableColumn(schema); colvarIdSeguimiento.ColumnName = "idSeguimiento"; colvarIdSeguimiento.DataType = DbType.Int32; colvarIdSeguimiento.MaxLength = 0; colvarIdSeguimiento.AutoIncrement = false; colvarIdSeguimiento.IsNullable = false; colvarIdSeguimiento.IsPrimaryKey = false; colvarIdSeguimiento.IsForeignKey = true; colvarIdSeguimiento.IsReadOnly = false; colvarIdSeguimiento.DefaultSetting = @"((0))"; colvarIdSeguimiento.ForeignKeyTableName = "Rem_Seguimiento"; schema.Columns.Add(colvarIdSeguimiento); TableSchema.TableColumn colvarDosis = new TableSchema.TableColumn(schema); colvarDosis.ColumnName = "dosis"; colvarDosis.DataType = DbType.Double; colvarDosis.MaxLength = 0; colvarDosis.AutoIncrement = false; colvarDosis.IsNullable = false; colvarDosis.IsPrimaryKey = false; colvarDosis.IsForeignKey = false; colvarDosis.IsReadOnly = false; colvarDosis.DefaultSetting = @"((0))"; colvarDosis.ForeignKeyTableName = ""; schema.Columns.Add(colvarDosis); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Rem_RelMedicamentoSeguimiento",schema); } } #endregion #region Props [XmlAttribute("IdRelMedicamentoSeguimiento")] [Bindable(true)] public int IdRelMedicamentoSeguimiento { get { return GetColumnValue<int>(Columns.IdRelMedicamentoSeguimiento); } set { SetColumnValue(Columns.IdRelMedicamentoSeguimiento, value); } } [XmlAttribute("IdMedicamento")] [Bindable(true)] public int IdMedicamento { get { return GetColumnValue<int>(Columns.IdMedicamento); } set { SetColumnValue(Columns.IdMedicamento, value); } } [XmlAttribute("IdClasificacion")] [Bindable(true)] public int IdClasificacion { get { return GetColumnValue<int>(Columns.IdClasificacion); } set { SetColumnValue(Columns.IdClasificacion, value); } } [XmlAttribute("IdSeguimiento")] [Bindable(true)] public int IdSeguimiento { get { return GetColumnValue<int>(Columns.IdSeguimiento); } set { SetColumnValue(Columns.IdSeguimiento, value); } } [XmlAttribute("Dosis")] [Bindable(true)] public double Dosis { get { return GetColumnValue<double>(Columns.Dosis); } set { SetColumnValue(Columns.Dosis, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysMedicamento ActiveRecord object related to this RemRelMedicamentoSeguimiento /// /// </summary> public DalSic.SysMedicamento SysMedicamento { get { return DalSic.SysMedicamento.FetchByID(this.IdMedicamento); } set { SetColumnValue("idMedicamento", value.IdMedicamento); } } /// <summary> /// Returns a RemClasificacion ActiveRecord object related to this RemRelMedicamentoSeguimiento /// /// </summary> public DalSic.RemClasificacion RemClasificacion { get { return DalSic.RemClasificacion.FetchByID(this.IdClasificacion); } set { SetColumnValue("idClasificacion", value.IdClasificacion); } } /// <summary> /// Returns a RemSeguimiento ActiveRecord object related to this RemRelMedicamentoSeguimiento /// /// </summary> public DalSic.RemSeguimiento RemSeguimiento { get { return DalSic.RemSeguimiento.FetchByID(this.IdSeguimiento); } set { SetColumnValue("idSeguimiento", value.IdSeguimiento); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdMedicamento,int varIdClasificacion,int varIdSeguimiento,double varDosis) { RemRelMedicamentoSeguimiento item = new RemRelMedicamentoSeguimiento(); item.IdMedicamento = varIdMedicamento; item.IdClasificacion = varIdClasificacion; item.IdSeguimiento = varIdSeguimiento; item.Dosis = varDosis; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRelMedicamentoSeguimiento,int varIdMedicamento,int varIdClasificacion,int varIdSeguimiento,double varDosis) { RemRelMedicamentoSeguimiento item = new RemRelMedicamentoSeguimiento(); item.IdRelMedicamentoSeguimiento = varIdRelMedicamentoSeguimiento; item.IdMedicamento = varIdMedicamento; item.IdClasificacion = varIdClasificacion; item.IdSeguimiento = varIdSeguimiento; item.Dosis = varDosis; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRelMedicamentoSeguimientoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdMedicamentoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdClasificacionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdSeguimientoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn DosisColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdRelMedicamentoSeguimiento = @"idRelMedicamentoSeguimiento"; public static string IdMedicamento = @"idMedicamento"; public static string IdClasificacion = @"idClasificacion"; public static string IdSeguimiento = @"idSeguimiento"; public static string Dosis = @"dosis"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Text; using System.Xml.Serialization; using GzsTool.Core.Common; using GzsTool.Core.Common.Interfaces; using GzsTool.Core.Crypto; using GzsTool.Core.Utility; namespace GzsTool.Core.Qar { [XmlType("Entry", Namespace = "Qar")] public class QarEntry { [XmlAttribute("Hash")] public ulong Hash { get; set; } [XmlAttribute("Key")] public uint Key { get; set; } [XmlAttribute("Encryption")] public uint Encryption { get; set; } [XmlAttribute("FilePath")] public string FilePath { get; set; } [XmlAttribute("Compressed")] public bool Compressed { get; set; } [XmlAttribute("MetaFlag")] public bool MetaFlag { get; set; } [XmlAttribute("Version")] public uint Version { get; set; } [XmlIgnore] public bool FileNameFound { get; set; } [XmlIgnore] public uint UncompressedSize { get; private set; } [XmlIgnore] public uint CompressedSize { get; private set; } [XmlIgnore] public long DataOffset { get; set; } [XmlAttribute("DataHash")] public byte[] DataHash { get; set; } public bool ShouldSerializeHash() { return FileNameFound == false; } public bool ShouldSerializeKey() { return Key != 0; } public bool ShouldSerializeEncryption() { return Encryption != 0; } public bool ShouldSerializeMetaFlag() { return MetaFlag; } public bool ShouldSerializeDataHash() { return DataHash != null; } public void CalculateHash() { if (Hash == 0) { Hash = Hashing.HashFileNameWithExtension(FilePath); } else { DebugAssertHashMatches(); } if (MetaFlag) { Hash = Hash | Hashing.MetaFlag; } } [Conditional("DEBUG")] private void DebugAssertHashMatches() { ulong newHash = Hashing.HashFileNameWithExtension(FilePath); if (Hash != newHash) { Debug.WriteLine("Hash mismatch '{0}' {1:x}!={2:x}", FilePath, newHash, Hash); } } public void Read(BinaryReader reader, uint version) { const uint xorMask1 = 0x41441043; const uint xorMask2 = 0x11C22050; const uint xorMask3 = 0xD05608C3; const uint xorMask4 = 0x532C7319; uint hashLow = reader.ReadUInt32() ^ xorMask1; uint hashHigh = reader.ReadUInt32() ^ xorMask1; Hash = (ulong) hashHigh << 32 | hashLow; MetaFlag = (Hash & Hashing.MetaFlag) > 0; uint size1 = reader.ReadUInt32() ^ xorMask2; uint size2 = reader.ReadUInt32() ^ xorMask3; Version = version; UncompressedSize = Version != 2 ? size1 : size2; CompressedSize = Version != 2 ? size2 : size1; Compressed = UncompressedSize != CompressedSize; uint md51 = reader.ReadUInt32() ^ xorMask4; uint md52 = reader.ReadUInt32() ^ xorMask1; uint md53 = reader.ReadUInt32() ^ xorMask1; uint md54 = reader.ReadUInt32() ^ xorMask2; byte[] md5Hash = new byte[16]; Buffer.BlockCopy(BitConverter.GetBytes(md51), 0, md5Hash, 0, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(md52), 0, md5Hash, 4, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(md53), 0, md5Hash, 8, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(md54), 0, md5Hash, 12, sizeof(uint)); DataHash = md5Hash; string filePath; FileNameFound = Hashing.TryGetFileNameFromHash(Hash, out filePath); FilePath = filePath; DataOffset = reader.BaseStream.Position; byte[] header = new byte[8]; using (Stream headerStream = new Decrypt1Stream(reader.BaseStream, (int)Version, header.Length, DataHash, hashLow: (uint)(Hash & 0xFFFFFFFF), streamMode: StreamMode.Read)) { headerStream.Read(header, 0, header.Length); Encryption = BitConverter.ToUInt32(header, 0); } if (Encryption == Cryptography.Magic1 || Encryption == Cryptography.Magic2) { Key = BitConverter.ToUInt32(header, 4); } else { Encryption = 0; } } public FileDataStreamContainer Export(Stream input) { FileDataStreamContainer fileDataStreamContainer = new FileDataStreamContainer { DataStream = ReadDataLazy(input), FileName = Hashing.NormalizeFilePath(FilePath) }; return fileDataStreamContainer; } private Func<Stream> ReadDataLazy(Stream input) { return () => { lock (input) { return ReadData(input); } }; } private Stream ReadData(Stream input) { input.Position = DataOffset; int dataSize = (int)CompressedSize; Stream stream = new Decrypt1Stream(input, (int)Version, dataSize, DataHash, hashLow: (uint)(Hash & 0xFFFFFFFF), streamMode: StreamMode.Read); if (Encryption == Cryptography.Magic1 || Encryption == Cryptography.Magic2) { int headerSize = Cryptography.GetHeaderSize(Encryption); stream.Read(new byte[headerSize], 0, headerSize); dataSize -= headerSize; stream = new Decrypt2Stream(stream, dataSize, Key, StreamMode.Read); } if (Compressed) { stream = Compression.UncompressStream(stream); } return stream; } public void Write(Stream output, IDirectory inputDirectory) { using (Stream inputStream = inputDirectory.ReadFileStream(Hashing.NormalizeFilePath(FilePath))) using (Md5Stream md5OutputStream = new Md5Stream(output)) { long headerPosition = output.Position; const int entryHeaderSize = 32; long dataStartPosition = headerPosition + entryHeaderSize; output.Position = dataStartPosition; uint uncompressedSize = (uint)inputStream.Length; Stream outputDataStream = md5OutputStream; Stream outputDataStreamCompressed = null; if (Compressed) { outputDataStreamCompressed = Compression.CompressStream(outputDataStream); outputDataStream = outputDataStreamCompressed; } if (Encryption != 0) { int encryptionHeaderSize = Cryptography.GetHeaderSize(Encryption); if (encryptionHeaderSize >= 8) { byte[] header = new byte[encryptionHeaderSize]; Buffer.BlockCopy(BitConverter.GetBytes(Encryption), 0, header, 0, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(Key), 0, header, 4, sizeof(uint)); if (encryptionHeaderSize == 16) { Buffer.BlockCopy(BitConverter.GetBytes(uncompressedSize), 0, header, 8, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(uncompressedSize), 0, header, 12, sizeof(uint)); } using (var headerStream = new MemoryStream(header)) { headerStream.CopyTo(outputDataStream); } } outputDataStream = new Decrypt2Stream(outputDataStream, (int)uncompressedSize, Key, StreamMode.Write); } inputStream.CopyTo(outputDataStream); outputDataStreamCompressed?.Close(); // TODO: HACK to support repacked files if (DataHash == null) { md5OutputStream.Flush(); DataHash = md5OutputStream.Hash; } long dataEndPosition = output.Position; uint compressedSize = (uint)(dataEndPosition - dataStartPosition); uncompressedSize = Compressed ? uncompressedSize : compressedSize; using (var decrypt1Stream = new Decrypt1Stream(output, (int)Version, (int)compressedSize, DataHash, hashLow: (uint)(Hash & 0xFFFFFFFF), streamMode: StreamMode.Write)) { CopyTo(output, decrypt1Stream, dataStartPosition, dataEndPosition); } output.Position = headerPosition; const ulong xorMask1Long = 0x4144104341441043; const uint xorMask1 = 0x41441043; const uint xorMask2 = 0x11C22050; const uint xorMask3 = 0xD05608C3; const uint xorMask4 = 0x532C7319; BinaryWriter writer = new BinaryWriter(output, Encoding.ASCII, true); writer.Write(Hash ^ xorMask1Long); writer.Write((Version != 2 ? uncompressedSize : compressedSize) ^ xorMask2); writer.Write((Version != 2 ? compressedSize : uncompressedSize) ^ xorMask3); writer.Write(BitConverter.ToUInt32(DataHash, 0) ^ xorMask4); writer.Write(BitConverter.ToUInt32(DataHash, 4) ^ xorMask1); writer.Write(BitConverter.ToUInt32(DataHash, 8) ^ xorMask1); writer.Write(BitConverter.ToUInt32(DataHash, 12) ^ xorMask2); output.Position = dataEndPosition; } } private void CopyTo( Stream input, Stream output, long dataStartPosition, long dataEndPosition) { long offset = dataStartPosition; byte[] buffer = new byte[4096]; while (offset < dataEndPosition) { int blockSize = 4096; int remainingSize = (int) (dataEndPosition - offset); if (remainingSize < blockSize) { blockSize = remainingSize; } input.Position = offset; input.Read(buffer, 0, blockSize); output.Position = offset; output.Write(buffer, 0, blockSize); offset += blockSize; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using AutoRest.Core.Validation; using AutoRest.Swagger.Validation; using System.Collections.Generic; using AutoRest.Core.Utilities; namespace AutoRest.Swagger.Model { /// <summary> /// Describes a single API operation on a path. /// </summary> [Rule(typeof(OperationDescriptionRequired))] public class Operation : SwaggerBase { private string _description; private string _summary; public Operation() { Consumes = new List<string>(); Produces = new List<string>(); } /// <summary> /// A list of tags for API documentation control. /// </summary> public IList<string> Tags { get; set; } /// <summary> /// A friendly serviceTypeName for the operation. The id MUST be unique among all /// operations described in the API. Tools and libraries MAY use the /// operation id to uniquely identify an operation. /// </summary> [Rule(typeof(OneUnderscoreInOperationId))] [Rule(typeof(OperationIdNounInVerb))] [Rule(typeof(GetOperationNameValidation))] [Rule(typeof(PutOperationNameValidation))] [Rule(typeof(PatchOperationNameValidation))] [Rule(typeof(DeleteOperationNameValidation))] public string OperationId { get; set; } public string Summary { get { return _summary; } set { _summary = value.StripControlCharacters(); } } [Rule(typeof(AvoidMsdnReferences))] public string Description { get { return _description; } set { _description = value.StripControlCharacters(); } } /// <summary> /// Additional external documentation for this operation. /// </summary> public ExternalDoc ExternalDocs { get; set; } /// <summary> /// A list of MIME types the operation can consume. /// </summary> [CollectionRule(typeof(NonAppJsonTypeWarning))] public IList<string> Consumes { get; set; } /// <summary> /// A list of MIME types the operation can produce. /// </summary> [CollectionRule(typeof(NonAppJsonTypeWarning))] public IList<string> Produces { get; set; } /// <summary> /// A list of parameters that are applicable for this operation. /// If a parameter is already defined at the Path Item, the /// new definition will override it, but can never remove it. /// </summary> [CollectionRule(typeof(OperationParametersValidation))] [CollectionRule(typeof(AnonymousParameterTypes))] public IList<SwaggerParameter> Parameters { get; set; } /// <summary> /// The list of possible responses as they are returned from executing this operation. /// </summary> [Rule(typeof(ResponseRequired))] public Dictionary<string, OperationResponse> Responses { get; set; } /// <summary> /// The transfer protocol for the operation. /// </summary> [CollectionRule(typeof(SupportedSchemesWarning))] public IList<TransferProtocolScheme> Schemes { get; set; } public bool Deprecated { get; set; } /// <summary> /// A declaration of which security schemes are applied for this operation. /// The list of values describes alternative security schemes that can be used /// (that is, there is a logical OR between the security requirements). /// This definition overrides any declared top-level security. To remove a /// top-level security declaration, an empty array can be used. /// </summary> public IList<Dictionary<string, List<string>>> Security { get; set; } /// <summary> /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes. /// </summary> /// <param name="context">The modified document context.</param> /// <param name="previous">The original document model.</param> /// <returns>A list of messages from the comparison.</returns> public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous) { var priorOperation = previous as Operation; var currentRoot = (context.CurrentRoot as ServiceDefinition); var previousRoot = (context.PreviousRoot as ServiceDefinition); if (priorOperation == null) { throw new ArgumentException("previous"); } base.Compare(context, previous); if (!OperationId.Equals(priorOperation.OperationId)) { context.LogBreakingChange(ComparisonMessages.ModifiedOperationId); } CheckParameters(context, priorOperation); if (Responses != null && priorOperation.Responses != null) { foreach (var response in Responses) { var oldResponse = priorOperation.FindResponse(response.Key, priorOperation.Responses); context.PushProperty(response.Key); if (oldResponse == null) { context.LogBreakingChange(ComparisonMessages.AddingResponseCode, response.Key); } else { response.Value.Compare(context, oldResponse); } context.Pop(); } foreach (var response in priorOperation.Responses) { var newResponse = this.FindResponse(response.Key, this.Responses); if (newResponse == null) { context.PushProperty(response.Key); context.LogBreakingChange(ComparisonMessages.RemovedResponseCode, response.Key); context.Pop(); } } } return context.Messages; } private void CheckParameters(ComparisonContext context, Operation priorOperation) { // Check that no parameters were removed or reordered, and compare them if it's not the case. var currentRoot = (context.CurrentRoot as ServiceDefinition); var previousRoot = (context.PreviousRoot as ServiceDefinition); foreach (var oldParam in priorOperation.Parameters .Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, previousRoot.Parameters))) { SwaggerParameter newParam = FindParameter(oldParam.Name, Parameters, currentRoot.Parameters); context.PushProperty(oldParam.Name); if (newParam != null) { newParam.Compare(context, oldParam); } else if (oldParam.IsRequired) { context.LogBreakingChange(ComparisonMessages.RemovedRequiredParameter, oldParam.Name); } context.Pop(); } // Check that no required parameters were added. foreach (var newParam in Parameters .Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, currentRoot.Parameters)) .Where(p => p != null && p.IsRequired)) { if (newParam == null) continue; SwaggerParameter oldParam = FindParameter(newParam.Name, priorOperation.Parameters, previousRoot.Parameters); if (oldParam == null) { context.PushProperty(newParam.Name); context.LogBreakingChange(ComparisonMessages.AddingRequiredParameter, newParam.Name); context.Pop(); } } } private SwaggerParameter FindParameter(string name, IEnumerable<SwaggerParameter> operationParameters, IDictionary<string, SwaggerParameter> clientParameters) { if (Parameters != null) { foreach (var param in operationParameters) { if (name.Equals(param.Name)) return param; var pRef = FindReferencedParameter(param.Reference, clientParameters); if (pRef != null && name.Equals(pRef.Name)) { return pRef; } } } return null; } private OperationResponse FindResponse(string name, IDictionary<string, OperationResponse> responses) { OperationResponse response = null; this.Responses.TryGetValue(name, out response); return response; } private static SwaggerParameter FindReferencedParameter(string reference, IDictionary<string, SwaggerParameter> parameters) { if (reference != null && reference.StartsWith("#", StringComparison.Ordinal)) { var parts = reference.Split('/'); if (parts.Length == 3 && parts[1].Equals("parameters")) { SwaggerParameter p = null; if (parameters.TryGetValue(parts[2], out p)) { return p; } } } return null; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function EditorGui::buildMenus(%this) { if(isObject(%this.menuBar)) return; //set up %cmdctrl variable so that it matches OS standards if( $platform $= "macos" ) { %cmdCtrl = "Cmd"; %menuCmdCtrl = "Cmd"; %quitShortcut = "Cmd Q"; %redoShortcut = "Cmd-Shift Z"; } else { %cmdCtrl = "Ctrl"; %menuCmdCtrl = "Alt"; %quitShortcut = "Alt F4"; %redoShortcut = "Ctrl Y"; } // Sub menus (temporary, until MenuBuilder gets updated) // The speed increments located here are overwritten in EditorCameraSpeedMenu::setupDefaultState. // The new min/max for the editor camera speed range can be set in each level's levelInfo object. if(!isObject(EditorCameraSpeedOptions)) { %this.cameraSpeedMenu = new PopupMenu(EditorCameraSpeedOptions) { superClass = "MenuBuilder"; class = "EditorCameraSpeedMenu"; item[0] = "Slowest" TAB %cmdCtrl @ "-Shift 1" TAB "5"; item[1] = "Slow" TAB %cmdCtrl @ "-Shift 2" TAB "35"; item[2] = "Slower" TAB %cmdCtrl @ "-Shift 3" TAB "70"; item[3] = "Normal" TAB %cmdCtrl @ "-Shift 4" TAB "100"; item[4] = "Faster" TAB %cmdCtrl @ "-Shift 5" TAB "130"; item[5] = "Fast" TAB %cmdCtrl @ "-Shift 6" TAB "165"; item[6] = "Fastest" TAB %cmdCtrl @ "-Shift 7" TAB "200"; }; } if(!isObject(EditorFreeCameraTypeOptions)) { %this.freeCameraTypeMenu = new PopupMenu(EditorFreeCameraTypeOptions) { superClass = "MenuBuilder"; class = "EditorFreeCameraTypeMenu"; item[0] = "Standard" TAB "Ctrl 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");"; item[1] = "Orbit Camera" TAB "Ctrl 2" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\");"; Item[2] = "-"; item[3] = "Smoothed" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Camera\");"; item[4] = "Smoothed Rotate" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Rot Camera\");"; }; } if(!isObject(EditorPlayerCameraTypeOptions)) { %this.playerCameraTypeMenu = new PopupMenu(EditorPlayerCameraTypeOptions) { superClass = "MenuBuilder"; class = "EditorPlayerCameraTypeMenu"; Item[0] = "First Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"1st Person Camera\");"; Item[1] = "Third Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"3rd Person Camera\");"; }; } if(!isObject(EditorCameraBookmarks)) { %this.cameraBookmarksMenu = new PopupMenu(EditorCameraBookmarks) { superClass = "MenuBuilder"; class = "EditorCameraBookmarksMenu"; //item[0] = "None"; }; } %this.viewTypeMenu = new PopupMenu() { superClass = "MenuBuilder"; item[ 0 ] = "Top" TAB "Alt 2" TAB "EditorGuiStatusBar.setCamera(\"Top View\");"; item[ 1 ] = "Bottom" TAB "Alt 5" TAB "EditorGuiStatusBar.setCamera(\"Bottom View\");"; item[ 2 ] = "Front" TAB "Alt 3" TAB "EditorGuiStatusBar.setCamera(\"Front View\");"; item[ 3 ] = "Back" TAB "Alt 6" TAB "EditorGuiStatusBar.setCamera(\"Back View\");"; item[ 4 ] = "Left" TAB "Alt 4" TAB "EditorGuiStatusBar.setCamera(\"Left View\");"; item[ 5 ] = "Right" TAB "Alt 7" TAB "EditorGuiStatusBar.setCamera(\"Right View\");"; item[ 6 ] = "Perspective" TAB "Alt 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");"; item[ 7 ] = "Isometric" TAB "Alt 8" TAB "EditorGuiStatusBar.setCamera(\"Isometric View\");"; }; // Menu bar %this.menuBar = new GuiMenuBar(WorldEditorMenubar) { dynamicItemInsertPos = 3; extent = "1024 20"; minExtent = "320 20"; horizSizing = "width"; profile = "GuiMenuBarProfile"; }; // File Menu %fileMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorFileMenu"; barTitle = "File"; }; %fileMenu.appendItem("New Level" TAB "" TAB "schedule( 1, 0, \"EditorNewLevel\" );"); %fileMenu.appendItem("Open Level..." TAB %cmdCtrl SPC "O" TAB "schedule( 1, 0, \"EditorOpenMission\" );"); %fileMenu.appendItem("Save Level" TAB %cmdCtrl SPC "S" TAB "EditorSaveMissionMenu();"); %fileMenu.appendItem("Save Level As..." TAB "" TAB "EditorSaveMissionAs();"); %fileMenu.appendItem("-"); if( $platform $= "windows" ) { %fileMenu.appendItem( "Open Project in Torsion" TAB "" TAB "EditorOpenTorsionProject();" ); %fileMenu.appendItem( "Open Level File in Torsion" TAB "" TAB "EditorOpenFileInTorsion();" ); %fileMenu.appendItem( "-" ); } %fileMenu.appendItem("Create Blank Terrain" TAB "" TAB "Canvas.pushDialog( CreateNewTerrainGui );"); %fileMenu.appendItem("Import Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainImportGui );"); %fileMenu.appendItem("Export Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainExportGui );"); %fileMenu.appendItem("-"); %fileMenu.appendItem("Export To COLLADA..." TAB "" TAB "EditorExportToCollada();"); //item[5] = "Import Terraform Data..." TAB "" TAB "Heightfield::import();"; //item[6] = "Import Texture Data..." TAB "" TAB "Texture::import();"; //item[7] = "-"; //item[8] = "Export Terraform Data..." TAB "" TAB "Heightfield::saveBitmap(\"\");"; %fileMenu.appendItem( "-" ); %fileMenu.appendItem( "Add FMOD Designer Audio..." TAB "" TAB "AddFMODProjectDlg.show();" ); %fileMenu.appendItem("-"); %fileMenu.appendItem("Play Level" TAB "F11" TAB "Editor.close(\"PlayGui\");"); %fileMenu.appendItem("Exit Level" TAB "" TAB "EditorExitMission();"); %fileMenu.appendItem("Quit" TAB %quitShortcut TAB "EditorQuitGame();"); %this.menuBar.insert(%fileMenu); // Edit Menu %editMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorEditMenu"; internalName = "EditMenu"; barTitle = "Edit"; item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "Editor.getUndoManager().undo();"; item[1] = "Redo" TAB %redoShortcut TAB "Editor.getUndoManager().redo();"; item[2] = "-"; item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "EditorMenuEditCut();"; item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "EditorMenuEditCopy();"; item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "EditorMenuEditPaste();"; item[6] = "Delete" TAB "Delete" TAB "EditorMenuEditDelete();"; item[7] = "-"; item[8] = "Deselect" TAB "X" TAB "EditorMenuEditDeselect();"; Item[9] = "Select..." TAB "" TAB "EditorGui.toggleObjectSelectionsWindow();"; item[10] = "-"; item[11] = "Audio Parameters..." TAB "" TAB "EditorGui.toggleSFXParametersWindow();"; item[12] = "Editor Settings..." TAB "" TAB "ESettingsWindow.ToggleVisibility();"; item[13] = "Snap Options..." TAB "" TAB "ESnapOptions.ToggleVisibility();"; item[14] = "-"; item[15] = "Game Options..." TAB "" TAB "Canvas.pushDialog(optionsDlg);"; item[16] = "PostEffect Manager" TAB "" TAB "Canvas.pushDialog(PostFXManager);"; }; %this.menuBar.insert(%editMenu); // View Menu %viewMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorViewMenu"; internalName = "viewMenu"; barTitle = "View"; item[ 0 ] = "Visibility Layers" TAB "Alt V" TAB "VisibilityDropdownToggle();"; item[ 1 ] = "Show Grid in Ortho Views" TAB %cmdCtrl @ "-Shift-Alt G" TAB "EditorGui.toggleOrthoGrid();"; }; %this.menuBar.insert(%viewMenu); // Camera Menu %cameraMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorCameraMenu"; barTitle = "Camera"; item[0] = "World Camera" TAB %this.freeCameraTypeMenu; item[1] = "Player Camera" TAB %this.playerCameraTypeMenu; item[2] = "-"; Item[3] = "Toggle Camera" TAB %menuCmdCtrl SPC "C" TAB "commandToServer('ToggleCamera');"; item[4] = "Place Camera at Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();"; item[5] = "Place Camera at Player" TAB "Alt Q" TAB "commandToServer('dropCameraAtPlayer');"; item[6] = "Place Player at Camera" TAB "Alt W" TAB "commandToServer('DropPlayerAtCamera');"; item[7] = "-"; item[8] = "Fit View to Selection" TAB "F" TAB "commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);"; item[9] = "Fit View To Selection and Orbit" TAB "Alt F" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\"); commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);"; item[10] = "-"; item[11] = "Speed" TAB %this.cameraSpeedMenu; item[12] = "View" TAB %this.viewTypeMenu; item[13] = "-"; Item[14] = "Add Bookmark..." TAB "Ctrl B" TAB "EditorGui.addCameraBookmarkByGui();"; Item[15] = "Manage Bookmarks..." TAB "Ctrl-Shift B" TAB "EditorGui.toggleCameraBookmarkWindow();"; item[16] = "Jump to Bookmark" TAB %this.cameraBookmarksMenu; }; %this.menuBar.insert(%cameraMenu); // Editors Menu %editorsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorToolsMenu"; barTitle = "Editors"; //item[0] = "Object Editor" TAB "F1" TAB WorldEditorInspectorPlugin; //item[1] = "Material Editor" TAB "F2" TAB MaterialEditorPlugin; //item[2] = "-"; //item[3] = "Terrain Editor" TAB "F3" TAB TerrainEditorPlugin; //item[4] = "Terrain Painter" TAB "F4" TAB TerrainPainterPlugin; //item[5] = "-"; }; %this.menuBar.insert(%editorsMenu); // Lighting Menu %lightingMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorLightingMenu"; barTitle = "Lighting"; item[0] = "Full Relight" TAB "Alt L" TAB "Editor.lightScene(\"\", forceAlways);"; item[1] = "Toggle ShadowViz" TAB "" TAB "toggleShadowViz();"; item[2] = "-"; item[3] = "Update Reflection Probes" TAB "" TAB "updateReflectionProbes();"; item[4] = "-"; // NOTE: The light managers will be inserted as the // last menu items in EditorLightingMenu::onAdd(). }; %this.menuBar.insert(%lightingMenu); // Tools Menu %toolsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorUtilitiesMenu"; barTitle = "Tools"; item[0] = "Network Graph" TAB "n" TAB "toggleNetGraph();"; item[1] = "Profiler" TAB "ctrl F2" TAB "showMetrics(true);"; item[2] = "Torque SimView" TAB "" TAB "tree();"; item[3] = "Make Selected a Mesh" TAB "" TAB "makeSelectedAMesh();"; }; %this.menuBar.insert(%toolsMenu); // Help Menu %helpMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorHelpMenu"; barTitle = "Help"; item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage(EWorldEditor.documentationURL);"; item[1] = "Offline User Guide..." TAB "" TAB "gotoWebPage(EWorldEditor.documentationLocal);"; item[2] = "Offline Reference Guide..." TAB "" TAB "shellexecute(EWorldEditor.documentationReference);"; item[3] = "Torque 3D Forums..." TAB "" TAB "gotoWebPage(EWorldEditor.forumURL);"; }; %this.menuBar.insert(%helpMenu); // Menus that are added/removed dynamically (temporary) // World Menu if(! isObject(%this.worldMenu)) { %this.dropTypeMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorDropTypeMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "at Origin" TAB "" TAB "atOrigin"; item[1] = "at Camera" TAB "" TAB "atCamera"; item[2] = "at Camera w/Rotation" TAB "" TAB "atCameraRot"; item[3] = "Below Camera" TAB "" TAB "belowCamera"; item[4] = "Screen Center" TAB "" TAB "screenCenter"; item[5] = "at Centroid" TAB "" TAB "atCentroid"; item[6] = "to Terrain" TAB "" TAB "toTerrain"; item[7] = "Below Selection" TAB "" TAB "belowSelection"; item[8] = "At Gizmo" TAB "" TAB "atGizmo"; }; %this.alignBoundsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorAlignBoundsMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "+X Axis" TAB "" TAB "0"; item[1] = "+Y Axis" TAB "" TAB "1"; item[2] = "+Z Axis" TAB "" TAB "2"; item[3] = "-X Axis" TAB "" TAB "3"; item[4] = "-Y Axis" TAB "" TAB "4"; item[5] = "-Z Axis" TAB "" TAB "5"; }; %this.alignCenterMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorAlignCenterMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "X Axis" TAB "" TAB "0"; item[1] = "Y Axis" TAB "" TAB "1"; item[2] = "Z Axis" TAB "" TAB "2"; }; %this.worldMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorWorldMenu"; barTitle = "Object"; item[0] = "Lock Selection" TAB %cmdCtrl @ " L" TAB "EWorldEditor.lockSelection(true); EWorldEditor.syncGui();"; item[1] = "Unlock Selection" TAB %cmdCtrl @ "-Shift L" TAB "EWorldEditor.lockSelection(false); EWorldEditor.syncGui();"; item[2] = "-"; item[3] = "Hide Selection" TAB %cmdCtrl @ " H" TAB "EWorldEditor.hideSelection(true); EWorldEditor.syncGui();"; item[4] = "Show Selection" TAB %cmdCtrl @ "-Shift H" TAB "EWorldEditor.hideSelection(false); EWorldEditor.syncGui();"; item[5] = "-"; item[6] = "Align Bounds" TAB %this.alignBoundsMenu; item[7] = "Align Center" TAB %this.alignCenterMenu; item[8] = "-"; item[9] = "Reset Transforms" TAB "Ctrl R" TAB "EWorldEditor.resetTransforms();"; item[10] = "Reset Selected Rotation" TAB "" TAB "EWorldEditor.resetSelectedRotation();"; item[11] = "Reset Selected Scale" TAB "" TAB "EWorldEditor.resetSelectedScale();"; item[12] = "Transform Selection..." TAB "Ctrl T" TAB "ETransformSelection.ToggleVisibility();"; item[13] = "-"; //item[13] = "Drop Camera to Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();"; //item[14] = "Add Selection to Instant Group" TAB "" TAB "EWorldEditor.addSelectionToAddGroup();"; item[14] = "Drop Selection" TAB "Ctrl D" TAB "EWorldEditor.dropSelection();"; //item[15] = "-"; item[15] = "Drop Location" TAB %this.dropTypeMenu; Item[16] = "-"; Item[17] = "Make Selection Prefab" TAB "" TAB "EditorMakePrefab();"; Item[18] = "Explode Selected Prefab" TAB "" TAB "EditorExplodePrefab();"; Item[19] = "-"; Item[20] = "Mount Selection A to B" TAB "" TAB "EditorMount();"; Item[21] = "Unmount Selected Object" TAB "" TAB "EditorUnmount();"; }; } } ////////////////////////////////////////////////////////////////////////// function EditorGui::attachMenus(%this) { %this.menuBar.attachToCanvas(Canvas, 0); } function EditorGui::detachMenus(%this) { %this.menuBar.removeFromCanvas(); } function EditorGui::setMenuDefaultState(%this) { if(! isObject(%this.menuBar)) return 0; for(%i = 0;%i < %this.menuBar.getMenuCount();%i++) { %menu = %this.menuBar.getMenu(%i); %menu.setupDefaultState(); } %this.worldMenu.setupDefaultState(); } ////////////////////////////////////////////////////////////////////////// function EditorGui::findMenu(%this, %name) { if(! isObject(%this.menuBar)) return 0; for(%i = 0; %i < %this.menuBar.getMenuCount(); %i++) { %menu = %this.menuBar.getMenu(%i); if(%name $= %menu.barTitle) return %menu; } return 0; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Impl.Unmanaged.Jni; using Apache.Ignite.Core.Log; /// <summary> /// Native interface manager. /// </summary> internal static class IgniteManager { /** Java Command line argument: Xms. Case sensitive. */ private const string CmdJvmMinMemJava = "-Xms"; /** Java Command line argument: Xmx. Case sensitive. */ private const string CmdJvmMaxMemJava = "-Xmx"; /** Java Command line argument: file.encoding. Case sensitive. */ private const string CmdJvmFileEncoding = "-Dfile.encoding="; /** Java Command line argument: java.util.logging.config.file. Case sensitive. */ private const string CmdJvmUtilLoggingConfigFile = "-Djava.util.logging.config.file="; /** Monitor for DLL load synchronization. */ private static readonly object SyncRoot = new object(); /** Configuration used on JVM start. */ private static JvmConfiguration _jvmCfg; /** Memory manager. */ private static readonly PlatformMemoryManager Mem = new PlatformMemoryManager(1024); /// <summary> /// Create JVM. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Logger</param> /// <returns>Callback context.</returns> internal static UnmanagedCallbacks CreateJvmContext(IgniteConfiguration cfg, ILogger log) { lock (SyncRoot) { // 1. Warn about possible configuration inconsistency. JvmConfiguration jvmCfg = JvmConfig(cfg); if (!cfg.SuppressWarnings && _jvmCfg != null) { if (!_jvmCfg.Equals(jvmCfg)) { log.Warn("Attempting to start Ignite node with different Java " + "configuration; current Java configuration will be ignored (consider " + "starting node in separate process) [oldConfig=" + _jvmCfg + ", newConfig=" + jvmCfg + ']'); } } // 2. Create unmanaged pointer. var jvm = CreateJvm(cfg, log); if (cfg.RedirectJavaConsoleOutput) { jvm.EnableJavaConsoleWriter(); } var cbs = new UnmanagedCallbacks(log, jvm); jvm.RegisterCallbacks(cbs); // 3. If this is the first JVM created, preserve configuration. if (_jvmCfg == null) { _jvmCfg = jvmCfg; } return cbs; } } /// <summary> /// Memory manager attached to currently running JVM. /// </summary> internal static PlatformMemoryManager Memory { get { return Mem; } } /// <summary> /// Create JVM. /// </summary> /// <returns>JVM.</returns> internal static Jvm CreateJvm(IgniteConfiguration cfg, ILogger log) { // Do not bother with classpath when JVM exists. var jvm = Jvm.Get(true); if (jvm != null) { return jvm; } var igniteHome = IgniteHome.Resolve(cfg.IgniteHome, log); var cp = Classpath.CreateClasspath(classPath: cfg.JvmClasspath, igniteHome: igniteHome, log: log); var jvmOpts = GetMergedJvmOptions(cfg, igniteHome); jvmOpts.Add(cp); return Jvm.GetOrCreate(jvmOpts); } /// <summary> /// Gets JvmOptions collection merged with individual properties (Min/Max mem, etc) according to priority. /// </summary> private static IList<string> GetMergedJvmOptions(IgniteConfiguration cfg, string igniteHome) { var jvmOpts = cfg.JvmOptions == null ? new List<string>() : cfg.JvmOptions.ToList(); // JvmInitialMemoryMB / JvmMaxMemoryMB have lower priority than CMD_JVM_OPT if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMinMemJava, StringComparison.OrdinalIgnoreCase)) && cfg.JvmInitialMemoryMb != IgniteConfiguration.DefaultJvmInitMem) { jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMinMemJava, cfg.JvmInitialMemoryMb)); } if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMaxMemJava, StringComparison.OrdinalIgnoreCase)) && cfg.JvmMaxMemoryMb != IgniteConfiguration.DefaultJvmMaxMem) { jvmOpts.Add( string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMaxMemJava, cfg.JvmMaxMemoryMb)); } if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmFileEncoding, StringComparison.Ordinal))) { jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}UTF-8", CmdJvmFileEncoding)); } if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmUtilLoggingConfigFile, StringComparison.Ordinal)) && !string.IsNullOrWhiteSpace(igniteHome)) { jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}", CmdJvmUtilLoggingConfigFile, Path.Combine(igniteHome, "config", "java.util.logging.properties"))); } return jvmOpts; } /// <summary> /// Create JVM configuration value object. /// </summary> /// <param name="cfg">Configuration.</param> /// <returns>JVM configuration.</returns> private static JvmConfiguration JvmConfig(IgniteConfiguration cfg) { return new JvmConfiguration { Home = cfg.IgniteHome, Dll = cfg.JvmDllPath, Classpath = cfg.JvmClasspath, Options = cfg.JvmOptions }; } /// <summary> /// JVM configuration. /// </summary> private class JvmConfiguration { /// <summary> /// Gets or sets the home. /// </summary> public string Home { get; set; } /// <summary> /// Gets or sets the DLL. /// </summary> public string Dll { get; set; } /// <summary> /// Gets or sets the cp. /// </summary> public string Classpath { get; set; } /// <summary> /// Gets or sets the options. /// </summary> public ICollection<string> Options { get; set; } /** <inheritDoc /> */ public override int GetHashCode() { return 0; } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] public override bool Equals(object obj) { JvmConfiguration other = obj as JvmConfiguration; if (other == null) return false; if (!string.Equals(Home, other.Home, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Classpath, other.Classpath, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Dll, other.Dll, StringComparison.OrdinalIgnoreCase)) return false; return (Options == null && other.Options == null) || (Options != null && other.Options != null && Options.Count == other.Options.Count && !Options.Except(other.Options).Any()); } /** <inheritDoc /> */ public override string ToString() { var sb = new StringBuilder("[IgniteHome=" + Home + ", JvmDllPath=" + Dll); if (Options != null && Options.Count > 0) { sb.Append(", JvmOptions=["); bool first = true; foreach (string opt in Options) { if (first) first = false; else sb.Append(", "); sb.Append(opt); } sb.Append(']'); } sb.Append(", Classpath=" + Classpath + ']'); return sb.ToString(); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class DisplayedDevice : DisplayedElement { [SerializeField] private UISprite levelSprite; [SerializeField] private UISprite controlSprite; [SerializeField] protected UISprite deviceBackgroundSprite; [SerializeField] private UILocalize moleculeOverlay; [SerializeField] private ParticleSystem feedbackParticleSystem; protected bool _isFeedbackParticleSystemActive = false; // prefab URIs private const string _uriPrefix = "Prefabs/Devices/"; private const string equippedPrefabURI = _uriPrefix + "DisplayedDevicePrefab"; public const string equippedWithMoleculesPrefabURI = _uriPrefix + "EquippedDisplayedDeviceWithMoleculesPrefab"; private const string listedPrefabURI = _uriPrefix + "ListedDevicePrefab"; // device icon // // common private const string _separator = "_"; private const string _baseDeviceTextureString = "device_"; private const string _quality256 = "256x256_"; private const string _quality80 = "80x80_"; private const string _quality64 = "64x64_"; private const string _qualityDefault = _quality64; // control on the promoter brick private const string _controlSuffix = "control_"; private const string _constitutiveSuffix = "constitutive"; private const string _activationSuffix = "activation"; private const string _inhibitionSuffix = "inhibition"; private const string _activationInhibitionSuffix = _activationSuffix + "_" + _inhibitionSuffix; private const string _controlConstitutiveSpriteName = _baseDeviceTextureString + _qualityDefault + _controlSuffix + _constitutiveSuffix; private const string _controlActivationSpriteName = _baseDeviceTextureString + _qualityDefault + _controlSuffix + _activationSuffix; private const string _controlInhibitionSpriteName = _baseDeviceTextureString + _qualityDefault + _controlSuffix + _inhibitionSuffix; private const string _controlActivationInhibitionSpriteName = _baseDeviceTextureString + _qualityDefault + _controlSuffix + _activationInhibitionSuffix; // level of expression on the RBS brick private const string _levelSuffix = "level"; private const string _level0Suffix = "0"; private const string _level1Suffix = "1"; private const string _level2Suffix = "2"; private const string _level3Suffix = "3"; private const string _textSuffix = "_text"; private const string _pictureSuffix = "_picture"; private const string _level0TextSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level0Suffix + _textSuffix; private const string _level1TextSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level1Suffix + _textSuffix; private const string _level2TextSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level2Suffix + _textSuffix; private const string _level3TextSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level3Suffix + _textSuffix; private const string _level0PictureSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level0Suffix + _pictureSuffix; private const string _level1PictureSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level1Suffix + _pictureSuffix; private const string _level2PictureSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level2Suffix + _pictureSuffix; private const string _level3PictureSpriteName = _baseDeviceTextureString + _qualityDefault + _levelSuffix + _level3Suffix + _pictureSuffix; // default texture private const string _defaultTexture = "default"; private const string _defaultTextureWithText = _defaultTexture + _textSuffix; // molecule name overlay private const string _moleculeOverlayPrefix = "BRICK.ICONLABEL."; // background private const string backgroundSuffix = "background_"; private const string squareBackgroundSuffix = "square"; private const string roundedSquareBackgroundSuffix = "rounded_square"; private const string circleBackgroundSuffix = "circle"; private const string squareBackgroundSpriteName = _baseDeviceTextureString + _qualityDefault + backgroundSuffix + squareBackgroundSuffix; private const string roundedSquareBackgroundSpriteName = _baseDeviceTextureString + _qualityDefault + backgroundSuffix + roundedSquareBackgroundSuffix; private const string circleBackgroundSpriteName = _baseDeviceTextureString + _qualityDefault + backgroundSuffix + circleBackgroundSuffix; private const string _equippedPrefix = "e_"; private const string _inventoriedPrefix = "i_"; private const string _listedPrefix = "l_"; private const string _craftSlotPrefix = "c_"; private string[] _deviceNamePrefixes = new string[4] { _equippedPrefix, _inventoriedPrefix, _listedPrefix, _craftSlotPrefix }; public Device _device; protected static DevicesDisplayer _devicesDisplayer; private DevicesDisplayer.DeviceType _deviceType; private static Dictionary<string, string> geneSpecialTextureDico = new Dictionary<string, string>() { {"ARAC", _defaultTextureWithText}, {"ATC", _defaultTextureWithText}, {"IPTG", _defaultTextureWithText}, {"LARA", _defaultTextureWithText}, {"REPR1", _defaultTextureWithText}, {"REPR2", _defaultTextureWithText}, {"REPR3", _defaultTextureWithText}, {"REPR4", _defaultTextureWithText} }; public static void reset() { _devicesDisplayer = null; } public void playFeedback() { _isFeedbackParticleSystemActive = true; feedbackParticleSystem.gameObject.SetActive(true); feedbackParticleSystem.Emit(50); if (gameObject.activeInHierarchy) { StartCoroutine(terminateParticleSystem()); } } IEnumerator terminateParticleSystem() { yield return new WaitForSeconds(1.5f); _isFeedbackParticleSystemActive = false; feedbackParticleSystem.Stop(); feedbackParticleSystem.gameObject.SetActive(false); yield return null; } private static string getTextureName(string proteinName) { string texture = _defaultTextureWithText; if (!geneSpecialTextureDico.TryGetValue(proteinName, out texture)) { texture = proteinName.ToLowerInvariant(); } return texture; } private void setBackgroundSprite(string backgroundSpriteName = circleBackgroundSpriteName) { if (null != deviceBackgroundSprite) { deviceBackgroundSprite.spriteName = backgroundSpriteName; deviceBackgroundSprite.gameObject.SetActive(true); // Debug.Log(this.GetType() + " setBackgroundSprite"); } } private void setMoleculeOverlay(string proteinName) { setMoleculeOverlay(proteinName, moleculeOverlay); } public static void setMoleculeOverlay(string proteinName, UILocalize moleculeOverlayLocalize, bool dontFilter = false) { // Debug.Log("DisplayedDevice setMoleculeOverlay(" + proteinName + ", " + moleculeOverlayLocalize + ", " + dontFilter + ")"); if (null != moleculeOverlayLocalize) { string texture = _defaultTextureWithText; if (dontFilter || geneSpecialTextureDico.TryGetValue(proteinName, out texture)) { moleculeOverlayLocalize.gameObject.SetActive(true); string before = moleculeOverlayLocalize.key; moleculeOverlayLocalize.key = _moleculeOverlayPrefix + proteinName.ToUpperInvariant(); moleculeOverlayLocalize.Localize(); // Debug.Log("DisplayedDevice setMoleculeOverlay() before=" + before + ", after=" + moleculeOverlayLocalize.key); } else { moleculeOverlayLocalize.gameObject.SetActive(false); } // Debug.Log("DisplayedDevice setMoleculeOverlay"); } } private void setLevelSprite(int levelIndex = -1, bool isPictureMode = true) { if (levelIndex == -1) { levelIndex = _device.levelIndex; } if (null != levelSprite) { string spriteName = getLevelSpriteName(levelIndex, isPictureMode); if (!string.IsNullOrEmpty(spriteName)) { levelSprite.spriteName = spriteName; levelSprite.gameObject.SetActive(true); } else { Debug.LogWarning(this.GetType() + " setLevelSprite empty sprite name"); levelSprite.gameObject.SetActive(false); } // Debug.Log(this.GetType() + " setLevelSprite"); } } private void setControlSprite(PromoterBrick.Regulation regulation) { if (null != controlSprite) { string spriteName = getControlSpriteName(regulation); if (!string.IsNullOrEmpty(spriteName)) { controlSprite.spriteName = spriteName; controlSprite.gameObject.SetActive(true); } else { Debug.LogWarning(this.GetType() + " setControlSprite empty sprite name"); controlSprite.gameObject.SetActive(false); } // Debug.Log(this.GetType() + " setControlSprite"); } } private void setDeviceIcon(int levelIndex = -1) { if (levelIndex == -1) { levelIndex = (null == _device)?0:_device.levelIndex; } string withLevelSuffix = getTextureName() + _separator + getLevelSuffix(levelIndex); if (_atlas.GetListOfSprites().Contains(withLevelSuffix)) { setSprite(withLevelSuffix); } else { setSprite(getTextureName()); } } private string getLevelSuffix(int levelIndex = -1) { string levelSuffix; if (levelIndex == -1) { levelIndex = _device.levelIndex; } switch (levelIndex) { case 0: levelSuffix = _level0Suffix; break; case 1: levelSuffix = _level1Suffix; break; case 2: levelSuffix = _level2Suffix; break; case 3: levelSuffix = _level3Suffix; break; default: levelSuffix = _level0Suffix; break; } return _levelSuffix + levelSuffix; } private string getLevelSpriteName(int levelIndex = -1, bool isPictureMode = true) { string spriteName; if (_device == null) { spriteName = ""; } else { if (levelIndex == -1) { levelIndex = _device.levelIndex; } switch (levelIndex) { case 0: spriteName = isPictureMode ? _level0PictureSpriteName : _level0TextSpriteName; break; case 1: spriteName = isPictureMode ? _level1PictureSpriteName : _level1TextSpriteName; break; case 2: spriteName = isPictureMode ? _level2PictureSpriteName : _level2TextSpriteName; break; case 3: spriteName = isPictureMode ? _level3PictureSpriteName : _level3TextSpriteName; break; default: spriteName = isPictureMode ? _level0PictureSpriteName : _level0TextSpriteName; break; } } return spriteName; } private string getControlSpriteName(PromoterBrick.Regulation regulation) { string spriteName = _controlConstitutiveSpriteName; switch (regulation) { case PromoterBrick.Regulation.CONSTANT: spriteName = _controlConstitutiveSpriteName; break; case PromoterBrick.Regulation.ACTIVATED: spriteName = _controlActivationSpriteName; break; case PromoterBrick.Regulation.REPRESSED: spriteName = _controlInhibitionSpriteName; break; case PromoterBrick.Regulation.BOTH: spriteName = _controlActivationInhibitionSpriteName; break; default: break; } return spriteName; } public static DisplayedDevice Create( Transform parentTransform , Vector3 localPosition , string spriteName , Device device , DevicesDisplayer devicesDisplayer , DevicesDisplayer.DeviceType deviceType ) { if (device == null) { Debug.LogWarning("DisplayedDevice Create device==null"); } string nullSpriteName = (spriteName != null) ? "" : "(null)"; Object prefab; if (deviceType == DevicesDisplayer.DeviceType.Equipped || deviceType == DevicesDisplayer.DeviceType.CraftSlot) { // Debug.Log("DisplayedDevice: will create Equipped " + equippedPrefabURI); prefab = Resources.Load(equippedPrefabURI); } // else if (deviceType == DevicesDisplayer.DeviceType.Inventoried) // deprecated // { // // Debug.Log("DisplayedDevice: will create Inventoried " + inventoriedPrefabURI); // prefab = Resources.Load(inventoriedPrefabURI); // } else if (deviceType == DevicesDisplayer.DeviceType.Listed) { // Debug.Log("DisplayedDevice: will create Listed " + listedPrefabURI); prefab = Resources.Load(listedPrefabURI); } else { Debug.LogWarning("DisplayedDevice Create : unmanaged device type " + deviceType); return null; } // Debug.Log("DisplayedDevice Create(type=" + deviceType // + ", parentTransform=" + parentTransform // + ", localPosition=" + localPosition // + ", device=" + device // + ", devicesDisplayer=" + devicesDisplayer // + ", spriteName=" + spriteName + nullSpriteName // ); DisplayedDevice result = (DisplayedDevice)DisplayedElement.Create( parentTransform , localPosition , "" , prefab ); result.Initialize(device, deviceType, devicesDisplayer); return result; } public string getTextureName() { string usedSpriteName = _baseDeviceTextureString; DevicesDisplayer.TextureQuality quality = DevicesDisplayer.getTextureQuality(); switch (quality) { case DevicesDisplayer.TextureQuality.HIGH: usedSpriteName += _quality256; break; case DevicesDisplayer.TextureQuality.NORMAL: usedSpriteName += _quality80; break; case DevicesDisplayer.TextureQuality.LOW: usedSpriteName += _quality64; break; default: usedSpriteName += _qualityDefault; break; } if (null == _device) { usedSpriteName += getTextureName(""); } else { usedSpriteName += getTextureName(_device.getFirstGeneProteinName()); } /* if(quality == DevicesDisplayer.TextureQuality.LOW) usedSpriteName += getLevelSuffix(device); */ // Debug.Log(this.GetType() + " getTextureName usedSpriteName=" + usedSpriteName); return usedSpriteName; } public void Initialize( Device device , DevicesDisplayer.DeviceType deviceType , DevicesDisplayer devicesDisplayer = null ) { // Debug.Log(this.GetType() + " Initialize"); if (device == null) { Debug.LogWarning(this.GetType() + " Initialize device==null"); } _device = Device.buildDevice(device); if (_device == null) { Debug.LogWarning(this.GetType() + " Initialize _device==null"); } // Debug.Log(this.GetType() + " Create built device " + _device + " from " + device); if (_devicesDisplayer == null) { _devicesDisplayer = DevicesDisplayer.get(); } // Debug.Log(this.GetType() + " Initialize ends"); _deviceType = deviceType; setName(); setBackgroundSprite(); setMoleculeOverlay(device.getFirstGeneProteinName()); int levelIndex = device.levelIndex; setLevelSprite(levelIndex); setControlSprite(device.getRegulation()); setDeviceIcon(levelIndex); // Debug.Log(this.GetType() + " Initialize done for " + gameObject.name); } private void setName() { gameObject.name = _deviceNamePrefixes[(int)_deviceType] + _device.getInternalName(); // Debug.Log(this.GetType() + " setName to " + gameObject.name); } protected string getDebugInfos() { return "device id=" + _id + ", inner device=" + _device + ", device type=" + _deviceType + ", time=" + Time.realtimeSinceStartup; } public void toggleEquipped() { if (_device == null) { Debug.LogWarning(this.GetType() + " toggleEquipped _device==null"); return; } DeviceContainer.AddingResult addingResult = _devicesDisplayer.askAddEquippedDevice(_device); // Debug.Log(this.GetType() + " toggleEquipped added device result=" + addingResult + ", " + getDebugInfos()); if (DeviceContainer.AddingResult.FAILURE_SAME_NAME == addingResult || DeviceContainer.AddingResult.FAILURE_SAME_DEVICE == addingResult) { if (_devicesDisplayer.askRemoveEquippedDevice(_device)) { RedMetricsManager.get().sendRichEvent(TrackingEvent.UNEQUIP, new CustomData(CustomDataTag.DEVICE, _device.getInternalName())); } } else { RedMetricsManager.get().sendRichEvent(TrackingEvent.EQUIP, new CustomData(CustomDataTag.DEVICE, _device.getInternalName())); } } // workaround to have proper scrolling of EDDWMs with displayed device icons in a UIPanel with clipping public void makeChildrenSiblings() { // Debug.Log(this.GetType() + " makeChildrenSiblings"); int childCount = transform.childCount; Transform[] transforms = new Transform[childCount]; for (int index = 0; index < childCount; index++) { // Debug.Log(this.GetType() + " makeChildrenSiblings saves " + transform.GetChild(index).name); transforms[index] = transform.GetChild(index); } foreach (Transform t in transforms) { // Debug.Log(this.GetType() + " makeChildrenSiblings edits " + t.name); t.parent = transform.parent; } } void Update() { if ((_isFeedbackParticleSystemActive) && (GameStateController.isPause()) && (null != feedbackParticleSystem)) { feedbackParticleSystem.Simulate(Time.unscaledDeltaTime, true, false); } } public override void OnPress(bool isPressed) { // Debug.Log(this.GetType() + " OnPress() of " + _device.getInternalName()); } protected virtual void OnHover(bool isOver) { // Debug.Log(this.GetType() + " OnHover("+isOver+") device=" + _device.getInternalName()); TooltipManager.displayTooltip(isOver, _device, transform.position); } //TODO remove tooltip only if tooltip was about this displayed device protected virtual void OnDestroy() { TooltipManager.displayTooltip(); } public override string ToString() { return "DisplayedDevice[" + this._device.getInternalName() + "]"; } }
// MbUnit Test Framework // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // MbUnit HomePage: http://mbunit.tigris.org // Author: Jonathan de Halleux namespace MbUnit.Core.Framework { using System; using System.IO; using System.Xml; using System.Threading; using System.Reflection; using System.Collections; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Activation; using System.Diagnostics; using MbUnit.Core.Remoting; [AttributeUsage(AttributeTargets.Class)] public class AppDomainAttribute : ContextAttribute, IContributeObjectSink { public AppDomainAttribute(string friendlyName) : base("AppDomain") { _friendlyName = friendlyName; } private string _friendlyName; public string FriendlyName { get { return _friendlyName; } } public string PrivateBinPath { get { return _privateBinPath; } set { _privateBinPath = value; } } private string _privateBinPath; public bool ShadowCopyFiles { get { return _shadowCopyFiles; } set { _shadowCopyFiles = value; } } private bool _shadowCopyFiles; public string Config { set { _config = value; } get { return _config; } } private string _config; public string ConfigFile { set { _configFile = value; } get { return _configFile; } } private string _configFile; public override bool IsContextOK(Context ctx, IConstructionCallMessage ctorMsg) { return (AppDomain.CurrentDomain.FriendlyName == _friendlyName); } public override void GetPropertiesForNewContext(IConstructionCallMessage msg) { _activationType = msg.ActivationType; base.GetPropertiesForNewContext(msg); } private Type _activationType; public Type ActivationType { get { return _activationType; } } public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink) { return new AppDomainMessageSink(this, obj, nextSink); } private static IDictionary _services = new Hashtable(); } internal class AppDomainMessageSink : IMessageSink { public AppDomainMessageSink(AppDomainAttribute appDomainAttribute, MarshalByRefObject obj, IMessageSink nextSink) { _appDomainAttribute = appDomainAttribute; _obj = obj; _nextSink = nextSink; string baseDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(baseDir); string friendlyName = appDomainAttribute.FriendlyName; AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = baseDir; string configFile = appDomainAttribute.ConfigFile; string config = appDomainAttribute.Config; if(config != null) { if(configFile == null) { configFile = friendlyName + ".config"; } configFile = Path.Combine(baseDir, configFile); setup.ConfigurationFile = configFile; using(StreamWriter writer = new StreamWriter(configFile)) { writer.Write(appDomainAttribute.Config); } } Type activationType = appDomainAttribute.ActivationType; XmlDocument doc = new XmlDocument(); if(configFile != null) { doc.Load(configFile); } mergeDependentAssemblies(doc, activationType); if(doc.DocumentElement != null) { if(configFile == null) { configFile = Path.GetTempFileName(); } doc.Save(configFile); } string binDir = baseDir; if(appDomainAttribute.PrivateBinPath != null) { string privateBinPath = appDomainAttribute.PrivateBinPath; setup.PrivateBinPath = privateBinPath; privateBinPath = privateBinPath.Split(new char[] {';'})[0]; binDir = Path.Combine(binDir, privateBinPath); Directory.CreateDirectory(binDir); } // Copy activated type assembly. string activationFile = new Uri(activationType.Assembly.CodeBase).LocalPath; string destFile = Path.Combine(binDir, Path.GetFileName(activationFile)); if(activationFile != destFile) { File.Copy(activationFile, destFile, true); } // Copy context attribute assembly. string contextsFile = new Uri(GetType().Assembly.CodeBase).LocalPath; string destContextsFile = Path.Combine(binDir, Path.GetFileName(contextsFile)); if(destContextsFile != destFile) { File.Copy(contextsFile, destContextsFile, true); } copyFiles(activationType, baseDir); if(appDomainAttribute.ShadowCopyFiles) { setup.ShadowCopyFiles = "true"; } _domain = AppDomain.CreateDomain(friendlyName, null, setup); _remoteObject = (MarshalByRefObject)_domain.CreateInstanceAndUnwrap( activationType.Assembly.FullName, activationType.FullName); } private AppDomainAttribute _appDomainAttribute; private MarshalByRefObject _obj; private IMessageSink _nextSink; private AppDomain _domain; private MarshalByRefObject _remoteObject; private static void mergeDependentAssemblies(XmlDocument doc, Type type) { object[] dependentAssemblies = type.GetCustomAttributes(typeof(DependentAssemblyAttribute), true); if(dependentAssemblies != null) { foreach(DependentAssemblyAttribute dependentAssembly in dependentAssemblies) { AssemblyName assemblyName = dependentAssembly.AssemblyName; string versionRange = dependentAssembly.OldVersion; if(versionRange == null) { versionRange = assemblyName.Version.ToString(); } string codeBase = null; if(dependentAssembly.NewVersion == null) { codeBase = assemblyName.CodeBase; } else { assemblyName.Version = new Version(dependentAssembly.NewVersion); } ConfigUtils.MergeDependentAssembly(doc, assemblyName, versionRange, codeBase); } } } private void copyFiles(Type type, string destination) { object[] copies = type.GetCustomAttributes(typeof(CopyAttribute), true); if(copies != null) { foreach(CopyAttribute copy in copies) { foreach(string file in copy.Files) { string fileName = Path.GetFileName(file); string destDir = destination; if(copy.Destination != null) { destDir = Path.Combine(destDir, copy.Destination); Directory.CreateDirectory(destDir); } string destFile = Path.Combine(destDir, fileName); File.Copy(file, destFile, true); } } } } private static string getAssemblyFileByName(string name, string dir) { string assemblyFile = Path.Combine(dir, name + ".dll"); if(File.Exists(assemblyFile)) { return assemblyFile; } assemblyFile = Path.Combine(dir, name + ".exe"); if(File.Exists(assemblyFile)) { return assemblyFile; } throw new ApplicationException("Couldn't find assembly with name '" + name + "' in directory '" + dir + "'"); } #region IMessageSink Members public IMessage SyncProcessMessage(IMessage msg) { try { if(msg is IMethodCallMessage) { IMethodCallMessage methodCall = (IMethodCallMessage)msg; object ret = methodCall.MethodBase.Invoke(_remoteObject, methodCall.Args); ArrayList outArgs = new ArrayList(); foreach(ParameterInfo parameter in methodCall.MethodBase.GetParameters()) { if(parameter.IsOut) { object arg = methodCall.Args[parameter.Position]; outArgs.Add(arg); } } return new ReturnMessage(ret, outArgs.ToArray(), outArgs.Count, methodCall.LogicalCallContext, methodCall); } return _nextSink.SyncProcessMessage(msg); } catch(Exception e) { return new ReturnMessage(e, (IMethodCallMessage)msg); } } public IMessageSink NextSink { get { return _nextSink; } } public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { throw new NotImplementedException(); } #endregion } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text.Formatting; using System.Threading; using InlineIL; using ZeroLog.Appenders; using ZeroLog.Utils; using static InlineIL.IL.Emit; namespace ZeroLog { internal unsafe partial class LogEvent : IInternalLogEvent { private const int _maxArgCapacity = byte.MaxValue; private string[] _strings; private IntPtr[] _argPointers; private Log _log; private LogEventArgumentExhaustionStrategy _argumentExhaustionStrategy; protected readonly byte* _startOfBuffer; protected readonly byte* _endOfBuffer; protected byte* _dataPointer; private byte _argCount; private bool _isTruncated; public LogEvent(BufferSegment bufferSegment, int argCapacity) { argCapacity = Math.Min(argCapacity, _maxArgCapacity); _argPointers = new IntPtr[argCapacity]; _strings = new string[argCapacity]; _startOfBuffer = bufferSegment.Data; _dataPointer = bufferSegment.Data; _endOfBuffer = bufferSegment.Data + bufferSegment.Length; _log = default!; } public Level Level { get; private set; } public DateTime Timestamp { get; private set; } public Thread? Thread { get; private set; } public string Name => _log.Name; public IAppender[] Appenders => _log.Appenders; public virtual bool IsPooled => true; public void Initialize(Level level, Log log, LogEventArgumentExhaustionStrategy argumentExhaustionStrategy) { Timestamp = SystemDateTime.UtcNow; Level = level; _log = log; _argCount = 0; _dataPointer = _startOfBuffer; _isTruncated = false; _argumentExhaustionStrategy = argumentExhaustionStrategy; Thread = Thread.CurrentThread; } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendGenericSlow<T>(T arg) { if (TypeUtilSlow<T>.IsNullableEnum) AppendNullableEnumInternal(arg); else if (TypeUtilSlow<T>.IsUnmanaged) AppendUnmanagedInternal(arg); else throw new NotSupportedException($"Type {typeof(T)} is not supported "); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendFormat(string format) { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(byte), 1)) return; AppendArgumentType(ArgumentType.FormatString); AppendString(format); AppendByte(_argCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent Append(string? s) { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte), 1)) return this; if (s == null) { AppendArgumentType(ArgumentType.Null); return this; } AppendArgumentType(ArgumentType.String); AppendString(s); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendKeyValue(string key, string? value) { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(byte), 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); if (value == null) { AppendArgumentType(ArgumentType.Null); return this; } AppendArgumentType(ArgumentType.String); AppendString(value); return this; } public ILogEvent AppendKeyValue<T>(string key, T value) where T : struct, Enum { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(EnumArg), 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); AppendArgumentType(ArgumentType.Enum); *(EnumArg*)_dataPointer = new EnumArg(TypeUtil<T>.TypeHandle, EnumCache.ToUInt64(value)); _dataPointer += sizeof(EnumArg); return this; } public ILogEvent AppendKeyValue<T>(string key, T? value) where T : struct, Enum { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(EnumArg), 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); if (value == null) { AppendArgumentType(ArgumentType.Null); return this; } AppendArgumentType(ArgumentType.Enum); *(EnumArg*)_dataPointer = new EnumArg(TypeUtil<T>.TypeHandle, EnumCache.ToUInt64(value.GetValueOrDefault())); _dataPointer += sizeof(EnumArg); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendKeyValueAscii(string key, byte[]? bytes, int length) { if (length < 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(int) + length, 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); if (bytes is null) { AppendArgumentType(ArgumentType.Null); return this; } AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); if (length != 0) AppendBytes(bytes, length); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendKeyValueAscii(string key, byte* bytes, int length) { if (length < 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(int) + length, 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); if (bytes == null) { AppendArgumentType(ArgumentType.Null); return this; } AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); AppendBytes(bytes, length); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendKeyValueAscii(string key, ReadOnlySpan<byte> bytes) { var length = bytes.Length; if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(int) + length, 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); AppendBytes(bytes); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendKeyValueAscii(string key, ReadOnlySpan<char> chars) { var length = chars.Length; if (!PrepareAppend(sizeof(ArgumentType) + sizeof(byte) + sizeof(ArgumentType) + sizeof(int) + length, 2)) return this; AppendArgumentType(ArgumentType.KeyString); AppendString(key); AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); foreach (var c in chars) *_dataPointer++ = (byte)c; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendAsciiString(byte[]? bytes, int length) { if (bytes == null) { if (PrepareAppend(sizeof(ArgumentType), 1)) AppendArgumentType(ArgumentType.Null); return this; } var remainingBytes = (int)(_endOfBuffer - _dataPointer); remainingBytes -= sizeof(ArgumentType) + sizeof(int); if (length > remainingBytes) { _isTruncated = true; length = remainingBytes; } if (length <= 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(int) + length, 1)) return this; AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); AppendBytes(bytes, length); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendAsciiString(byte* bytes, int length) { if (bytes == null) { if (PrepareAppend(sizeof(ArgumentType), 1)) AppendArgumentType(ArgumentType.Null); return this; } var remainingBytes = (int)(_endOfBuffer - _dataPointer); remainingBytes -= sizeof(ArgumentType) + sizeof(int); if (length > remainingBytes) { _isTruncated = true; length = remainingBytes; } if (length <= 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(int) + length, 1)) return this; AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); AppendBytes(bytes, length); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendAsciiString(ReadOnlySpan<byte> bytes) { var remainingBytes = (int)(_endOfBuffer - _dataPointer); remainingBytes -= sizeof(ArgumentType) + sizeof(int); var length = bytes.Length; if (length > remainingBytes) { _isTruncated = true; length = remainingBytes; } if (length <= 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(int) + length, 1)) return this; AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); AppendBytes(bytes.Slice(0, length)); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendAsciiString(ReadOnlySpan<char> chars) { var remainingBytes = (int)(_endOfBuffer - _dataPointer); remainingBytes -= sizeof(ArgumentType) + sizeof(int); var length = chars.Length; if (length > remainingBytes) { _isTruncated = true; length = remainingBytes; } if (length <= 0 || !PrepareAppend(sizeof(ArgumentType) + sizeof(int) + length, 1)) return this; AppendArgumentType(ArgumentType.AsciiString); AppendInt32(length); foreach (var c in chars.Slice(0, length)) *_dataPointer++ = (byte)c; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendEnum<T>(T value) where T : struct, Enum { return AppendEnumInternal(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ILogEvent AppendEnum<T>(T? value) where T : struct, Enum { if (value == null) { if (PrepareAppend(sizeof(ArgumentType), 1)) AppendArgumentType(ArgumentType.Null); return this; } return AppendEnumInternal(value.GetValueOrDefault()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ILogEvent AppendEnumInternal<T>(T value) { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(EnumArg), 1)) return this; AppendArgumentType(ArgumentType.Enum); *(EnumArg*)_dataPointer = new EnumArg(TypeUtil<T>.TypeHandle, EnumCache.ToUInt64(value)); _dataPointer += sizeof(EnumArg); return this; } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendNullableEnumInternal<T>(T value) // T = Nullable<SomeEnum> { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(EnumArg), 1)) return; var enumValue = EnumCache.ToUInt64Nullable(value); if (enumValue == null) { AppendArgumentType(ArgumentType.Null); return; } AppendArgumentType(ArgumentType.Enum); *(EnumArg*)_dataPointer = new EnumArg(TypeUtilSlow<T>.UnderlyingTypeHandle, enumValue.GetValueOrDefault()); _dataPointer += sizeof(EnumArg); } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendUnmanagedInternal<T>(T arg) // T = unmanaged or Nullable<unmanaged> { if (!PrepareAppend(sizeof(ArgumentType) + sizeof(UnmanagedArgHeader) + UnsafeTools.SizeOf<T>(), 1)) return; // If T is a Nullable<unmanaged>, we copy it as-is and let the formatter deal with it. // We're already in a slower execution path at this point. AppendArgumentType(ArgumentType.Unmanaged); *(UnmanagedArgHeader*)_dataPointer = new UnmanagedArgHeader(TypeUtil<T>.TypeHandle, UnsafeTools.SizeOf<T>()); _dataPointer += sizeof(UnmanagedArgHeader); IL.Push(_dataPointer); IL.Push(arg); Stobj(typeof(T)); _dataPointer += UnsafeTools.SizeOf<T>(); } public void Log() { _log.Enqueue(this); } public void WriteToStringBuffer(StringBuffer stringBuffer, KeyValuePointerBuffer keyValuePointerBuffer) { var endOfData = _dataPointer; var dataPointer = _startOfBuffer; keyValuePointerBuffer.Clear(); while (dataPointer < endOfData) { if (!ConsumeKeyValue(ref dataPointer, keyValuePointerBuffer)) stringBuffer.Append(ref dataPointer, StringView.Empty, _strings, _argPointers, _argCount); } Debug.Assert(dataPointer == endOfData, "Buffer over-read"); if (keyValuePointerBuffer.KeyPointerCount > 0) JsonWriter.WriteJsonToStringBuffer(stringBuffer, keyValuePointerBuffer, _strings); if (_isTruncated) stringBuffer.Append(LogManager.Config.TruncatedMessageSuffix); } private static bool ConsumeKeyValue(ref byte* dataPointer, KeyValuePointerBuffer keyValuePointerBuffer) { var argumentType = (ArgumentType)(*dataPointer & ArgumentTypeMask.ArgumentType); if (argumentType != ArgumentType.KeyString) return false; // Save a pointer to the key for later when we append the Key/Value JSON. keyValuePointerBuffer.AddKeyPointer(dataPointer); // Skip the key. SkipCurrentArgument(ref dataPointer); // Skip the value. SkipCurrentArgument(ref dataPointer); return true; } private static void SkipCurrentArgument(ref byte* dataPointer) { var argumentType = (ArgumentType)(*dataPointer & ArgumentTypeMask.ArgumentType); dataPointer += sizeof(ArgumentType); switch (argumentType) { case ArgumentType.String: case ArgumentType.KeyString: case ArgumentType.Byte: dataPointer += sizeof(byte); break; case ArgumentType.AsciiString: var length = *(int*)dataPointer; dataPointer += sizeof(int) + length; break; case ArgumentType.Boolean: dataPointer += sizeof(bool); break; case ArgumentType.Char: dataPointer += sizeof(char); break; case ArgumentType.Int16: dataPointer += sizeof(short); break; case ArgumentType.Int32: dataPointer += sizeof(int); break; case ArgumentType.Int64: dataPointer += sizeof(long); break; case ArgumentType.Single: dataPointer += sizeof(float); break; case ArgumentType.Double: dataPointer += sizeof(double); break; case ArgumentType.Decimal: dataPointer += sizeof(decimal); break; case ArgumentType.Guid: dataPointer += sizeof(Guid); break; case ArgumentType.DateTime: dataPointer += sizeof(DateTime); break; case ArgumentType.TimeSpan: dataPointer += sizeof(TimeSpan); break; case ArgumentType.Enum: dataPointer += sizeof(EnumArg); break; case ArgumentType.Null: break; case ArgumentType.FormatString: case ArgumentType.Unmanaged: throw new NotSupportedException($"Type is not supported {argumentType}"); default: throw new ArgumentOutOfRangeException(); } } public void WriteToStringBufferUnformatted(StringBuffer stringBuffer) { var endOfData = _dataPointer; var dataPointer = _startOfBuffer; while (dataPointer < endOfData) { AppendArgumentToStringBufferUnformatted(stringBuffer, ref dataPointer); if (dataPointer < endOfData) stringBuffer.Append(", "); } Debug.Assert(dataPointer == endOfData, "Buffer over-read"); if (_isTruncated) stringBuffer.Append(LogManager.Config.TruncatedMessageSuffix); } private void AppendArgumentToStringBufferUnformatted(StringBuffer stringBuffer, ref byte* dataPointer) { var argument = *dataPointer; dataPointer += sizeof(ArgumentType); var argumentType = (ArgumentType)(argument & ArgumentTypeMask.ArgumentType); var hasFormatSpecifier = (argument & ArgumentTypeMask.FormatSpecifier) != 0; if (hasFormatSpecifier) dataPointer += sizeof(byte); // Skip it switch (argumentType) { case ArgumentType.String: case ArgumentType.KeyString: stringBuffer.Append('"'); stringBuffer.Append(_strings[*dataPointer]); stringBuffer.Append('"'); dataPointer += sizeof(byte); break; case ArgumentType.AsciiString: var length = *(int*)dataPointer; dataPointer += sizeof(int); stringBuffer.Append('"'); stringBuffer.Append(new AsciiString(dataPointer, length)); stringBuffer.Append('"'); dataPointer += length; break; case ArgumentType.Boolean: stringBuffer.Append(*(bool*)dataPointer); dataPointer += sizeof(bool); break; case ArgumentType.Byte: stringBuffer.Append(*dataPointer, StringView.Empty); dataPointer += sizeof(byte); break; case ArgumentType.Char: stringBuffer.Append('\''); stringBuffer.Append(*(char*)dataPointer); stringBuffer.Append('\''); dataPointer += sizeof(char); break; case ArgumentType.Int16: stringBuffer.Append(*(short*)dataPointer, StringView.Empty); dataPointer += sizeof(short); break; case ArgumentType.Int32: stringBuffer.Append(*(int*)dataPointer, StringView.Empty); dataPointer += sizeof(int); break; case ArgumentType.Int64: stringBuffer.Append(*(long*)dataPointer, StringView.Empty); dataPointer += sizeof(long); break; case ArgumentType.Single: stringBuffer.Append(*(float*)dataPointer, StringView.Empty); dataPointer += sizeof(float); break; case ArgumentType.Double: stringBuffer.Append(*(double*)dataPointer, StringView.Empty); dataPointer += sizeof(double); break; case ArgumentType.Decimal: stringBuffer.Append(*(decimal*)dataPointer, StringView.Empty); dataPointer += sizeof(decimal); break; case ArgumentType.Guid: stringBuffer.Append(*(Guid*)dataPointer, StringView.Empty); dataPointer += sizeof(Guid); break; case ArgumentType.DateTime: stringBuffer.Append(*(DateTime*)dataPointer, StringView.Empty); dataPointer += sizeof(DateTime); break; case ArgumentType.TimeSpan: stringBuffer.Append(*(TimeSpan*)dataPointer, StringView.Empty); dataPointer += sizeof(TimeSpan); break; case ArgumentType.FormatString: var formatStringIndex = *dataPointer; dataPointer += sizeof(byte) + sizeof(byte); stringBuffer.Append('"'); stringBuffer.Append(_strings[formatStringIndex]); stringBuffer.Append('"'); break; case ArgumentType.Enum: var enumArg = (EnumArg*)dataPointer; dataPointer += sizeof(EnumArg); enumArg->AppendTo(stringBuffer); break; case ArgumentType.Unmanaged: var unmanagedArgHeader = (UnmanagedArgHeader*)dataPointer; dataPointer += sizeof(UnmanagedArgHeader); unmanagedArgHeader->AppendUnformattedTo(stringBuffer, dataPointer); dataPointer += unmanagedArgHeader->Size; break; case ArgumentType.Null: stringBuffer.Append(LogManager.Config.NullDisplayString); break; default: throw new ArgumentOutOfRangeException(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool PrepareAppend(int requestedBytes, int requestedArgSlots) => _dataPointer + requestedBytes <= _endOfBuffer && _argCount + requestedArgSlots <= _argPointers.Length || PrepareAppendSlow(requestedBytes); [MethodImpl(MethodImplOptions.NoInlining)] private bool PrepareAppendSlow(int requestedBytes) { if (_dataPointer + requestedBytes <= _endOfBuffer && _argumentExhaustionStrategy == LogEventArgumentExhaustionStrategy.Allocate) { var newCapacity = Math.Min(_argPointers.Length * 2, _maxArgCapacity); if (newCapacity > _argPointers.Length) { Array.Resize(ref _argPointers, newCapacity); Array.Resize(ref _strings, newCapacity); return true; } } _isTruncated = true; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendArgumentType(ArgumentType argumentType) { _argPointers[_argCount++] = new IntPtr(_dataPointer); *(ArgumentType*)_dataPointer = argumentType; _dataPointer += sizeof(ArgumentType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [SuppressMessage("ReSharper", "BitwiseOperatorOnEnumWithoutFlags")] private void AppendArgumentTypeWithFormat(ArgumentType argumentType) { _argPointers[_argCount++] = new IntPtr(_dataPointer); *(ArgumentType*)_dataPointer = argumentType | (ArgumentType)ArgumentTypeMask.FormatSpecifier; _dataPointer += sizeof(ArgumentType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendString(string value) { var argIndex = _argCount - 1; *_dataPointer = (byte)argIndex; _dataPointer += sizeof(byte); _strings[argIndex] = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendBytes(byte[] bytes, int length) { UnsafeTools.CopyBlockUnaligned(ref *_dataPointer, ref bytes[0], (uint)length); _dataPointer += length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendBytes(byte* bytes, int length) { UnsafeTools.CopyBlockUnaligned(_dataPointer, bytes, (uint)length); _dataPointer += length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendBytes(ReadOnlySpan<byte> bytes) { bytes.CopyTo(new Span<byte>(_dataPointer, bytes.Length)); _dataPointer += bytes.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendInt32(int i) { *(int*)_dataPointer = i; _dataPointer += sizeof(int); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AppendByte(byte i) { *_dataPointer = i; _dataPointer += sizeof(byte); } public void SetTimestamp(DateTime timestamp) { Timestamp = timestamp; } } }
/* * 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.Data; using MbUnit.Framework; using Northwind; namespace SubSonic.Tests { /// <summary> /// Summary for the ActiveRecordTest class /// </summary> [TestFixture] public class ActiveRecordTest { /// <summary> /// Setups this instance. /// </summary> [SetUp] public void Setup() { Query qry = new Query(Product.Schema); qry.QueryType = QueryType.Delete; qry.AddWhere("productName", Comparison.Like, "Unit Test%"); qry.Execute(); Query qry2 = new Query(Supplier.Schema); qry2.QueryType = QueryType.Delete; qry2.AddWhere("CompanyName", Comparison.Like, "Unit Test%"); qry2.Execute(); } /// <summary> /// Products_s the crud. /// </summary> [Test] [Rollback] public void Products_Crud() { //add a new product Product product = CreateTestProduct(); product.Save(""); //get the new id int newID = product.ProductID; product = new Product(newID); product.ReorderLevel = 100; product.Save("unit test"); //pull it out to confirm product = new Product(newID); Assert.IsTrue(product.ReorderLevel == 100, "Bad Save"); } /// <summary> /// Products_s the null crud. /// </summary> [Test] [Rollback] public void Products_NullCrud() { //add a new product Product product = new Product(); product.CategoryID = 1; product.Discontinued = false; product.ProductName = "Unit Test Product"; product.QuantityPerUnit = null; product.ReorderLevel = null; product.SupplierID = null; product.UnitPrice = null; product.UnitsInStock = null; product.UnitsOnOrder = null; product.Save(""); //get the new id int newID = product.ProductID; product = new Product(newID); product.ReorderLevel = 100; product.Save("unit test"); //pull it out to confirm product = new Product(newID); Assert.IsTrue(product.ReorderLevel == 100, "Bad Save"); Assert.IsTrue(product.SupplierID == null, "Bad Save, Null not inserted"); //delete it ActiveRecord<Product>.Delete(newID); //delete all unit tests Query qry = new Query(Product.Schema); qry.QueryType = QueryType.Delete; qry.AddWhere("productName", "Unit Test Product"); qry.Execute(); } /// <summary> /// Products_s the collection load. /// </summary> [Test] public void Products_CollectionLoad() { ProductCollection coll = new ProductCollection(); using(IDataReader rdr = ReadOnlyRecord<Product>.FetchAll()) { coll.Load(rdr); rdr.Close(); } Assert.IsTrue(coll.Count > 0); } /// <summary> /// Gets the new command. /// </summary> [Test] [Rollback] public void GetNewCommand() { Product p = CreateTestProduct(); Assert.IsTrue(p.IsNew, "Should be New"); Assert.IsTrue(p.GetSaveCommand().CommandSql.Contains("INSERT INTO"), "Should be INSERT Statement"); Assert.AreEqual("Northwind", p.GetSaveCommand().ProviderName, "Provider Name not set"); } /// <summary> /// Gets the update command. /// </summary> [Test] [Rollback] public void GetUpdateCommand() { Product p = CreateTestProduct(); p.Discontinued = true; p.IsNew = false; Assert.IsFalse(p.IsNew, "Should not be New"); Assert.IsTrue(p.IsDirty, "Should be Dirty"); Assert.IsTrue(p.GetSaveCommand().CommandSql.Contains("UPDATE"), "Should be UPDATE Statement"); Assert.AreEqual("Northwind", p.GetSaveCommand().ProviderName, "Provider Name not set"); } /// <summary> /// Gets the no changes command. /// </summary> [Test] [Rollback] public void GetNoChangesCommand() { Product p = CreateTestProduct(); p.Save(); p.IsNew = false; Assert.IsFalse(p.IsNew, "Should not be New"); Assert.IsFalse(p.IsDirty, "Should not be Dirty"); Assert.IsNull(p.GetSaveCommand(), "Should be NULL"); } /// <summary> /// Saves the when not dirty. /// </summary> [Test] [Rollback] public void SaveWhenNotDirty() { Product p = CreateTestProduct(); p.Save(); int id = p.ProductID; p.Discontinued = true; p.ReorderLevel = 2112; p.MarkClean(); Assert.IsFalse(p.IsDirty, "Should NOT be dirty"); p.Save(); p = new Product(id); Assert.AreEqual(false, p.Discontinued, "Should not be false"); Assert.AreEqual(Int16.Parse("3"), p.ReorderLevel, "Should not be set"); } //[Test] //public void TestNewRecordDeepSave() //{ // Supplier s = new Supplier(); // s.CompanyName = "Unit Test Supplier"; // Product p1 = CreateTestProduct(); // Product p2 = CreateTestProduct(); // s.Products().Add(p1); // s.Products().Add(p2); // s.DeepSave(); // Assert.IsNotNull(s.SupplierID, "SupplierID is null"); // Assert.AreEqual(s.SupplierID, p1.SupplierID, "SupplierID not set."); // Assert.AreEqual(s.SupplierID, p2.SupplierID, "SupplierID not set."); //} //[Test] //public void TestExistingRecordDeepSave() //{ // Supplier s = new Supplier(); // s.CompanyName = "Unit Test Supplier"; // s.Save(); // Assert.IsNotNull(s.SupplierID, "SupplierID is null"); // Product p1 = CreateTestProduct(); // Product p2 = CreateTestProduct(); // s.Products.Add(p1); // s.Products.Add(p2); // s.DeepSave(); // Assert.AreEqual(s.SupplierID, p1.SupplierID, "SupplierID not set."); // Assert.AreEqual(s.SupplierID, p2.SupplierID, "SupplierID not set."); //} /// <summary> /// Creates the test product. /// </summary> /// <returns></returns> private static Product CreateTestProduct() { Product product = new Product(); product.CategoryID = 1; product.Discontinued = false; product.ProductName = "Unit Test Product"; product.QuantityPerUnit = "Qty"; product.ReorderLevel = 3; product.SupplierID = 1; product.UnitPrice = 99; product.UnitsInStock = 20; product.UnitsOnOrder = 9; return product; } /// <summary> /// Tests to make sure that our DirtyColumns change is tracking dirty columns properly /// </summary> [Test] public void DirtyColumnsExist() { Product p = new Product(1); //make sure no dirties Assert.IsTrue(p.DirtyColumns.Count == 0); //set the product name to something different p.ProductName = DateTime.Now.ToString(); //see if the dirty col is set right Assert.IsTrue(p.DirtyColumns.Count == 1 && p.DirtyColumns[0].ColumnName == "ProductName"); //p.Save("bbep"); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A moving company. /// </summary> public class MovingCompany_Core : TypeCore, IHomeAndConstructionBusiness { public MovingCompany_Core() { this._TypeId = 172; this._Id = "MovingCompany"; this._Schema_Org_Url = "http://schema.org/MovingCompany"; string label = ""; GetLabel(out label, "MovingCompany", typeof(MovingCompany_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,128}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{128}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// 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 ShuffleHighInt16228() { var test = new ImmUnaryOpTest__ShuffleHighInt16228(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShuffleHighInt16228 { private struct TestStruct { public Vector256<Int16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShuffleHighInt16228 testClass) { var result = Avx2.ShuffleHigh(_fld, 228); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static ImmUnaryOpTest__ShuffleHighInt16228() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmUnaryOpTest__ShuffleHighInt16228() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShuffleHigh( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 228 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShuffleHigh( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 228 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShuffleHigh( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 228 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)228 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)228 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)228 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShuffleHigh( _clsVar, 228 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ShuffleHigh(firstOp, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShuffleHigh(firstOp, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShuffleHigh(firstOp, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShuffleHighInt16228(); var result = Avx2.ShuffleHigh(test._fld, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShuffleHigh(_fld, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShuffleHigh(test._fld, 228); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> firstOp, 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<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, 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<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != firstOp[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShuffleHigh)}<Int16>(Vector256<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; } } } }
//--------------------------------------------------------------------------- // // <copyright file="ElementUtil.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // // History: // 07/16/2003 : BrendanM Ported to WCP // //--------------------------------------------------------------------------- using System; using System.Windows.Threading; using System.Threading; using System.Windows; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows.Automation.Peers; using System.Security; using MS.Win32; using MS.Internal.Media; using System.Runtime.InteropServices; using System.Globalization; using MS.Internal.PresentationCore; // SafeSecurityHelper using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace MS.Internal.Automation { // static class providing utility information for working with WCP elements internal class ElementUtil { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // static class, so use private ctor private ElementUtil() { } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static Visual GetParent( Visual el ) { return VisualTreeHelper.GetParent(el) as Visual; } internal static Visual GetFirstChild( Visual el ) { if (el == null) { return null; } return FindVisibleSibling ( el, 0, true ); } internal static Visual GetLastChild( Visual el ) { if (el == null) { return null; } return FindVisibleSibling ( el, el.InternalVisualChildrenCount - 1, false ); } // Warning: Method is O(N). See FindVisibleSibling function for more information. internal static Visual GetNextSibling( Visual el ) { // To get next/previous sibling, have to find out where we // are in our parent's children collection (ie. our siblings) Visual parent = VisualTreeHelper.GetParent(el) as Visual; // If parent is null, we're at root, so have no siblings if (parent == null) { return null; } return FindVisibleSibling ( parent, el, true /* Next */); } // Warning: Method is O(N). See FindVisibleSibling function for more information. internal static Visual GetPreviousSibling( Visual el ) { // To get next/previous sibling, have to find out where we // are in our parent's children collection (ie. our siblings) Visual parent = VisualTreeHelper.GetParent(el) as Visual; // If parent is null, we're at root, so have no siblings if (parent == null) { return null; } return FindVisibleSibling ( parent, el, false /* Previous */); } internal static Visual GetRoot( Visual el ) { // Keep moving up parent chain till we reach the top... Visual scan = el; for( ; ; ) { Visual test = VisualTreeHelper.GetParent(scan) as Visual; if( test == null ) break; scan = test; } return scan; } // Get bounding rectangle, in coords relative to root (not screen) internal static Rect GetLocalRect( UIElement element ) { // Get top-most visual. Visual parent = GetRoot( element ); // Get the points for the rectangle and transform them. double height = element.RenderSize.Height; double width = element.RenderSize.Width; Rect rect = new Rect(0, 0, width, height); GeneralTransform g = element.TransformToAncestor(parent); return g.TransformBounds(rect); } // Get bounding rectangle, relative to screen internal static Rect GetScreenRect( IntPtr hwnd, UIElement el ) { Rect rc = GetLocalRect( el ); // Map from local to screen coords... NativeMethods.RECT rcWin32 = new NativeMethods.RECT( (int) rc.Left, (int) rc.Top, (int) rc.Right, (int) rc.Bottom ); try { SafeSecurityHelper.TransformLocalRectToScreen(new HandleRef(null, hwnd), ref rcWin32); } catch (System.ComponentModel.Win32Exception) { return Rect.Empty; } rc = new Rect( rcWin32.left, rcWin32.top, rcWin32.right - rcWin32.left, rcWin32.bottom - rcWin32.top ); return rc; } // Get element at given point (screen coords) ///<SecurityNote> /// Critical - accepts critical data. Hwnd was created under an elevation. /// - calls HwndSource.CriticalFromHwnd to get the HwndSource for this visual /// TreatAsSafe - returning an element is considered safe. /// - the hwndSource is not exposed. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe ] internal static Visual GetElementFromPoint( IntPtr hwnd, Visual root, Point pointScreen ) { HwndSource hwndSource = HwndSource.CriticalFromHwnd(hwnd); if(hwndSource == null) return null; Point pointClient = PointUtil.ScreenToClient( pointScreen, hwndSource ); Point pointRoot = PointUtil.ClientToRoot(pointClient, hwndSource); PointHitTestResult result = VisualTreeUtils.AsNearestPointHitTestResult(VisualTreeHelper.HitTest(root, pointRoot)); Visual visual = (result != null) ? result.VisualHit : null; return visual; } // Ensures that an element is enabled; throws exception otherwise //[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647 internal static void CheckEnabled(Visual visual) { UIElement el = visual as UIElement; if( el != null && ! el.IsEnabled ) { throw new ElementNotEnabledException(); } } //[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647 internal static object Invoke(AutomationPeer peer, DispatcherOperationCallback work, object arg) { Dispatcher dispatcher = peer.Dispatcher; // Null dispatcher likely means the visual is in bad shape! if( dispatcher == null ) { throw new ElementNotAvailableException(); } Exception remoteException = null; bool completed = false; object retVal = dispatcher.Invoke( DispatcherPriority.Send, TimeSpan.FromMinutes(3), (DispatcherOperationCallback) delegate(object unused) { try { return work(arg); } catch(Exception e) { remoteException = e; return null; } catch //for non-CLS Compliant exceptions { remoteException = null; return null; } finally { completed = true; } }, null); if(completed) { if(remoteException != null) { throw remoteException; } } else { bool dispatcherInShutdown = dispatcher.HasShutdownStarted; if(dispatcherInShutdown) { throw new InvalidOperationException(SR.Get(SRID.AutomationDispatcherShutdown)); } else { throw new TimeoutException(SR.Get(SRID.AutomationTimeout)); } } return retVal; } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // private static Visual FindVisibleSibling ( Visual parent, int start, bool searchForwards) { int index = start; int childrenCount = parent.InternalVisualChildrenCount; while ( index >= 0 && index < childrenCount ) { Visual sibling = parent.InternalGetVisualChild(index); // if its visible or something other than a UIElement keep it if ( !(sibling is UIElement) || (((UIElement)sibling).Visibility == Visibility.Visible ) ) return sibling; index += searchForwards ? 1 : -1; } return null; } // private static Visual FindVisibleSibling(Visual parent, Visual child, bool searchForwards) { // // First we figure out the index of the specified child Visual. This is why the runtime // of this method is O(n). int childrenCount = parent.InternalVisualChildrenCount; int childIndex; for (childIndex = 0; childIndex < childrenCount; childIndex++) { Visual current = parent.InternalGetVisualChild(childIndex); if (current == child) { // Found the child. break; } } // // Now that we have the child index, we can go and lookup the sibling. if(searchForwards) return FindVisibleSibling(parent, childIndex+1, searchForwards); // (FindVisibleSibling can deal with out of range indices). else return FindVisibleSibling(parent, childIndex-1, searchForwards); // (FindVisibleSibling can deal with out of range indices). } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // static class, so no private fields #endregion Private Fields } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Threading; using log4net; using OpenSim.Framework; using OpenMetaverse; using OpenMetaverse.Packets; using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket; namespace OpenSim.Region.ClientStack.LindenUDP { #region Delegates /// <summary> /// Fired when updated networking stats are produced for this client /// </summary> /// <param name="inPackets">Number of incoming packets received since this /// event was last fired</param> /// <param name="outPackets">Number of outgoing packets sent since this /// event was last fired</param> /// <param name="unAckedBytes">Current total number of bytes in packets we /// are waiting on ACKs for</param> public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes); /// <summary> /// Fired when the queue for one or more packet categories is empty. This /// event can be hooked to put more data on the empty queues /// </summary> /// <param name="category">Categories of the packet queues that are empty</param> public delegate void QueueEmpty(ThrottleOutPacketTypeFlags categories); #endregion Delegates /// <summary> /// Tracks state for a client UDP connection and provides client-specific methods /// </summary> public sealed class LLUDPClient { // TODO: Make this a config setting /// <summary>Percentage of the task throttle category that is allocated to avatar and prim /// state updates</summary> const float STATE_TASK_PERCENTAGE = 0.8f; private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary>The number of packet categories to throttle on. If a throttle category is added /// or removed, this number must also change</summary> const int THROTTLE_CATEGORY_COUNT = 8; /// <summary>Fired when updated networking stats are produced for this client</summary> public event PacketStats OnPacketStats; /// <summary>Fired when the queue for a packet category is empty. This event can be /// hooked to put more data on the empty queue</summary> public event QueueEmpty OnQueueEmpty; /// <summary>AgentID for this client</summary> public readonly UUID AgentID; /// <summary>The remote address of the connected client</summary> public readonly IPEndPoint RemoteEndPoint; /// <summary>Circuit code that this client is connected on</summary> public readonly uint CircuitCode; /// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary> public readonly IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(200); /// <summary>Packets we have sent that need to be ACKed by the client</summary> public readonly UnackedPacketCollection NeedAcks = new UnackedPacketCollection(); /// <summary>ACKs that are queued up, waiting to be sent to the client</summary> public readonly OpenSim.Framework.LocklessQueue<uint> PendingAcks = new OpenSim.Framework.LocklessQueue<uint>(); /// <summary>Current packet sequence number</summary> public int CurrentSequence; /// <summary>Current ping sequence number</summary> public byte CurrentPingSequence; /// <summary>True when this connection is alive, otherwise false</summary> public bool IsConnected = true; /// <summary>True when this connection is paused, otherwise false</summary> public bool IsPaused; /// <summary>Environment.TickCount when the last packet was received for this client</summary> public int TickLastPacketReceived; /// <summary>Smoothed round-trip time. A smoothed average of the round-trip time for sending a /// reliable packet to the client and receiving an ACK</summary> public float SRTT; /// <summary>Round-trip time variance. Measures the consistency of round-trip times</summary> public float RTTVAR; /// <summary>Retransmission timeout. Packets that have not been acknowledged in this number of /// milliseconds or longer will be resent</summary> /// <remarks>Calculated from <seealso cref="SRTT"/> and <seealso cref="RTTVAR"/> using the /// guidelines in RFC 2988</remarks> public int RTO; /// <summary>Number of bytes received since the last acknowledgement was sent out. This is used /// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2)</summary> public int BytesSinceLastACK; /// <summary>Number of packets received from this client</summary> public int PacketsReceived; /// <summary>Number of packets sent to this client</summary> public int PacketsSent; /// <summary>Number of packets resent to this client</summary> public int PacketsResent; /// <summary>Total byte count of unacked packets sent to this client</summary> public int UnackedBytes; /// <summary>Total number of received packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsReceivedReported; /// <summary>Total number of sent packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsSentReported; /// <summary>Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired</summary> private int m_nextOnQueueEmpty = 1; /// <summary>Throttle bucket for this agent's connection</summary> private readonly AdaptiveTokenBucket m_throttleClient; public AdaptiveTokenBucket FlowThrottle { get { return m_throttleClient; } } /// <summary>Throttle bucket for this agent's connection</summary> private readonly TokenBucket m_throttleCategory; /// <summary>Throttle buckets for each packet category</summary> private readonly TokenBucket[] m_throttleCategories; /// <summary>Outgoing queues for throttled packets</summary> private readonly OpenSim.Framework.LocklessQueue<OutgoingPacket>[] m_packetOutboxes = new OpenSim.Framework.LocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT]; /// <summary>A container that can hold one packet for each outbox, used to store /// dequeued packets that are being held for throttling</summary> private readonly OutgoingPacket[] m_nextPackets = new OutgoingPacket[THROTTLE_CATEGORY_COUNT]; /// <summary>A reference to the LLUDPServer that is managing this client</summary> private readonly LLUDPServer m_udpServer; /// <summary>Caches packed throttle information</summary> private byte[] m_packedThrottles; private int m_defaultRTO = 1000; // 1sec is the recommendation in the RFC private int m_maxRTO = 60000; /// <summary> /// Default constructor /// </summary> /// <param name="server">Reference to the UDP server this client is connected to</param> /// <param name="rates">Default throttling rates and maximum throttle limits</param> /// <param name="parentThrottle">Parent HTB (hierarchical token bucket) /// that the child throttles will be governed by</param> /// <param name="circuitCode">Circuit code for this connection</param> /// <param name="agentID">AgentID for the connected agent</param> /// <param name="remoteEndPoint">Remote endpoint for this connection</param> public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO) { AgentID = agentID; RemoteEndPoint = remoteEndPoint; CircuitCode = circuitCode; m_udpServer = server; if (defaultRTO != 0) m_defaultRTO = defaultRTO; if (maxRTO != 0) m_maxRTO = maxRTO; // Create a token bucket throttle for this client that has the scene token bucket as a parent m_throttleClient = new AdaptiveTokenBucket(parentThrottle, rates.Total, rates.AdaptiveThrottlesEnabled); // Create a token bucket throttle for the total categary with the client bucket as a throttle m_throttleCategory = new TokenBucket(m_throttleClient, 0); // Create an array of token buckets for this clients different throttle categories m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT]; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { ThrottleOutPacketType type = (ThrottleOutPacketType)i; // Initialize the packet outboxes, where packets sit while they are waiting for tokens m_packetOutboxes[i] = new OpenSim.Framework.LocklessQueue<OutgoingPacket>(); // Initialize the token buckets that control the throttling for each category m_throttleCategories[i] = new TokenBucket(m_throttleCategory, rates.GetRate(type)); } // Default the retransmission timeout to three seconds RTO = m_defaultRTO; // Initialize this to a sane value to prevent early disconnects TickLastPacketReceived = Environment.TickCount & Int32.MaxValue; } /// <summary> /// Shuts down this client connection /// </summary> public void Shutdown() { IsConnected = false; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { m_packetOutboxes[i].Clear(); m_nextPackets[i] = null; } // pull the throttle out of the scene throttle m_throttleClient.Parent.UnregisterRequest(m_throttleClient); OnPacketStats = null; OnQueueEmpty = null; } /// <summary> /// Gets information about this client connection /// </summary> /// <returns>Information about the client connection</returns> public ClientInfo GetClientInfo() { // TODO: This data structure is wrong in so many ways. Locking and copying the entire lists // of pending and needed ACKs for every client every time some method wants information about // this connection is a recipe for poor performance ClientInfo info = new ClientInfo(); info.pendingAcks = new Dictionary<uint, uint>(); info.needAck = new Dictionary<uint, byte[]>(); info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate; info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate; info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate; info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate; info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate; info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate; info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate; info.totalThrottle = (int)m_throttleCategory.DripRate; return info; } /// <summary> /// Modifies the UDP throttles /// </summary> /// <param name="info">New throttling values</param> public void SetClientInfo(ClientInfo info) { // TODO: Allowing throttles to be manually set from this function seems like a reasonable // idea. On the other hand, letting external code manipulate our ACK accounting is not // going to happen throw new NotImplementedException(); } /// <summary> /// Return statistics information about client packet queues. /// </summary> /// /// FIXME: This should really be done in a more sensible manner rather than sending back a formatted string. /// /// <returns></returns> public string GetStats() { return string.Format( "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}", PacketsReceived, PacketsSent, PacketsResent, UnackedBytes, m_packetOutboxes[(int)ThrottleOutPacketType.Resend].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Land].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Wind].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Cloud].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Task].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Texture].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Asset].Count, m_packetOutboxes[(int)ThrottleOutPacketType.State].Count); } public void SendPacketStats() { PacketStats callback = OnPacketStats; if (callback != null) { int newPacketsReceived = PacketsReceived - m_packetsReceivedReported; int newPacketsSent = PacketsSent - m_packetsSentReported; callback(newPacketsReceived, newPacketsSent, UnackedBytes); m_packetsReceivedReported += newPacketsReceived; m_packetsSentReported += newPacketsSent; } } public void SetThrottles(byte[] throttleData) { byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7 * 4]; Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i * 4, 4); adjData = newData; } else { adjData = throttleData; } // 0.125f converts from bits to bytes int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // State is a subcategory of task that we allocate a percentage to int state = 0; // Make sure none of the throttles are set below our packet MTU, // otherwise a throttle could become permanently clogged resend = Math.Max(resend, LLUDPServer.MTU); land = Math.Max(land, LLUDPServer.MTU); wind = Math.Max(wind, LLUDPServer.MTU); cloud = Math.Max(cloud, LLUDPServer.MTU); task = Math.Max(task, LLUDPServer.MTU); texture = Math.Max(texture, LLUDPServer.MTU); asset = Math.Max(asset, LLUDPServer.MTU); //int total = resend + land + wind + cloud + task + texture + asset; //m_log.DebugFormat("[LLUDPCLIENT]: {0} is setting throttles. Resend={1}, Land={2}, Wind={3}, Cloud={4}, Task={5}, Texture={6}, Asset={7}, Total={8}", // AgentID, resend, land, wind, cloud, task, texture, asset, total); // Update the token buckets with new throttle values TokenBucket bucket; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend]; bucket.RequestedDripRate = resend; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land]; bucket.RequestedDripRate = land; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind]; bucket.RequestedDripRate = wind; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud]; bucket.RequestedDripRate = cloud; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset]; bucket.RequestedDripRate = asset; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task]; bucket.RequestedDripRate = task; bucket = m_throttleCategories[(int)ThrottleOutPacketType.State]; bucket.RequestedDripRate = state; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture]; bucket.RequestedDripRate = texture; // Reset the packed throttles cached data m_packedThrottles = null; } public byte[] GetThrottlesPacked(float multiplier) { byte[] data = m_packedThrottles; if (data == null) { float rate; data = new byte[7 * 4]; int i = 0; // multiply by 8 to convert bytes back to bits rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate * 8 * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; m_packedThrottles = data; } return data; } /// <summary> /// Queue an outgoing packet if appropriate. /// </summary> /// <param name="packet"></param> /// <param name="forceQueue">Always queue the packet if at all possible.</param> /// <returns> /// true if the packet has been queued, /// false if the packet has not been queued and should be sent immediately. /// </returns> public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue) { int category = (int)packet.Category; if (category >= 0 && category < m_packetOutboxes.Length) { OpenSim.Framework.LocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category]; TokenBucket bucket = m_throttleCategories[category]; // Don't send this packet if there is already a packet waiting in the queue // even if we have the tokens to send it, tokens should go to the already // queued packets if (queue.Count > 0) { queue.Enqueue(packet); return true; } if (!forceQueue && bucket.RemoveTokens(packet.Buffer.DataLength)) { // Enough tokens were removed from the bucket, the packet will not be queued return false; } else { // Force queue specified or not enough tokens in the bucket, queue this packet queue.Enqueue(packet); return true; } } else { // We don't have a token bucket for this category, so it will not be queued return false; } } /// <summary> /// Loops through all of the packet queues for this client and tries to send /// an outgoing packet from each, obeying the throttling bucket limits /// </summary> /// /// <remarks> /// Packet queues are inspected in ascending numerical order starting from 0. Therefore, queues with a lower /// ThrottleOutPacketType number will see their packet get sent first (e.g. if both Land and Wind queues have /// packets, then the packet at the front of the Land queue will be sent before the packet at the front of the /// wind queue). /// /// This function is only called from a synchronous loop in the /// UDPServer so we don't need to bother making this thread safe /// </remarks> /// /// <returns>True if any packets were sent, otherwise false</returns> public bool DequeueOutgoing() { OutgoingPacket packet; OpenSim.Framework.LocklessQueue<OutgoingPacket> queue; TokenBucket bucket; bool packetSent = false; ThrottleOutPacketTypeFlags emptyCategories = 0; //string queueDebugOutput = String.Empty; // Serious debug business for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { bucket = m_throttleCategories[i]; //queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business if (m_nextPackets[i] != null) { // This bucket was empty the last time we tried to send a packet, // leaving a dequeued packet still waiting to be sent out. Try to // send it again OutgoingPacket nextPacket = m_nextPackets[i]; if (bucket.RemoveTokens(nextPacket.Buffer.DataLength)) { // Send the packet m_udpServer.SendPacketFinal(nextPacket); m_nextPackets[i] = null; packetSent = true; } } else { // No dequeued packet waiting to be sent, try to pull one off // this queue queue = m_packetOutboxes[i]; if (queue.Dequeue(out packet)) { // A packet was pulled off the queue. See if we have // enough tokens in the bucket to send it out if (bucket.RemoveTokens(packet.Buffer.DataLength)) { // Send the packet m_udpServer.SendPacketFinal(packet); packetSent = true; } else { // Save the dequeued packet for the next iteration m_nextPackets[i] = packet; } // If the queue is empty after this dequeue, fire the queue // empty callback now so it has a chance to fill before we // get back here if (queue.Count == 0) emptyCategories |= CategoryToFlag(i); } else { // No packets in this queue. Fire the queue empty callback // if it has not been called recently emptyCategories |= CategoryToFlag(i); } } } if (emptyCategories != 0) BeginFireQueueEmpty(emptyCategories); //m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business return packetSent; } /// <summary> /// Called when an ACK packet is received and a round-trip time for a /// packet is calculated. This is used to calculate the smoothed /// round-trip time, round trip time variance, and finally the /// retransmission timeout /// </summary> /// <param name="r">Round-trip time of a single packet and its /// acknowledgement</param> public void UpdateRoundTrip(float r) { const float ALPHA = 0.125f; const float BETA = 0.25f; const float K = 4.0f; if (RTTVAR == 0.0f) { // First RTT measurement SRTT = r; RTTVAR = r * 0.5f; } else { // Subsequence RTT measurement RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r); SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r; } int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR)); // Clamp the retransmission timeout to manageable values rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO); RTO = rto; //m_log.Debug("[LLUDPCLIENT]: Setting agent " + this.Agent.FullName + "'s RTO to " + RTO + "ms with an RTTVAR of " + // RTTVAR + " based on new RTT of " + r + "ms"); } /// <summary> /// Exponential backoff of the retransmission timeout, per section 5.5 /// of RFC 2988 /// </summary> public void BackoffRTO() { // Reset SRTT and RTTVAR, we assume they are bogus since things // didn't work out and we're backing off the timeout SRTT = 0.0f; RTTVAR = 0.0f; // Double the retransmission timeout RTO = Math.Min(RTO * 2, m_maxRTO); } /// <summary> /// Does an early check to see if this queue empty callback is already /// running, then asynchronously firing the event /// </summary> /// <param name="throttleIndex">Throttle category to fire the callback /// for</param> private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories) { if (m_nextOnQueueEmpty != 0 && (Environment.TickCount & Int32.MaxValue) >= m_nextOnQueueEmpty) { // Use a value of 0 to signal that FireQueueEmpty is running m_nextOnQueueEmpty = 0; // Asynchronously run the callback Util.FireAndForget(FireQueueEmpty, categories); } } /// <summary> /// Fires the OnQueueEmpty callback and sets the minimum time that it /// can be called again /// </summary> /// <param name="o">Throttle categories to fire the callback for, /// stored as an object to match the WaitCallback delegate /// signature</param> private void FireQueueEmpty(object o) { const int MIN_CALLBACK_MS = 30; ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o; QueueEmpty callback = OnQueueEmpty; int start = Environment.TickCount & Int32.MaxValue; if (callback != null) { try { callback(categories); } catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); } } m_nextOnQueueEmpty = start + MIN_CALLBACK_MS; if (m_nextOnQueueEmpty == 0) m_nextOnQueueEmpty = 1; } /// <summary> /// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a /// flag value /// </summary> /// <param name="i">Throttle category to convert</param> /// <returns>Flag representation of the throttle category</returns> private static ThrottleOutPacketTypeFlags CategoryToFlag(int i) { ThrottleOutPacketType category = (ThrottleOutPacketType)i; /* * Land = 1, /// <summary>Wind data</summary> Wind = 2, /// <summary>Cloud data</summary> Cloud = 3, /// <summary>Any packets that do not fit into the other throttles</summary> Task = 4, /// <summary>Texture assets</summary> Texture = 5, /// <summary>Non-texture assets</summary> Asset = 6, /// <summary>Avatar and primitive data</summary> /// <remarks>This is a sub-category of Task</remarks> State = 7, */ switch (category) { case ThrottleOutPacketType.Land: return ThrottleOutPacketTypeFlags.Land; case ThrottleOutPacketType.Wind: return ThrottleOutPacketTypeFlags.Wind; case ThrottleOutPacketType.Cloud: return ThrottleOutPacketTypeFlags.Cloud; case ThrottleOutPacketType.Task: return ThrottleOutPacketTypeFlags.Task; case ThrottleOutPacketType.Texture: return ThrottleOutPacketTypeFlags.Texture; case ThrottleOutPacketType.Asset: return ThrottleOutPacketTypeFlags.Asset; case ThrottleOutPacketType.State: return ThrottleOutPacketTypeFlags.State; default: return 0; } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal partial class ImplementInterfaceCodeAction : CodeAction { protected readonly bool Explicitly; protected readonly bool Abstractly; protected readonly ISymbol ThroughMember; protected readonly Document Document; protected readonly State State; protected readonly AbstractImplementInterfaceService Service; private readonly string _equivalenceKey; internal ImplementInterfaceCodeAction( AbstractImplementInterfaceService service, Document document, State state, bool explicitly, bool abstractly, ISymbol throughMember) { this.Service = service; this.Document = document; this.State = state; this.Abstractly = abstractly; this.Explicitly = explicitly; this.ThroughMember = throughMember; _equivalenceKey = ComputeEquivalenceKey(state, explicitly, abstractly, throughMember, this.GetType().FullName); } public static ImplementInterfaceCodeAction CreateImplementAbstractlyCodeAction( AbstractImplementInterfaceService service, Document document, State state) { return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: true, throughMember: null); } public static ImplementInterfaceCodeAction CreateImplementCodeAction( AbstractImplementInterfaceService service, Document document, State state) { return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null); } public static ImplementInterfaceCodeAction CreateImplementExplicitlyCodeAction( AbstractImplementInterfaceService service, Document document, State state) { return new ImplementInterfaceCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null); } public static ImplementInterfaceCodeAction CreateImplementThroughMemberCodeAction( AbstractImplementInterfaceService service, Document document, State state, ISymbol throughMember) { return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: throughMember); } public override string Title { get { if (Explicitly) { return FeaturesResources.Implement_interface_explicitly; } else if (Abstractly) { return FeaturesResources.Implement_interface_abstractly; } else if (ThroughMember != null) { return string.Format(FeaturesResources.Implement_interface_through_0, GetDescription(ThroughMember)); } else { return FeaturesResources.Implement_interface; } } } private static string ComputeEquivalenceKey( State state, bool explicitly, bool abstractly, ISymbol throughMember, string codeActionTypeName) { var interfaceType = state.InterfaceTypes.First(); var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); var assemblyName = interfaceType.ContainingAssembly.Name; return GetCodeActionEquivalenceKey(assemblyName, typeName, explicitly, abstractly, throughMember, codeActionTypeName); } // internal for testing purposes. internal static string GetCodeActionEquivalenceKey( string interfaceTypeAssemblyName, string interfaceTypeFullyQualifiedName, bool explicitly, bool abstractly, ISymbol throughMember, string codeActionTypeName) { if (throughMember != null) { return null; } return explicitly.ToString() + ";" + abstractly.ToString() + ";" + interfaceTypeAssemblyName + ";" + interfaceTypeFullyQualifiedName + ";" + codeActionTypeName; } public override string EquivalenceKey => _equivalenceKey; private static string GetDescription(ISymbol throughMember) { switch (throughMember) { case IFieldSymbol field: return field.Name; case IPropertySymbol property: return property.Name; default: throw new InvalidOperationException(); } } protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { return GetUpdatedDocumentAsync(cancellationToken); } public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToken) { var unimplementedMembers = Explicitly ? State.UnimplementedExplicitMembers : State.UnimplementedMembers; return GetUpdatedDocumentAsync(Document, unimplementedMembers, State.ClassOrStructType, State.ClassOrStructDecl, cancellationToken); } public virtual async Task<Document> GetUpdatedDocumentAsync( Document document, ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> unimplementedMembers, INamedTypeSymbol classOrStructType, SyntaxNode classOrStructDecl, CancellationToken cancellationToken) { var result = document; var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var isComImport = unimplementedMembers.Any(t => t.Item1.IsComImport); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var propertyGenerationBehavior = options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior); var memberDefinitions = GenerateMembers( compilation, unimplementedMembers, propertyGenerationBehavior, cancellationToken); // Only group the members in the destination if the user wants that *and* // it's not a ComImport interface. Member ordering in ComImport interfaces // matters, so we don't want to much with them. var insertionBehavior = options.GetOption(ImplementTypeOptions.InsertionBehavior); var groupMembers = !isComImport && insertionBehavior == ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind; result = await CodeGenerator.AddMemberDeclarationsAsync( result.Project.Solution, classOrStructType, memberDefinitions, new CodeGenerationOptions( contextLocation: classOrStructDecl.GetLocation(), autoInsertionLocation: groupMembers, sortMembers: groupMembers), cancellationToken).ConfigureAwait(false); return result; } private ImmutableArray<ISymbol> GenerateMembers( Compilation compilation, ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> unimplementedMembers, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { // As we go along generating members we may end up with conflicts. For example, say // you have "interface IFoo { string Bar { get; } }" and "interface IQuux { int Bar // { get; } }" and we need to implement both 'Bar' methods. The second will have to // be explicitly implemented as it will conflict with the first. So we need to keep // track of what we've actually implemented so that we can check further interface // members against both the actual type and that list. // // Similarly, if you have two interfaces with the same member, then we don't want to // implement that member twice. // // Note: if we implement a method explicitly then we do *not* add it to this list. // That's because later members won't conflict with it even if they have the same // signature otherwise. i.e. if we chose to implement IFoo.Bar explicitly, then we // could implement IQuux.Bar implicitly (and vice versa). var implementedVisibleMembers = new List<ISymbol>(); var implementedMembers = ArrayBuilder<ISymbol>.GetInstance(); foreach (var tuple in unimplementedMembers) { var interfaceType = tuple.type; var unimplementedInterfaceMembers = tuple.members; foreach (var unimplementedInterfaceMember in unimplementedInterfaceMembers) { var member = GenerateMember( compilation, unimplementedInterfaceMember, implementedVisibleMembers, propertyGenerationBehavior, cancellationToken); if (member != null) { implementedMembers.Add(member); if (!(member.ExplicitInterfaceImplementations().Any() && Service.HasHiddenExplicitImplementation)) { implementedVisibleMembers.Add(member); } } } } return implementedMembers.ToImmutableAndFree(); } private bool IsReservedName(string name) { return IdentifiersMatch(State.ClassOrStructType.Name, name) || State.ClassOrStructType.TypeParameters.Any(t => IdentifiersMatch(t.Name, name)); } private string DetermineMemberName(ISymbol member, List<ISymbol> implementedVisibleMembers) { if (HasConflictingMember(member, implementedVisibleMembers)) { var memberNames = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Select(m => m.Name); return NameGenerator.GenerateUniqueName( string.Format("{0}_{1}", member.ContainingType.Name, member.Name), n => !memberNames.Contains(n) && !implementedVisibleMembers.Any(m => IdentifiersMatch(m.Name, n)) && !IsReservedName(n)); } return member.Name; } private ISymbol GenerateMember( Compilation compilation, ISymbol member, List<ISymbol> implementedVisibleMembers, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { // First check if we already generate a member that matches the member we want to // generate. This can happen in C# when you have interfaces that have the same // method, and you are implementing implicitly. For example: // // interface IFoo { void Foo(); } // // interface IBar : IFoo { new void Foo(); } // // class C : IBar // // In this case we only want to generate 'Foo' once. if (HasMatchingMember(implementedVisibleMembers, member)) { return null; } var memberName = DetermineMemberName(member, implementedVisibleMembers); // See if we need to generate an invisible member. If we do, then reset the name // back to what then member wants it to be. var generateInvisibleMember = GenerateInvisibleMember(member, memberName); memberName = generateInvisibleMember ? member.Name : memberName; var generateAbstractly = !generateInvisibleMember && Abstractly; // Check if we need to add 'new' to the signature we're adding. We only need to do this // if we're not generating something explicit and we have a naming conflict with // something in our base class hierarchy. var addNew = !generateInvisibleMember && HasNameConflict(member, memberName, State.ClassOrStructType.GetBaseTypes()); // Check if we need to add 'unsafe' to the signature we're generating. var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>(); var addUnsafe = member.IsUnsafe() && !syntaxFacts.IsUnsafeContext(State.Location); return GenerateMember( compilation, member, memberName, generateInvisibleMember, generateAbstractly, addNew, addUnsafe, propertyGenerationBehavior, cancellationToken); } private bool GenerateInvisibleMember(ISymbol member, string memberName) { if (Service.HasHiddenExplicitImplementation) { // User asked for an explicit (i.e. invisible) member. if (Explicitly) { return true; } // Have to create an invisible member if we have constraints we can't express // with a visible member. if (HasUnexpressibleConstraint(member)) { return true; } // If we had a conflict with a member of the same name, then we have to generate // as an invisible member. if (member.Name != memberName) { return true; } } // Can't generate an invisible member if the language doesn't support it. return false; } private bool HasUnexpressibleConstraint(ISymbol member) { // interface IFoo<T> { void Bar<U>() where U : T; } // // class A : IFoo<int> { } // // In this case we cannot generate an implement method for Bar. That's because we'd // need to say "where U : int" and that's disallowed by the language. So we must // generate something explicit here. if (member.Kind != SymbolKind.Method) { return false; } var method = member as IMethodSymbol; return method.TypeParameters.Any(IsUnexpressibleTypeParameter); } private static bool IsUnexpressibleTypeParameter(ITypeParameterSymbol typeParameter) { var condition1 = typeParameter.ConstraintTypes.Count(t => t.TypeKind == TypeKind.Class) >= 2; var condition2 = typeParameter.ConstraintTypes.Any(ts => ts.IsUnexpressibleTypeParameterConstraint()); var condition3 = typeParameter.HasReferenceTypeConstraint && typeParameter.ConstraintTypes.Any(ts => ts.IsReferenceType && ts.SpecialType != SpecialType.System_Object); return condition1 || condition2 || condition3; } private ISymbol GenerateMember( Compilation compilation, ISymbol member, string memberName, bool generateInvisibly, bool generateAbstractly, bool addNew, bool addUnsafe, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { var factory = this.Document.GetLanguageService<SyntaxGenerator>(); var modifiers = new DeclarationModifiers(isAbstract: generateAbstractly, isNew: addNew, isUnsafe: addUnsafe); var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly; var accessibility = member.Name == memberName || generateAbstractly ? Accessibility.Public : Accessibility.Private; switch (member) { case IMethodSymbol method: return GenerateMethod(compilation, method, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken); case IPropertySymbol property: return GenerateProperty(compilation, property, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, propertyGenerationBehavior, cancellationToken); case IEventSymbol @event: var accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, statements: factory.CreateThrowNotImplementedStatementBlock(compilation)); return CodeGenerationSymbolFactory.CreateEventSymbol( @event, accessibility: accessibility, modifiers: modifiers, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(@event) : default, name: memberName, addMethod: GetAddOrRemoveMethod(generateInvisibly, accessor, memberName, factory.AddEventHandler), removeMethod: GetAddOrRemoveMethod(generateInvisibly, accessor, memberName, factory.RemoveEventHandler)); } return null; } private IMethodSymbol GetAddOrRemoveMethod(bool generateInvisibly, IMethodSymbol accessor, string memberName, Func<SyntaxNode, SyntaxNode, SyntaxNode> createAddOrRemoveHandler) { if (ThroughMember != null) { var factory = Document.GetLanguageService<SyntaxGenerator>(); var throughExpression = CreateThroughExpression(factory); var statement = factory.ExpressionStatement(createAddOrRemoveHandler( factory.MemberAccessExpression(throughExpression, memberName), factory.IdentifierName("value"))); return CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, statements: ImmutableArray.Create(statement)); } return generateInvisibly ? accessor : null; } private SyntaxNode CreateThroughExpression(SyntaxGenerator generator) { var through = ThroughMember.IsStatic ? GenerateName(generator, State.ClassOrStructType.IsGenericType) : generator.ThisExpression(); through = generator.MemberAccessExpression( through, generator.IdentifierName(ThroughMember.Name)); var throughMemberType = ThroughMember.GetMemberType(); if ((State.InterfaceTypes != null) && (throughMemberType != null)) { // In the case of 'implement interface through field / property' , we need to know what // interface we are implementing so that we can insert casts to this interface on every // usage of the field in the generated code. Without these casts we would end up generating // code that fails compilation in certain situations. // // For example consider the following code. // class C : IReadOnlyList<int> { int[] field; } // When applying the 'implement interface through field' code fix in the above example, // we need to generate the following code to implement the Count property on IReadOnlyList<int> // class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...} // as opposed to the following code which will fail to compile (because the array field // doesn't have a property named .Count) - // class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...} // // The 'InterfaceTypes' property on the state object always contains only one item // in the case of C# i.e. it will contain exactly the interface we are trying to implement. // This is also the case most of the time in the case of VB, except in certain error conditions // (recursive / circular cases) where the span of the squiggle for the corresponding // diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces // in the Implements clause. For the purposes of inserting the above cast, we ignore the // uncommon case and optimize for the common one - in other words, we only apply the cast // in cases where we can unambiguously figure out which interface we are trying to implement. var interfaceBeingImplemented = State.InterfaceTypes.SingleOrDefault(); if (interfaceBeingImplemented != null) { if (!throughMemberType.Equals(interfaceBeingImplemented)) { through = generator.CastExpression(interfaceBeingImplemented, through.WithAdditionalAnnotations(Simplifier.Annotation)); } else if (!ThroughMember.IsStatic && ThroughMember is IPropertySymbol throughMemberProperty && throughMemberProperty.ExplicitInterfaceImplementations.Any()) { // If we are implementing through an explicitly implemented property, we need to cast 'this' to // the explicitly implemented interface type before calling the member, as in: // ((IA)this).Prop.Member(); // var explicitlyImplementedProperty = throughMemberProperty.ExplicitInterfaceImplementations[0]; var explicitImplementationCast = generator.CastExpression( explicitlyImplementedProperty.ContainingType, generator.ThisExpression()); through = generator.MemberAccessExpression(explicitImplementationCast, generator.IdentifierName(explicitlyImplementedProperty.Name)); through = through.WithAdditionalAnnotations(Simplifier.Annotation); } } } return through.WithAdditionalAnnotations(Simplifier.Annotation); } private SyntaxNode GenerateName(SyntaxGenerator factory, bool isGenericType) { return isGenericType ? factory.GenericName(State.ClassOrStructType.Name, State.ClassOrStructType.TypeArguments) : factory.IdentifierName(State.ClassOrStructType.Name); } private bool HasNameConflict( ISymbol member, string memberName, IEnumerable<INamedTypeSymbol> baseTypes) { // There's a naming conflict if any member in the base types chain is accessible to // us, has our name. Note: a simple name won't conflict with a generic name (and // vice versa). A method only conflicts with another method if they have the same // parameter signature (return type is irrelevant). return baseTypes.Any(ts => ts.GetMembers(memberName) .Where(m => m.IsAccessibleWithin(State.ClassOrStructType)) .Any(m => HasNameConflict(member, memberName, m))); } private static bool HasNameConflict( ISymbol member, string memberName, ISymbol baseMember) { Contract.Requires(memberName == baseMember.Name); if (member.Kind == SymbolKind.Method && baseMember.Kind == SymbolKind.Method) { // A method only conflicts with another method if they have the same parameter // signature (return type is irrelevant). var method1 = (IMethodSymbol)member; var method2 = (IMethodSymbol)baseMember; if (method1.MethodKind == MethodKind.Ordinary && method2.MethodKind == MethodKind.Ordinary && method1.TypeParameters.Length == method2.TypeParameters.Length) { return method1.Parameters.Select(p => p.Type) .SequenceEqual(method2.Parameters.Select(p => p.Type)); } } // Any non method members with the same name simple name conflict. return true; } private bool IdentifiersMatch(string identifier1, string identifier2) { return this.IsCaseSensitive ? identifier1 == identifier2 : StringComparer.OrdinalIgnoreCase.Equals(identifier1, identifier2); } private bool IsCaseSensitive { get { return this.Document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive; } } private bool HasMatchingMember(List<ISymbol> implementedVisibleMembers, ISymbol member) { // If this is a language that doesn't support implicit implementation then no // implemented members will ever match. For example, if you have: // // Interface IFoo : sub Foo() : End Interface // // Interface IBar : Inherits IFoo : Shadows Sub Foo() : End Interface // // Class C : Implements IBar // // We'll first end up generating: // // Public Sub Foo() Implements IFoo.Foo // // However, that same method won't be viable for IBar.Foo (unlike C#) because it // explicitly specifies its interface). if (!Service.CanImplementImplicitly) { return false; } return implementedVisibleMembers.Any(m => MembersMatch(m, member)); } private bool MembersMatch(ISymbol member1, ISymbol member2) { if (member1.Kind != member2.Kind) { return false; } if (member1.DeclaredAccessibility != member2.DeclaredAccessibility || member1.IsStatic != member2.IsStatic) { return false; } if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any()) { return false; } return SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors( member1, member2, this.IsCaseSensitive); } } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // A spin lock is a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop ("spins") // repeatedly checking until the lock becomes available. As the thread remains active performing a non-useful task, // the use of such a lock is a kind of busy waiting and consumes CPU resources without performing real work. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading { /// <summary> /// Provides a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop /// repeatedly checking until the lock becomes available. /// </summary> /// <remarks> /// <para> /// Spin locks can be used for leaf-level locks where the object allocation implied by using a <see /// cref="System.Threading.Monitor"/>, in size or due to garbage collection pressure, is overly /// expensive. Avoiding blocking is another reason that a spin lock can be useful, however if you expect /// any significant amount of blocking, you are probably best not using spin locks due to excessive /// spinning. Spinning can be beneficial when locks are fine grained and large in number (for example, a /// lock per node in a linked list) as well as when lock hold times are always extremely short. In /// general, while holding a spin lock, one should avoid blocking, calling anything that itself may /// block, holding more than one spin lock at once, making dynamically dispatched calls (interface and /// virtuals), making statically dispatched calls into any code one doesn't own, or allocating memory. /// </para> /// <para> /// <see cref="SpinLock"/> should only be used when it's been determined that doing so will improve an /// application's performance. It's also important to note that <see cref="SpinLock"/> is a value type, /// for performance reasons. As such, one must be very careful not to accidentally copy a SpinLock /// instance, as the two instances (the original and the copy) would then be completely independent of /// one another, which would likely lead to erroneous behavior of the application. If a SpinLock instance /// must be passed around, it should be passed by reference rather than by value. /// </para> /// <para> /// Do not store <see cref="SpinLock"/> instances in readonly fields. /// </para> /// <para> /// All members of <see cref="SpinLock"/> are thread-safe and may be used from multiple threads /// concurrently. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] public struct SpinLock { // The current ownership state is a single signed int. There are two modes: // // 1) Ownership tracking enabled: the high bit is 0, and the remaining bits // store the managed thread ID of the current owner. When the 31 low bits // are 0, the lock is available. // 2) Performance mode: when the high bit is 1, lock availability is indicated by the low bit. // When the low bit is 1 -- the lock is held; 0 -- the lock is available. // // There are several masks and constants below for convenience. private volatile int _owner; // After how many yields, call Sleep(1) private const int SLEEP_ONE_FREQUENCY = 40; // After how many yields, check the timeout private const int TIMEOUT_CHECK_FREQUENCY = 10; // Thr thread tracking disabled mask private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000 //the lock is held by some thread, but we don't know which private const int LOCK_ANONYMOUS_OWNED = 0x1; // 0000 0000 0000 0000 0000 0000 0000 0001 // Waiters mask if the thread tracking is disabled private const int WAITERS_MASK = ~(LOCK_ID_DISABLE_MASK | 1); // 0111 1111 1111 1111 1111 1111 1111 1110 // The Thread tacking is disabled and the lock bit is set, used in Enter fast path to make sure the id is disabled and lock is available private const int ID_DISABLED_AND_ANONYMOUS_OWNED = unchecked((int)0x80000001); // 1000 0000 0000 0000 0000 0000 0000 0001 // If the thread is unowned if: // m_owner zero and the thread tracking is enabled // m_owner & LOCK_ANONYMOUS_OWNED = zero and the thread tracking is disabled private const int LOCK_UNOWNED = 0; // The maximum number of waiters (only used if the thread tracking is disabled) // The actual maximum waiters count is this number divided by two because each waiter increments the waiters count by 2 // The waiters count is calculated by m_owner & WAITERS_MASK 01111....110 private static int MAXIMUM_WAITERS = WAITERS_MASK; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareExchange(ref int location, int value, int comparand, ref bool success) { int result = Interlocked.CompareExchange(ref location, value, comparand); success = (result == comparand); return result; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/> /// structure with the option to track thread IDs to improve debugging. /// </summary> /// <remarks> /// The default constructor for <see cref="SpinLock"/> tracks thread ownership. /// </remarks> /// <param name="enableThreadOwnerTracking">Whether to capture and use thread IDs for debugging /// purposes.</param> public SpinLock(bool enableThreadOwnerTracking) { _owner = LOCK_UNOWNED; if (!enableThreadOwnerTracking) { _owner |= LOCK_ID_DISABLE_MASK; Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now"); } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/> /// structure with the option to track thread IDs to improve debugging. /// </summary> /// <remarks> /// The default constructor for <see cref="SpinLock"/> tracks thread ownership. /// </remarks> /// <summary> /// Acquires the lock in a reliable manner, such that even if an exception occurs within the method /// call, <paramref name="lockTaken"/> can be examined reliably to determine whether the lock was /// acquired. /// </summary> /// <remarks> /// <see cref="SpinLock"/> is a non-reentrant lock, meaning that if a thread holds the lock, it is /// not allowed to enter the lock again. If thread ownership tracking is enabled (whether it's /// enabled is available through <see cref="IsThreadOwnerTrackingEnabled"/>), an exception will be /// thrown when a thread tries to re-enter a lock it already holds. However, if thread ownership /// tracking is disabled, attempting to enter a lock already held will result in deadlock. /// </remarks> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="T:System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling Enter. /// </exception> public void Enter(ref bool lockTaken) { // Try to keep the code and branching in this method as small as possible in order to inline the method int observedOwner = _owner; if (lockTaken || // invalid parameter (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block waiting for the lock to be available. If the /// lock is not available when TryEnter is called, it will return immediately without any further /// spinning. /// </remarks> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="T:System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> public void TryEnter(ref bool lockTaken) { int observedOwner = _owner; if (((observedOwner & LOCK_ID_DISABLE_MASK) == 0) | lockTaken) { // Thread tracking enabled or invalid arg. Take slow path. ContinueTryEnter(0, ref lockTaken); } else if ((observedOwner & LOCK_ANONYMOUS_OWNED) != 0) { // Lock already held by someone lockTaken = false; } else { // Lock wasn't held; try to acquire it. CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken); } } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be /// available. It will block until either the lock is available or until the <paramref /// name="timeout"/> /// has expired. /// </remarks> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="T:System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/> milliseconds. /// </exception> public void TryEnter(TimeSpan timeout, ref bool lockTaken) { // Validate the timeout long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } // Call reliable enter with the int-based timeout milliseconds TryEnter((int)timeout.TotalMilliseconds, ref lockTaken); } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be /// available. It will block until either the lock is available or until the <paramref /// name="millisecondsTimeout"/> has expired. /// </remarks> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="T:System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is /// a negative number other than -1, which represents an infinite time-out.</exception> public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { int observedOwner = _owner; if (millisecondsTimeout < -1 || //invalid parameter lockTaken || //invalid parameter (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth } /// <summary> /// Try acquire the lock with long path, this is usually called after the first path in Enter and /// TryEnter failed The reason for short path is to make it inline in the run time which improves the /// performance. This method assumed that the parameter are validated in Enter or TryEnter method. /// </summary> /// <param name="millisecondsTimeout">The timeout milliseconds</param> /// <param name="lockTaken">The lockTaken param</param> private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken) { // The fast path doesn't throw any exception, so we have to validate the parameters here if (lockTaken) { lockTaken = false; throw new ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } uint startTime = 0; if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout != 0) { startTime = TimeoutHelper.GetTime(); } if (IsThreadOwnerTrackingEnabled) { // Slow path for enabled thread tracking mode ContinueTryEnterWithThreadTracking(millisecondsTimeout, startTime, ref lockTaken); return; } // then thread tracking is disabled // In this case there are three ways to acquire the lock // 1- the first way the thread either tries to get the lock if it's free or updates the waiters, if the turn >= the processors count then go to 3 else go to 2 // 2- In this step the waiter threads spins and tries to acquire the lock, the number of spin iterations and spin count is dependent on the thread turn // the late the thread arrives the more it spins and less frequent it check the lock availability // Also the spins count is increases each iteration // If the spins iterations finished and failed to acquire the lock, go to step 3 // 3- This is the yielding step, there are two ways of yielding Thread.Yield and Sleep(1) // If the timeout is expired in after step 1, we need to decrement the waiters count before returning int observedOwner; int turn = int.MaxValue; //***Step 1, take the lock or update the waiters // try to acquire the lock directly if possible or update the waiters count observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { if (CompareExchange(ref _owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner) { // Acquired lock return; } if (millisecondsTimeout == 0) { // Did not acquire lock in CompareExchange and timeout is 0 so fail fast return; } } else if (millisecondsTimeout == 0) { // Did not acquire lock as owned and timeout is 0 so fail fast return; } else //failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow { if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS) { // This can still overflow, but maybe there will never be that many waiters turn = (Interlocked.Add(ref _owner, 2) & WAITERS_MASK) >> 1; } } // lock acquired failed and waiters updated //*** Step 2, Spinning and Yielding var spinner = new SpinWait(); if (turn > PlatformHelper.ProcessorCount) { spinner.Count = SpinWait.YieldThreshold; } while (true) { spinner.SpinOnce(SLEEP_ONE_FREQUENCY); observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero observedOwner | 1 // don't decrement it. just set the lock bit, it is zero because a previous call of Exit(false) which corrupted the waiters : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit Debug.Assert((newOwner & WAITERS_MASK) >= 0); if (CompareExchange(ref _owner, newOwner, observedOwner, ref lockTaken) == observedOwner) { return; } } if (spinner.Count % TIMEOUT_CHECK_FREQUENCY == 0) { // Check the timeout. if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) { DecrementWaiters(); return; } } } } /// <summary> /// decrements the waiters, in case of the timeout is expired /// </summary> private void DecrementWaiters() { SpinWait spinner = new SpinWait(); while (true) { int observedOwner = _owner; if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false) if (Interlocked.CompareExchange(ref _owner, observedOwner - 2, observedOwner) == observedOwner) { Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped break; } spinner.SpinOnce(); } } /// <summary> /// ContinueTryEnter for the thread tracking mode enabled /// </summary> private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken) { Debug.Assert(IsThreadOwnerTrackingEnabled); int lockUnowned = 0; // We are using thread IDs to mark ownership. Snap the thread ID and check for recursion. // We also must or the ID enablement bit, to ensure we propagate when we CAS it in. int newOwner = Environment.CurrentManagedThreadId; if (_owner == newOwner) { // We don't allow lock recursion. throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException); } SpinWait spinner = new SpinWait(); // Loop until the lock has been successfully acquired or, if specified, the timeout expires. do { // We failed to get the lock, either from the fast route or the last iteration // and the timeout hasn't expired; spin once and try again. spinner.SpinOnce(); // Test before trying to CAS, to avoid acquiring the line exclusively unnecessarily. if (_owner == lockUnowned) { if (CompareExchange(ref _owner, newOwner, lockUnowned, ref lockTaken) == lockUnowned) { return; } } // Check the timeout. We only RDTSC if the next spin will yield, to amortize the cost. if (millisecondsTimeout == 0 || (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)) { return; } } while (true); } /// <summary> /// Releases the lock. /// </summary> /// <remarks> /// The default overload of <see cref="Exit()"/> provides the same behavior as if calling <see /// cref="Exit(bool)"/> using true as the argument, but Exit() could be slightly faster than Exit(true). /// </remarks> /// <exception cref="SynchronizationLockException"> /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. /// </exception> public void Exit() { //This is the fast path for the thread tracking is disabled, otherwise go to the slow path if ((_owner & LOCK_ID_DISABLE_MASK) == 0) ExitSlowPath(true); else Interlocked.Decrement(ref _owner); } /// <summary> /// Releases the lock. /// </summary> /// <param name="useMemoryBarrier"> /// A Boolean value that indicates whether a memory fence should be issued in order to immediately /// publish the exit operation to other threads. /// </param> /// <remarks> /// Calling <see cref="Exit(bool)"/> with the <paramref name="useMemoryBarrier"/> argument set to /// true will improve the fairness of the lock at the expense of some performance. The default <see /// cref="Enter"/> /// overload behaves as if specifying true for <paramref name="useMemoryBarrier"/>. /// </remarks> /// <exception cref="SynchronizationLockException"> /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. /// </exception> public void Exit(bool useMemoryBarrier) { // This is the fast path for the thread tracking is disabled and not to use memory barrier, otherwise go to the slow path // The reason not to add else statement if the usememorybarrier is that it will add more branching in the code and will prevent // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true. int tmpOwner = _owner; if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier) { _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } else { ExitSlowPath(useMemoryBarrier); } } /// <summary> /// The slow path for exit method if the fast path failed /// </summary> /// <param name="useMemoryBarrier"> /// A Boolean value that indicates whether a memory fence should be issued in order to immediately /// publish the exit operation to other threads /// </param> private void ExitSlowPath(bool useMemoryBarrier) { bool threadTrackingEnabled = (_owner & LOCK_ID_DISABLE_MASK) == 0; if (threadTrackingEnabled && !IsHeldByCurrentThread) { throw new SynchronizationLockException(SR.SpinLock_Exit_SynchronizationLockException); } if (useMemoryBarrier) { if (threadTrackingEnabled) { Interlocked.Exchange(ref _owner, LOCK_UNOWNED); } else { Interlocked.Decrement(ref _owner); } } else { if (threadTrackingEnabled) { _owner = LOCK_UNOWNED; } else { int tmpOwner = _owner; _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } } } /// <summary> /// Gets whether the lock is currently held by any thread. /// </summary> public bool IsHeld { get { if (IsThreadOwnerTrackingEnabled) return _owner != LOCK_UNOWNED; return (_owner & LOCK_ANONYMOUS_OWNED) != LOCK_UNOWNED; } } /// <summary> /// Gets whether the lock is currently held by any thread. /// </summary> /// <summary> /// Gets whether the lock is held by the current thread. /// </summary> /// <remarks> /// If the lock was initialized to track owner threads, this will return whether the lock is acquired /// by the current thread. It is invalid to use this property when the lock was initialized to not /// track thread ownership. /// </remarks> /// <exception cref="T:System.InvalidOperationException"> /// Thread ownership tracking is disabled. /// </exception> public bool IsHeldByCurrentThread { get { if (!IsThreadOwnerTrackingEnabled) { throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread); } return ((_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId); } } /// <summary>Gets whether thread ownership tracking is enabled for this instance.</summary> public bool IsThreadOwnerTrackingEnabled => (_owner & LOCK_ID_DISABLE_MASK) == 0; #region Debugger proxy class /// <summary> /// Internal class used by debug type proxy attribute to display the owner thread ID /// </summary> internal class SystemThreading_SpinLockDebugView { // SpinLock object private SpinLock _spinLock; /// <summary> /// SystemThreading_SpinLockDebugView constructor /// </summary> /// <param name="spinLock">The SpinLock to be proxied.</param> public SystemThreading_SpinLockDebugView(SpinLock spinLock) { // Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it. _spinLock = spinLock; } /// <summary> /// Checks if the lock is held by the current thread or not /// </summary> public bool? IsHeldByCurrentThread { get { try { return _spinLock.IsHeldByCurrentThread; } catch (InvalidOperationException) { return null; } } } /// <summary> /// Gets the current owner thread, zero if it is released /// </summary> public int? OwnerThreadID { get { if (_spinLock.IsThreadOwnerTrackingEnabled) { return _spinLock._owner; } else { return null; } } } /// <summary> /// Gets whether the lock is currently held by any thread or not. /// </summary> public bool IsHeld => _spinLock.IsHeld; } #endregion } } #pragma warning restore 0420
// Copyright (c) 2006-2007 Frank Laub // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using OpenSSL.Core; namespace OpenSSL.Crypto { #region MessageDigest /// <summary> /// Wraps the EVP_MD object /// </summary> public class MessageDigest : Base { private EVP_MD raw; /// <summary> /// Creates a EVP_MD struct /// </summary> /// <param name="ptr"></param> /// <param name="owner"></param> internal MessageDigest(IntPtr ptr, bool owner) : base(ptr, owner) { this.raw = (EVP_MD)Marshal.PtrToStructure(this.ptr, typeof(EVP_MD)); } /// <summary> /// Prints MessageDigest /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write("MessageDigest"); } /// <summary> /// Not implemented, these objects should never be disposed. /// </summary> protected override void OnDispose() { throw new NotImplementedException(); } /// <summary> /// Calls EVP_get_digestbyname() /// </summary> /// <param name="name"></param> /// <returns></returns> public static MessageDigest CreateByName(string name) { byte[] buf = Encoding.ASCII.GetBytes(name); IntPtr ptr = Native.EVP_get_digestbyname(buf); if (ptr == IntPtr.Zero) return null; return new MessageDigest(ptr, false); } /// <summary> /// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNamesSorted { get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, true).Result.ToArray(); } } /// <summary> /// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNames { get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, false).Result.ToArray(); } } #region EVP_MD [StructLayout(LayoutKind.Sequential)] struct EVP_MD { public int type; public int pkey_type; public int md_size; public uint flags; public IntPtr init; public IntPtr update; public IntPtr final; public IntPtr copy; public IntPtr cleanup; public IntPtr sign; public IntPtr verify; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public int[] required_pkey_type; public int block_size; public int ctx_size; } #endregion #region MessageDigests /// <summary> /// EVP_md_null() /// </summary> public static MessageDigest Null = new MessageDigest(Native.EVP_md_null(), false); /// <summary> /// EVP_md2() /// </summary> public static MessageDigest MD2 = new MessageDigest(Native.EVP_md2(), false); /// <summary> /// EVP_md4() /// </summary> public static MessageDigest MD4 = new MessageDigest(Native.EVP_md4(), false); /// <summary> /// EVP_md5() /// </summary> public static MessageDigest MD5 = new MessageDigest(Native.EVP_md5(), false); /// <summary> /// EVP_sha() /// </summary> public static MessageDigest SHA = new MessageDigest(Native.EVP_sha(), false); /// <summary> /// EVP_sha1() /// </summary> public static MessageDigest SHA1 = new MessageDigest(Native.EVP_sha1(), false); /// <summary> /// EVP_sha224() /// </summary> public static MessageDigest SHA224 = new MessageDigest(Native.EVP_sha224(), false); /// <summary> /// EVP_sha256() /// </summary> public static MessageDigest SHA256 = new MessageDigest(Native.EVP_sha256(), false); /// <summary> /// EVP_sha384() /// </summary> public static MessageDigest SHA384 = new MessageDigest(Native.EVP_sha384(), false); /// <summary> /// EVP_sha512() /// </summary> public static MessageDigest SHA512 = new MessageDigest(Native.EVP_sha512(), false); /// <summary> /// EVP_dss() /// </summary> public static MessageDigest DSS = new MessageDigest(Native.EVP_dss(), false); /// <summary> /// EVP_dss1() /// </summary> public static MessageDigest DSS1 = new MessageDigest(Native.EVP_dss1(), false); /// <summary> /// EVP_ripemd160() /// </summary> public static MessageDigest RipeMD160 = new MessageDigest(Native.EVP_ripemd160(), false); #endregion #region Properties /// <summary> /// Returns the block_size field /// </summary> public int BlockSize { get { return this.raw.block_size; } } /// <summary> /// Returns the md_size field /// </summary> public int Size { get { return this.raw.md_size; } } /// <summary> /// Returns the type field using OBJ_nid2ln() /// </summary> public string LongName { get { return Native.PtrToStringAnsi(Native.OBJ_nid2ln(this.raw.type), false); } } /// <summary> /// Returns the type field using OBJ_nid2sn() /// </summary> public string Name { get { return Native.PtrToStringAnsi(Native.OBJ_nid2sn(this.raw.type), false); } } #endregion } #endregion /// <summary> /// Wraps the EVP_MD_CTX object /// </summary> public class MessageDigestContext : Base { #region EVP_MD_CTX [StructLayout(LayoutKind.Sequential)] struct EVP_MD_CTX { public IntPtr digest; public IntPtr engine; public uint flags; public IntPtr md_data; } #endregion private MessageDigest md; /// <summary> /// Calls BIO_get_md_ctx() then BIO_get_md() /// </summary> /// <param name="bio"></param> public MessageDigestContext(BIO bio) : base(Native.ExpectNonNull(Native.BIO_get_md_ctx(bio.Handle)), false) { this.md = new MessageDigest(Native.ExpectNonNull(Native.BIO_get_md(bio.Handle)), false); } /// <summary> /// Calls EVP_MD_CTX_create() then EVP_MD_CTX_init() /// </summary> /// <param name="md"></param> public MessageDigestContext(MessageDigest md) : base(Native.EVP_MD_CTX_create(), true) { Native.EVP_MD_CTX_init(this.ptr); this.md = md; } /// <summary> /// Prints the long name /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write("MessageDigestContext: " + this.md.LongName); } #region Methods /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex() /// </summary> /// <param name="msg"></param> /// <returns></returns> public byte[] Digest(byte[] msg) { byte[] digest = new byte[this.md.Size]; uint len = (uint)digest.Length; Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length)); Native.ExpectSuccess(Native.EVP_DigestFinal_ex(this.ptr, digest, ref len)); return digest; } /// <summary> /// Calls EVP_DigestInit_ex() /// </summary> public void Init() { Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero)); } /// <summary> /// Calls EVP_DigestUpdate() /// </summary> /// <param name="msg"></param> public void Update(byte[] msg) { Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length)); } /// <summary> /// Calls EVP_DigestFinal_ex() /// </summary> /// <returns></returns> public byte[] DigestFinal() { byte[] digest = new byte[this.md.Size]; uint len = (uint)digest.Length; Native.ExpectSuccess(Native.EVP_DigestFinal_ex(this.ptr, digest, ref len)); return digest; } /// <summary> /// Calls EVP_SignFinal() /// </summary> /// <param name="pkey"></param> /// <returns></returns> public byte[] SignFinal(CryptoKey pkey) { byte[] digest = new byte[this.md.Size]; byte[] sig = new byte[pkey.Size]; uint len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle)); return sig; } /// <summary> /// Calls EVP_VerifyFinal() /// </summary> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public bool VerifyFinal(byte[] sig, CryptoKey pkey) { int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_SignFinal() /// </summary> /// <param name="msg"></param> /// <param name="pkey"></param> /// <returns></returns> public byte[] Sign(byte[] msg, CryptoKey pkey) { byte[] sig = new byte[pkey.Size]; uint len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length)); Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle)); byte[] ret = new byte[len]; Buffer.BlockCopy(sig, 0, ret, 0, (int)len); return ret; } /// <summary> /// Calls EVP_SignFinal() /// </summary> /// <param name="md"></param> /// <param name="bio"></param> /// <param name="pkey"></param> /// <returns></returns> public static byte[] Sign(MessageDigest md, BIO bio, CryptoKey pkey) { BIO bmd = BIO.MessageDigest(md); bmd.Push(bio); while (true) { ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4); if (bytes.Count == 0) break; } MessageDigestContext ctx = new MessageDigestContext(bmd); byte[] sig = new byte[pkey.Size]; uint len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_SignFinal(ctx.Handle, sig, ref len, pkey.Handle)); byte[] ret = new byte[len]; Buffer.BlockCopy(sig, 0, ret, 0, (int)len); return ret; } /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_VerifyFinal() /// </summary> /// <param name="msg"></param> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public bool Verify(byte[] msg, byte[] sig, CryptoKey pkey) { Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length)); int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } /// <summary> /// Calls EVP_VerifyFinal() /// </summary> /// <param name="md"></param> /// <param name="bio"></param> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public static bool Verify(MessageDigest md, BIO bio, byte[] sig, CryptoKey pkey) { BIO bmd = BIO.MessageDigest(md); bmd.Push(bio); while (true) { ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4); if (bytes.Count == 0) break; } MessageDigestContext ctx = new MessageDigestContext(bmd); int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ctx.Handle, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } #endregion #region IDisposable Members /// <summary> /// Calls EVP_MD_CTX_cleanup() and EVP_MD_CTX_destroy() /// </summary> protected override void OnDispose() { Native.EVP_MD_CTX_cleanup(this.ptr); Native.EVP_MD_CTX_destroy(this.ptr); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace VSTestApp.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AngularJSAuthRefreshToken.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System.Xml; using Spring.Core.TypeResolution; using Spring.Objects; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Xml; using Spring.Util; #endregion namespace Spring.Remoting.Config { /// <summary> /// Implementation of the custom configuration parser for remoting definitions. /// </summary> /// <author>Bruno Baia</author> [ NamespaceParser( Namespace = "http://www.springframework.net/remoting", SchemaLocationAssemblyHint = typeof(RemotingNamespaceParser), SchemaLocation = "/Spring.Remoting.Config/spring-remoting-1.1.xsd") ] public sealed class RemotingNamespaceParser : ObjectsNamespaceParser { private const string RemotingTypePrefix = "remoting: "; static RemotingNamespaceParser() { TypeRegistry.RegisterType( RemotingTypePrefix + RemotingConfigurerConstants.RemotingConfigurerElement, typeof(RemotingConfigurer)); TypeRegistry.RegisterType( RemotingTypePrefix + SaoFactoryObjectConstants.SaoFactoryObjectElement, typeof(SaoFactoryObject)); TypeRegistry.RegisterType( RemotingTypePrefix + CaoFactoryObjectConstants.CaoFactoryObjectElement, typeof(CaoFactoryObject)); TypeRegistry.RegisterType( RemotingTypePrefix + RemoteObjectFactoryConstants.RemoteObjectFactoryElement, typeof(RemoteObjectFactory)); TypeRegistry.RegisterType( RemotingTypePrefix + SaoExporterConstants.SaoExporterElement, typeof(SaoExporter)); TypeRegistry.RegisterType( RemotingTypePrefix + CaoExporterConstants.CaoExporterElement, typeof(CaoExporter)); } /// <summary> /// Initializes a new instance of the <see cref="RemotingNamespaceParser"/> class. /// </summary> public RemotingNamespaceParser() {} /// <summary> /// Parse the specified element and register any resulting /// IObjectDefinitions with the IObjectDefinitionRegistry that is /// embedded in the supplied ParserContext. /// </summary> /// <param name="element">The element to be parsed into one or more IObjectDefinitions</param> /// <param name="parserContext">The object encapsulating the current state of the parsing /// process.</param> /// <returns> /// The primary IObjectDefinition (can be null as explained above) /// </returns> /// <remarks> /// Implementations should return the primary IObjectDefinition /// that results from the parse phase if they wish to used nested /// inside (for example) a <code>&lt;property&gt;</code> tag. /// <para>Implementations may return null if they will not /// be used in a nested scenario. /// </para> /// </remarks> public override IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext) { string name = element.GetAttribute(ObjectDefinitionConstants.IdAttribute); IConfigurableObjectDefinition remotingDefinition = ParseRemotingDefinition(element, name, parserContext); if (!StringUtils.HasText(name)) { name = ObjectDefinitionReaderUtils.GenerateObjectName(remotingDefinition, parserContext.Registry); } parserContext.Registry.RegisterObjectDefinition(name, remotingDefinition); return null; } /// <summary> /// Parses remoting definitions. /// </summary> /// <param name="element">Validator XML element.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>A remoting object definition.</returns> private IConfigurableObjectDefinition ParseRemotingDefinition( XmlElement element, string name, ParserContext parserContext) { switch (element.LocalName) { case RemotingConfigurerConstants.RemotingConfigurerElement: return ParseRemotingConfigurer(element, name, parserContext); case SaoFactoryObjectConstants.SaoFactoryObjectElement: return ParseSaoFactoryObject(element, name, parserContext); case CaoFactoryObjectConstants.CaoFactoryObjectElement: return ParseCaoFactoryObject(element, name, parserContext); case RemoteObjectFactoryConstants.RemoteObjectFactoryElement: return ParseRemoteObjectFactory(element, name, parserContext); case SaoExporterConstants.SaoExporterElement: return ParseSaoExporter(element, name, parserContext); case CaoExporterConstants.CaoExporterElement: return ParseCaoExporter(element, name, parserContext); } return null; } /// <summary> /// Parses the RemotingConfigurer definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>RemotingConfigurer object definition.</returns> private IConfigurableObjectDefinition ParseRemotingConfigurer( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string filename = element.GetAttribute(RemotingConfigurerConstants.FilenameAttribute); string useConfigFile = element.GetAttribute(RemotingConfigurerConstants.UseConfigFileAttribute); string ensureSecurity = element.GetAttribute(RemotingConfigurerConstants.EnsureSecurityAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(filename)) { properties.Add("Filename", filename); } if (StringUtils.HasText(useConfigFile)) { properties.Add("UseConfigFile", useConfigFile); } if (StringUtils.HasText(ensureSecurity)) { properties.Add("EnsureSecurity", ensureSecurity); } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the SaoFactoryObject definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>SaoFactoryObject object definition.</returns> private IConfigurableObjectDefinition ParseSaoFactoryObject( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string serviceInterface = element.GetAttribute(SaoFactoryObjectConstants.ServiceInterfaceAttribute); string serviceUrl = element.GetAttribute(SaoFactoryObjectConstants.ServiceUrlAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(serviceInterface)) { properties.Add("ServiceInterface", serviceInterface); } if (StringUtils.HasText(serviceUrl)) { properties.Add("ServiceUrl", serviceUrl); } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the CaoFactoryObject definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>CaoFactoryObject object definition.</returns> private IConfigurableObjectDefinition ParseCaoFactoryObject( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string remoteTargetName = element.GetAttribute(CaoFactoryObjectConstants.RemoteTargetNameAttribute); string serviceUrl = element.GetAttribute(CaoFactoryObjectConstants.ServiceUrlAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(remoteTargetName)) { properties.Add("RemoteTargetName", remoteTargetName); } if (StringUtils.HasText(serviceUrl)) { properties.Add("ServiceUrl", serviceUrl); } foreach (XmlElement child in element.ChildNodes) { switch (child.LocalName) { case CaoFactoryObjectConstants.ConstructorArgumentsElement: properties.Add("ConstructorArguments", base.ParseListElement(child, name, parserContext)); break; } } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the RemoteObjectFactory definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>RemoteObjectFactory object definition.</returns> private IConfigurableObjectDefinition ParseRemoteObjectFactory( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string targetName = element.GetAttribute(RemoteObjectFactoryConstants.TargetNameAttribute); string infinite = element.GetAttribute(RemoteObjectFactoryConstants.InfiniteAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(targetName)) { properties.Add("Target", targetName); } if (StringUtils.HasText(infinite)) { properties.Add("Infinite", infinite); } foreach (XmlElement child in element.ChildNodes) { switch (child.LocalName) { case LifeTimeConstants.LifeTimeElement: ParseLifeTime(properties, child, parserContext); break; case InterfacesConstants.InterfacesElement: properties.Add("Interfaces", base.ParseListElement(child, name, parserContext)); break; } } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the SaoExporter definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>SaoExporter object definition.</returns> private IConfigurableObjectDefinition ParseSaoExporter( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string targetName = element.GetAttribute(SaoExporterConstants.TargetNameAttribute); string applicationName = element.GetAttribute(SaoExporterConstants.ApplicationNameAttribute); string serviceName = element.GetAttribute(SaoExporterConstants.ServiceNameAttribute); string infinite = element.GetAttribute(SaoExporterConstants.InfiniteAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(targetName)) { properties.Add("TargetName", targetName); } if (StringUtils.HasText(applicationName)) { properties.Add("ApplicationName", applicationName); } if (StringUtils.HasText(serviceName)) { properties.Add("ServiceName", serviceName); } if (StringUtils.HasText(infinite)) { properties.Add("Infinite", infinite); } foreach (XmlElement child in element.ChildNodes) { switch (child.LocalName) { case LifeTimeConstants.LifeTimeElement: ParseLifeTime(properties, child, parserContext); break; case InterfacesConstants.InterfacesElement: properties.Add("Interfaces", base.ParseListElement(child, name, parserContext)); break; } } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the CaoExporter definition. /// </summary> /// <param name="element">The element to parse.</param> /// <param name="name">The name of the object definition.</param> /// <param name="parserContext">The parser context.</param> /// <returns>CaoExporter object definition.</returns> private IConfigurableObjectDefinition ParseCaoExporter( XmlElement element, string name, ParserContext parserContext) { string typeName = GetTypeName(element); string targetName = element.GetAttribute(CaoExporterConstants.TargetNameAttribute); string infinite = element.GetAttribute(CaoExporterConstants.InfiniteAttribute); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.HasText(targetName)) { properties.Add("TargetName", targetName); } if (StringUtils.HasText(infinite)) { properties.Add("Infinite", infinite); } foreach (XmlElement child in element.ChildNodes) { switch (child.LocalName) { case LifeTimeConstants.LifeTimeElement: ParseLifeTime(properties, child, parserContext); break; case InterfacesConstants.InterfacesElement: properties.Add("Interfaces", base.ParseListElement(child, name, parserContext)); break; } } IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition( typeName, null, parserContext.ReaderContext.Reader.Domain); cod.PropertyValues = properties; return cod; } /// <summary> /// Parses the LifeTime definition. /// </summary> private void ParseLifeTime(MutablePropertyValues properties, XmlElement child, ParserContext parserContext) { string initialLeaseTime = child.GetAttribute(LifeTimeConstants.InitialLeaseTimeAttribute); string renewOnCallTime = child.GetAttribute(LifeTimeConstants.RenewOnCallTimeAttribute); string sponsorshipTimeout = child.GetAttribute(LifeTimeConstants.SponsorshipTimeoutAttribute); if (StringUtils.HasText(initialLeaseTime)) { properties.Add("InitialLeaseTime", initialLeaseTime); } if (StringUtils.HasText(renewOnCallTime)) { properties.Add("RenewOnCallTime", renewOnCallTime); } if (StringUtils.HasText(sponsorshipTimeout)) { properties.Add("SponsorshipTimeout", sponsorshipTimeout); } } /// <summary> /// Gets the name of the object type for the specified element. /// </summary> /// <param name="element">The element.</param> /// <returns>The name of the object type.</returns> private string GetTypeName(XmlElement element) { string typeName = element.GetAttribute(ObjectDefinitionConstants.TypeAttribute); if (StringUtils.IsNullOrEmpty(typeName)) { return RemotingTypePrefix + element.LocalName; } return typeName; } #region Element & Attribute Name Constants private class RemotingConfigurerConstants { public const string RemotingConfigurerElement = "configurer"; public const string FilenameAttribute = "filename"; public const string UseConfigFileAttribute = "useConfigFile"; public const string EnsureSecurityAttribute = "ensureSecurity"; } private class SaoFactoryObjectConstants { public const string SaoFactoryObjectElement = "saoFactory"; public const string ServiceInterfaceAttribute = "serviceInterface"; public const string ServiceUrlAttribute = "serviceUrl"; } private class CaoFactoryObjectConstants { public const string CaoFactoryObjectElement = "caoFactory"; public const string ConstructorArgumentsElement = "constructor-args"; public const string RemoteTargetNameAttribute = "remoteTargetName"; public const string ServiceUrlAttribute = "serviceUrl"; } private class LifeTimeConstants { public const string LifeTimeElement = "lifeTime"; public const string InitialLeaseTimeAttribute = "initialLeaseTime"; public const string RenewOnCallTimeAttribute = "renewOnCallTime"; public const string SponsorshipTimeoutAttribute = "sponsorshipTimeout"; } private class InterfacesConstants { public const string InterfacesElement = "interfaces"; } private class RemoteObjectFactoryConstants { public const string RemoteObjectFactoryElement = "remoteObjectFactory"; public const string TargetNameAttribute = "targetName"; public const string InfiniteAttribute = "infinite"; } private class SaoExporterConstants { public const string SaoExporterElement = "saoExporter"; public const string TargetNameAttribute = "targetName"; public const string ApplicationNameAttribute = "applicationName"; public const string ServiceNameAttribute = "serviceName"; public const string InfiniteAttribute = "infinite"; } private class CaoExporterConstants { public const string CaoExporterElement = "caoExporter"; public const string TargetNameAttribute = "targetName"; public const string InfiniteAttribute = "infinite"; } #endregion } }
using FluentValidation; using Stylet; using SyncTrayzor.Properties; using SyncTrayzor.Services; using SyncTrayzor.Services.Config; using SyncTrayzor.Syncthing; using SyncTrayzor.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Windows; using System.IO; using SyncTrayzor.Services.Metering; namespace SyncTrayzor.Pages.Settings { public class FolderSettings : PropertyChangedBase { public string FolderId { get; set; } public string FolderLabel { get; set; } public bool IsWatched { get; set; } public bool IsWatchAllowed { get; set; } public bool VisibleIsWatched { get => this.IsWatched && this.IsWatchAllowed; set { if (this.IsWatchAllowed) this.IsWatched = value; else throw new InvalidOperationException(); } } public bool IsNotified { get; set; } } public class SettingsViewModel : Screen { // We can be opened directly on this tab. All of the layout is done in xaml, so this is // the neatest way we can select it... private const int loggingTabIndex = 3; private readonly IConfigurationProvider configurationProvider; private readonly IAutostartProvider autostartProvider; private readonly IWindowManager windowManager; private readonly IProcessStartProvider processStartProvider; private readonly IAssemblyProvider assemblyProvider; private readonly IApplicationState applicationState; private readonly IApplicationPathsProvider applicationPathsProvider; private readonly ISyncthingManager syncthingManager; private readonly List<SettingItem> settings = new List<SettingItem>(); public int SelectedTabIndex { get; set; } public SettingItem<bool> MinimizeToTray { get; } public SettingItem<bool> CloseToTray { get; } public SettingItem<bool> NotifyOfNewVersions { get; } public SettingItem<bool> ObfuscateDeviceIDs { get; } public SettingItem<bool> UseComputerCulture { get; } public SettingItem<bool> DisableHardwareRendering { get; } public SettingItem<bool> EnableConflictFileMonitoring { get; } public SettingItem<bool> EnableFailedTransferAlerts { get; } public bool PauseDevicesOnMeteredNetworksSupported { get; } public SettingItem<bool> PauseDevicesOnMeteredNetworks { get; } public SettingItem<bool> ShowTrayIconOnlyOnClose { get; } public SettingItem<bool> ShowSynchronizedBalloonEvenIfNothingDownloaded { get; } public SettingItem<bool> ShowDeviceConnectivityBalloons { get; } public SettingItem<bool> ShowDeviceOrFolderRejectedBalloons { get; } public BindableCollection<LabelledValue<IconAnimationMode>> IconAnimationModes { get; } public SettingItem<IconAnimationMode> IconAnimationMode { get; } public SettingItem<bool> StartSyncthingAutomatically { get; } public BindableCollection<LabelledValue<SyncthingPriorityLevel>> PriorityLevels { get; } public SettingItem<SyncthingPriorityLevel> SyncthingPriorityLevel { get; } public SettingItem<string> SyncthingAddress { get; } public bool CanReadAutostart { get; set; } public bool CanWriteAutostart { get; set; } public bool CanReadOrWriteAutostart => this.CanReadAutostart || this.CanWriteAutostart; public bool CanReadAndWriteAutostart => this.CanReadAutostart && this.CanWriteAutostart; public bool StartOnLogon { get; set; } public bool StartMinimized { get; set; } public bool StartMinimizedEnabled => this.CanReadAndWriteAutostart && this.StartOnLogon; public SettingItem<string> SyncthingCommandLineFlags { get; } public SettingItem<string> SyncthingEnvironmentalVariables { get; } public SettingItem<string> SyncthingCustomPath { get; } public SettingItem<string> SyncthingCustomHomePath { get; } public SettingItem<bool> SyncthingDenyUpgrade { get; } private bool updatingFolderSettings; public bool? AreAllFoldersWatched { get; set; } public bool? AreAllFoldersNotified { get; set; } public BindableCollection<FolderSettings> FolderSettings { get; } = new BindableCollection<FolderSettings>(); public bool IsAnyFolderWatchEnabledInSyncthing { get; private set; } public BindableCollection<LabelledValue<LogLevel>> LogLevels { get; } public SettingItem<LogLevel> SelectedLogLevel { get; set; } public SettingsViewModel( IConfigurationProvider configurationProvider, IAutostartProvider autostartProvider, IWindowManager windowManager, IProcessStartProvider processStartProvider, IAssemblyProvider assemblyProvider, IApplicationState applicationState, IApplicationPathsProvider applicationPathsProvider, ISyncthingManager syncthingManager, IMeteredNetworkManager meteredNetworkManager) { this.configurationProvider = configurationProvider; this.autostartProvider = autostartProvider; this.windowManager = windowManager; this.processStartProvider = processStartProvider; this.assemblyProvider = assemblyProvider; this.applicationState = applicationState; this.applicationPathsProvider = applicationPathsProvider; this.syncthingManager = syncthingManager; this.MinimizeToTray = this.CreateBasicSettingItem(x => x.MinimizeToTray); this.NotifyOfNewVersions = this.CreateBasicSettingItem(x => x.NotifyOfNewVersions); this.CloseToTray = this.CreateBasicSettingItem(x => x.CloseToTray); this.ObfuscateDeviceIDs = this.CreateBasicSettingItem(x => x.ObfuscateDeviceIDs); this.UseComputerCulture = this.CreateBasicSettingItem(x => x.UseComputerCulture); this.UseComputerCulture.RequiresSyncTrayzorRestart = true; this.DisableHardwareRendering = this.CreateBasicSettingItem(x => x.DisableHardwareRendering); this.DisableHardwareRendering.RequiresSyncTrayzorRestart = true; this.EnableConflictFileMonitoring = this.CreateBasicSettingItem(x => x.EnableConflictFileMonitoring); this.EnableFailedTransferAlerts = this.CreateBasicSettingItem(x => x.EnableFailedTransferAlerts); this.PauseDevicesOnMeteredNetworks = this.CreateBasicSettingItem(x => x.PauseDevicesOnMeteredNetworks); this.PauseDevicesOnMeteredNetworksSupported = meteredNetworkManager.IsSupportedByWindows; this.ShowTrayIconOnlyOnClose = this.CreateBasicSettingItem(x => x.ShowTrayIconOnlyOnClose); this.ShowSynchronizedBalloonEvenIfNothingDownloaded = this.CreateBasicSettingItem(x => x.ShowSynchronizedBalloonEvenIfNothingDownloaded); this.ShowDeviceConnectivityBalloons = this.CreateBasicSettingItem(x => x.ShowDeviceConnectivityBalloons); this.ShowDeviceOrFolderRejectedBalloons = this.CreateBasicSettingItem(x => x.ShowDeviceOrFolderRejectedBalloons); this.IconAnimationModes = new BindableCollection<LabelledValue<IconAnimationMode>>() { LabelledValue.Create(Resources.SettingsView_TrayIconAnimation_DataTransferring, Services.Config.IconAnimationMode.DataTransferring), LabelledValue.Create(Resources.SettingsView_TrayIconAnimation_Syncing, Services.Config.IconAnimationMode.Syncing), LabelledValue.Create(Resources.SettingsView_TrayIconAnimation_Disabled, Services.Config.IconAnimationMode.Disabled), }; this.IconAnimationMode = this.CreateBasicSettingItem(x => x.IconAnimationMode); this.StartSyncthingAutomatically = this.CreateBasicSettingItem(x => x.StartSyncthingAutomatically); this.SyncthingPriorityLevel = this.CreateBasicSettingItem(x => x.SyncthingPriorityLevel); this.SyncthingPriorityLevel.RequiresSyncthingRestart = true; this.SyncthingAddress = this.CreateBasicSettingItem(x => x.SyncthingAddress, new SyncthingAddressValidator()); this.SyncthingAddress.RequiresSyncthingRestart = true; this.CanReadAutostart = this.autostartProvider.CanRead; this.CanWriteAutostart = this.autostartProvider.CanWrite; if (this.autostartProvider.CanRead) { var currentSetup = this.autostartProvider.GetCurrentSetup(); this.StartOnLogon = currentSetup.AutoStart; this.StartMinimized = currentSetup.StartMinimized; } this.SyncthingCommandLineFlags = this.CreateBasicSettingItem( x => String.Join(" ", x.SyncthingCommandLineFlags), (x, v) => { KeyValueStringParser.TryParse(v, out var envVars, mustHaveValue: false); x.SyncthingCommandLineFlags = envVars.Select(item => KeyValueStringParser.FormatItem(item.Key, item.Value)).ToList(); }, new SyncthingCommandLineFlagsValidator()); this.SyncthingCommandLineFlags.RequiresSyncthingRestart = true; this.SyncthingEnvironmentalVariables = this.CreateBasicSettingItem( x => KeyValueStringParser.Format(x.SyncthingEnvironmentalVariables), (x, v) => { KeyValueStringParser.TryParse(v, out var envVars); x.SyncthingEnvironmentalVariables = new EnvironmentalVariableCollection(envVars); }, new SyncthingEnvironmentalVariablesValidator()); this.SyncthingEnvironmentalVariables.RequiresSyncthingRestart = true; this.SyncthingCustomPath = this.CreateBasicSettingItem(x => x.SyncthingCustomPath); // This *shouldn't* be necessary, but the code to copy the syncthing.exe binary if it doesn't exist // is only run at startup, so require a restart... this.SyncthingCustomPath.RequiresSyncTrayzorRestart = true; this.SyncthingCustomHomePath = this.CreateBasicSettingItem(x => x.SyncthingCustomHomePath); this.SyncthingCustomHomePath.RequiresSyncthingRestart = true; this.SyncthingDenyUpgrade = this.CreateBasicSettingItem(x => x.SyncthingDenyUpgrade); this.SyncthingDenyUpgrade.RequiresSyncthingRestart = true; this.PriorityLevels = new BindableCollection<LabelledValue<SyncthingPriorityLevel>>() { LabelledValue.Create(Resources.SettingsView_Syncthing_ProcessPriority_AboveNormal, Services.Config.SyncthingPriorityLevel.AboveNormal), LabelledValue.Create(Resources.SettingsView_Syncthing_ProcessPriority_Normal, Services.Config.SyncthingPriorityLevel.Normal), LabelledValue.Create(Resources.SettingsView_Syncthing_ProcessPriority_BelowNormal, Services.Config.SyncthingPriorityLevel.BelowNormal), LabelledValue.Create(Resources.SettingsView_Syncthing_ProcessPriority_Idle, Services.Config.SyncthingPriorityLevel.Idle), }; this.LogLevels = new BindableCollection<LabelledValue<LogLevel>>() { LabelledValue.Create(Resources.SettingsView_Logging_LogLevel_Info, LogLevel.Info), LabelledValue.Create(Resources.SettingsView_Logging_LogLevel_Debug, LogLevel.Debug), LabelledValue.Create(Resources.SettingsView_Logging_LogLevel_Trace, LogLevel.Trace), }; this.SelectedLogLevel = this.CreateBasicSettingItem(x => x.LogLevel); var configuration = this.configurationProvider.Load(); foreach (var settingItem in this.settings) { settingItem.LoadValue(configuration); } this.Bind(s => s.FolderSettings, (o2, e2) => { foreach (var folderSetting in this.FolderSettings) { folderSetting.Bind(s => s.IsWatched, (o, e) => this.UpdateAreAllFoldersWatched()); folderSetting.Bind(s => s.IsNotified, (o, e) => this.UpdateAreAllFoldersNotified()); } }); this.Bind(s => s.AreAllFoldersNotified, (o, e) => { if (this.updatingFolderSettings) return; this.updatingFolderSettings = true; foreach (var folderSetting in this.FolderSettings) { folderSetting.IsNotified = e.NewValue.GetValueOrDefault(false); } this.updatingFolderSettings = false; }); this.Bind(s => s.AreAllFoldersWatched, (o, e) => { if (this.updatingFolderSettings) return; this.updatingFolderSettings = true; foreach (var folderSetting in this.FolderSettings) { if (folderSetting.IsWatchAllowed) folderSetting.IsWatched = e.NewValue.GetValueOrDefault(false); } this.updatingFolderSettings = false; }); this.UpdateAreAllFoldersWatched(); this.UpdateAreAllFoldersNotified(); } protected override void OnInitialActivate() { if (syncthingManager.State == SyncthingState.Running && syncthingManager.IsDataLoaded) this.LoadFromSyncthingStartupData(); else this.syncthingManager.DataLoaded += this.SyncthingDataLoaded; } protected override void OnClose() { this.syncthingManager.DataLoaded -= this.SyncthingDataLoaded; } private void SyncthingDataLoaded(object sender, EventArgs e) { this.LoadFromSyncthingStartupData(); } private void LoadFromSyncthingStartupData() { var configuration = this.configurationProvider.Load(); // We have to merge two sources of data: the folder settings from config, and the actual folder // configuration from Syncthing (which we use to get the folder label). They should be in sync... this.FolderSettings.Clear(); var folderSettings = new List<FolderSettings>(configuration.Folders.Count); foreach (var configFolder in configuration.Folders) { if (this.syncthingManager.Folders.TryFetchById(configFolder.ID, out var folder)) { folderSettings.Add(new FolderSettings() { FolderId = configFolder.ID, FolderLabel = folder?.Label ?? configFolder.ID, IsWatched = configFolder.IsWatched, IsWatchAllowed = !folder.IsFsWatcherEnabled, IsNotified = configFolder.NotificationsEnabled, }); } } this.FolderSettings.AddRange(folderSettings.OrderBy(x => x.FolderLabel)); this.IsAnyFolderWatchEnabledInSyncthing = this.FolderSettings.Any(x => !x.IsWatchAllowed); this.UpdateAreAllFoldersWatched(); this.UpdateAreAllFoldersNotified(); this.NotifyOfPropertyChange(nameof(this.FolderSettings)); } private SettingItem<T> CreateBasicSettingItem<T>(Expression<Func<Configuration, T>> accessExpression, IValidator<SettingItem<T>> validator = null) { return this.CreateBasicSettingItemImpl(v => new SettingItem<T>(accessExpression, v), validator); } private SettingItem<T> CreateBasicSettingItem<T>(Func<Configuration, T> getter, Action<Configuration, T> setter, IValidator<SettingItem<T>> validator = null, Func<T, T, bool> comparer = null) { return this.CreateBasicSettingItemImpl(v => new SettingItem<T>(getter, setter, v, comparer), validator); } private SettingItem<T> CreateBasicSettingItemImpl<T>(Func<IModelValidator, SettingItem<T>> generator, IValidator<SettingItem<T>> validator) { IModelValidator modelValidator = validator == null ? null : new FluentModelValidator<SettingItem<T>>(validator); var settingItem = generator(modelValidator); this.settings.Add(settingItem); settingItem.ErrorsChanged += (o, e) => this.NotifyOfPropertyChange(() => this.CanSave); return settingItem; } private void UpdateAreAllFoldersWatched() { if (this.updatingFolderSettings) return; this.updatingFolderSettings = true; if (this.FolderSettings.All(x => x.VisibleIsWatched)) this.AreAllFoldersWatched = true; else if (this.FolderSettings.All(x => !x.VisibleIsWatched)) this.AreAllFoldersWatched = false; else this.AreAllFoldersWatched = null; this.updatingFolderSettings = false; } private void UpdateAreAllFoldersNotified() { if (this.updatingFolderSettings) return; this.updatingFolderSettings = true; if (this.FolderSettings.All(x => x.IsNotified)) this.AreAllFoldersNotified = true; else if (this.FolderSettings.All(x => !x.IsNotified)) this.AreAllFoldersNotified = false; else this.AreAllFoldersNotified = null; this.updatingFolderSettings = false; } public bool CanSave => this.settings.All(x => !x.HasErrors); public void Save() { this.configurationProvider.AtomicLoadAndSave(configuration => { foreach (var settingItem in this.settings) { settingItem.SaveValue(configuration); } configuration.Folders = this.FolderSettings.Select(x => new FolderConfiguration(x.FolderId, x.IsWatched, x.IsNotified)).ToList(); }); if (this.autostartProvider.CanWrite) { // I've seen this fail, even though we successfully wrote on startup try { var autostartConfig = new AutostartConfiguration() { AutoStart = this.StartOnLogon, StartMinimized = this.StartMinimized }; this.autostartProvider.SetAutoStart(autostartConfig); } catch { this.windowManager.ShowMessageBox( Resources.SettingsView_CannotSetAutoStart_Message, Resources.SettingsView_CannotSetAutoStart_Title, MessageBoxButton.OK, MessageBoxImage.Error); } } if (this.settings.Any(x => x.HasChanged && x.RequiresSyncTrayzorRestart)) { var result = this.windowManager.ShowMessageBox( Resources.SettingsView_RestartSyncTrayzor_Message, Resources.SettingsView_RestartSyncTrayzor_Title, MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { this.processStartProvider.StartDetached(this.assemblyProvider.Location); this.applicationState.Shutdown(); } } else if ((this.settings.Any(x => x.HasChanged && x.RequiresSyncthingRestart)) && this.syncthingManager.State == SyncthingState.Running) { var result = this.windowManager.ShowMessageBox( Resources.SettingsView_RestartSyncthing_Message, Resources.SettingsView_RestartSyncthing_Title, MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { this.RestartSyncthing(); } } this.RequestClose(true); } private async void RestartSyncthing() { await this.syncthingManager.RestartAsync(); } public void Cancel() { this.RequestClose(false); } public void ShowSyncthingLogFile() { this.processStartProvider.ShowFileInExplorer(Path.Combine(this.applicationPathsProvider.LogFilePath, "syncthing.log")); } public void ShowSyncTrayzorLogFile() { this.processStartProvider.ShowFileInExplorer(Path.Combine(this.applicationPathsProvider.LogFilePath, "SyncTrayzor.log")); } public void SelectLoggingTab() { this.SelectedTabIndex = loggingTabIndex; } } }
//#define TRACE_SERIALIZATION using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using Orleans.CodeGeneration; using Orleans.GrainDirectory; using Orleans.Runtime; namespace Orleans.Serialization { internal static class BinaryTokenStreamReaderExtensinons { /// <summary> Read an <c>GrainId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal static GrainId ReadGrainId(this IBinaryTokenStreamReader @this) { UniqueKey key = @this.ReadUniqueKey(); return GrainId.GetGrainId(key); } /// <summary> Read an <c>ActivationId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal static ActivationId ReadActivationId(this IBinaryTokenStreamReader @this) { UniqueKey key = @this.ReadUniqueKey(); return ActivationId.GetActivationId(key); } internal static UniqueKey ReadUniqueKey(this IBinaryTokenStreamReader @this) { ulong n0 = @this.ReadULong(); ulong n1 = @this.ReadULong(); ulong typeCodeData = @this.ReadULong(); string keyExt = @this.ReadString(); return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt); } internal static CorrelationId ReadCorrelationId(this IBinaryTokenStreamReader @this) { return new CorrelationId(@this.ReadBytes(CorrelationId.SIZE_BYTES)); } internal static GrainDirectoryEntryStatus ReadMultiClusterStatus(this IBinaryTokenStreamReader @this) { byte val = @this.ReadByte(); return (GrainDirectoryEntryStatus)val; } /// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal static ActivationAddress ReadActivationAddress(this IBinaryTokenStreamReader @this) { var silo = @this.ReadSiloAddress(); var grain = @this.ReadGrainId(); var act = @this.ReadActivationId(); if (silo.Equals(SiloAddress.Zero)) silo = null; if (act.Equals(ActivationId.Zero)) act = null; return ActivationAddress.GetAddress(silo, grain, act); } /// <summary> /// Peek at the next token in this input stream. /// </summary> /// <returns>Next token thatr will be read from the stream.</returns> internal static SerializationTokenType PeekToken(this IBinaryTokenStreamReader @this) { // TODO try to avoid that return ((BinaryTokenStreamReader) @this).PeekToken(); } /// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal static SerializationTokenType ReadToken(this IBinaryTokenStreamReader @this) { // TODO try to avoid that return ((BinaryTokenStreamReader) @this).ReadToken(); } internal static bool TryReadSimpleType(this IBinaryTokenStreamReader @this, out object result, out SerializationTokenType token) { token = @this.ReadToken(); byte[] bytes; switch (token) { case SerializationTokenType.True: result = true; break; case SerializationTokenType.False: result = false; break; case SerializationTokenType.Null: result = null; break; case SerializationTokenType.Object: result = new object(); break; case SerializationTokenType.Int: result = @this.ReadInt(); break; case SerializationTokenType.Uint: result = @this.ReadUInt(); break; case SerializationTokenType.Short: result = @this.ReadShort(); break; case SerializationTokenType.Ushort: result = @this.ReadUShort(); break; case SerializationTokenType.Long: result = @this.ReadLong(); break; case SerializationTokenType.Ulong: result = @this.ReadULong(); break; case SerializationTokenType.Byte: result = @this.ReadByte(); break; case SerializationTokenType.Sbyte: result = @this.ReadSByte(); break; case SerializationTokenType.Float: result = @this.ReadFloat(); break; case SerializationTokenType.Double: result = @this.ReadDouble(); break; case SerializationTokenType.Decimal: result = @this.ReadDecimal(); break; case SerializationTokenType.String: result = @this.ReadString(); break; case SerializationTokenType.Character: result = @this.ReadChar(); break; case SerializationTokenType.Guid: bytes = @this.ReadBytes(16); result = new Guid(bytes); break; case SerializationTokenType.Date: result = DateTime.FromBinary(@this.ReadLong()); break; case SerializationTokenType.TimeSpan: result = new TimeSpan(@this.ReadLong()); break; case SerializationTokenType.GrainId: result = @this.ReadGrainId(); break; case SerializationTokenType.ActivationId: result = @this.ReadActivationId(); break; case SerializationTokenType.SiloAddress: result = @this.ReadSiloAddress(); break; case SerializationTokenType.ActivationAddress: result = @this.ReadActivationAddress(); break; case SerializationTokenType.IpAddress: result = @this.ReadIPAddress(); break; case SerializationTokenType.IpEndPoint: result = @this.ReadIPEndPoint(); break; case SerializationTokenType.CorrelationId: result = new CorrelationId(@this.ReadBytes(CorrelationId.SIZE_BYTES)); break; default: result = null; return false; } return true; } internal static Type CheckSpecialTypeCode(SerializationTokenType token) { switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); #if false // Note: not yet implemented as simple types on the Writer side case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); #endif default: break; } return null; } /// <summary> Read a <c>Type</c> value from the stream. </summary> internal static Type ReadSpecifiedTypeHeader(this IBinaryTokenStreamReader @this, SerializationManager serializationManager) { // Assumes that the SpecifiedType token has already been read var token = @this.ReadToken(); switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); case SerializationTokenType.Request: return typeof(InvokeMethodRequest); case SerializationTokenType.Response: return typeof(Response); case SerializationTokenType.StringObjDict: return typeof(Dictionary<string, object>); case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.Tuple + 1: return typeof(Tuple<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Tuple + 2: return typeof(Tuple<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.Tuple + 3: return typeof(Tuple<,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 3)); case SerializationTokenType.Tuple + 4: return typeof(Tuple<,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 4)); case SerializationTokenType.Tuple + 5: return typeof(Tuple<,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 5)); case SerializationTokenType.Tuple + 6: return typeof(Tuple<,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 6)); case SerializationTokenType.Tuple + 7: return typeof(Tuple<,,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 7)); case SerializationTokenType.Array + 1: var et1 = @this.ReadFullTypeHeader(serializationManager); return et1.MakeArrayType(); case SerializationTokenType.Array + 2: var et2 = @this.ReadFullTypeHeader(serializationManager); return et2.MakeArrayType(2); case SerializationTokenType.Array + 3: var et3 = @this.ReadFullTypeHeader(serializationManager); return et3.MakeArrayType(3); case SerializationTokenType.Array + 4: var et4 = @this.ReadFullTypeHeader(serializationManager); return et4.MakeArrayType(4); case SerializationTokenType.Array + 5: var et5 = @this.ReadFullTypeHeader(serializationManager); return et5.MakeArrayType(5); case SerializationTokenType.Array + 6: var et6 = @this.ReadFullTypeHeader(serializationManager); return et6.MakeArrayType(6); case SerializationTokenType.Array + 7: var et7 = @this.ReadFullTypeHeader(serializationManager); return et7.MakeArrayType(7); case SerializationTokenType.Array + 8: var et8 = @this.ReadFullTypeHeader(serializationManager); return et8.MakeArrayType(8); case SerializationTokenType.List: return typeof(List<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Dictionary: return typeof(Dictionary<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.KeyValuePair: return typeof(KeyValuePair<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.Set: return typeof(HashSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.SortedList: return typeof(SortedList<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.SortedSet: return typeof(SortedSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Stack: return typeof(Stack<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Queue: return typeof(Queue<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.LinkedList: return typeof(LinkedList<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Nullable: return typeof(Nullable<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); case SerializationTokenType.SByteArray: return typeof(sbyte[]); case SerializationTokenType.NamedType: var typeName = @this.ReadString(); try { return serializationManager.ResolveTypeName(typeName); } catch (TypeAccessException ex) { throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message); } default: break; } throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference"); } /// <summary> Read a <c>Type</c> value from the stream. </summary> /// <param name="this">The IBinaryTokenStreamReader to read from</param> /// <param name="serializationManager">The serialization manager used to resolve type names.</param> /// <param name="expected">Expected Type, if known.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> private static Type ReadFullTypeHeader(this IBinaryTokenStreamReader @this, SerializationManager serializationManager, Type expected = null) { var token = @this.ReadToken(); if (token == SerializationTokenType.ExpectedType) { return expected; } var t = CheckSpecialTypeCode(token); if (t != null) { return t; } if (token == SerializationTokenType.SpecifiedType) { #if TRACE_SERIALIZATION var tt = ReadSpecifiedTypeHeader(); Trace("--Read specified type header for type {0}", tt); return tt; #else return @this.ReadSpecifiedTypeHeader(serializationManager); #endif } throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected"); } private static Type[] ReadGenericArguments(this IBinaryTokenStreamReader @this, SerializationManager serializationManager, int n) { var args = new Type[n]; for (var i = 0; i < n; i++) { args[i] = @this.ReadFullTypeHeader(serializationManager); } return args; } } /// <summary> /// Reader for Orleans binary token streams /// </summary> public class BinaryTokenStreamReader : IBinaryTokenStreamReader { private IList<ArraySegment<byte>> buffers; private int buffersCount; private int currentSegmentIndex; private ArraySegment<byte> currentSegment; private byte[] currentBuffer; private int currentOffset; private int currentSegmentOffset; private int currentSegmentCount; private int totalProcessedBytes; private int currentSegmentOffsetPlusCount; private int totalLength; private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]); private static readonly byte[] emptyByteArray = new byte[0]; /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input byte array. /// </summary> /// <param name="input">Input binary data to be tokenized.</param> public BinaryTokenStreamReader(byte[] input) : this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) }) { } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffers. /// </summary> /// <param name="buffs">The list of ArraySegments to use for the data.</param> public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs) { this.Reset(buffs); Trace("Starting new stream reader"); } /// <summary> /// Resets this instance with the provided data. /// </summary> /// <param name="buffs">The underlying buffers.</param> public void Reset(IList<ArraySegment<byte>> buffs) { buffers = buffs; totalProcessedBytes = 0; currentSegmentIndex = 0; InitializeCurrentSegment(0); totalLength = buffs.Sum(b => b.Count); buffersCount = buffs.Count; } private void InitializeCurrentSegment(int segmentIndex) { currentSegment = buffers[segmentIndex]; currentBuffer = currentSegment.Array; currentOffset = currentSegment.Offset; currentSegmentOffset = currentOffset; currentSegmentCount = currentSegment.Count; currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount; } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffer. /// </summary> /// <param name="buff">ArraySegment to use for the data.</param> public BinaryTokenStreamReader(ArraySegment<byte> buff) : this(new[] { buff }) { } /// <summary> Current read position in the stream. </summary> public int CurrentPosition => currentOffset + totalProcessedBytes - currentSegmentOffset; /// <summary> /// Gets the total length. /// </summary> public int Length => this.totalLength; /// <summary> /// Creates a copy of the current stream reader. /// </summary> /// <returns>The new copy</returns> public IBinaryTokenStreamReader Copy() { return new BinaryTokenStreamReader(this.buffers); } private void StartNextSegment() { totalProcessedBytes += currentSegment.Count; currentSegmentIndex++; if (currentSegmentIndex < buffersCount) { InitializeCurrentSegment(currentSegmentIndex); } else { currentSegment = emptySegment; currentBuffer = null; currentOffset = 0; currentSegmentOffset = 0; currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount; } } private byte[] CheckLength(int n, out int offset) { bool ignore; byte[] res; if (TryCheckLengthFast(n, out res, out offset, out ignore)) { return res; } return CheckLength(n, out offset, out ignore); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryCheckLengthFast(int n, out byte[] res, out int offset, out bool safeToUse) { safeToUse = false; res = null; offset = 0; var nextOffset = currentOffset + n; if (nextOffset <= currentSegmentOffsetPlusCount) { offset = currentOffset; currentOffset = nextOffset; res = currentBuffer; return true; } return false; } private byte[] CheckLength(int n, out int offset, out bool safeToUse) { safeToUse = false; offset = 0; if (currentOffset == currentSegmentOffsetPlusCount) { StartNextSegment(); } byte[] res; if (TryCheckLengthFast(n, out res, out offset, out safeToUse)) { return res; } if ((CurrentPosition + n > totalLength)) { throw new SerializationException( String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}", CurrentPosition, n, totalLength)); } var temp = new byte[n]; var i = 0; while (i < n) { var segmentOffsetPlusCount = currentSegmentOffsetPlusCount; var bytesFromThisBuffer = Math.Min(segmentOffsetPlusCount - currentOffset, n - i); Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer); i += bytesFromThisBuffer; currentOffset += bytesFromThisBuffer; if (currentOffset >= segmentOffsetPlusCount) { if (currentSegmentIndex >= buffersCount) { throw new SerializationException( String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count)); } StartNextSegment(); } } safeToUse = true; offset = 0; return temp; } /// <summary> Read a <c>bool</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public bool ReadBoolean() { return ReadToken() == SerializationTokenType.True; } /// <summary> Read an <c>Int32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public int ReadInt() { int offset; var buff = CheckLength(sizeof(int), out offset); var val = BitConverter.ToInt32(buff, offset); Trace("--Read int {0}", val); return val; } /// <summary> Read an <c>UInt32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public uint ReadUInt() { int offset; var buff = CheckLength(sizeof(uint), out offset); var val = BitConverter.ToUInt32(buff, offset); Trace("--Read uint {0}", val); return val; } /// <summary> Read an <c>Int16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public short ReadShort() { int offset; var buff = CheckLength(sizeof(short), out offset); var val = BitConverter.ToInt16(buff, offset); Trace("--Read short {0}", val); return val; } /// <summary> Read an <c>UInt16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ushort ReadUShort() { int offset; var buff = CheckLength(sizeof(ushort), out offset); var val = BitConverter.ToUInt16(buff, offset); Trace("--Read ushort {0}", val); return val; } /// <summary> Read an <c>Int64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public long ReadLong() { int offset; var buff = CheckLength(sizeof(long), out offset); var val = BitConverter.ToInt64(buff, offset); Trace("--Read long {0}", val); return val; } /// <summary> Read an <c>UInt64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ulong ReadULong() { int offset; var buff = CheckLength(sizeof(ulong), out offset); var val = BitConverter.ToUInt64(buff, offset); Trace("--Read ulong {0}", val); return val; } /// <summary> Read an <c>float</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public float ReadFloat() { int offset; var buff = CheckLength(sizeof(float), out offset); var val = BitConverter.ToSingle(buff, offset); Trace("--Read float {0}", val); return val; } /// <summary> Read an <c>double</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public double ReadDouble() { int offset; var buff = CheckLength(sizeof(double), out offset); var val = BitConverter.ToDouble(buff, offset); Trace("--Read double {0}", val); return val; } /// <summary> Read an <c>decimal</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public decimal ReadDecimal() { int offset; var buff = CheckLength(4 * sizeof(int), out offset); var raw = new int[4]; Trace("--Read decimal"); var n = offset; for (var i = 0; i < 4; i++) { raw[i] = BitConverter.ToInt32(buff, n); n += sizeof(int); } return new decimal(raw); } public DateTime ReadDateTime() { var n = ReadLong(); return n == 0 ? default(DateTime) : DateTime.FromBinary(n); } /// <summary> Read an <c>string</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public string ReadString() { var n = ReadInt(); if (n == 0) { Trace("--Read empty string"); return String.Empty; } string s = null; // a length of -1 indicates that the string is null. if (-1 != n) { int offset; var buff = CheckLength(n, out offset); s = Encoding.UTF8.GetString(buff, offset, n); } Trace("--Read string '{0}'", s); return s; } /// <summary> Read the next bytes from the stream. </summary> /// <param name="count">Number of bytes to read.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte[] ReadBytes(int count) { if (count == 0) { return emptyByteArray; } bool safeToUse; int offset; byte[] buff; if (!TryCheckLengthFast(count, out buff, out offset, out safeToUse)) { buff = CheckLength(count, out offset, out safeToUse); } Trace("--Read byte array of length {0}", count); if (!safeToUse) { var result = new byte[count]; Array.Copy(buff, offset, result, 0, count); return result; } else { return buff; } } /// <summary> Read the next bytes from the stream. </summary> /// <param name="destination">Output array to store the returned data in.</param> /// <param name="offset">Offset into the destination array to write to.</param> /// <param name="count">Number of bytes to read.</param> public void ReadByteArray(byte[] destination, int offset, int count) { if (offset + count > destination.Length) { throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small"); } var buffOffset = 0; var buff = count == 0 ? emptyByteArray : CheckLength(count, out buffOffset); Buffer.BlockCopy(buff, buffOffset, destination, offset, count); } /// <summary> Read an <c>char</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public char ReadChar() { Trace("--Read char"); return Convert.ToChar(ReadShort()); } /// <summary> Read an <c>byte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte ReadByte() { int offset; var buff = CheckLength(1, out offset); Trace("--Read byte"); return buff[offset]; } /// <summary> Read an <c>sbyte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public sbyte ReadSByte() { int offset; var buff = CheckLength(1, out offset); Trace("--Read sbyte"); return unchecked((sbyte)(buff[offset])); } /// <summary> Read an <c>IPAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPAddress ReadIPAddress() { int offset; var buff = CheckLength(16, out offset); bool v4 = true; for (var i = 0; i < 12; i++) { if (buff[offset + i] != 0) { v4 = false; break; } } if (v4) { var v4Bytes = new byte[4]; for (var i = 0; i < 4; i++) { v4Bytes[i] = buff[offset + 12 + i]; } return new IPAddress(v4Bytes); } else { var v6Bytes = new byte[16]; for (var i = 0; i < 16; i++) { v6Bytes[i] = buff[offset + i]; } return new IPAddress(v6Bytes); } } public Guid ReadGuid() { byte[] bytes = ReadBytes(16); return new Guid(bytes); } /// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPEndPoint ReadIPEndPoint() { var addr = ReadIPAddress(); var port = ReadInt(); return new IPEndPoint(addr, port); } /// <summary> Read an <c>SiloAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public SiloAddress ReadSiloAddress() { var ep = ReadIPEndPoint(); var gen = ReadInt(); return SiloAddress.New(ep, gen); } public TimeSpan ReadTimeSpan() { return new TimeSpan(ReadLong()); } /// <summary> /// Read a block of data into the specified output <c>Array</c>. /// </summary> /// <param name="array">Array to output the data to.</param> /// <param name="n">Number of bytes to read.</param> public void ReadBlockInto(Array array, int n) { int offset; var buff = CheckLength(n, out offset); Buffer.BlockCopy(buff, offset, array, 0, n); Trace("--Read block of {0} bytes", n); } private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentPosition); trace.Flush(); } /// <summary> /// Peek at the next token in this input stream. /// </summary> /// <returns>Next token thatr will be read from the stream.</returns> internal SerializationTokenType PeekToken() { if (currentOffset == currentSegment.Count + currentSegment.Offset) StartNextSegment(); return (SerializationTokenType)currentBuffer[currentOffset]; } /// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal SerializationTokenType ReadToken() { int offset; var buff = CheckLength(1, out offset); return (SerializationTokenType)buff[offset]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single> { private float m_value; // Do not rename (binary serialization) // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const float NegativeZero = (float)-0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) < 0x7F800000; } /// <summary>Determines whether the specified value is infinite.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; } /// <summary>Determines whether the specified value is NaN.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; } /// <summary>Determines whether the specified value is negative.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(float f) { var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); return (bits & 0x80000000) == 0x80000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0); } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public unsafe override int GetHashCode() { float f = m_value; if (f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static float Parse(String s, NumberStyles style, NumberFormatInfo info) { return Number.ParseSingle(s, style, info); } public static Boolean TryParse(String s, out Single result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(String s, NumberStyles style, NumberFormatInfo info, out Single result) { if (s == null) { result = 0; return false; } bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { String sTrim = s.Trim(); if (sTrim.Equals(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (sTrim.Equals(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (sTrim.Equals(info.NaNSymbol)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// 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 Internal.Metadata.NativeFormat.Writer; using Ecma = System.Reflection.Metadata; using Cts = Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using TypeAttributes = System.Reflection.TypeAttributes; namespace ILCompiler.Metadata { partial class Transform<TPolicy> { internal EntityMap<Cts.TypeDesc, MetadataRecord> _types = new EntityMap<Cts.TypeDesc, MetadataRecord>(EqualityComparer<Cts.TypeDesc>.Default); private Action<Cts.MetadataType, TypeDefinition> _initTypeDef; private Action<Cts.MetadataType, TypeReference> _initTypeRef; private Action<Cts.ArrayType, TypeSpecification> _initSzArray; private Action<Cts.ArrayType, TypeSpecification> _initArray; private Action<Cts.ByRefType, TypeSpecification> _initByRef; private Action<Cts.PointerType, TypeSpecification> _initPointer; private Action<Cts.InstantiatedType, TypeSpecification> _initTypeInst; private Action<Cts.SignatureTypeVariable, TypeSpecification> _initTypeVar; private Action<Cts.SignatureMethodVariable, TypeSpecification> _initMethodVar; public override MetadataRecord HandleType(Cts.TypeDesc type) { Debug.Assert(!IsBlocked(type)); MetadataRecord rec; if (_types.TryGet(type, out rec)) { return rec; } if (type.IsSzArray) { var arrayType = (Cts.ArrayType)type; rec = _types.Create(arrayType, _initSzArray ?? (_initSzArray = InitializeSzArray)); } else if (type.IsArray) { var arrayType = (Cts.ArrayType)type; rec = _types.Create(arrayType, _initArray ?? (_initArray = InitializeArray)); } else if (type.IsByRef) { var byRefType = (Cts.ByRefType)type; rec = _types.Create(byRefType, _initByRef ?? (_initByRef = InitializeByRef)); } else if (type.IsPointer) { var pointerType = (Cts.PointerType)type; rec = _types.Create(pointerType, _initPointer ?? (_initPointer = InitializePointer)); } else if (type is Cts.SignatureTypeVariable) { var variable = (Cts.SignatureTypeVariable)type; rec = _types.Create(variable, _initTypeVar ?? (_initTypeVar = InitializeTypeVariable)); } else if (type is Cts.SignatureMethodVariable) { var variable = (Cts.SignatureMethodVariable)type; rec = _types.Create(variable, _initMethodVar ?? (_initMethodVar = InitializeMethodVariable)); } else if (type is Cts.InstantiatedType) { var instType = (Cts.InstantiatedType)type; rec = _types.Create(instType, _initTypeInst ?? (_initTypeInst = InitializeTypeInstance)); } else { var metadataType = (Cts.MetadataType)type; if (_policy.GeneratesMetadata(metadataType)) { rec = _types.Create(metadataType, _initTypeDef ?? (_initTypeDef = InitializeTypeDef)); } else { rec = _types.Create(metadataType, _initTypeRef ?? (_initTypeRef = InitializeTypeRef)); } } Debug.Assert(rec is TypeDefinition || rec is TypeReference || rec is TypeSpecification); return rec; } private void InitializeSzArray(Cts.ArrayType entity, TypeSpecification record) { record.Signature = new SZArraySignature { ElementType = HandleType(entity.ElementType), }; } private void InitializeArray(Cts.ArrayType entity, TypeSpecification record) { record.Signature = new ArraySignature { ElementType = HandleType(entity.ElementType), Rank = entity.Rank, // TODO: LowerBounds // TODO: Sizes }; } private void InitializeByRef(Cts.ByRefType entity, TypeSpecification record) { record.Signature = new ByReferenceSignature { Type = HandleType(entity.ParameterType) }; } private void InitializePointer(Cts.PointerType entity, TypeSpecification record) { record.Signature = new PointerSignature { Type = HandleType(entity.ParameterType) }; } private void InitializeTypeVariable(Cts.SignatureTypeVariable entity, TypeSpecification record) { record.Signature = new TypeVariableSignature { Number = entity.Index }; } private void InitializeMethodVariable(Cts.SignatureMethodVariable entity, TypeSpecification record) { record.Signature = new MethodTypeVariableSignature { Number = entity.Index }; } private void InitializeTypeInstance(Cts.InstantiatedType entity, TypeSpecification record) { var sig = new TypeInstantiationSignature { GenericType = HandleType(entity.GetTypeDefinition()), }; for (int i = 0; i < entity.Instantiation.Length; i++) { sig.GenericTypeArguments.Add(HandleType(entity.Instantiation[i])); } record.Signature = sig; } private TypeReference GetNestedReferenceParent(Cts.MetadataType entity) { // This special code deals with the metadata format requirement saying that // nested type *references* need to have a type *reference* as their containing type. // This is potentially in conflict with our other rule that says to always resolve // references to their definition records (we are avoiding emitting references // to things that have a definition within the same blob to save space). Cts.MetadataType containingType = entity.ContainingType; MetadataRecord parentRecord = HandleType(containingType); TypeReference parentReferenceRecord = parentRecord as TypeReference; if (parentReferenceRecord != null) { // Easy case - parent type doesn't have a definition record. return parentReferenceRecord; } // Parent has a type definition record. We need to make a new record that's a reference. // We don't bother with interning these because this will be rare and metadata writer // will do the interning anyway. Debug.Assert(parentRecord is TypeDefinition); parentReferenceRecord = new TypeReference { TypeName = HandleString(containingType.Name), }; if (containingType.ContainingType != null) { parentReferenceRecord.ParentNamespaceOrType = GetNestedReferenceParent(containingType); } else { parentReferenceRecord.ParentNamespaceOrType = HandleNamespaceReference(_policy.GetModuleOfType(containingType), containingType.Namespace); } return parentReferenceRecord; } private void InitializeTypeRef(Cts.MetadataType entity, TypeReference record) { Debug.Assert(entity.IsTypeDefinition); if (entity.ContainingType != null) { record.ParentNamespaceOrType = GetNestedReferenceParent(entity); } else { record.ParentNamespaceOrType = HandleNamespaceReference(_policy.GetModuleOfType(entity), entity.Namespace); } record.TypeName = HandleString(entity.Name); } private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) { Debug.Assert(entity.IsTypeDefinition); if (entity.ContainingType != null) { var enclosingType = (TypeDefinition)HandleType(entity.ContainingType); record.EnclosingType = enclosingType; enclosingType.NestedTypes.Add(record); var namespaceDefinition = HandleNamespaceDefinition(_policy.GetModuleOfType(entity.ContainingType), entity.ContainingType.Namespace); record.NamespaceDefinition = namespaceDefinition; } else { var namespaceDefinition = HandleNamespaceDefinition(_policy.GetModuleOfType(entity), entity.Namespace); record.NamespaceDefinition = namespaceDefinition; namespaceDefinition.TypeDefinitions.Add(record); } record.Name = HandleString(entity.Name); Cts.ClassLayoutMetadata layoutMetadata = entity.GetClassLayout(); record.Size = checked((uint)layoutMetadata.Size); record.PackingSize = checked((ushort)layoutMetadata.PackingSize); record.Flags = GetTypeAttributes(entity); if (entity.HasBaseType) { record.BaseType = HandleType(entity.BaseType); } record.Interfaces.Capacity = entity.ExplicitlyImplementedInterfaces.Length; foreach (var interfaceType in entity.ExplicitlyImplementedInterfaces) { if (IsBlocked(interfaceType)) continue; record.Interfaces.Add(HandleType(interfaceType)); } if (entity.HasInstantiation) { record.GenericParameters.Capacity = entity.Instantiation.Length; foreach (var p in entity.Instantiation) record.GenericParameters.Add(HandleGenericParameter((Cts.GenericParameterDesc)p)); } foreach (var field in entity.GetFields()) { if (_policy.GeneratesMetadata(field)) { record.Fields.Add(HandleFieldDefinition(field)); } } foreach (var method in entity.GetMethods()) { if (_policy.GeneratesMetadata(method)) { record.Methods.Add(HandleMethodDefinition(method)); } } var ecmaEntity = entity as Cts.Ecma.EcmaType; if (ecmaEntity != null) { Ecma.TypeDefinition ecmaRecord = ecmaEntity.MetadataReader.GetTypeDefinition(ecmaEntity.Handle); foreach (var e in ecmaRecord.GetEvents()) { Event evt = HandleEvent(ecmaEntity.EcmaModule, e); if (evt != null) record.Events.Add(evt); } foreach (var property in ecmaRecord.GetProperties()) { Property prop = HandleProperty(ecmaEntity.EcmaModule, property); if (prop != null) record.Properties.Add(prop); } Ecma.CustomAttributeHandleCollection customAttributes = ecmaRecord.GetCustomAttributes(); if (customAttributes.Count > 0) { record.CustomAttributes = HandleCustomAttributes(ecmaEntity.EcmaModule, customAttributes); } foreach (var miHandle in ecmaRecord.GetMethodImplementations()) { Ecma.MetadataReader reader = ecmaEntity.EcmaModule.MetadataReader; Ecma.MethodImplementation miDef = reader.GetMethodImplementation(miHandle); Cts.MethodDesc methodBody = (Cts.MethodDesc)ecmaEntity.EcmaModule.GetObject(miDef.MethodBody); Cts.MethodDesc methodDecl = (Cts.MethodDesc)ecmaEntity.EcmaModule.GetObject(miDef.MethodDeclaration); MethodImpl methodImplRecord = new MethodImpl { MethodBody = HandleQualifiedMethod(methodBody), MethodDeclaration = HandleQualifiedMethod(methodDecl) }; record.MethodImpls.Add(methodImplRecord); } } } private TypeAttributes GetTypeAttributes(Cts.MetadataType type) { TypeAttributes result; var ecmaType = type as Cts.Ecma.EcmaType; if (ecmaType != null) { Ecma.TypeDefinition ecmaRecord = ecmaType.MetadataReader.GetTypeDefinition(ecmaType.Handle); result = ecmaRecord.Attributes; } else { result = 0; if (type.IsExplicitLayout) result |= TypeAttributes.ExplicitLayout; if (type.IsSequentialLayout) result |= TypeAttributes.SequentialLayout; if (type.IsInterface) result |= TypeAttributes.Interface; if (type.IsSealed) result |= TypeAttributes.Sealed; if (type.IsBeforeFieldInit) result |= TypeAttributes.BeforeFieldInit; // Not set: Abstract, Ansi/Unicode/Auto, HasSecurity, Import, visibility, Serializable, // WindowsRuntime, HasSecurity, SpecialName, RTSpecialName } return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Rate.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeFixes; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Linq; using Microsoft.CodeAnalysis.Formatting; namespace RefactoringEssentials.CSharp.Diagnostics { [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] public class CompareOfFloatsByEqualityOperatorCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CSharpDiagnosticIDs.CompareOfFloatsByEqualityOperatorAnalyzerID); } } // Does not make sense here, because the fixes produce code that is not compilable //public override FixAllProvider GetFixAllProvider() //{ // return WellKnownFixAllProviders.BatchFixer; //} public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span) as BinaryExpressionSyntax; if (node == null) return; CodeAction action; var floatType = diagnostic.Descriptor.CustomTags.ElementAt(1); switch (diagnostic.Descriptor.CustomTags.ElementAt(0)) { case "1": action = AddIsNaNIssue(document, semanticModel, root, node, node.Right, floatType); break; case "2": action = AddIsNaNIssue(document, semanticModel, root, node, node.Left, floatType); break; case "3": action = AddIsPositiveInfinityIssue(document, semanticModel, root, node, node.Right, floatType); break; case "4": action = AddIsPositiveInfinityIssue(document, semanticModel, root, node, node.Left, floatType); break; case "5": action = AddIsNegativeInfinityIssue(document, semanticModel, root, node, node.Right, floatType); break; case "6": action = AddIsNegativeInfinityIssue(document, semanticModel, root, node, node.Left, floatType); break; case "7": action = AddIsZeroIssue(document, semanticModel, root, node, node.Right, floatType); break; case "8": action = AddIsZeroIssue(document, semanticModel, root, node, node.Left, floatType); break; default: action = AddCompareIssue(document, semanticModel, root, node, floatType); break; } if (action != null) { context.RegisterCodeFix(action, diagnostic); } } static CodeAction AddIsNaNIssue(Document document, SemanticModel semanticModel, SyntaxNode root, BinaryExpressionSyntax node, ExpressionSyntax argExpr, string floatType) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Warning, string.Format(node.IsKind(SyntaxKind.EqualsExpression) ? "Replace with '{0}.IsNaN(...)' call" : "Replace with '!{0}.IsNaN(...)' call", floatType), token => { SyntaxNode newRoot; ExpressionSyntax expr; var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(argExpr)); expr = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(floatType), SyntaxFactory.IdentifierName("IsNaN") ), SyntaxFactory.ArgumentList( arguments ) ); if (node.IsKind(SyntaxKind.NotEqualsExpression)) expr = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, expr); expr = expr.WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode((SyntaxNode)node, expr); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); } static CodeAction AddIsPositiveInfinityIssue(Document document, SemanticModel semanticModel, SyntaxNode root, BinaryExpressionSyntax node, ExpressionSyntax argExpr, string floatType) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Warning, string.Format(node.IsKind(SyntaxKind.EqualsExpression) ? "Replace with '{0}.IsPositiveInfinity(...)' call" : "Replace with '!{0}.IsPositiveInfinity(...)' call", floatType), token => { SyntaxNode newRoot; ExpressionSyntax expr; var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(argExpr)); expr = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(floatType), SyntaxFactory.IdentifierName("IsPositiveInfinity") ), SyntaxFactory.ArgumentList( arguments ) ); if (node.IsKind(SyntaxKind.NotEqualsExpression)) expr = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, expr); expr = expr.WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode((SyntaxNode)node, expr); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); } static CodeAction AddIsNegativeInfinityIssue(Document document, SemanticModel semanticModel, SyntaxNode root, BinaryExpressionSyntax node, ExpressionSyntax argExpr, string floatType) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Warning, string.Format(node.IsKind(SyntaxKind.EqualsExpression) ? "Replace with '{0}.IsNegativeInfinity(...)' call" : "Replace with '!{0}.IsNegativeInfinity(...)' call", floatType), token => { SyntaxNode newRoot; ExpressionSyntax expr; var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(argExpr)); expr = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(floatType), SyntaxFactory.IdentifierName("IsNegativeInfinity") ), SyntaxFactory.ArgumentList( arguments ) ); if (node.IsKind(SyntaxKind.NotEqualsExpression)) expr = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, expr); expr = expr.WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode((SyntaxNode)node, expr); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); } static CodeAction AddIsZeroIssue(Document document, SemanticModel semanticModel, SyntaxNode root, BinaryExpressionSyntax node, ExpressionSyntax argExpr, string floatType) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Warning, "Fix floating point number comparison", token => { SyntaxNode newRoot; ExpressionSyntax expr; var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(argExpr)); expr = SyntaxFactory.BinaryExpression( node.IsKind(SyntaxKind.EqualsExpression) ? SyntaxKind.LessThanExpression : SyntaxKind.GreaterThanExpression, SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseTypeName("System.Math").WithAdditionalAnnotations(Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation), SyntaxFactory.IdentifierName("Abs") ), SyntaxFactory.ArgumentList( arguments ) ), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("EPSILON").WithAdditionalAnnotations(RenameAnnotation.Create())) ); expr = expr.WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode((SyntaxNode)node, expr); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); } static CodeAction AddCompareIssue(Document document, SemanticModel semanticModel, SyntaxNode root, BinaryExpressionSyntax node, string floatType) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Warning, "Fix floating point number comparison", token => { SyntaxNode newRoot; ExpressionSyntax expr; var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, node.Left, node.Right))); expr = SyntaxFactory.BinaryExpression( node.IsKind(SyntaxKind.EqualsExpression) ? SyntaxKind.LessThanExpression : SyntaxKind.GreaterThanExpression, SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseTypeName("System.Math").WithAdditionalAnnotations(Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation), SyntaxFactory.IdentifierName("Abs") ), SyntaxFactory.ArgumentList( arguments ) ), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("EPSILON").WithAdditionalAnnotations(RenameAnnotation.Create())) ); expr = expr.WithAdditionalAnnotations(Formatter.Annotation); newRoot = root.ReplaceNode((SyntaxNode)node, expr); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); } } }
// // 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.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.OperationalInsights; using Microsoft.Azure.Management.OperationalInsights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.OperationalInsights { /// <summary> /// Operations for managing Operational Insights linked services. /// </summary> internal partial class LinkedServiceOperations : IServiceOperations<OperationalInsightsManagementClient>, ILinkedServiceOperations { /// <summary> /// Initializes a new instance of the LinkedServiceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal LinkedServiceOperations(OperationalInsightsManagementClient client) { this._client = client; } private OperationalInsightsManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.OperationalInsights.OperationalInsightsManagementClient. /// </summary> public OperationalInsightsManagementClient Client { get { return this._client; } } /// <summary> /// Create or update a linked service. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the linked service. /// </param> /// <param name='workspaceName'> /// Required. The name of the parent workspace that will contain the /// linked service /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a linked /// service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update linked service operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string workspaceName, LinkedServiceCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (workspaceName == null) { throw new ArgumentNullException("workspaceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.ResourceId == null) { throw new ArgumentNullException("parameters.Properties.ResourceId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.OperationalInsights/workspaces/"; url = url + Uri.EscapeDataString(workspaceName); url = url + "/linkedServices/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject linkedServiceCreateOrUpdateParametersValue = new JObject(); requestDoc = linkedServiceCreateOrUpdateParametersValue; linkedServiceCreateOrUpdateParametersValue["name"] = parameters.Name; JObject propertiesValue = new JObject(); linkedServiceCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["resourceId"] = parameters.Properties.ResourceId; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); linkedServiceInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); linkedServiceInstance.Type = typeInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken resourceIdValue = propertiesValue2["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes a linked service instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the linked service. /// </param> /// <param name='workspaceName'> /// Required. The name of the workspace that contains the linked /// service. /// </param> /// <param name='linkedServiceName'> /// Required. Name of the linked service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string workspaceName, string linkedServiceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (workspaceName == null) { throw new ArgumentNullException("workspaceName"); } if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("linkedServiceName", linkedServiceName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.OperationalInsights/workspaces/"; url = url + Uri.EscapeDataString(workspaceName); url = url + "/linkedServices/"; url = url + Uri.EscapeDataString(linkedServiceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a linked service instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the linked service. /// </param> /// <param name='workspaceName'> /// Required. The name of the workspace that contains the linked /// service. /// </param> /// <param name='linkedServiceName'> /// Required. Name of the linked service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The get linked service operation response. /// </returns> public async Task<LinkedServiceGetResponse> GetAsync(string resourceGroupName, string workspaceName, string linkedServiceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (workspaceName == null) { throw new ArgumentNullException("workspaceName"); } if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("linkedServiceName", linkedServiceName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.OperationalInsights/workspaces/"; url = url + Uri.EscapeDataString(workspaceName); url = url + "/linkedServices/"; url = url + Uri.EscapeDataString(linkedServiceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); linkedServiceInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); linkedServiceInstance.Type = typeInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken resourceIdValue = propertiesValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the first page of linked services instances in a workspace /// with the link to the next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the linked services. /// </param> /// <param name='workspaceName'> /// Required. The workspace that contains the linked services. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The list linked service operation response. /// </returns> public async Task<LinkedServiceListResponse> ListAsync(string resourceGroupName, string workspaceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (workspaceName == null) { throw new ArgumentNullException("workspaceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.OperationalInsights/workspaces/"; url = url + Uri.EscapeDataString(workspaceName); url = url + "/linkedServices"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedServices.Add(linkedServiceInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); linkedServiceInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); linkedServiceInstance.Type = typeInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken resourceIdValue = propertiesValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of linked service instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next linked service page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The list linked service operation response. /// </returns> public async Task<LinkedServiceListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedServices.Add(linkedServiceInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); linkedServiceInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); linkedServiceInstance.Type = typeInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken resourceIdValue = propertiesValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace NetOffice.DeveloperToolbox.Controls.Text { public partial class Scroller : UserControl { /// <summary> /// String list. /// </summary> string[] m_text = new string[0]; /// <summary> /// Offset for animation. /// </summary> int m_scrollingOffset = 0; /// <summary> /// Top part size of text in percents. /// </summary> int m_topPartSizePercent = 50; /// <summary> /// Font, which is used to draw. /// </summary> Font m_font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel); /// <summary> /// Constructor /// </summary> public Scroller() { InitializeComponent(); // Enables double buffering (to remove flickering) and enables user paint. SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); } /// <summary> /// Text to scroll. /// </summary> public string TextToScroll { get { return string.Join("\n", m_text); } set { string buffer = value; // Splits text by "\n" symbol. m_text = buffer.Split(new char[1] { '\n' }); } } /// <summary> /// Timer interval. /// </summary> public int Interval { get { return m_timer.Interval; } set { m_timer.Interval = value; } } /// <summary> /// Font, which is used to draw. /// </summary> public Font TextFont { get { return m_font; } set { m_font = value; } } /// <summary> /// Top part size of text in percents (of control width). /// </summary> public int TopPartSizePercent { get { return m_topPartSizePercent; } set { if ((value >= 10) && (value <= 100)) { m_topPartSizePercent = value; } else throw new InvalidEnumArgumentException("The value must be more than zero. and less than 100."); } } /// <summary> /// Paint handler. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPaint(object sender, PaintEventArgs e) { // Sets antialiasing mode for better quality. e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // Prepares background. e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle); // Creates GraphicsPath for text. GraphicsPath path = new GraphicsPath(); // Visible lines counter; int visibleLines = 0; for (int i = m_text.Length - 1; i >= 0; i--) { Point pt = new Point((int)((this.ClientSize.Width - e.Graphics.MeasureString(m_text[i], m_font).Width) / 2), (int)(m_scrollingOffset + this.ClientSize.Height - (m_text.Length - i) * m_font.Size)); // Adds visible lines to path. if ((pt.Y + this.Font.Size > 0) && (pt.Y < this.Height)) { path.AddString(m_text[i], m_font.FontFamily, (int)m_font.Style, m_font.Size, pt, StringFormat.GenericTypographic); visibleLines++; } } // For repeat scrolling. if ((visibleLines == 0) && (m_scrollingOffset < 0)) { m_scrollingOffset = (int)this.Font.SizeInPoints * m_text.Length; } int topSizeWidth = (int)(this.Width * m_topPartSizePercent / 100.0f); // Wraps Graphics path from rectangle to trapeze. path.Warp( new PointF[4] { new PointF((this.Width - topSizeWidth) / 2, 0), new PointF(this.Width - (this.Width - topSizeWidth) / 2, 0), new PointF(0, this.Height), new PointF(this.Width, this.Height) }, new RectangleF(this.ClientRectangle.X, this.ClientRectangle.Y, this.ClientRectangle.Width, this.ClientRectangle.Height), null, WarpMode.Perspective ); // Draws wrapped path. e.Graphics.FillPath(new SolidBrush(this.ForeColor), path); path.Dispose(); // Draws fog effect with help of gradient brush with alpha colors. using (Brush br = new LinearGradientBrush(new Point(0, 0), new Point(0, this.Height), Color.FromArgb(255, this.BackColor), Color.FromArgb(0, this.BackColor))) { e.Graphics.FillRectangle(br, this.ClientRectangle); } } /// <summary> /// Starts the animation from the beginning. /// </summary> public void Start() { // Calculates scrolling offset. m_scrollingOffset = (int)this.Font.SizeInPoints * m_text.Length; m_timer.Start(); } /// <summary> /// Stops the animation. /// </summary> public void Stop() { m_timer.Stop(); } /// <summary> /// Timer handler. /// </summary> private void OnTimerTick(object sender, EventArgs e) { // Changes the offset. m_scrollingOffset--; // Repaints whole control area. Invalidate(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// PublicIPAddressesOperations operations. /// </summary> public partial interface IPublicIPAddressesOperations { /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified public IP address in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); // Signaled when UI thread is ready to process messages. private static readonly ManualResetEventSlim s_uiReady = new ManualResetEventSlim(false); // A WinForms control that enables us to execute code on UI thread. // TODO (tomat): consider removing dependency on WinForms. private static Control s_ui; internal static readonly ImmutableArray<string> DefaultSourceSearchPaths = ImmutableArray.Create<string>(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); private readonly InteractiveAssemblyLoader _assemblyLoader; private readonly MetadataShadowCopyProvider _metadataFileProvider; // the search paths - updated from the hostObject private ImmutableArray<string> _sourceSearchPaths; private ObjectFormatter _objectFormatter; private IRepl _repl; private InteractiveHostObject _hostObject; private ObjectFormattingOptions _formattingOptions; // Session is not thread-safe by itself, // so we need to lock whenever we compile a submission or add a reference: private readonly object _sessionGuard = new object(); private ScriptOptions _options = ScriptOptions.Default; private ScriptState _lastResult; #region Setup public Service() { // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider(); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _sourceSearchPaths = DefaultSourceSearchPaths; _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: 200, memberIndentation: " "); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replType) { Contract.ThrowIfNull(replType); _repl = (IRepl)Activator.CreateInstance(replType); _objectFormatter = _repl.CreateObjectFormatter(); _hostObject = new InteractiveHostObject(); _options = _options .WithBaseDirectory(Directory.GetCurrentDirectory()) .AddReferences(_hostObject.GetType().Assembly); _hostObject.ReferencePaths.AddRange(_options.SearchPaths); _hostObject.SourcePaths.AddRange(_sourceSearchPaths); Console.OutputEncoding = Encoding.UTF8; } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new System.Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); var uiThread = new Thread(UIThread); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); s_uiReady.Wait(); // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } private static void UIThread() { s_ui = new Control(); s_ui.CreateControl(); s_uiReady.Set(); Application.Run(); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<object> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_sessionGuard) { _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(referenceSearchPaths); _options = _options.WithSearchPaths(referenceSearchPaths).WithBaseDirectory(baseDirectory); _hostObject.SourcePaths.Clear(); _hostObject.SourcePaths.AddRange(sourceSearchPaths); _sourceSearchPaths = sourceSearchPaths.AsImmutable(); Directory.SetCurrentDirectory(baseDirectory); } operation.Completed(null); } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); var success = false; try { InitializeContext(initializationFile, isRestarting); success = true; } catch (Exception e) { ReportUnhandledException(e); } finally { CompleteExecution(operation, success); } } private string ResolveReferencePath(string reference, string baseFilePath) { var references = _options.ReferenceResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (references.IsDefaultOrEmpty) { return null; } return references.Single().FilePath; } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); var success = false; try { // TODO (tomat): This lock blocks all other session operations. // We should be able to run multiple assembly resolutions and code execution in parallel. string fullPath; lock (_sessionGuard) { fullPath = ResolveReferencePath(reference, baseFilePath: null); if (fullPath != null) { success = LoadReference(fullPath, suppressWarnings: false, addReference: true); } } if (fullPath == null) { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); var success = false; try { success = Execute(text); } catch (Exception e) { ReportUnhandledException(e); } finally { CompleteExecution(operation, success); } } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); string fullPath = null; bool success = false; try { fullPath = ResolveRelativePath(path, _options.BaseDirectory, displayPath: false); success = fullPath != null && ExecuteFile(fullPath); } catch (Exception e) { ReportUnhandledException(e); } finally { CompleteExecution(operation, success, fullPath); } } private void CompleteExecution(RemoteAsyncOperation<RemoteExecutionResult> operation, bool success, string resolvedPath = null) { // TODO (tomat): we should be resetting this info just before the execution to ensure that the services see the same // as the next execution. // send any updates to the host object and current directory back to the client: var newSourcePaths = _hostObject.SourcePaths.List.GetNewContent(); var newReferencePaths = _hostObject.ReferencePaths.List.GetNewContent(); var currentDirectory = Directory.GetCurrentDirectory(); var oldWorkingDirectory = _options.BaseDirectory; var newWorkingDirectory = (oldWorkingDirectory != currentDirectory) ? currentDirectory : null; // update local search paths, the client updates theirs on operation completion: if (newSourcePaths != null) { _sourceSearchPaths = newSourcePaths.AsImmutable(); } if (newReferencePaths != null) { _options = _options.WithSearchPaths(newReferencePaths); } _options = _options.WithBaseDirectory(currentDirectory); operation.Completed(new RemoteExecutionResult(success, newSourcePaths, newReferencePaths, newWorkingDirectory, resolvedPath)); } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations public ObjectFormattingOptions ObjectFormattingOptions { get { return _formattingOptions; } set { if (value == null) { throw new ArgumentNullException("value"); } _formattingOptions = value; } } /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private void InitializeContext(string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_repl.GetLogo()); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _repl.GetCommandLineParser(); // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var args = parser.Parse(new[] { "@" + initializationFileOpt }, Path.GetDirectoryName(initializationFileOpt), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options lock (_sessionGuard) { // TODO (tomat): consolidate with other reference resolving foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); string fullPath = ResolveReferencePath(cmdLineReference.Reference, baseFilePath: null); LoadReference(fullPath, suppressWarnings: true, addReference: true); } } var rspDirectory = Path.GetDirectoryName(initializationFileOpt); foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, displayPath: true); if (fullPath != null) { ExecuteFile(fullPath); } } } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } private string ResolveRelativePath(string path, string baseDirectory, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, _sourceSearchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private bool LoadReference(string fullOriginalPath, bool suppressWarnings, bool addReference) { AssemblyLoadResult result; try { result = LoadFromPathThrowing(fullOriginalPath, addReference); } catch (FileNotFoundException e) { Console.Error.WriteLine(e.Message); return false; } catch (ArgumentException e) { Console.Error.WriteLine((e.InnerException ?? e).Message); return false; } catch (TargetInvocationException e) { // The user might have hooked AssemblyResolve event, which might have thrown an exception. // Display stack trace in this case. Console.Error.WriteLine(e.InnerException.ToString()); return false; } if (!result.IsSuccessful && !suppressWarnings) { Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath)); } return true; } // Testing utility. // TODO (tomat): needed since MetadataReference is not serializable . // Has to be public to be callable via remoting. public AssemblyLoadResult LoadReferenceThrowing(string reference, bool addReference) { var fullPath = ResolveReferencePath(reference, baseFilePath: null); if (fullPath == null) { throw new FileNotFoundException(message: null, fileName: reference); } return LoadFromPathThrowing(fullPath, addReference); } private AssemblyLoadResult LoadFromPathThrowing(string fullOriginalPath, bool addReference) { var result = _assemblyLoader.LoadFromPath(fullOriginalPath); if (addReference && result.IsSuccessful) { var reference = _metadataFileProvider.GetReference(fullOriginalPath); _options = _options.AddReferences(reference); } return result; } public ObjectHandle ExecuteAndWrap(string text) { return new ObjectHandle(ExecuteInner(Compile(text))); } private Script Compile(string text, string path = null) { // note that the actual submission execution runs on the UI thread, not under this lock: lock (_sessionGuard) { Script script = _repl.CreateScript(text).WithOptions(_options); if (_lastResult != null) { script = script.WithPrevious(_lastResult.Script); } else { script = script.WithGlobalsType(_hostObject.GetType()); } if (path != null) { script = script.WithPath(path).WithOptions(script.Options.WithIsInteractive(false)); } // force build so exception is thrown now if errors are found. script.Build(); // load all references specified in #r's -- they will all be PE references (may be shadow copied): foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences) { // FullPath refers to the original reference path, not the copy: LoadReference(reference.FilePath, suppressWarnings: false, addReference: false); } return script; } } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <param name="fullPath">Full source path.</param> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private bool ExecuteFile(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); string content; try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); return false; } // TODO (tomat): engine.CompileSubmission shouldn't throw Script script; try { script = Compile(content, fullPath); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); return false; } object result; ExecuteOnUIThread(script, out result); return true; } private void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { writer.WriteLine(attemptedFilePaths.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string path in attemptedFilePaths) { writer.Write(" "); writer.WriteLine(Path.GetDirectoryName(path)); } } /// <summary> /// Executes specified code. /// </summary> /// <param name="text">Source code.</param> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// The resulting value (if any) is formatted and printed to the output stream. /// </remarks> private bool Execute(string text) { Script script; try { script = Compile(text); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); return false; } object result; if (!ExecuteOnUIThread(script, out result)) { return true; } bool hasValue; var resultType = script.GetCompilation().GetSubmissionResultType(out hasValue); if (hasValue) { if (resultType != null && resultType.SpecialType == SpecialType.System_Void) { Console.Out.WriteLine(_objectFormatter.VoidDisplayString); } else { Console.Out.WriteLine(_objectFormatter.FormatObject(result, _formattingOptions)); } } return true; } private class ExecuteSubmissionError { public readonly Exception Exception; public ExecuteSubmissionError(Exception exception) { this.Exception = exception; } } private bool ExecuteOnUIThread(Script script, out object result) { result = s_ui.Invoke(new Func<object>(() => { try { return ExecuteInner(script); } catch (Exception e) { return new ExecuteSubmissionError(e); } })); var error = result as ExecuteSubmissionError; if (error != null) { // TODO (tomat): format exception Console.Error.WriteLine(error.Exception); return false; } else { return true; } } private object ExecuteInner(Script script) { var globals = _lastResult != null ? (object)_lastResult : (object)_hostObject; var result = script.Run(globals); _lastResult = result; return result.ReturnValue; } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _repl.GetDiagnosticFormatter(); foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #endregion } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// Manages an Oculus Rift head-mounted display (HMD). /// </summary> public class OVRDisplay { /// <summary> /// Specifies the size and field-of-view for one eye texture. /// </summary> public struct EyeRenderDesc { /// <summary> /// The horizontal and vertical size of the texture. /// </summary> public Vector2 resolution; /// <summary> /// The angle of the horizontal and vertical field of view in degrees. /// </summary> public Vector2 fov; } /// <summary> /// Contains latency measurements for a single frame of rendering. /// </summary> public struct LatencyData { /// <summary> /// The time it took to render both eyes in seconds. /// </summary> public float render; /// <summary> /// The time it took to perform TimeWarp in seconds. /// </summary> public float timeWarp; /// <summary> /// The time between the end of TimeWarp and scan-out in seconds. /// </summary> public float postPresent; public float renderError; public float timeWarpError; } private bool needsConfigureTexture; private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[2]; /// <summary> /// Creates an instance of OVRDisplay. Called by OVRManager. /// </summary> public OVRDisplay() { UpdateTextures(); } /// <summary> /// Updates the internal state of the OVRDisplay. Called by OVRManager. /// </summary> public void Update() { UpdateTextures(); } /// <summary> /// Occurs when the head pose is reset. /// </summary> public event System.Action RecenteredPose; /// <summary> /// Recenters the head pose. /// </summary> public void RecenterPose() { VR.InputTracking.Recenter(); if (RecenteredPose != null) { RecenteredPose(); } } /// <summary> /// Gets the current linear acceleration of the head. /// </summary> public Vector3 acceleration { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular acceleration of the head. /// </summary> public Quaternion angularAcceleration { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the current linear velocity of the head. /// </summary> public Vector3 velocity { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular velocity of the head. /// </summary> public Quaternion angularVelocity { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the resolution and field of view for the given eye. /// </summary> public EyeRenderDesc GetEyeRenderDesc(VR.VRNode eye) { return eyeDescs[(int)eye]; } /// <summary> /// Gets the current measured latency values. /// </summary> public LatencyData latency { get { if (!OVRManager.isHmdPresent) return new LatencyData(); string latency = OVRPlugin.latency; var r = new Regex("Render: ([0-9]+[.][0-9]+)ms, TimeWarp: ([0-9]+[.][0-9]+)ms, PostPresent: ([0-9]+[.][0-9]+)ms", RegexOptions.None); var ret = new LatencyData(); Match match = r.Match(latency); if (match.Success) { ret.render = float.Parse(match.Groups[1].Value); ret.timeWarp = float.Parse(match.Groups[2].Value); ret.postPresent = float.Parse(match.Groups[3].Value); } return ret; } } /// <summary> /// Gets the recommended MSAA level for optimal quality/performance the current device. /// </summary> public int recommendedMSAALevel { get { int result = OVRPlugin.recommendedMSAALevel; if (result == 1) result = 0; return result; } } private void UpdateTextures() { ConfigureEyeDesc(VR.VRNode.LeftEye); ConfigureEyeDesc(VR.VRNode.RightEye); } private void ConfigureEyeDesc(VR.VRNode eye) { if (!OVRManager.isHmdPresent) return; OVRPlugin.Sizei size = OVRPlugin.GetEyeTextureSize((OVRPlugin.Eye)eye); OVRPlugin.Frustumf frust = OVRPlugin.GetEyeFrustum((OVRPlugin.Eye)eye); eyeDescs[(int)eye] = new EyeRenderDesc() { resolution = new Vector2(size.w, size.h), fov = Mathf.Rad2Deg * new Vector2(frust.fovX, frust.fovY), }; } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Peddler { public class SingleGeneratorTests { private const int numberOfAttempts = 1000; [Fact] public void Next_ValidValue() { var generator = new SingleGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); } } [Fact] public void NextDistinct_ValidDistinctValues() { var generator = new SingleGenerator(); var original = generator.Next(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var distinct = generator.NextDistinct(original); Assert.False(Single.IsInfinity(distinct)); Assert.False(Single.IsNaN(distinct)); Assert.NotEqual(original, distinct, generator.EqualityComparer); } } [Theory] [InlineData(0.0f)] [InlineData(0.5f)] [InlineData(1.0f)] [InlineData(10.0f)] [InlineData(-0.5f)] [InlineData(-1.0f)] [InlineData(-10.0f)] [InlineData(Single.MinValue)] [InlineData(5E+30f)] [InlineData(3.402822E+38f)] // Largest value less than MaxValue public void Next_GreaterThan(Single min) { var generator = new SingleGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextGreaterThan(min); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.Equal(1, generator.Comparer.Compare(value, min)); } } [Theory] [InlineData(0.0f)] [InlineData(0.5f)] [InlineData(1.0f)] [InlineData(10.0f)] [InlineData(-0.5f)] [InlineData(-1.0f)] [InlineData(-10.0f)] [InlineData(Single.MinValue)] [InlineData(5E+30f)] [InlineData(3.402822E+38f)] // Largest value less than MaxValue public void Next_GreaterThanOrEqual(Single min) { var generator = new SingleGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextGreaterThanOrEqualTo(min); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, min), 0, 1); } } [Theory] [InlineData(0.0f)] [InlineData(0.5f)] [InlineData(1.0f)] [InlineData(10.0f)] [InlineData(Single.MaxValue)] [InlineData(-5E+30f)] [InlineData(-3.402822E+38f)] // Smallest value greater than MinValue public void Next_LessThan(Single max) { var generator = new SingleGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextLessThan(max); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.Equal(-1, generator.Comparer.Compare(value, max)); } } [Theory] [InlineData(0.0f)] [InlineData(0.5f)] [InlineData(1.0f)] [InlineData(10.0f)] [InlineData(Single.MaxValue)] [InlineData(-5E+30f)] [InlineData(-3.402822E+38f)] // Smallest value greater than MinValue public void Next_LessThanOrEqual(Single max) { var generator = new SingleGenerator(); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextLessThanOrEqualTo(max); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, max), -1, 0); } } [Theory] [InlineData(0f, 0.1f)] [InlineData(0f, 10f)] [InlineData(0f, Single.MaxValue)] [InlineData(1f, 10f)] [InlineData(-0.1f, 0.1f)] [InlineData(-0.1f, Single.MaxValue)] [InlineData(-10f, 0f)] [InlineData(-10f, -1f)] public void Next_FixedRange(Single min, Single max) { var generator = new SingleGenerator(min, max); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, max), -1, 0); Assert.InRange(generator.Comparer.Compare(value, min), 0, 1); } } [Theory] [InlineData(0f, 0.1f, 0.05f)] [InlineData(0f, 10f, 5f)] [InlineData(0f, Single.MaxValue, 5f)] [InlineData(1f, 10f, 5f)] [InlineData(-0.1f, 0.1f, 0f)] [InlineData(-0.1f, Single.MaxValue, 5f)] [InlineData(-10f, 0f, -5f)] [InlineData(-10f, -1f, -5f)] public void NextGreaterThan_FixedRange(Single min, Single max, Single other) { var generator = new SingleGenerator(min, max); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextGreaterThan(other); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, max), -1, 0); Assert.Equal(1, generator.Comparer.Compare(value, other)); } } [Theory] [InlineData(0f, 0.1f, 0.05f)] [InlineData(0f, 10f, 5f)] [InlineData(0f, Single.MaxValue, 5f)] [InlineData(1f, 10f, 5f)] [InlineData(-0.1f, 0.1f, 0f)] [InlineData(-0.1f, Single.MaxValue, 5f)] [InlineData(-10f, 0f, -5f)] [InlineData(-10f, -1f, -5f)] public void NextGreaterThanOrEqualTo_FixedRange(Single min, Single max, Single other) { var generator = new SingleGenerator(min, max); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextGreaterThanOrEqualTo(other); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, max), -1, 0); Assert.InRange(generator.Comparer.Compare(value, other), 0, 1); } } [Theory] [InlineData(0f, 0.1f, 0.05f)] [InlineData(0f, 10f, 5f)] [InlineData(0f, Single.MaxValue, 5f)] [InlineData(1f, 10f, 5f)] [InlineData(-0.1f, 0.1f, 0f)] [InlineData(-0.1f, Single.MaxValue, 5f)] [InlineData(-10f, 0f, -5f)] [InlineData(-10f, -1f, -5f)] public void NextLessThan_FixedRange(Single min, Single max, Single other) { var generator = new SingleGenerator(min, max); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextLessThan(other); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, min), 0, 1); Assert.Equal(-1, generator.Comparer.Compare(value, other)); } } [Theory] [InlineData(0f, 0.1f, 0.05f)] [InlineData(0f, 10f, 5f)] [InlineData(0f, Single.MaxValue, 5f)] [InlineData(1f, 10f, 5f)] [InlineData(-0.1f, 0.1f, 0f)] [InlineData(-0.1f, Single.MaxValue, 5f)] [InlineData(-10f, 0f, -5f)] [InlineData(-10f, -1f, -5f)] public void NextLessThanOrEqualTo_FixedRange(Single min, Single max, Single other) { var generator = new SingleGenerator(min, max); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextLessThanOrEqualTo(other); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(value, min), 0, 1); Assert.InRange(generator.Comparer.Compare(value, other), -1, 0); } } [Fact] public void EpsilonExponent_VerifyCompleteness() { // Generate numbers from 0 to 10 in intervals of 0.1 (effectively 101 possible // values: 0, 0.1, 0.2 ... 9.9, 10.0) // // After generating 10000 random values the probability of having failed to generate any // one of these values is 101 * ((100 / 101) ^ 10000) = 6.17 * (10 ^ -42) which seems // unlikely. var generator = new SingleGenerator(0, 10, epsilonExponent: -1); var generatedValues = Enumerable.Range(0, 10000) .Select(_ => (Int32)Math.Round(generator.Next() * 10)) .ToImmutableHashSet(); Assert.True(generatedValues.All(value => value >= 0 && value <= 100)); for (var value = 0; value <= 100; value++) { Assert.Contains(value, generatedValues); } } [Theory] [InlineData(0f)] [InlineData(0.1f)] [InlineData(5.5f)] [InlineData(9.9f)] [InlineData(10f)] public void EpsilonExponent_Distinct_VerifyCompleteness(Single other) { // Generate numbers from 0 to 10 in intervals of 0.1 (effectively 101 possible // values: 0, 0.1, 0.2 ... 9.9, 10.0) with the exception of one pre-selected value. // // After generating 10000 random values the probability of having failed to generate any // one of these values is 101 * ((100 / 101) ^ 10000) = 6.17 * (10 ^ -42) which seems // unlikely. var generator = new SingleGenerator(0, 10, epsilonExponent: -1); var generatedValues = Enumerable.Range(0, 10000) .Select(_ => (Int32)Math.Round(generator.NextDistinct(other) * 10)) .ToImmutableHashSet(); Assert.True(generatedValues.All(value => value >= 0 && value <= 100)); for (var value = 0; value <= 100; value++) { if (value == (Int32)Math.Round(other * 10)) { Assert.DoesNotContain(value, generatedValues); } else { Assert.Contains(value, generatedValues); } } } [Theory] [InlineData(0f)] [InlineData(0.1f)] [InlineData(5.5f)] [InlineData(9.9f)] [InlineData(10f)] [InlineData(20f)] [InlineData(50f)] [InlineData(100f)] public void SignificantFigures_Distinct(Single other) { // When generating values with a limited number of significant figures it is distinct // values must differ but a sufficient margin to be detectable when rounded to the // specified number of significant figures. // // For example when generating numbers from 0 to 100 with two significant figures and a // minimum exponent of -1, there are 101 values >= 0 and < 10 (0, 0.1, 0.2 ... 9.9, 10) // and there are 90 values > 10 and <= 100 (11, 12, .. 99, 100). Notably values such as // 12.4 are not representable and when generating a value that is distinct from 12 it is // important that a value that rounds to 12 is not generated. var generator = new SingleGenerator(0, 100, epsilonExponent: -1, significantFigures: 2); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.NextDistinct(other); if (other < 10) { Assert.NotEqual( (Int32)Math.Round(other * 10), (Int32)Math.Round(value * 10) ); } else { Assert.NotEqual( (Int32)Math.Round(other), (Int32)Math.Round(value) ); } } } [Fact] public void EpsilonExponent_MaxValue() { var generator = new SingleGenerator(epsilonExponent: SingleGenerator.MaximumEpsilonExponent); for (var attempt = 0; attempt < numberOfAttempts; attempt++) { var value = generator.Next(); Assert.False(Single.IsInfinity(value)); Assert.False(Single.IsNaN(value)); Assert.InRange(generator.Comparer.Compare(Math.Abs(value), Single.MaxValue), -1, 0); Assert.InRange( generator.Comparer.Compare( Math.Abs(value), (Single)Math.Pow(10, SingleGenerator.MaximumEpsilonExponent)), 0, 1 ); } } } }
namespace CodEx { /// <summary> /// Class Reader provides user friendly adaptor for reading text files and text console input. /// If offers simple methods to Read numbers, chars and string tokens. /// </summary> public class Reader : System.IDisposable { #region Inicialization and destruction /// <summary>Initializes reader object and assigns given stream reader.</summary> /// <param name="s">Stream reader object used as input.</param> private Reader(System.IO.TextReader s) { stream = s; buf = new char[BUFLEN]; index = 0; len = 0; } /// <summary>Opens given file and assigns it to created Reader object.</summary> /// <param name="fname">Name of the file to be opened.</param> public Reader(string fname) : this(new System.IO.StreamReader(fname, System.Text.Encoding.ASCII, false)) { } /// <summary>Static singleton value that keeps console Reader object.</summary> private static Reader console = null; /// <summary>Method providing access to universal console Reader object.</summary> public static Reader Console() { if (console == null) console = new Reader(System.Console.In); return console; } /// <summary>Internal disposer of reader stream.</summary> private void FreeStream() { if (stream != null) { ((System.IDisposable)stream).Dispose(); stream = null; } } /// <summary> /// Method that closes the reader and underlying stream object. /// It is recomended to use this method rather than wait for fializer. /// </summary> public void Dispose() { FreeStream(); System.GC.SuppressFinalize(this); } /// <summary>Finalizer is not usually used. But if it is, it does the same as Dispose method.</summary> ~Reader() { FreeStream(); } #endregion #region Public core methods /// <summary>Reads one character from input.</summary> /// <param name="c">Output variable where the character is stored.</param> /// <returns>True if the reading was successfull, false otherwise.</returns> public bool Char(out char c) { if (!Update()) { c = '\0'; return false; } c = buf[index++]; return true; } /// <summary>Reads integer number from text file.</summary> /// <param name="i">Output variable where the integer is stored.</param> /// <returns>True if the reading was successfull, false otherwise.</returns> public bool Int(out int i) { if (!SkipSpaces()) { i = 0; return false; } i = 0; int sign = 1; if (buf[index] == '+') index++; else if (buf[index] == '-') { sign = -1; index++; } if (!Update() || !System.Char.IsDigit(buf[index])) throw new System.IO.IOException("No digit found when reading number."); while (Update() && System.Char.IsDigit(buf[index])) { i = i * 10 + sign * ((int)buf[index++] - (int)'0'); } return true; } /// <summary>Reads real number from text file.</summary> /// <param name="d">Output variable where the double is stored.</param> /// <returns>True if the reading was successfull, false otherwise.</returns> public bool Double(out double d) { { int i; if (!Int(out i)) { d = 0; return false; } d = i; } if (Update() && buf[index] == '.') { index++; double frac = 1.0; while (Update() && System.Char.IsDigit(buf[index])) { frac /= 10.0; d += frac * ((int)buf[index++] - (int)'0'); } } if (Update() && System.Char.ToLower(buf[index]) == 'e') { index++; d *= System.Math.Pow(10, Int()); // If no exponent can be parsed -> IOException. } return true; } /// <summary>Reads one string token from input. Token does not contain any blank spaces.</summary> /// <returns>String object containing the token or null if reading was not successfull.</returns> public string Word() { if (!SkipSpaces()) return null; int start = index; while (index < len && !System.Char.IsWhiteSpace(buf[index])) index++; if (index < len) return new string(buf, start, index-start); System.Text.StringBuilder sb=new System.Text.StringBuilder(); sb.Append(buf, start, index-start); while (index == len && Update()) { while (index < len && !System.Char.IsWhiteSpace(buf[index])) index++; sb.Append(buf, 0, index); } return sb.ToString(); } /// <summary>Reads rest of the line from input.</summary> /// <returns>String object containing the line or null if EOF was met.</returns> public string Line() { if (!Update()) return null; int start = index; while (index < len && buf[index]!='\n') index++; if (index < len) return new string(buf, start, index++-start); System.Text.StringBuilder sb=new System.Text.StringBuilder(); sb.Append(buf, start, index-start); while (index == len && Update()) { while (index < len && buf[index]!='\n') index++; sb.Append(buf, 0, index); } if (index < len) index++; return sb.ToString(); } #endregion #region Convenience methods /// <summary>Checks if the input stream ended.</summary> /// <returns>True if there are no more characters on the input.</returns> public bool EOF() { return !Update(); } /// <summary>Skips whitespace characters and then checks for EOF.</summary> /// <returns>True if there are only blank characters left in the input.</returns> public bool SeekEOF() { return !SkipSpaces(); } /// <summary>Alias for Dispose method that closes underlying stream.</summary> public void Close() { Dispose(); } /// <summary>Reads one character from input. Throws IOException on error.</summary> /// <returns>Character that was Read from the input.</returns> public char Char() { char ret; if (!Char(out ret)) throw new System.IO.IOException("Reading after EOF."); return ret; } /// <summary>Reads integer number from input. Throws IOException on error.</summary> /// <returns>Integer that was Read from the input.</returns> public int Int() { int ret; if (!Int(out ret)) throw new System.IO.IOException("Reading after EOF."); return ret; } /// <summary>Reads real number from input. Throws IOException on error.</summary> /// <returns>Double that was Read from the input.</returns> public double Double() { double ret; if (!Double(out ret)) throw new System.IO.IOException("Reading after EOF."); return ret; } #endregion #region Fields /// <summary>Underlying stram object. It is not null while the stream is opened.</summary> private System.IO.TextReader stream; /// <summary>Read but unprocessed data. Null after EOF.</summary> private char[] buf; private const int BUFLEN = 16384; /// <summary>Actual index to the buf.</summary> private int index; /// <summary>Length of buf. Len == -1 means EOF.</summary> private int len; #endregion #region Private methods /// <summary>Ensures that index is lesser than len whenever possible.</summary> /// <returns>False on EOF, true otherwise.</returns> private bool Update() { // if (stream == null || len == -1) return false; if (index < len) return true; index = 0; if ((len = stream.Read(buf, 0, BUFLEN)) == 0) { len=-1; buf=null; return false; } return true; } /// <summary>Skip whitespaces.</summary> /// <returns>Returns false when EOF is found while skipping, true otherwise.</returns> private bool SkipSpaces() { while (Update()) { while (index < len && System.Char.IsWhiteSpace(buf[index])) index++; if (index < len) return true; } return false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Mvc.TagHelpers.Cache { /// <summary> /// An instance of <see cref="CacheTagKey"/> represents the state of <see cref="CacheTagHelper"/> /// or <see cref="DistributedCacheTagHelper"/> keys. /// </summary> public class CacheTagKey : IEquatable<CacheTagKey> { private static readonly char[] AttributeSeparator = new[] { ',' }; private static readonly Func<IRequestCookieCollection, string, string> CookieAccessor = (c, key) => c[key]; private static readonly Func<IHeaderDictionary, string, string> HeaderAccessor = (c, key) => c[key]; private static readonly Func<IQueryCollection, string, string> QueryAccessor = (c, key) => c[key]; private static readonly Func<RouteValueDictionary, string, string> RouteValueAccessor = (c, key) => Convert.ToString(c[key], CultureInfo.InvariantCulture); private const string CacheKeyTokenSeparator = "||"; private const string VaryByName = "VaryBy"; private const string VaryByHeaderName = "VaryByHeader"; private const string VaryByQueryName = "VaryByQuery"; private const string VaryByRouteName = "VaryByRoute"; private const string VaryByCookieName = "VaryByCookie"; private const string VaryByUserName = "VaryByUser"; private const string VaryByCulture = "VaryByCulture"; private readonly string _prefix; private readonly string _varyBy; private readonly DateTimeOffset? _expiresOn; private readonly TimeSpan? _expiresAfter; private readonly TimeSpan? _expiresSliding; private readonly IList<KeyValuePair<string, string>> _headers; private readonly IList<KeyValuePair<string, string>> _queries; private readonly IList<KeyValuePair<string, string>> _routeValues; private readonly IList<KeyValuePair<string, string>> _cookies; private readonly bool _varyByUser; private readonly bool _varyByCulture; private readonly string _username; private readonly CultureInfo _requestCulture; private readonly CultureInfo _requestUICulture; private string _generatedKey; private int? _hashcode; /// <summary> /// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="CacheTagHelper"/>. /// </summary> /// <param name="tagHelper">The <see cref="CacheTagHelper"/>.</param> /// <param name="context">The <see cref="TagHelperContext"/>.</param> /// <returns>A new <see cref="CacheTagKey"/>.</returns> public CacheTagKey(CacheTagHelper tagHelper, TagHelperContext context) : this(tagHelper) { Key = context.UniqueId; _prefix = nameof(CacheTagHelper); } /// <summary> /// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="DistributedCacheTagHelper"/>. /// </summary> /// <param name="tagHelper">The <see cref="DistributedCacheTagHelper"/>.</param> /// <returns>A new <see cref="CacheTagKey"/>.</returns> public CacheTagKey(DistributedCacheTagHelper tagHelper) : this((CacheTagHelperBase)tagHelper) { Key = tagHelper.Name; _prefix = nameof(DistributedCacheTagHelper); } private CacheTagKey(CacheTagHelperBase tagHelper) { var httpContext = tagHelper.ViewContext.HttpContext; var request = httpContext.Request; _expiresAfter = tagHelper.ExpiresAfter; _expiresOn = tagHelper.ExpiresOn; _expiresSliding = tagHelper.ExpiresSliding; _varyBy = tagHelper.VaryBy; _cookies = ExtractCollection(tagHelper.VaryByCookie, request.Cookies, CookieAccessor); _headers = ExtractCollection(tagHelper.VaryByHeader, request.Headers, HeaderAccessor); _queries = ExtractCollection(tagHelper.VaryByQuery, request.Query, QueryAccessor); _routeValues = ExtractCollection( tagHelper.VaryByRoute, tagHelper.ViewContext.RouteData.Values, RouteValueAccessor); _varyByUser = tagHelper.VaryByUser; _varyByCulture = tagHelper.VaryByCulture; if (_varyByUser) { _username = httpContext.User?.Identity?.Name; } if (_varyByCulture) { _requestCulture = CultureInfo.CurrentCulture; _requestUICulture = CultureInfo.CurrentUICulture; } } // Internal for unit testing. internal string Key { get; } /// <summary> /// Creates a <see cref="string"/> representation of the key. /// </summary> /// <returns>A <see cref="string"/> uniquely representing the key.</returns> public string GenerateKey() { // Caching as the key is immutable and it can be called multiple times during a request. if (_generatedKey != null) { return _generatedKey; } var builder = new StringBuilder(_prefix); builder .Append(CacheKeyTokenSeparator) .Append(Key); if (!string.IsNullOrEmpty(_varyBy)) { builder .Append(CacheKeyTokenSeparator) .Append(VaryByName) .Append(CacheKeyTokenSeparator) .Append(_varyBy); } AddStringCollection(builder, VaryByCookieName, _cookies); AddStringCollection(builder, VaryByHeaderName, _headers); AddStringCollection(builder, VaryByQueryName, _queries); AddStringCollection(builder, VaryByRouteName, _routeValues); if (_varyByUser) { builder .Append(CacheKeyTokenSeparator) .Append(VaryByUserName) .Append(CacheKeyTokenSeparator) .Append(_username); } if (_varyByCulture) { builder .Append(CacheKeyTokenSeparator) .Append(VaryByCulture) .Append(CacheKeyTokenSeparator) .Append(_requestCulture) .Append(CacheKeyTokenSeparator) .Append(_requestUICulture); } _generatedKey = builder.ToString(); return _generatedKey; } /// <summary> /// Creates a hashed value of the key. /// </summary> /// <returns>A cryptographic hash of the key.</returns> public string GenerateHashedKey() { var key = GenerateKey(); // The key is typically too long to be useful, so we use a cryptographic hash // as the actual key (better randomization and key distribution, so small vary // values will generate dramatically different keys). var contentBytes = Encoding.UTF8.GetBytes(key); var hashedBytes = SHA256.HashData(contentBytes); return Convert.ToBase64String(hashedBytes); } /// <inheritdoc /> public override bool Equals(object obj) { if (obj is CacheTagKey other) { return Equals(other); } return false; } /// <inheritdoc /> public bool Equals(CacheTagKey other) { return string.Equals(other.Key, Key, StringComparison.Ordinal) && other._expiresAfter == _expiresAfter && other._expiresOn == _expiresOn && other._expiresSliding == _expiresSliding && string.Equals(other._varyBy, _varyBy, StringComparison.Ordinal) && AreSame(_cookies, other._cookies) && AreSame(_headers, other._headers) && AreSame(_queries, other._queries) && AreSame(_routeValues, other._routeValues) && (_varyByUser == other._varyByUser && (!_varyByUser || string.Equals(other._username, _username, StringComparison.Ordinal))) && CultureEquals(); bool CultureEquals() { if (_varyByCulture != other._varyByCulture) { return false; } if (!_varyByCulture) { // Neither has culture set. return true; } return _requestCulture.Equals(other._requestCulture) && _requestUICulture.Equals(other._requestUICulture); } } /// <inheritdoc /> public override int GetHashCode() { // The hashcode is intentionally not using the computed // stringified key in order to prevent string allocations // in the common case where it's not explicitly required. // Caching as the key is immutable and it can be called // multiple times during a request. if (_hashcode.HasValue) { return _hashcode.Value; } var hashCode = new HashCode(); hashCode.Add(Key, StringComparer.Ordinal); hashCode.Add(_expiresAfter); hashCode.Add(_expiresOn); hashCode.Add(_expiresSliding); hashCode.Add(_varyBy, StringComparer.Ordinal); hashCode.Add(_username, StringComparer.Ordinal); hashCode.Add(_requestCulture); hashCode.Add(_requestUICulture); CombineCollectionHashCode(ref hashCode, VaryByCookieName, _cookies); CombineCollectionHashCode(ref hashCode, VaryByHeaderName, _headers); CombineCollectionHashCode(ref hashCode, VaryByQueryName, _queries); CombineCollectionHashCode(ref hashCode, VaryByRouteName, _routeValues); _hashcode = hashCode.ToHashCode(); return _hashcode.Value; } private static IList<KeyValuePair<string, string>> ExtractCollection<TSourceCollection>( string keys, TSourceCollection collection, Func<TSourceCollection, string, string> accessor) { if (string.IsNullOrEmpty(keys)) { return null; } var tokenizer = new StringTokenizer(keys, AttributeSeparator); var result = new List<KeyValuePair<string, string>>(); foreach (var item in tokenizer) { var trimmedValue = item.Trim(); if (trimmedValue.Length != 0) { var value = accessor(collection, trimmedValue.Value); result.Add(new KeyValuePair<string, string>(trimmedValue.Value, value ?? string.Empty)); } } return result; } private static void AddStringCollection( StringBuilder builder, string collectionName, IList<KeyValuePair<string, string>> values) { if (values == null || values.Count == 0) { return; } // keyName(param1=value1|param2=value2) builder .Append(CacheKeyTokenSeparator) .Append(collectionName) .Append('('); for (var i = 0; i < values.Count; i++) { var item = values[i]; if (i > 0) { builder.Append(CacheKeyTokenSeparator); } builder .Append(item.Key) .Append(CacheKeyTokenSeparator) .Append(item.Value); } builder.Append(')'); } private static void CombineCollectionHashCode( ref HashCode hashCode, string collectionName, IList<KeyValuePair<string, string>> values) { if (values != null) { hashCode.Add(collectionName, StringComparer.Ordinal); for (var i = 0; i < values.Count; i++) { var item = values[i]; hashCode.Add(item.Key); hashCode.Add(item.Value); } } } private static bool AreSame(IList<KeyValuePair<string, string>> values1, IList<KeyValuePair<string, string>> values2) { if (values1 == values2) { return true; } if (values1 == null || values2 == null || values1.Count != values2.Count) { return false; } for (var i = 0; i < values1.Count; i++) { if (!string.Equals(values1[i].Key, values2[i].Key, StringComparison.Ordinal) || !string.Equals(values1[i].Value, values2[i].Value, StringComparison.Ordinal)) { return false; } } return true; } } }
/** * This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). * It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) */ using UnityEngine; using UnityEditor; using UnityEditorInternal; using System; using System.Linq; using System.Collections; using System.Collections.Generic; namespace Fungus { public class FlowchartWindow : EditorWindow { public static List<Block> deleteList = new List<Block>(); protected List<Block> windowBlockMap = new List<Block>(); // The ReorderableList control doesn't drag properly when used with GUI.DragWindow(), // so we just implement dragging ourselves. protected int dragWindowId = -1; protected Vector2 startDragPosition; public const float minZoomValue = 0.25f; public const float maxZoomValue = 1f; protected GUIStyle nodeStyle = new GUIStyle(); protected static BlockInspector blockInspector; protected bool mouseOverVariables = false; protected int forceRepaintCount; protected Texture2D addTexture; [MenuItem("Tools/Fungus/Flowchart Window")] static void Init() { GetWindow(typeof(FlowchartWindow), false, "Flowchart"); } protected virtual void OnEnable() { // All block nodes use the same GUIStyle, but with a different background nodeStyle.border.left = 20; nodeStyle.border.right = 20; nodeStyle.border.top = 5; nodeStyle.border.bottom = 5; nodeStyle.padding.left = 20; nodeStyle.padding.right = 20; nodeStyle.padding.top = 5; nodeStyle.padding.bottom = 5; nodeStyle.contentOffset = Vector2.zero; nodeStyle.alignment = TextAnchor.MiddleCenter; nodeStyle.wordWrap = true; addTexture = Resources.Load("Icons/add_small") as Texture2D; } protected virtual void OnInspectorUpdate() { // Ensure the Block Inspector is always showing the currently selected block Flowchart flowchart = GetFlowchart(); if (flowchart == null) { return; } if (Selection.activeGameObject == null && flowchart.selectedBlock != null) { if (blockInspector == null) { ShowBlockInspector(flowchart); } blockInspector.block = flowchart.selectedBlock; } forceRepaintCount--; forceRepaintCount = Math.Max(0, forceRepaintCount); Repaint(); } static public Flowchart GetFlowchart() { // Using a temp hidden object to track the active Flowchart across // serialization / deserialization when playing the game in the editor. FungusState fungusState = GameObject.FindObjectOfType<FungusState>(); if (fungusState == null) { GameObject go = new GameObject("_FungusState"); go.hideFlags = HideFlags.HideInHierarchy; fungusState = go.AddComponent<FungusState>(); } if (Selection.activeGameObject != null) { Flowchart fs = Selection.activeGameObject.GetComponent<Flowchart>(); if (fs != null) { fungusState.selectedFlowchart = fs; } } return fungusState.selectedFlowchart; } protected virtual void OnGUI() { Flowchart flowchart = GetFlowchart(); if (flowchart == null) { GUILayout.Label("No Flowchart scene object selected"); return; } // Delete any scheduled objects foreach (Block deleteBlock in deleteList) { bool isSelected = (flowchart.selectedBlock == deleteBlock); foreach (Command command in deleteBlock.commandList) { Undo.DestroyObjectImmediate(command); } Undo.DestroyObjectImmediate(deleteBlock); flowchart.ClearSelectedCommands(); if (isSelected) { // Revert to showing properties for the Flowchart Selection.activeGameObject = flowchart.gameObject; } } deleteList.Clear(); DrawFlowchartView(flowchart); DrawOverlay(flowchart); if (forceRepaintCount > 0) { // Redraw on next frame to get crisp refresh rate Repaint(); } } protected virtual void DrawOverlay(Flowchart flowchart) { GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.Space(8); if (GUILayout.Button(new GUIContent(addTexture, "Add a new block"))) { Vector2 newNodePosition = new Vector2(50 - flowchart.scrollPos.x, 50 - flowchart.scrollPos.y); CreateBlock(flowchart, newNodePosition); } GUILayout.Space(8); flowchart.zoom = GUILayout.HorizontalSlider(flowchart.zoom, minZoomValue, maxZoomValue, GUILayout.Width(100)); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel); if (flowchart.description.Length > 0) { GUILayout.Label(flowchart.description, EditorStyles.helpBox); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(GUILayout.Width(440)); GUILayout.FlexibleSpace(); flowchart.variablesScrollPos = GUILayout.BeginScrollView(flowchart.variablesScrollPos, GUILayout.MaxHeight(position.height * 0.75f)); GUILayout.FlexibleSpace(); GUILayout.Space(8); FlowchartEditor flowchartEditor = Editor.CreateEditor (flowchart) as FlowchartEditor; flowchartEditor.DrawVariablesGUI(); DestroyImmediate(flowchartEditor); Rect variableWindowRect = GUILayoutUtility.GetLastRect(); if (flowchart.variablesExpanded && flowchart.variables.Count > 0) { variableWindowRect.y -= 20; variableWindowRect.height += 20; } if (Event.current.type == EventType.Repaint) { mouseOverVariables = variableWindowRect.Contains(Event.current.mousePosition); } GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } protected virtual void DrawFlowchartView(Flowchart flowchart) { Block[] blocks = flowchart.GetComponents<Block>(); foreach (Block block in blocks) { flowchart.scrollViewRect.xMin = Mathf.Min(flowchart.scrollViewRect.xMin, block.nodeRect.xMin - 400); flowchart.scrollViewRect.xMax = Mathf.Max(flowchart.scrollViewRect.xMax, block.nodeRect.xMax + 400); flowchart.scrollViewRect.yMin = Mathf.Min(flowchart.scrollViewRect.yMin, block.nodeRect.yMin - 400); flowchart.scrollViewRect.yMax = Mathf.Max(flowchart.scrollViewRect.yMax, block.nodeRect.yMax + 400); } // Calc rect for script view Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.zoom, this.position.height / flowchart.zoom); EditorZoomArea.Begin(flowchart.zoom, scriptViewRect); DrawGrid(flowchart); GLDraw.BeginGroup(scriptViewRect); if (Event.current.button == 0 && Event.current.type == EventType.MouseDown && !mouseOverVariables) { flowchart.selectedBlock = null; if (!EditorGUI.actionKey) { flowchart.ClearSelectedCommands(); } Selection.activeGameObject = flowchart.gameObject; } // The center of the Flowchart depends on the block positions and window dimensions, so we calculate it // here in the FlowchartWindow class and store it on the Flowchart object for use later. CalcFlowchartCenter(flowchart, blocks); // Draw connections foreach (Block block in blocks) { DrawConnections(flowchart, block, false); } foreach (Block block in blocks) { DrawConnections(flowchart, block, true); } GUIStyle windowStyle = new GUIStyle(); windowStyle.stretchHeight = true; BeginWindows(); windowBlockMap.Clear(); for (int i = 0; i < blocks.Length; ++i) { Block block = blocks[i]; float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.blockName)).x + 10; float nodeWidthB = 0f; if (block.eventHandler != null) { nodeWidthB = nodeStyle.CalcSize(new GUIContent(block.eventHandler.GetSummary())).x + 10; } block.nodeRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120); block.nodeRect.height = 40; if (Event.current.button == 0) { if (Event.current.type == EventType.MouseDrag && dragWindowId == i) { block.nodeRect.x += Event.current.delta.x; block.nodeRect.y += Event.current.delta.y; forceRepaintCount = 6; } else if (Event.current.type == EventType.MouseUp && dragWindowId == i) { Vector2 newPos = new Vector2(block.nodeRect.x, block.nodeRect.y); block.nodeRect.x = startDragPosition.x; block.nodeRect.y = startDragPosition.y; Undo.RecordObject(block, "Node Position"); block.nodeRect.x = newPos.x; block.nodeRect.y = newPos.y; dragWindowId = -1; forceRepaintCount = 6; } } Rect windowRect = new Rect(block.nodeRect); windowRect.x += flowchart.scrollPos.x; windowRect.y += flowchart.scrollPos.y; GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle); GUI.backgroundColor = Color.white; windowBlockMap.Add(block); } EndWindows(); // Draw Event Handler labels foreach (Block block in blocks) { if (block.eventHandler != null) { string handlerLabel = ""; EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block.eventHandler.GetType()); if (info != null) { handlerLabel = "<" + info.EventHandlerName + "> "; } GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel); handlerStyle.wordWrap = true; handlerStyle.margin.top = 0; handlerStyle.margin.bottom = 0; handlerStyle.alignment = TextAnchor.MiddleCenter; Rect rect = new Rect(block.nodeRect); rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block.nodeRect.width); rect.x += flowchart.scrollPos.x; rect.y += flowchart.scrollPos.y - rect.height; GUI.Label(rect, handlerLabel, handlerStyle); } } // Draw play icons beside all executing blocks if (Application.isPlaying) { foreach (Block b in blocks) { if (b.IsExecuting()) { b.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; b.activeCommand.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; forceRepaintCount = 6; } if (b.executingIconTimer > Time.realtimeSinceStartup) { Rect rect = new Rect(b.nodeRect); rect.x += flowchart.scrollPos.x - 37; rect.y += flowchart.scrollPos.y + 3; rect.width = 34; rect.height = 34; if (!b.IsExecuting()) { float alpha = (b.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime; alpha = Mathf.Clamp01(alpha); GUI.color = new Color(1f, 1f, 1f, alpha); } if (GUI.Button(rect, FungusEditorResources.texPlayBig as Texture, new GUIStyle())) { SelectBlock(flowchart, b); } GUI.color = Color.white; } } } PanAndZoom(flowchart); GLDraw.EndGroup(); EditorZoomArea.End(); } public virtual void CalcFlowchartCenter(Flowchart flowchart, Block[] blocks) { if (flowchart == null || blocks.Count() == 0) { return; } Vector2 min = blocks[0].nodeRect.min; Vector2 max = blocks[0].nodeRect.max; foreach (Block block in blocks) { min.x = Mathf.Min(min.x, block.nodeRect.center.x); min.y = Mathf.Min(min.y, block.nodeRect.center.y); max.x = Mathf.Max(max.x, block.nodeRect.center.x); max.y = Mathf.Max(max.y, block.nodeRect.center.y); } Vector2 center = (min + max) * -0.5f; center.x += position.width * 0.5f; center.y += position.height * 0.5f; flowchart.centerPosition = center; } protected virtual void PanAndZoom(Flowchart flowchart) { // Right click to drag view bool drag = false; // Pan tool if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Pan && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { drag = true; } // Right or middle button drag if (Event.current.button > 0 && Event.current.type == EventType.MouseDrag) { drag = true; } // Alt + left mouse drag if (Event.current.alt && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { drag = true; } if (drag) { flowchart.scrollPos += Event.current.delta; forceRepaintCount = 6; } bool zoom = false; // Scroll wheel if (Event.current.type == EventType.ScrollWheel) { zoom = true; } // Zoom tool if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { zoom = true; } if (zoom) { flowchart.zoom -= Event.current.delta.y * 0.01f; flowchart.zoom = Mathf.Clamp(flowchart.zoom, minZoomValue, maxZoomValue); forceRepaintCount = 6; } } protected virtual void DrawGrid(Flowchart flowchart) { float width = this.position.width / flowchart.zoom; float height = this.position.height / flowchart.zoom; // Match background color of scene view if (EditorGUIUtility.isProSkin) { GUI.color = new Color32(71, 71, 71, 255); } else { GUI.color = new Color32(86, 86, 86, 255); } GUI.DrawTexture( new Rect(0,0, width, height), EditorGUIUtility.whiteTexture ); GUI.color = Color.white; Color color = new Color32(96, 96, 96, 255); float gridSize = 128f; float x = flowchart.scrollPos.x % gridSize; while (x < width) { GLDraw.DrawLine(new Vector2(x, 0), new Vector2(x, height), color, 1f); x += gridSize; } float y = (flowchart.scrollPos.y % gridSize); while (y < height) { if (y >= 0) { GLDraw.DrawLine(new Vector2(0, y), new Vector2(width, y), color, 1f); } y += gridSize; } } protected virtual void SelectBlock(Flowchart flowchart, Block block) { // Select the block and also select currently executing command ShowBlockInspector(flowchart); flowchart.selectedBlock = block; flowchart.ClearSelectedCommands(); if (block.activeCommand != null) { flowchart.AddSelectedCommand(block.activeCommand); } } public static Block CreateBlock(Flowchart flowchart, Vector2 position) { Block newBlock = flowchart.CreateBlock(position); Undo.RegisterCreatedObjectUndo(newBlock, "New Block"); ShowBlockInspector(flowchart); flowchart.selectedBlock = newBlock; flowchart.ClearSelectedCommands(); return newBlock; } protected virtual void DeleteBlock(Flowchart flowchart, Block block) { foreach (Command command in block.commandList) { Undo.DestroyObjectImmediate(command); } Undo.DestroyObjectImmediate(block); flowchart.ClearSelectedCommands(); } protected virtual void DrawWindow(int windowId) { Block block = windowBlockMap[windowId]; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null) { return; } // Select block when node is clicked if (Event.current.button == 0 && Event.current.type == EventType.MouseDown && !mouseOverVariables) { // Check if might be start of a window drag if (Event.current.button == 0 && Event.current.alt == false) { dragWindowId = windowId; startDragPosition.x = block.nodeRect.x; startDragPosition.y = block.nodeRect.y; } if (windowId < windowBlockMap.Count) { Undo.RecordObject(flowchart, "Select"); SelectBlock(flowchart, block); GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus) } } bool selected = (flowchart.selectedBlock == block); GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle); if (block.eventHandler != null) { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texEventNodeOn : FungusEditorResources.texEventNodeOff; } else { // Count the number of unique connections (excluding self references) List<Block> uniqueList = new List<Block>(); List<Block> connectedBlocks = block.GetConnectedBlocks(); foreach (Block connectedBlock in connectedBlocks) { if (connectedBlock == block || uniqueList.Contains(connectedBlock)) { continue; } uniqueList.Add(connectedBlock); } if (uniqueList.Count > 1) { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texChoiceNodeOn : FungusEditorResources.texChoiceNodeOff; } else { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texProcessNodeOn : FungusEditorResources.texProcessNodeOff; } } nodeStyleCopy.normal.textColor = Color.black; // Make sure node is wide enough to fit the node name text float width = nodeStyleCopy.CalcSize(new GUIContent(block.blockName)).x; block.nodeRect.width = Mathf.Max (block.nodeRect.width, width); GUI.backgroundColor = Color.white; GUILayout.Box(block.blockName, nodeStyleCopy, GUILayout.Width(block.nodeRect.width), GUILayout.Height(block.nodeRect.height)); if (block.description.Length > 0) { GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox); descriptionStyle.wordWrap = true; GUILayout.Label(block.description, descriptionStyle); } if (Event.current.type == EventType.ContextClick) { GenericMenu menu = new GenericMenu (); menu.AddItem(new GUIContent ("Duplicate"), false, DuplicateBlock, block); menu.AddItem(new GUIContent ("Delete"), false, DeleteBlock, block); menu.ShowAsContext(); } } protected virtual void DrawConnections(Flowchart flowchart, Block block, bool highlightedOnly) { if (block == null) { return; } List<Block> connectedBlocks = new List<Block>(); bool blockIsSelected = (flowchart.selectedBlock == block); foreach (Command command in block.commandList) { if (command == null) { continue; } bool commandIsSelected = false; foreach (Command selectedCommand in flowchart.selectedCommands) { if (selectedCommand == command) { commandIsSelected = true; break; } } bool highlight = command.isExecuting || (blockIsSelected && commandIsSelected); if (highlightedOnly && !highlight || !highlightedOnly && highlight) { continue; } connectedBlocks.Clear(); command.GetConnectedBlocks(ref connectedBlocks); foreach (Block blockB in connectedBlocks) { if (blockB == null || block == blockB || blockB.GetFlowchart() != flowchart) { continue; } Rect startRect = new Rect(block.nodeRect); startRect.x += flowchart.scrollPos.x; startRect.y += flowchart.scrollPos.y; Rect endRect = new Rect(blockB.nodeRect); endRect.x += flowchart.scrollPos.x; endRect.y += flowchart.scrollPos.y; DrawRectConnection(startRect, endRect, highlight); } } } protected virtual void DrawRectConnection(Rect rectA, Rect rectB, bool highlight) { Vector2[] pointsA = new Vector2[] { new Vector2(rectA.xMin + 5, rectA.center.y), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMin + 2), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMax - 2), new Vector2(rectA.xMax - 5, rectA.center.y) }; Vector2[] pointsB = new Vector2[] { new Vector2(rectB.xMin + 5, rectB.center.y), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMin + 2), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMax - 2), new Vector2(rectB.xMax - 5, rectB.center.y) }; Vector2 pointA = Vector2.zero; Vector2 pointB = Vector2.zero; float minDist = float.MaxValue; foreach (Vector2 a in pointsA) { foreach (Vector2 b in pointsB) { float d = Vector2.Distance(a, b); if (d < minDist) { pointA = a; pointB = b; minDist = d; } } } Color color = Color.grey; if (highlight) { color = Color.green; } GLDraw.DrawConnectingCurve(pointA, pointB, color, 1.025f); Rect dotARect = new Rect(pointA.x - 5, pointA.y - 5, 10, 10); GUI.Label(dotARect, "", new GUIStyle("U2D.dragDotActive")); Rect dotBRect = new Rect(pointB.x - 5, pointB.y - 5, 10, 10); GUI.Label(dotBRect, "", new GUIStyle("U2D.dragDotActive")); } public static void DeleteBlock(object obj) { Block block = obj as Block; FlowchartWindow.deleteList.Add(block); } protected static void DuplicateBlock(object obj) { Flowchart flowchart = GetFlowchart(); Block block = obj as Block; Vector2 newPosition = new Vector2(block.nodeRect.position.x + block.nodeRect.width + 20, block.nodeRect.y); Block oldBlock = block; Block newBlock = FlowchartWindow.CreateBlock(flowchart, newPosition); newBlock.blockName = flowchart.GetUniqueBlockKey(oldBlock.blockName + " (Copy)"); Undo.RecordObject(newBlock, "Duplicate Block"); foreach (Command command in oldBlock.commandList) { if (ComponentUtility.CopyComponent(command)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { Command[] commands = flowchart.GetComponents<Command>(); Command pastedCommand = commands.Last<Command>(); if (pastedCommand != null) { pastedCommand.itemId = flowchart.NextItemId(); newBlock.commandList.Add (pastedCommand); } } // This stops the user pasting the command manually into another game object. ComponentUtility.CopyComponent(flowchart.transform); } } if (oldBlock.eventHandler != null) { if (ComponentUtility.CopyComponent(oldBlock.eventHandler)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { EventHandler[] eventHandlers = flowchart.GetComponents<EventHandler>(); EventHandler pastedEventHandler = eventHandlers.Last<EventHandler>(); if (pastedEventHandler != null) { pastedEventHandler.parentBlock = newBlock; newBlock.eventHandler = pastedEventHandler; } } } } } protected static void ShowBlockInspector(Flowchart flowchart) { if (blockInspector == null) { // Create a Scriptable Object with a custom editor which we can use to inspect the selected block. // Editors for Scriptable Objects display using the full height of the inspector window. blockInspector = ScriptableObject.CreateInstance<BlockInspector>() as BlockInspector; blockInspector.hideFlags = HideFlags.DontSave; } Selection.activeObject = blockInspector; EditorUtility.SetDirty(blockInspector); } /** * Displays a temporary text alert in the center of the Flowchart window. */ public static void ShowNotification(string notificationText) { EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart"); if (window != null) { window.ShowNotification(new GUIContent(notificationText)); } } } }
// Copyright 2021 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using ArcGISRuntime.Helpers; using ArcGISRuntime.Samples.Shared.Managers; using Esri.ArcGISRuntime; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ContextThemeWrapper = AndroidX.AppCompat.View.ContextThemeWrapper; namespace ArcGISRuntime.Samples.SearchPortalMaps { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Search for webmap", category: "Map", description: "Find webmap portal items by using a search term.", instructions: "Enter search terms into the search bar. Once the search is complete, a list is populated with the resultant webmaps. Tap on a webmap to set it to the map view. Scrolling to the bottom of the webmap recycler view will get more results.", tags: new[] { "keyword", "query", "search", "webmap" })] [ArcGISRuntime.Samples.Shared.Attributes.ClassFile("Helpers\\ArcGISLoginPrompt.cs")] public class SearchPortalMaps : Activity { // Hold a reference to the map view private MapView _myMapView; // Dictionary to hold URIs to web maps private Dictionary<string, Uri> _webMapUris; // URL of the server. private const string ServerUrl = "https://www.arcgis.com/sharing/rest"; // Button layout at the top of the page private LinearLayout _buttonPanel; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Search a portal for maps"; // Create the UI, setup the control references and execute initialization CreateLayout(); _ = Initialize(); } private async Task Initialize() { // Remove API key. ApiKeyManager.DisableKey(); ArcGISLoginPrompt.SetChallengeHandler(); bool loggedIn = await ArcGISLoginPrompt.EnsureAGOLCredentialAsync(this); // Display a default map if (loggedIn) DisplayDefaultMap(); } private void DisplayDefaultMap() => _myMapView.Map = new Map(BasemapStyle.ArcGISLightGray); protected override void OnDestroy() { base.OnDestroy(); // Restore API key if leaving sample. ApiKeyManager.EnableKey(); } private void SearchMapsClicked(object sender, EventArgs e) { // Create a dialog to show save options (title, description, and tags) SearchMapsDialogFragment searchMapsDialog = new SearchMapsDialogFragment(); searchMapsDialog.OnSearchClicked += OnSearchMapsClicked; // Begin a transaction to show a UI fragment (the search dialog) FragmentTransaction trans = FragmentManager.BeginTransaction(); searchMapsDialog.Show(trans, "search maps"); } private async void MyMapsClicked(object sender, EventArgs e) { try { // Get web map portal items in the current user's folder IEnumerable<PortalItem> mapItems = null; // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already) bool loggedIn = await ArcGISLoginPrompt.EnsureAGOLCredentialAsync(this); if (!loggedIn) { return; } // Connect to the portal (will connect using the provided credentials) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Get the user's content (items in the root folder and a collection of sub-folders) PortalUserContent myContent = await portal.User.GetContentAsync(); // Get the web map items in the root folder mapItems = from item in myContent.Items where item.Type == PortalItemType.WebMap select item; // Loop through all sub-folders and get web map items, add them to the mapItems collection foreach (PortalFolder folder in myContent.Folders) { IEnumerable<PortalItem> folderItems = await portal.User.GetContentAsync(folder.FolderId); mapItems = mapItems.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item); } // Show the map results ShowMapList(mapItems); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } } private async void OnSearchMapsClicked(object sender, OnSearchMapEventArgs e) { try { // Get web map portal items from a keyword search IEnumerable<PortalItem> mapItems = null; // Connect to the portal (anonymously) ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl)); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags string queryExpression = $"tags:\"{e.SearchText}\" access:public type: (\"web map\" NOT \"web mapping application\")"; // Create a query parameters object with the expression and a limit of 10 results PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results PortalQueryResultSet<PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results mapItems = findResult.Results; // Show the map results ShowMapList(mapItems); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } } private void ShowMapList(IEnumerable<PortalItem> webmapItems) { // Create menu to show map results PopupMenu mapsMenu = new PopupMenu(this, _buttonPanel); mapsMenu.MenuItemClick += OnMapsMenuItemClicked; // Create a dictionary of web maps and show the titles in the menu _webMapUris = new Dictionary<string, Uri>(); foreach (PortalItem item in webmapItems) { if (!_webMapUris.ContainsKey(item.Title)) { _webMapUris.Add(item.Title, item.Url); mapsMenu.Menu.Add(item.Title); } } //Show menu in the view mapsMenu.Show(); } private void OnMapsMenuItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e) { // Get the selected web map item URI from the dictionary string mapTitle = e.Item.TitleCondensedFormatted.ToString(); Uri selectedMapUri = _webMapUris[mapTitle]; if (selectedMapUri == null) { return; } // Create a new map, pass the web map portal item to the constructor Map webMap = new Map(selectedMapUri); // Handle change in the load status (to report load errors) webMap.LoadStatusChanged += WebMapLoadStatusChanged; // Show the web map in the map view _myMapView.Map = webMap; } private void WebMapLoadStatusChanged(object sender, Esri.ArcGISRuntime.LoadStatusEventArgs e) { // Report errors if map failed to load if (e.Status == LoadStatus.FailedToLoad) { Map map = (Map)sender; Exception err = map.LoadError; if (err != null) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Map Load Error"); alertBuilder.SetMessage(err.Message); alertBuilder.Show(); } } } private void CreateLayout() { // Create a new vertical layout for the app LinearLayout mainLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Create a layout for app buttons _buttonPanel = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Create button to show search UI Button searchMapsButton = new Button(this) { Text = "Search Maps" }; searchMapsButton.Click += SearchMapsClicked; // Create another button to show maps from user's ArcGIS Online account Button myMapsButton = new Button(this) { Text = "My Maps" }; myMapsButton.Click += MyMapsClicked; // Add buttons to the horizontal layout panel _buttonPanel.AddView(searchMapsButton); _buttonPanel.AddView(myMapsButton); // Add button panel to the main layout mainLayout.AddView(_buttonPanel); // Add the map view to the layout _myMapView = new MapView(this); mainLayout.AddView(_myMapView); // Show the layout in the app SetContentView(mainLayout); } } #region UI for entering web map search text // A custom DialogFragment class to show input controls for searching for maps public class SearchMapsDialogFragment : DialogFragment { // Inputs for portal item search text private EditText _mapSearchTextbox; // Raise an event so the listener can access the input search text value when the form has been completed public event EventHandler<OnSearchMapEventArgs> OnSearchClicked; public SearchMapsDialogFragment() { } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Dialog to display LinearLayout dialogView = null; // Get the context for creating the dialog controls Android.Content.Context ctx = Activity.ApplicationContext; ContextThemeWrapper ctxWrapper = new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeMaterialLight); // Set a dialog title Dialog.SetTitle("Search Portal"); try { base.OnCreateView(inflater, container, savedInstanceState); // The container for the dialog is a vertical linear layout dialogView = new LinearLayout(ctxWrapper) { Orientation = Orientation.Vertical }; // Add a text box for entering web map search text _mapSearchTextbox = new EditText(ctxWrapper) { Hint = "Search text" }; dialogView.AddView(_mapSearchTextbox); // Add a button to complete search Button searchMapsButton = new Button(ctxWrapper) { Text = "Search" }; searchMapsButton.Click += SearchMapsButtonClick; dialogView.AddView(searchMapsButton); } catch (Exception ex) { // Show the exception message AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Activity); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } // Return the new view for display return dialogView; } // A click handler for the search button private void SearchMapsButtonClick(object sender, EventArgs e) { try { // Get information for the new portal item string search = _mapSearchTextbox.Text; // Create a new OnSaveMapEventArgs object to store the information entered by the user OnSearchMapEventArgs mapSearchArgs = new OnSearchMapEventArgs(search); // Raise the OnSaveClicked event so the main activity can handle the event and save the map OnSearchClicked?.Invoke(this, mapSearchArgs); // Close the dialog Dismiss(); } catch (Exception ex) { // Show the exception message (dialog will stay open so user can try again) AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Activity); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } } } // Custom EventArgs class for containing map search expression text public class OnSearchMapEventArgs : EventArgs { // Search text public string SearchText { get; set; } public OnSearchMapEventArgs(string searchText) : base() { // Store the web map search text SearchText = searchText; } } #endregion UI for entering web map search text }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace System.Data.Common { internal static partial class ADP { // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx) // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features private static Task<bool> _trueTask; internal static Task<bool> TrueTask => _trueTask ?? (_trueTask = Task.FromResult(true)); private static Task<bool> _falseTask; internal static Task<bool> FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false)); internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; static partial void TraceException(string trace, Exception e); internal static void TraceExceptionAsReturnValue(Exception e) { TraceException("<comm.ADP.TraceException|ERR|THROW> '{0}'", e); } internal static void TraceExceptionWithoutRethrow(Exception e) { Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e); } internal static ArgumentException Argument(string error) { ArgumentException e = new ArgumentException(error); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException Argument(string error, Exception inner) { ArgumentException e = new ArgumentException(error, inner); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException Argument(string error, string parameter) { ArgumentException e = new ArgumentException(error, parameter); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentNullException ArgumentNull(string parameter) { ArgumentNullException e = new ArgumentNullException(parameter); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentNullException ArgumentNull(string parameter, string error) { ArgumentNullException e = new ArgumentNullException(parameter, error); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) { ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) { ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message); TraceExceptionAsReturnValue(e); return e; } internal static IndexOutOfRangeException IndexOutOfRange(string error) { IndexOutOfRangeException e = new IndexOutOfRangeException(error); TraceExceptionAsReturnValue(e); return e; } internal static InvalidCastException InvalidCast(string error) { return InvalidCast(error, null); } internal static InvalidCastException InvalidCast(string error, Exception inner) { InvalidCastException e = new InvalidCastException(error, inner); TraceExceptionAsReturnValue(e); return e; } internal static InvalidOperationException InvalidOperation(string error) { InvalidOperationException e = new InvalidOperationException(error); TraceExceptionAsReturnValue(e); return e; } internal static NotSupportedException NotSupported() { NotSupportedException e = new NotSupportedException(); TraceExceptionAsReturnValue(e); return e; } internal static NotSupportedException NotSupported(string error) { NotSupportedException e = new NotSupportedException(error); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) { return ArgumentOutOfRange(SR.Format(SR.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); } internal static InvalidOperationException DataAdapter(string error) { return InvalidOperation(error); } private static InvalidOperationException Provider(string error) { return InvalidOperation(error); } internal static ArgumentException InvalidMultipartName(string property, string value) { ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartName, property, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) { ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameQuoteUsage, property, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) { ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameToManyParts, property, value, limit)); TraceExceptionAsReturnValue(e); return e; } internal static void CheckArgumentNull(object value, string parameterName) { if (null == value) { throw ArgumentNull(parameterName); } } // only StackOverflowException & ThreadAbortException are sealed classes private static readonly Type s_stackOverflowType = typeof(StackOverflowException); private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException); private static readonly Type s_threadAbortType = typeof(ThreadAbortException); private static readonly Type s_nullReferenceType = typeof(NullReferenceException); private static readonly Type s_accessViolationType = typeof(AccessViolationException); private static readonly Type s_securityType = typeof(SecurityException); internal static bool IsCatchableExceptionType(Exception e) { // a 'catchable' exception is defined by what it is not. Debug.Assert(e != null, "Unexpected null exception!"); Type type = e.GetType(); return ((type != s_stackOverflowType) && (type != s_outOfMemoryType) && (type != s_threadAbortType) && (type != s_nullReferenceType) && (type != s_accessViolationType) && !s_securityType.IsAssignableFrom(type)); } internal static bool IsCatchableOrSecurityExceptionType(Exception e) { // a 'catchable' exception is defined by what it is not. // since IsCatchableExceptionType defined SecurityException as not 'catchable' // this method will return true for SecurityException has being catchable. // the other way to write this method is, but then SecurityException is checked twice // return ((e is SecurityException) || IsCatchableExceptionType(e)); Debug.Assert(e != null, "Unexpected null exception!"); Type type = e.GetType(); return ((type != s_stackOverflowType) && (type != s_outOfMemoryType) && (type != s_threadAbortType) && (type != s_nullReferenceType) && (type != s_accessViolationType)); } // Invalid Enumeration internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) { return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name); } // // DbConnectionOptions, DataAccess // internal static ArgumentException ConnectionStringSyntax(int index) { return Argument(SR.Format(SR.ADP_ConnectionStringSyntax, index)); } internal static ArgumentException KeywordNotSupported(string keyword) { return Argument(SR.Format(SR.ADP_KeywordNotSupported, keyword)); } internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) { return ADP.Argument(SR.Format(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); } // // DbConnectionOptions, DataAccess, SqlClient // internal static Exception InvalidConnectionOptionValue(string key) { return InvalidConnectionOptionValue(key, null); } internal static Exception InvalidConnectionOptionValue(string key, Exception inner) { return Argument(SR.Format(SR.ADP_InvalidConnectionOptionValue, key), inner); } // // Generic Data Provider Collection // internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) { return Argument(SR.Format(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); } internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) { return ArgumentNull(parameter, SR.Format(SR.ADP_CollectionNullValue, collection.Name, itemType.Name)); } internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) { return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); } internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) { return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); } internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) { return InvalidCast(SR.Format(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); } // // DbConnection // private static string ConnectionStateMsg(ConnectionState state) { switch (state) { case (ConnectionState.Closed): case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed return SR.ADP_ConnectionStateMsg_Closed; case (ConnectionState.Connecting): return SR.ADP_ConnectionStateMsg_Connecting; case (ConnectionState.Open): return SR.ADP_ConnectionStateMsg_Open; case (ConnectionState.Open | ConnectionState.Executing): return SR.ADP_ConnectionStateMsg_OpenExecuting; case (ConnectionState.Open | ConnectionState.Fetching): return SR.ADP_ConnectionStateMsg_OpenFetching; default: return SR.Format(SR.ADP_ConnectionStateMsg, state.ToString()); } } // // : Stream // internal static Exception StreamClosed([CallerMemberName] string method = "") { return InvalidOperation(SR.Format(SR.ADP_StreamClosed, method)); } internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) { var resultString = new StringBuilder(); if (!string.IsNullOrEmpty(quotePrefix)) { resultString.Append(quotePrefix); } // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar". if (!string.IsNullOrEmpty(quoteSuffix)) { resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix)); resultString.Append(quoteSuffix); } else { resultString.Append(unQuotedString); } return resultString.ToString(); } // // Generic Data Provider Collection // internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) { return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection) { return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } internal enum InternalErrorCode { UnpooledObjectHasOwner = 0, UnpooledObjectHasWrongOwner = 1, PushingObjectSecondTime = 2, PooledObjectHasOwner = 3, PooledObjectInPoolMoreThanOnce = 4, CreateObjectReturnedNull = 5, NewObjectCannotBePooled = 6, NonPooledObjectUsedMoreThanOnce = 7, AttemptingToPoolOnRestrictedToken = 8, // ConnectionOptionsInUse = 9, ConvertSidToStringSidWReturnedNull = 10, // UnexpectedTransactedObject = 11, AttemptingToConstructReferenceCollectionOnStaticObject = 12, AttemptingToEnlistTwice = 13, CreateReferenceCollectionReturnedNull = 14, PooledObjectWithoutPool = 15, UnexpectedWaitAnyResult = 16, SynchronousConnectReturnedPending = 17, CompletedConnectReturnedPending = 18, NameValuePairNext = 20, InvalidParserState1 = 21, InvalidParserState2 = 22, InvalidParserState3 = 23, InvalidBuffer = 30, UnimplementedSMIMethod = 40, InvalidSmiCall = 41, SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50, SqlDependencyProcessDispatcherFailureCreateInstance = 51, SqlDependencyProcessDispatcherFailureAppDomain = 52, SqlDependencyCommandHashIsNotAssociatedWithNotification = 53, UnknownTransactionFailure = 60, } internal static Exception InternalError(InternalErrorCode internalError) { return InvalidOperation(SR.Format(SR.ADP_InternalProviderError, (int)internalError)); } // // : DbDataReader // internal static Exception DataReaderClosed([CallerMemberName] string method = "") { return InvalidOperation(SR.Format(SR.ADP_DataReaderClosed, method)); } internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) { return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) { return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) { return IndexOutOfRange(SR.Format(SR.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidDataLength(long length) { return IndexOutOfRange(SR.Format(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); } internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) => 0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase); internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions); internal static bool IsEmptyArray(string[] array) => (null == array) || (0 == array.Length); internal static bool IsNull(object value) { if ((null == value) || (DBNull.Value == value)) { return true; } INullable nullable = (value as INullable); return ((null != nullable) && nullable.IsNull); } internal static Exception InvalidSeekOrigin(string parameterName) { return ArgumentOutOfRange(SR.ADP_InvalidSeekOrigin, parameterName); } internal static readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform); internal static readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5)); internal static void SetCurrentTransaction(Transaction transaction) { Transaction.Current = transaction; } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Globalization; using System.Numerics; using Xunit; namespace SixLabors.Fonts.Tests { public class FontRectangleTests { [Fact] public void DefaultConstructorTest() => Assert.Equal(default, FontRectangle.Empty); [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void NonDefaultConstructorTest(float x, float y, float width, float height) { var rect1 = new FontRectangle(x, y, width, height); var p = new Vector2(x, y); var s = new Vector2(width, height); var rect2 = new FontRectangle(p, s); Assert.Equal(rect1, rect2); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void FromLTRBTest(float left, float top, float right, float bottom) { var expected = new FontRectangle(left, top, right - left, bottom - top); var actual = FontRectangle.FromLTRB(left, top, right, bottom); Assert.Equal(expected, actual); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void DimensionsTest(float x, float y, float width, float height) { var rect = new FontRectangle(x, y, width, height); var p = new Vector2(x, y); var s = new Vector2(width, height); Assert.Equal(p, rect.Location); Assert.Equal(s, rect.Size); Assert.Equal(x, rect.X); Assert.Equal(y, rect.Y); Assert.Equal(width, rect.Width); Assert.Equal(height, rect.Height); Assert.Equal(x, rect.Left); Assert.Equal(y, rect.Top); Assert.Equal(x + width, rect.Right); Assert.Equal(y + height, rect.Bottom); } [Fact] public void IsEmptyTest() { Assert.True(FontRectangle.Empty.IsEmpty); Assert.True(default(FontRectangle).IsEmpty); Assert.True(new FontRectangle(1, -2, -10, 10).IsEmpty); Assert.True(new FontRectangle(1, -2, 10, -10).IsEmpty); Assert.True(new FontRectangle(1, -2, 0, 0).IsEmpty); Assert.False(new FontRectangle(0, 0, 10, 10).IsEmpty); } [Theory] [InlineData(0, 0)] [InlineData(float.MaxValue, float.MinValue)] public void LocationSetTest(float x, float y) { var point = new Vector2(x, y); var rect = new FontRectangle(point.X, point.Y, 10, 10); Assert.Equal(point, rect.Location); Assert.Equal(point.X, rect.X); Assert.Equal(point.Y, rect.Y); } [Theory] [InlineData(0, 0)] [InlineData(float.MaxValue, float.MinValue)] public void SizeSetTest(float x, float y) { var size = new Vector2(x, y); var rect = new FontRectangle(10, 10, size.X, size.Y); Assert.Equal(size, rect.Size); Assert.Equal(size.X, rect.Width); Assert.Equal(size.Y, rect.Height); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void EqualityTest(float x, float y, float width, float height) { var rect1 = new FontRectangle(x, y, width, height); var rect2 = new FontRectangle(width, height, x, y); Assert.True(rect1 != rect2); Assert.False(rect1 == rect2); Assert.False(rect1.Equals(rect2)); Assert.False(rect1.Equals((object)rect2)); } [Fact] public void GetHashCodeTest() { var rect1 = new FontRectangle(10, 10, 10, 10); var rect2 = new FontRectangle(10, 10, 10, 10); Assert.Equal(rect1.GetHashCode(), rect2.GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new FontRectangle(20, 10, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new FontRectangle(10, 20, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new FontRectangle(10, 10, 20, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new FontRectangle(10, 10, 10, 20).GetHashCode()); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void ContainsTest(float x, float y, float width, float height) { var rect = new FontRectangle(x, y, width, height); float x1 = (x + width) / 2; float y1 = (y + height) / 2; var p = new Vector2(x1, y1); var r = new FontRectangle(x1, y1, width / 2, height / 2); Assert.False(rect.Contains(x1, y1)); Assert.False(rect.Contains(p)); Assert.False(rect.Contains(r)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue / 2, float.MinValue / 2, float.MinValue / 2, float.MaxValue / 2)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void InflateTest(float x, float y, float width, float height) { var rect = new FontRectangle(x, y, width, height); var inflatedRect = new FontRectangle(x - width, y - height, width + (2 * width), height + (2 * height)); rect = rect.Inflate(width, height); Assert.Equal(inflatedRect, rect); var s = new Vector2(x, y); inflatedRect = FontRectangle.Inflate(rect, x, y); rect = rect.Inflate(s); Assert.Equal(inflatedRect, rect); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MaxValue / 2, float.MinValue / 2)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void IntersectTest(float x, float y, float width, float height) { var rect1 = new FontRectangle(x, y, width, height); var rect2 = new FontRectangle(y, x, width, height); var expectedRect = FontRectangle.Intersect(rect1, rect2); rect1 = rect1.Intersect(rect2); Assert.Equal(expectedRect, rect1); Assert.False(rect1.IntersectsWith(expectedRect)); } [Fact] public void IntersectIntersectingRectsTest() { var rect1 = new FontRectangle(0, 0, 5, 5); var rect2 = new FontRectangle(1, 1, 3, 3); var expected = new FontRectangle(1, 1, 3, 3); Assert.Equal(expected, FontRectangle.Intersect(rect1, rect2)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void UnionTest(float x, float y, float width, float height) { var a = new FontRectangle(x, y, width, height); var b = new FontRectangle(width, height, x, y); float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); var expectedRectangle = new FontRectangle(x1, y1, x2 - x1, y2 - y1); Assert.Equal(expectedRectangle, FontRectangle.Union(a, b)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void OffsetTest(float x, float y, float width, float height) { var r1 = new FontRectangle(x, y, width, height); var expectedRect = new FontRectangle(x + width, y + height, width, height); var p = new Vector2(width, height); r1 = r1.Offset(p); Assert.Equal(expectedRect, r1); expectedRect = expectedRect.Offset(p); r1 = r1.Offset(width, height); Assert.Equal(expectedRect, r1); } [Fact] public void ToStringTest() { var r = new FontRectangle(5, 5.1F, 1.3F, 1); Assert.Equal(string.Format(CultureInfo.CurrentCulture, "FontRectangle [ X={0}, Y={1}, Width={2}, Height={3} ]", r.X, r.Y, r.Width, r.Height), r.ToString()); } [Theory] [InlineData(float.MinValue, float.MaxValue, float.MaxValue, float.MaxValue)] [InlineData(float.MinValue, float.MaxValue, float.MaxValue, float.MinValue)] [InlineData(float.MinValue, float.MaxValue, float.MinValue, float.MaxValue)] [InlineData(float.MinValue, float.MaxValue, float.MinValue, float.MinValue)] [InlineData(float.MinValue, float.MinValue, float.MaxValue, float.MaxValue)] [InlineData(float.MinValue, float.MinValue, float.MaxValue, float.MinValue)] [InlineData(float.MinValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MinValue, float.MinValue, float.MinValue, float.MinValue)] [InlineData(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue)] [InlineData(float.MaxValue, float.MaxValue, float.MaxValue, float.MinValue)] [InlineData(float.MaxValue, float.MaxValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue)] [InlineData(float.MaxValue, float.MinValue, float.MaxValue, float.MaxValue)] [InlineData(float.MaxValue, float.MinValue, float.MaxValue, float.MinValue)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MinValue)] [InlineData(0, 0, 0, 0)] public void DeconstructTest(float x, float y, float width, float height) { (float dx, float dy, float dw, float dh) = new FontRectangle(x, y, width, height); Assert.Equal(x, dx); Assert.Equal(y, dy); Assert.Equal(width, dw); Assert.Equal(height, dh); } } }
// 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace System { /// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br /> /// Currently contains:<br /> /// <ul> /// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces /// and <code>System.Threading.Tasks.Task</code>.</li> /// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code> /// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li> /// </ul></summary> [CLSCompliant(false)] public static class WindowsRuntimeSystemExtensions { #region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Convenience Helpers private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime) { Contract.Requires(sink != null); CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); }, sink); concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); }, ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info)); } private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info)); } #endregion Convenience Helpers #region Converters from IAsyncAction to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter(this IAsyncAction source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionAdapter; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncAction to Task #region Converters from IAsyncOperation<TResult> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationAdapter<TResult>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperation<TResult> to Task #region Converters from IAsyncActionWithProgress<TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, TProgress>(cancellationToken); source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncActionWithProgress<TProgress> to Task #region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the started asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, TProgress>(cancellationToken); source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task #endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) public static IAsyncAction AsAsyncAction(this Task source) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null); } public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null); } #endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) private static void CommonlyUsedGenericInstantiations() { // This method is an aid for NGen to save common generic // instantiations into the ngen image. ((IAsyncOperation<bool>)null).AsTask(); ((IAsyncOperation<string>)null).AsTask(); ((IAsyncOperation<object>)null).AsTask(); ((IAsyncOperation<uint>)null).AsTask(); ((IAsyncOperationWithProgress<uint, uint>)null).AsTask(); ((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask(); ((IAsyncOperationWithProgress<string, ulong>)null).AsTask(); } } // class WindowsRuntimeSystemExtensions } // namespace // WindowsRuntimeExtensions.cs
// 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\Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LeadingSignCount_Int64() { var test = new ScalarUnaryOpTest__LeadingSignCount_Int64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // 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 ScalarUnaryOpTest__LeadingSignCount_Int64 { private struct TestStruct { public Int64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetInt64(); return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__LeadingSignCount_Int64 testClass) { var result = ArmBase.Arm64.LeadingSignCount(_fld); testClass.ValidateResult(_fld, result); } } private static Int64 _data; private static Int64 _clsVar; private Int64 _fld; static ScalarUnaryOpTest__LeadingSignCount_Int64() { _clsVar = TestLibrary.Generator.GetInt64(); } public ScalarUnaryOpTest__LeadingSignCount_Int64() { Succeeded = true; _fld = TestLibrary.Generator.GetInt64(); _data = TestLibrary.Generator.GetInt64(); } public bool IsSupported => ArmBase.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = ArmBase.Arm64.LeadingSignCount( Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(ArmBase.Arm64).GetMethod(nameof(ArmBase.Arm64.LeadingSignCount), new Type[] { typeof(Int64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)) }); ValidateResult(_data, (Int32)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = ArmBase.Arm64.LeadingSignCount( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)); var result = ArmBase.Arm64.LeadingSignCount(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__LeadingSignCount_Int64(); var result = ArmBase.Arm64.LeadingSignCount(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = ArmBase.Arm64.LeadingSignCount(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = ArmBase.Arm64.LeadingSignCount(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Int64 data, Int32 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; int expectedResult = 0; for (int index = 62; (((ulong)data >> index) & 1) == (((ulong)data >> 63) & 1); index--) { expectedResult++; } isUnexpectedResult = (expectedResult != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(ArmBase.Arm64)}.{nameof(ArmBase.Arm64.LeadingSignCount)}<Int32>(Int64): LeadingSignCount failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using EnjoyDialogs.SCIM.Areas.HelpPage.Models; namespace EnjoyDialogs.SCIM.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { var apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { var invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------------------------------- // Torque Game Builder // Copyright (C) GarageGames.com, Inc. //--------------------------------------------------------------------------------------------- // This holds the last scenegraph that was loaded. $lastLoadedScene = ""; function getLastLoadedScene() { return $lastLoadedScene; } // This variable determines whether the scenegraph in the level file or the existing scenegraph // should be used. $useNewSceneGraph = false; //--------------------------------------------------------------------------------------------- // t2dSceneWindow.loadLevel // Loads a level file into a scene window. //--------------------------------------------------------------------------------------------- function t2dSceneWindow::loadLevel(%sceneWindow, %levelFile) { // Clean up any previously loaded stuff. %sceneWindow.endLevel(); // Load the level. $useNewSceneGraph = true; %scenegraph = %sceneWindow.addToLevel(%levelFile); if (!isObject(%scenegraph)) return 0; %sceneWindow.setSceneGraph(%scenegraph); // Set the window properties from the scene graph if they are available. %cameraPosition = %sceneWindow.getCurrentCameraPosition(); %cameraSize = t2dVectorSub(getWords(%sceneWindow.getCurrentCameraArea(), 2, 3), getWords(%sceneWindow.getCurrentCameraArea(), 0, 1)); if (%scenegraph.cameraPosition !$= "") %cameraPosition = %scenegraph.cameraPosition; if (%scenegraph.cameraSize !$= "") %cameraSize = %scenegraph.cameraSize; %sceneWindow.setCurrentCameraPosition(%cameraPosition, %cameraSize); // Only perform "onLevelLoaded" callbacks when we're NOT editing a level // // This is so that objects that may have script associated with them that // the level builder cannot undo will not be executed while using the tool. // if (!$LevelEditorActive) { // Notify the scenegraph that it was loaded. if( %scenegraph.isMethod( "onLevelLoaded" ) ) %scenegraph.onLevelLoaded(); // And finally, notify all the objects that they were loaded. %sceneObjectList = %scenegraph.getSceneObjectList(); %sceneObjectCount = getWordCount(%sceneObjectList); for (%i = 0; %i < %sceneObjectCount; %i++) { %sceneObject = getWord(%sceneObjectList, %i); //if( %sceneObject.isMethod( "onLevelLoaded" ) ) %sceneObject.onLevelLoaded(%scenegraph); } } $lastLoadedScene = %scenegraph; return %scenegraph; } //--------------------------------------------------------------------------------------------- // t2dSceneWindow.addToLevel // Adds a level file to a scene window's scenegraph. //--------------------------------------------------------------------------------------------- function t2dSceneWindow::addToLevel(%sceneWindow, %levelFile) { %scenegraph = %sceneWindow.getSceneGraph(); if (!isObject(%scenegraph)) { %scenegraph = new t2dSceneGraph(); %sceneWindow.setSceneGraph(%scenegraph); } %newScenegraph = %scenegraph.addToLevel(%levelFile); $lastLoadedScene = %newScenegraph; return %newScenegraph; } //--------------------------------------------------------------------------------------------- // t2dSceneGraph.addToLevel // Loads a level file into a scenegraph. //--------------------------------------------------------------------------------------------- function t2dSceneGraph::loadLevel(%sceneGraph, %levelFile) { %sceneGraph.endLevel(); %newScenegraph = %sceneGraph.addToLevel(%levelFile); if (isObject(%newScenegraph) && !$LevelEditorActive) { // Notify the scenegraph that it was loaded. if( %newScenegraph.isMethod( "onLevelLoaded" ) ) %newScenegraph.onLevelLoaded(); // And finally, notify all the objects that they were loaded. %sceneObjectList = %newScenegraph.getSceneObjectList(); %sceneObjectCount = getWordCount(%sceneObjectList); for (%i = 0; %i < %sceneObjectCount; %i++) { %sceneObject = getWord(%sceneObjectList, %i); //if( %sceneObject.isMethod( "onLevelLoaded" ) ) %sceneObject.onLevelLoaded(%newScenegraph); } } $lastLoadedScene = %newScenegraph; return %newScenegraph; } //--------------------------------------------------------------------------------------------- // t2dSceneGraph.addToLevel // Adds a level file to a scenegraph. //--------------------------------------------------------------------------------------------- function t2dSceneGraph::addToLevel(%scenegraph, %levelFile) { // Reset this. It should always be false unless we are loading into a scenewindow. %useNewSceneGraph = $useNewSceneGraph; $useNewSceneGraph = false; // Prevent name clashes when loading a scenegraph with the same name as this one %scenegraph = %scenegraph.getId(); // Make sure the file is valid. if ((!isFile(%levelFile)) && (!isFile(%levelFile @ ".dso"))) { error("Error loading level " @ %levelFile @ ". Invalid file."); return 0; } // Load up the level. exec(%levelFile); // The level file should have contained a scenegraph, which should now be in the instant // group. And, it should be the only thing in the group. if (!isObject(%levelContent)) { error("Invalid level file specified: " @ %levelFile); return 0; } %newScenegraph = %scenegraph; %object = %levelContent; $LevelManagement::newObjects = ""; if (%object.getClassName() $= "t2dSceneObjectGroup") { %newScenegraph.addToScene(%object); for (%i = 0; %i < %object.getCount(); %i++) { %obj = %object.getObject(%i); if (%obj.getClassName() $= "t2dParticleEffect") { %newScenegraph.addToScene(%obj); %oldPosition = %obj.getPosition(); %oldSize = %obj.getSize(); %obj.loadEffect(%obj.effectFile); %obj.setPosition(%oldPosition); %obj.setSize(%oldSize); %obj.playEffect(); } else if (%obj.getClassName() $= "t2dTileLayer") { %oldPosition = %obj.getPosition(); %oldSize = %obj.getSize(); %tileMap = %newScenegraph.getGlobalTileMap(); if (isObject(%tileMap)) { %tileMap.addTileLayer(%obj); %obj.loadTileLayer(%obj.layerFile); %obj.setPosition(%oldPosition); %obj.setSize(%oldSize); } else error("Unable to find scene graph's global tile map."); } } $LevelManagement::newObjects = %object; } else if( %object.getClassName() $= "t2dSceneObjectSet" ) { // Add each object in the set to the scene. for (%i = 0; %i < %object.getCount(); %i++) { %obj = %object.getObject(%i); %newScenegraph.addToScene( %obj ); if (%obj.getClassName() $= "t2dParticleEffect") { %oldPosition = %obj.getPosition(); %oldSize = %obj.getSize(); %obj.loadEffect(%obj.effectFile); %obj.setPosition(%oldPosition); %obj.setSize(%oldSize); %obj.playEffect(); } else if (%obj.getClassName() $= "t2dTileLayer") { %oldPosition = %obj.getPosition(); %oldSize = %obj.getSize(); %tileMap = %newScenegraph.getGlobalTileMap(); if (isObject(%tileMap)) { %tileMap.addTileLayer(%obj); %obj.loadTileLayer(%obj.layerFile); %obj.setPosition(%oldPosition); %obj.setSize(%oldSize); } else error("Unable to find scene graph's global tile map."); } } $LevelManagement::newObjects = %object; } else if (%object.isMemberOfClass("t2dSceneObject")) { if (%object.getClassName() $= "t2dParticleEffect") { %newScenegraph.addToScene(%object); %oldPosition = %object.getPosition(); %oldSize = %object.getSize(); %object.loadEffect(%object.effectFile); %object.setPosition(%oldPosition); %object.setSize(%oldSize); %object.playEffect(); } else if (%object.getClassName() $= "t2dTileLayer") { %oldPosition = %object.getPosition(); %oldSize = %object.getSize(); %tileMap = %newScenegraph.getGlobalTileMap(); if (isObject(%tileMap)) { %tileMap.addTileLayer(%object); %object.loadTileLayer(%object.layerFile); %object.setPosition(%oldPosition); %object.setSize(%oldSize); } else error("Unable to find scene graph's global tile map."); } else %newScenegraph.addToScene(%object); $LevelManagement::newObjects = %object; } // If we got a scenegraph... else if (%object.getClassName() $= "t2dSceneGraph") { %fromSceneGraph = 0; %toSceneGraph = 0; // If we are supposed to use the new scenegraph, we need to copy from the existing scene // graph to the new one. Otherwise, we copy the loaded stuff into the existing one. if (%useNewSceneGraph) { %fromSceneGraph = %newScenegraph; %toSceneGraph = %object; } else { %fromSceneGraph = %object; %toSceneGraph = %newScenegraph; } if (isObject(%fromSceneGraph.getGlobalTileMap())) %fromSceneGraph.getGlobalTileMap().delete(); // If the existing scenegraph has objects in it, then the new stuff should probably be // organized nicely in its own group. if ((%toSceneGraph.getCount() > 0) && (%fromSceneGraph.getCount() > 0)) { %newGroup = new t2dSceneObjectGroup(); while (%fromSceneGraph.getCount() > 0) { %obj = %fromSceneGraph.getObject(0); %fromSceneGraph.removeFromScene(%obj); %obj.setPosition(%obj.getPosition()); // This sets physics.dirty.... =) %newGroup.add(%obj); } %toSceneGraph.add(%newGroup); $LevelManagement::newObjects = %newGroup; } else // if it does not then simply move the objects over { while (%fromSceneGraph.getCount() > 0) { %obj = %fromSceneGraph.getObject(0); %fromSceneGraph.removeFromScene(%obj); %obj.setPosition(%obj.getPosition()); // This sets physics.dirty.... =) %toSceneGraph.addToScene(%obj); } $LevelManagement::newObjects = %toSceneGraph; } %newScenegraph = %toSceneGraph; %fromSceneGraph.delete(); } // Unsupported object type. else { error("Error loading level " @ %levelFile @ ". " @ %object.getClassName() @ " is not a valid level object type."); return 0; } if( isObject( $persistentObjectSet ) ) { // Now we need to move all the persistent objects into the scene. %count = $persistentObjectSet.getCount(); for (%i = 0; %i < %count; %i++) { %object = $persistentObjectSet.getObject(%i); %sg = %object.getSceneGraph(); if(%sg) %sg.removeFromScene(%object); %newScenegraph.addToScene(%object); %object.setPosition( %object.getPosition() ); } } // And finally, perform any post creation actions %newScenegraph.performPostInit(); $lastLoadedScene = %newScenegraph; return %newScenegraph; } //--------------------------------------------------------------------------------------------- // t2dSceneWindow.endLevel // Clears a scene window. //--------------------------------------------------------------------------------------------- function t2dSceneWindow::endLevel(%sceneWindow) { %scenegraph = %sceneWindow.getSceneGraph(); if (!isObject(%scenegraph)) return; %scenegraph.endLevel(); if (isObject(%scenegraph)) { if( isObject( %scenegraph.getGlobalTileMap() ) ) %scenegraph.getGlobalTileMap().delete(); %scenegraph.delete(); } $lastLoadedScene = ""; } //--------------------------------------------------------------------------------------------- // t2dSceneGraph.endLevel // Clears a scenegraph. //--------------------------------------------------------------------------------------------- function t2dSceneGraph::endLevel(%sceneGraph) { if (!$LevelEditorActive) { %sceneObjectList = %sceneGraph.getSceneObjectList(); // And finally, notify all the objects that they were loaded. for (%i = 0; %i < getWordCount(%sceneObjectList); %i++) { %sceneObject = getWord(%sceneObjectList, %i); //if( %sceneObject.isMethod( "onLevelEnded" ) ) %sceneObject.onLevelEnded(%sceneGraph); } // Notify the scenegraph that the level ended. if( %sceneGraph.isMethod( "onLevelEnded" ) ) %sceneGraph.onLevelEnded(); } if( isObject( $persistentObjectSet ) ) { %count = $persistentObjectSet.getCount(); for (%i = 0; %i < %count; %i++) { %object = $persistentObjectSet.getObject(%i); %scenegraph.removeFromScene(%object); } } %globalTileMap = %sceneGraph.getGlobalTileMap(); if (isObject(%globalTileMap)) %sceneGraph.removeFromScene(%globalTileMap); %scenegraph.clearScene(true); if (isObject(%globalTileMap)) %sceneGraph.addToScene(%globalTileMap); $lastLoadedScene = ""; } function t2dSceneObject::onLevelLoaded(%this, %scenegraph) { } function t2dSceneObject::onLevelEnded(%this, %scenegraph) { }
//----------------------------------------------------------------------- // <copyright file="ReadLengthLimitingStream.cs" company="Microsoft"> // Copyright 2013 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. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.Azure.Storage.Core { using Microsoft.Azure.Storage.Core.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// Stream that will be used to limit read operations on a wrapped stream. /// </summary> internal class ReadLengthLimitingStream : Stream { private readonly Stream wrappedStream; private long streamBeginIndex; private long position; private long length; private bool disposed = false; public ReadLengthLimitingStream(Stream wrappedStream, long length) { if (!wrappedStream.CanSeek || !wrappedStream.CanRead) { throw new NotSupportedException(); } CommonUtility.AssertNotNull("wrappedSream", wrappedStream); this.wrappedStream = wrappedStream; this.length = Math.Min(length, wrappedStream.Length - wrappedStream.Position); this.streamBeginIndex = wrappedStream.Position; this.Position = 0; } public override bool CanRead { get { return this.wrappedStream.CanRead; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return this.length; } } public override void SetLength(long value) { throw new NotSupportedException(); } public override long Position { get { return this.position; } set { CommonUtility.AssertInBounds("position", value, 0, this.Length); this.position = value; this.wrappedStream.Position = this.streamBeginIndex + value; } } public override void Flush() { this.wrappedStream.Flush(); } public override long Seek(long offset, SeekOrigin origin) { long startIndex; // Map offset to the specified SeekOrigin of the substream. switch (origin) { case SeekOrigin.Begin: startIndex = 0; break; case SeekOrigin.Current: startIndex = this.Position; break; case SeekOrigin.End: startIndex = this.length - offset; offset = 0; break; default: throw new ArgumentOutOfRangeException(); } this.Position = startIndex + offset; return this.Position; } public override int Read(byte[] buffer, int offset, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (this.Position + count > this.Length) { count = (int)(this.Length - this.Position); } int bytesRead = this.wrappedStream.Read(buffer, offset, count); this.Position += bytesRead; return bytesRead; } #if WINDOWS_DESKTOP public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (this.Position + count > this.Length) { count = (int)(this.Length - this.Position); } return this.wrappedStream.BeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { int bytesRead = this.wrappedStream.EndRead(asyncResult); this.Position += bytesRead; return bytesRead; } #endif public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (this.Position + count > this.Length) { count = (int)(this.Length - this.Position); } int bytesRead = await this.wrappedStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); this.Position += bytesRead; return bytesRead; } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { this.wrappedStream.Dispose(); } disposed = true; base.Dispose(disposing); } } }
using KaoriStudio.Core.Helpers; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace KaoriStudio.Core.Configuration { using TypeCodeSet = System.Collections.Generic.HashSet<System.TypeCode>; /// <summary> /// A configuration map /// </summary> [Serializable] public partial class ConfigurationDictionary : IDictionary<string, object>, ICloneable, IEquatable<ConfigurationDictionary> { #region "Members" private List<KeyValuePair<string, object>> mapData; private List<object> arrayData; private static Dictionary<TypeCode, TypeCodeSet> typeCodeMatches; private int _version; #endregion #region "Exceptions" static KeyNotFoundException KNFException(string key) { return new KeyNotFoundException(String.Format("Could not locate key {0}", key)); } static KeyNotFoundException KNFException(string key, Type type) { return new KeyNotFoundException(String.Format("Could not locate key {0} with value of type {1}", key, type.FullName)); } static KeyNotFoundException KNFConvertException(string key, Type type) { return new KeyNotFoundException(String.Format("Could not locate key {0} with value convertible to type {1}", key, type.FullName)); } private static void ThrowVersion() { throw new InvalidOperationException("ConfigurationDictionary was modified while enumerating"); } #endregion #region "Constructors" /// <summary> /// Creates a blank configuration map /// </summary> public ConfigurationDictionary() { this.arrayData = null; this.mapData = null; this._version = 0; } /// <summary> /// Creates a configuration map with key-value pairings /// </summary> /// <param name="pairs">The set of key-value pairs</param> public ConfigurationDictionary(IEnumerable<KeyValuePair<string, object>> pairs) { this.arrayData = null; this.mapData = new List<KeyValuePair<string, object>>(pairs); if (this.mapData.Count == 0) this.mapData = null; if (this.mapData.ForAll(x => x.Key == null)) { this.arrayData = new List<object>(this.mapData.Select(x => x.Value)); this.mapData = null; } this._version = 0; } /// <summary> /// Creates a configuration map of values /// </summary> /// <param name="values">The set of values</param> public ConfigurationDictionary(IEnumerable<object> values) { this.arrayData = new List<object>(values); if (this.arrayData.Count == 0) this.arrayData = null; this.mapData = null; this._version = 0; } #endregion #region "Miscellaneous" static ConfigurationDictionary() { typeCodeMatches = new Dictionary<TypeCode, TypeCodeSet>(); PopulateTypeCodeGroup(new TypeCodeSet(new TypeCode[] { TypeCode.Byte, TypeCode.SByte, TypeCode.Int16, TypeCode.UInt16, TypeCode.Int32, TypeCode.UInt32, TypeCode.Int64, TypeCode.UInt64 })); PopulateTypeCodeGroup(new TypeCodeSet(new TypeCode[] { TypeCode.Single, TypeCode.Double, TypeCode.Decimal })); } private static void PopulateTypeCodeGroup(TypeCodeSet grp) { foreach (TypeCode tc in grp) typeCodeMatches[tc] = grp; } private static void CheckBounds<T>(T[] array, int arrayIndex, int count) { if (array == null) throw new ArgumentNullException("array", "array is null"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "arrayIndex is less than 0"); if (array.Length < (count + arrayIndex)) throw new ArgumentException("Array has insufficient space"); } private void ConvertToMap() { this.mapData = new List<KeyValuePair<string, object>>(this.arrayData.Select(X => new KeyValuePair<string, object>(null, X))); this.arrayData = null; this._version++; } /// <inheritdoc/> public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { if (this.arrayData != null) { CheckBounds(array, arrayIndex, this.arrayData.Count); for (int i = arrayIndex, j = 0; j < this.arrayData.Count; i++, j++) { array[i] = new KeyValuePair<string, object>(null, this.arrayData[j]); } } else if (this.mapData != null) { CheckBounds(array, arrayIndex, this.mapData.Count); for (int i = arrayIndex, j = 0; j < this.mapData.Count; i++, j++) { array[i] = this.mapData[j]; } } else CheckBounds(array, arrayIndex, 0); } /// <summary> /// Tries to read a path /// </summary> /// <typeparam name="T">The type</typeparam> /// <param name="path">The path</param> /// <param name="value">The value</param> /// <returns>Whether the value was found</returns> public bool TryGetPath<T>(string[] path, out T value) { ConfigurationDictionary current = this; for (int i = 0; i < path.Length; i++) { var pathPart = path[i]; if (i == path.Length - 1) { T attempt; if (current.TryGetValueAs<T>(pathPart, out attempt)) { value = attempt; return true; } else { value = default(T); return false; } } else { ConfigurationDictionary attempt; if (current.TryGetValueAs<ConfigurationDictionary>(pathPart, out attempt)) { current = attempt; } else { value = default(T); return false; } } } value = default(T); return false; } #endregion #region "Properties" /// <summary> /// Whether this configuration map is an array of values /// </summary> public bool IsArray { get { return this.arrayData != null; } } /// <summary> /// Whether this configuration map is a key-value map /// </summary> public bool IsMap { get { return this.mapData != null; } } /// <summary> /// The number of values in this configuration map /// </summary> public int Count { get { if (this.arrayData != null) return this.arrayData.Count; else if (this.mapData != null) return this.mapData.Count; else return 0; } } /// <summary> /// Whether this configuration map is read only /// </summary> public bool IsReadOnly { get { return false; } } #endregion #region "Add" /// <summary> /// Adds a key-value pair to the configuration map /// </summary> /// <param name="item">The pair to add</param> public void Add(KeyValuePair<string, object> item) { this.Add(item.Key, item.Value); } /// <summary> /// Adds an entry to the configuration map /// </summary> /// <param name="key">The key of the entry</param> /// <param name="value">The value of the entry</param> public void Add(string key, object value) { if (key == null) { if (this.arrayData != null) this.arrayData.Add(value); else if (this.mapData != null) this.mapData.Add(new KeyValuePair<string, object>(null, value)); else { this.arrayData = new List<object>(); this.arrayData.Add(value); } } else { if (this.arrayData != null) this.ConvertToMap(); else if (this.mapData == null) this.mapData = new List<KeyValuePair<string, object>>(); this.mapData.Add(new KeyValuePair<string, object>(key, value)); } this._version++; } /// <summary> /// Adds a value to the configuration map /// </summary> /// <param name="value">The value</param> public void Add(object value) { if (this.arrayData != null) this.arrayData.Add(value); else if (this.mapData != null) this.mapData.Add(new KeyValuePair<string, object>(null, value)); else { this.arrayData = new List<object>(); this.arrayData.Add(value); } this._version++; } #endregion #region "Contains" /// <summary> /// Searches for a key-value pair /// </summary> /// <param name="item">The key-value pair to search for</param> /// <returns>Whether the key-value pair could be found</returns> public bool Contains(KeyValuePair<string, object> item) { if (item.Key == null && this.arrayData != null) return this.ContainsValue(item.Value); else if (this.arrayData != null || this.mapData == null) return false; else { if (item.Value == null) { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (pair.Value == null && item.Key == pair.Key) return true; } return false; } else { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (item.Key == pair.Key && item.Value.Equals(pair.Value)) return true; } return false; } } } /// <summary> /// Searches for a key /// </summary> /// <param name="key">The key to search for</param> /// <returns>Whether the key could be found</returns> public bool ContainsKey(string key) { if (this.arrayData != null) { if (key == null) return true; else return false; } else if (this.mapData != null) { if (key == null) { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (pair.Key == null) return true; } return false; } else { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (key == pair.Key) return true; } return false; } } else { return false; } } /// <summary> /// Searches for a value /// </summary> /// <param name="value">The value to search for</param> /// <returns>Whether the value could be found</returns> public bool ContainsValue(object value) { if (this.arrayData != null) { if (value == null) { for (int i = 0; i < this.arrayData.Count; i++) { if (this.arrayData[i] == null) return true; } return false; } else { for (int i = 0; i < this.arrayData.Count; i++) { if (value.Equals(this.arrayData[i])) return true; } return false; } } else if (this.mapData != null) { if (value == null) { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (pair.Value == null) return true; } return false; } else { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (value.Equals(pair.Value)) return true; } return false; } } else return false; } #endregion #region "Enumerator" /// <summary> /// Gets the enumerator for this configuration map /// </summary> /// <returns>The enumerator for this configuration map</returns> public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { if (this.arrayData != null) return this.ArrayEnumerator(); else if (this.mapData != null) return this.mapData.GetEnumerator(); else return Enumerable.Empty<KeyValuePair<string, object>>().GetEnumerator(); } private IEnumerator<KeyValuePair<string, object>> ArrayEnumerator() { for (int i = 0; i < arrayData.Count; i++) yield return new KeyValuePair<string, object>(null, this.arrayData[i]); } /// <summary> /// A map enumerator /// </summary> public struct Enumerator : IEnumerator<KeyValuePair<string, object>>, IEnumerator { private ConfigurationDictionary map; private int index; private bool isArray; private int version; private KeyValuePair<string, object> current; /// <summary> /// The current pair /// </summary> public KeyValuePair<string, object> Current { get { return current; } } object IEnumerator.Current { get { return current; } } /// <summary> /// Creates a new map enumerator /// </summary> /// <param name="map">The map</param> public Enumerator(ConfigurationDictionary map) { this.map = map; this.index = (map.arrayData == null && map.mapData == null) ? -1 : 0; this.isArray = map.arrayData != null; this.version = map._version; this.current = default(KeyValuePair<string, object>); } /// <summary> /// Disposes of the enumerator /// </summary> public void Dispose() { } /// <summary> /// Moves to the next pair /// </summary> /// <returns>Whether any pair is left</returns> public bool MoveNext() { if (version != map._version) ThrowVersion(); if (index != -1) { if (isArray) { if (index < map.arrayData.Count) { current = new KeyValuePair<string, object>(null, map.arrayData[index]); index++; return true; } } else { if (index < map.mapData.Count) { current = map.mapData[index]; index++; return true; } } } return false; } /// <summary> /// Resets the enumerator /// </summary> public void Reset() { if (version != map._version) ThrowVersion(); if (index != -1) index = 0; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region "Remove and Clear" /// <summary> /// Removes a key-value pair from this configuration map /// </summary> /// <param name="item">The key-value pair to remove</param> /// <returns>Whether the pair was removed</returns> public bool Remove(KeyValuePair<string, object> item) { if (item.Key == null && this.arrayData != null) return this.RemoveValue(item.Value); else if (this.arrayData != null) return false; else if (this.mapData != null) { if (item.Value == null) { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (pair.Value == null && item.Key == pair.Key) { this._version++; this.mapData.RemoveAt(i); return true; } } return false; } else { for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; if (item.Value.Equals(pair.Value) && item.Key == pair.Key) { this._version++; this.mapData.RemoveAt(i); return true; } } return false; } } else return false; } /// <summary> /// Removes a pair at a given index /// </summary> /// <param name="index">The index</param> public void RemoveAt(int index) { if (this.arrayData != null) { this.arrayData.RemoveAt(index); this._version++; } else if (this.mapData != null) { this.mapData.RemoveAt(index); this._version++; } else throw new IndexOutOfRangeException(); } /// <summary> /// Removes a range of pairs /// </summary> /// <param name="index">The starting index</param> /// <param name="count">The number of pairs to remove</param> public void RemoveRange(int index, int count) { if (this.arrayData != null) { this.arrayData.RemoveRange(index, count); this._version++; } else if (this.mapData != null) { this.mapData.RemoveRange(index, count); this._version++; } else if (count != 0) throw new IndexOutOfRangeException(); } /// <summary> /// Removes a pair with a given key /// </summary> /// <param name="key">The key</param> /// <returns>Whether the pair was removed</returns> public bool Remove(string key) { return this.Remove(key, 1) != 0; } /// <summary> /// Removes pairs with a given key /// </summary> /// <param name="key">The key</param> /// <param name="multiple">Whether to remove occurrences after the first</param> /// <returns>The number of pairs removed</returns> public int Remove(string key, bool multiple) { return this.Remove(key, multiple ? -1 : 1); } /// <summary> /// Removes pairs with a given key /// </summary> /// <param name="key">The key</param> /// <param name="max">The maximum number of pairs to remove, negative values indicate unlimited</param> /// <returns>The number of pairs removed</returns> public int Remove(string key, int max) { if (max == 0) return 0; if (this.arrayData != null) { if (key == null) { if (max >= this.arrayData.Count || max < 0) { int count = this.arrayData.Count; this.arrayData.Clear(); this.arrayData = null; this._version++; return count; } else { this.arrayData.RemoveRange(0, max); this._version++; return max; } } else return 0; } else if (this.mapData != null) { int total = 0; for (int i = 0; i < this.mapData.Count; i++) { if (key == this.mapData[i].Key) { this.mapData.RemoveAt(i); i--; total++; if (total == max) break; } } this._version += total; return total; } else return 0; } /// <summary> /// Removes a pair with a given value /// </summary> /// <param name="value">The value</param> /// <returns>Whether a pair with the value was removed</returns> public bool RemoveValue(object value) { return this.RemoveValue(value, 1) != 0; } /// <summary> /// Removes pairs with a given value /// </summary> /// <param name="value">The value</param> /// <param name="multiple">Whether to remove occurrences after the first</param> /// <returns>The number of pairs removed</returns> public int RemoveValue(object value, bool multiple) { return this.RemoveValue(value, multiple ? -1 : 1); } /// <summary> /// Removes pairs with a given value /// </summary> /// <param name="value">The value</param> /// <param name="max">The maximum number of pairs to remove, negative values indicate unlimited</param> /// <returns>The number of pairs removed</returns> public int RemoveValue(object value, int max) { if (max == 0) return 0; if (this.arrayData != null) { int total = 0; if (value == null) { for (int i = 0; i < this.arrayData.Count; i++) { if (this.arrayData[i] == null) { this.arrayData.RemoveAt(i); i--; total++; if (total == max) break; } } } else { for (int i = 0; i < this.arrayData.Count; i++) { if (value.Equals(this.arrayData[i])) { this.arrayData.RemoveAt(i); i--; total++; if (total == max) break; } } } this._version += total; return total; } else if (this.mapData != null) { int total = 0; if (value == null) { for (int i = 0; i < this.mapData.Count; i++) { if (this.mapData[i].Value == null) { this.mapData.RemoveAt(i); i--; total++; if (total == max) break; } } } else { for (int i = 0; i < this.mapData.Count; i++) { if (value.Equals(this.mapData[i].Value)) { this.mapData.RemoveAt(i); i--; total++; if (total == max) break; } } } this._version += total; return total; } else return 0; } /// <summary> /// Empties this configuration map /// </summary> public void Clear() { if (this.arrayData != null) { this.arrayData.Clear(); this.arrayData = null; } else if (this.mapData != null) { this.mapData.Clear(); this.mapData = null; } this._version++; } #endregion ///<inheritdoc/> public bool Equals(ConfigurationDictionary other) { if (this.Count != other.Count) return false; if ((this.arrayData == null) != (other.arrayData == null)) return false; using (var thisEnumerator = this.GetEnumerator()) using (var otherEnumerator = other.GetEnumerator()) { while (thisEnumerator.MoveNext() && otherEnumerator.MoveNext()) { var thisCurrent = thisEnumerator.Current; var otherCurrent = otherEnumerator.Current; if (!string.Equals(thisCurrent.Key, otherCurrent.Key) || !object.Equals(thisCurrent.Value, otherCurrent.Value)) return false; } } return true; } #region "Clone" object ICloneable.Clone() { return this.Clone(); } /// <summary> /// Creates a deep copy of this configuration map /// </summary> /// <returns>A deep copy</returns> public ConfigurationDictionary Clone() { if (this.arrayData != null) { ConfigurationDictionary clone = new ConfigurationDictionary(); clone.arrayData = new List<object>(this.arrayData.Count); for (int i = 0; i < this.arrayData.Count; i++) { var val = this.arrayData[i]; var cloneable = val as ICloneable; if (cloneable != null) clone.arrayData[i] = cloneable; else clone.arrayData[i] = val; } return clone; } else if (this.mapData != null) { ConfigurationDictionary clone = new ConfigurationDictionary(); clone.mapData = new List<KeyValuePair<string, object>>(this.mapData.Count); for (int i = 0; i < this.mapData.Count; i++) { var pair = this.mapData[i]; var cloneable = pair.Value as ICloneable; if (cloneable != null) clone.mapData[i] = new KeyValuePair<string, object>(pair.Key, cloneable); else clone.mapData[i] = pair; } return clone; } else return new ConfigurationDictionary(); } #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. /****************************************************************************** * 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 SubtractInt32() { var test = new SimpleBinaryOpTest__SubtractInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // 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(); // 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__SubtractInt32 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[ElementCount]; private static Int32[] _data2 = new Int32[ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32> _dataTable; static SimpleBinaryOpTest__SubtractInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Subtract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Subtract( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Subtract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractInt32(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Subtract(_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<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, 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 = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if ((int)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((int)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Int32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using NUnit.Framework; using UnityEngine; using Plugins.CountlySDK.Models; using Plugins.CountlySDK; using System.Threading.Tasks; using System.Web; using System.Collections.Specialized; using Plugins.CountlySDK.Enums; using Newtonsoft.Json.Linq; using System.Linq; using System.Collections.Generic; namespace Tests { public class DeviceIdTests { private readonly string _serverUrl = "https://xyz.com/"; private readonly string _appKey = "772c091355076ead703f987fee94490"; /// <summary> /// It validates device id generated by SDK. /// </summary> [Test] public void TestDeviceIdGeneratedBySDK() { CountlyConfiguration configuration = new CountlyConfiguration { ServerUrl = _serverUrl, AppKey = _appKey, }; Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Device); Assert.IsNotNull(Countly.Instance.Device.DeviceId); Assert.IsNotEmpty(Countly.Instance.Device.DeviceId); } /// <summary> /// It validates device id provided in config. /// </summary> [Test] public void TestDeviceIdGivenInConfig() { CountlyConfiguration configuration = new CountlyConfiguration { ServerUrl = _serverUrl, AppKey = _appKey, DeviceId = "device_id" }; Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Device); Assert.AreEqual("device_id", Countly.Instance.Device.DeviceId); } /// <summary> /// It validates the working of methods 'ChangeDeviceIdWithMerge' and 'ChangeDeviceIdWithoutMerge' on giving same device id. /// </summary> [Test] public async void TestSameDeviceIdLogic() { CountlyConfiguration configuration = new CountlyConfiguration { ServerUrl = _serverUrl, AppKey = _appKey, DeviceId = "device_id" }; Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Device); Assert.AreEqual("device_id", Countly.Instance.Device.DeviceId); Countly.Instance.Device._requestCountlyHelper._requestRepo.Clear(); await Countly.Instance.Device.ChangeDeviceIdWithMerge("device_id"); Assert.AreEqual(0, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); await Countly.Instance.Device.ChangeDeviceIdWithoutMerge("device_id"); Assert.AreEqual(0, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); Assert.AreEqual("device_id", Countly.Instance.Device.DeviceId); } /// <summary> /// It validates the functionality of method 'ChangeDeviceIdWithoutMerge'. /// </summary> [Test] public async void TestDeviceServiceMethod_ChangeDeviceIdWithoutMerge() { CountlyConfiguration configuration = new CountlyConfiguration { AppKey = _appKey, ServerUrl = _serverUrl, }; Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Consents); string oldDeviceId = Countly.Instance.Device.DeviceId; Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear(); await Countly.Instance.Device.ChangeDeviceIdWithoutMerge("new_device_id"); //RQ will have begin session and end session requests Assert.AreEqual(2, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); CountlyRequestModel requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual("1", collection.Get("end_session")); Assert.AreEqual(oldDeviceId, collection.Get("device_id")); Assert.IsNotNull(collection["session_duration"]); requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual("1", collection.Get("begin_session")); Assert.AreEqual("new_device_id", collection.Get("device_id")); Assert.AreEqual("new_device_id", Countly.Instance.Device.DeviceId); } /// <summary> /// It validates the consent removal after changing the device id without merging. /// </summary> [Test] public async void TestConsentRemoval_ChangeDeviceIdWithoutMerge() { CountlyConfiguration configuration = new CountlyConfiguration { AppKey = _appKey, ServerUrl = _serverUrl, RequiresConsent = true, }; configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events, Consents.Clicks, Consents.StarRating, Consents.Views, Consents.Users, Consents.Sessions, Consents.Push, Consents.RemoteConfig, Consents.Location, Consents.Feedback }); Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Consents); Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear(); string oldDeviceId = Countly.Instance.Device.DeviceId; await Countly.Instance.Device.ChangeDeviceIdWithoutMerge("new_device_id_1"); //RQ will have end session request Assert.AreEqual(1, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); CountlyRequestModel requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual("1", collection.Get("end_session")); Assert.AreEqual(oldDeviceId, collection.Get("device_id")); Assert.IsNotNull(collection["session_duration"]); Assert.IsTrue(Countly.Instance.Consents.RequiresConsent); Consents[] consents = System.Enum.GetValues(typeof(Consents)).Cast<Consents>().ToArray(); foreach (Consents consent in consents) { Assert.IsFalse(Countly.Instance.Consents.CheckConsentInternal(consent)); } } /// <summary> /// It validates functionality of method 'ChangeDeviceIdWithMerge'. /// </summary> [Test] public async void TestConset_ChangeDeviceIdWithMerge() { CountlyConfiguration configuration = new CountlyConfiguration { AppKey = _appKey, ServerUrl = _serverUrl, }; Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Consents); string oldDeviceId = Countly.Instance.Device.DeviceId; Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear(); await Countly.Instance.Device.ChangeDeviceIdWithMerge("new_device_id"); //RQ will have begin session and end session requests Assert.AreEqual(1, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); CountlyRequestModel requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual(oldDeviceId, collection.Get("old_device_id")); Assert.AreEqual("new_device_id", collection.Get("device_id")); Assert.AreEqual("new_device_id", Countly.Instance.Device.DeviceId); } /// <summary> /// It validates the functionality of method 'ChangeDeviceIdWithoutMerge' when automatic session tracking is enabled. /// </summary> [Test] public async void TestMethod_ChangeDeviceIdWithoutMerge_WhenAutomaticSessionTrackingEnabled() { CountlyConfiguration configuration = new CountlyConfiguration { AppKey = _appKey, ServerUrl = _serverUrl, RequiresConsent = true, IsAutomaticSessionTrackingDisabled = false, }; configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events, Consents.Clicks, Consents.StarRating, Consents.Views, Consents.Users, Consents.Sessions, Consents.Push, Consents.RemoteConfig, Consents.Location, Consents.Feedback }); Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Consents); string oldDeviceId = Countly.Instance.Device.DeviceId; Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear(); await Countly.Instance.Device.ChangeDeviceIdWithoutMerge("new_device_id"); //RQ will have end session request Assert.AreEqual(1, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); CountlyRequestModel requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual("1", collection.Get("end_session")); Assert.AreEqual(oldDeviceId, collection.Get("device_id")); Assert.IsNotNull(collection["session_duration"]); Countly.Instance.Consents.GiveConsentAll(); //RQ will have consent request and begin session request Assert.AreEqual(2, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); collection = HttpUtility.ParseQueryString(requestModel.RequestData); JObject consentObj = JObject.Parse(collection.Get("consent")); Assert.AreEqual(11, consentObj.Count); Assert.IsTrue(consentObj.GetValue("push").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("users").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("views").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("clicks").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("events").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("crashes").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("sessions").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("location").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("feedback").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("star-rating").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("remote-config").ToObject<bool>()); requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); collection = HttpUtility.ParseQueryString(requestModel.RequestData); Assert.AreEqual("1", collection.Get("begin_session")); Assert.AreEqual("new_device_id", collection.Get("device_id")); Assert.AreEqual("new_device_id", Countly.Instance.Device.DeviceId); } /// <summary> /// It validates the functionality of method 'ChangeDeviceIdWithoutMerge' when automatic session tracking is disabled. /// </summary> [Test] public async void TestMethod_ChangeDeviceIdWithoutMerge_WhenAutomaticSessionTrackingIsDisabled() { CountlyConfiguration configuration = new CountlyConfiguration { AppKey = _appKey, ServerUrl = _serverUrl, RequiresConsent = true, IsAutomaticSessionTrackingDisabled = true, }; configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events, Consents.Clicks, Consents.StarRating, Consents.Views, Consents.Users, Consents.Sessions, Consents.Push, Consents.RemoteConfig, Consents.Location, Consents.Feedback }); Countly.Instance.Init(configuration); Assert.IsNotNull(Countly.Instance.Consents); Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear(); await Countly.Instance.Device.ChangeDeviceIdWithoutMerge("new_device_id"); //Since automatic session tracking is disabled, RQ will be empty Assert.AreEqual(0, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); Countly.Instance.Consents.GiveConsentAll(); //RQ will have only consent request Assert.AreEqual(1, Countly.Instance.Device._requestCountlyHelper._requestRepo.Count); CountlyRequestModel requestModel = Countly.Instance.Device._requestCountlyHelper._requestRepo.Dequeue(); NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData); JObject consentObj = JObject.Parse(collection.Get("consent")); Assert.AreEqual(11, consentObj.Count); Assert.IsTrue(consentObj.GetValue("push").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("users").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("views").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("clicks").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("events").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("crashes").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("sessions").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("location").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("feedback").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("star-rating").ToObject<bool>()); Assert.IsTrue(consentObj.GetValue("remote-config").ToObject<bool>()); Assert.IsTrue(Countly.Instance.Configuration.IsAutomaticSessionTrackingDisabled); } [TearDown] public void End() { Countly.Instance.ClearStorage(); Object.DestroyImmediate(Countly.Instance); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using System.Xml.Serialization; using Apache.Geode.Client.Tests; namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; public class PutTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_update; private Int32 m_cnt; private bool m_isCreate; #endregion public PutTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps, bool isCreate) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_update = 0; m_cnt = 0; m_isCreate = isCreate; } public override void DoTask(int iters, object data) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("PutTask::DoTask:"); Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); int offset = Util.Rand(m_MaxKeys); int count = offset; while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; TKey key = default(TKey); try { key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); DeltaTestImpl oldVal = (m_maps[localcnt])[key] as DeltaTestImpl; if (oldVal == null) { Util.Log(Util.LogLevel.Error, "oldDelta Cannot be null"); } DeltaTestImpl obj = new DeltaTestImpl(oldVal); obj.SetIntVar(oldVal.GetIntVar() + 1); m_region[key] = (TVal)(object)obj; Interlocked.Increment(ref m_update); Util.BBSet("ToDeltaBB", key.ToString(), oldVal.GetToDeltaCounter()); bool removeKey = (m_maps[localcnt]).Remove(key); if (removeKey) { (m_maps[localcnt]).Add(key, (TVal)(object)obj); } } catch (Exception ex) { Util.Log(Util.LogLevel.Error, "Exception while putting key[{0}] for region {1} in iteration " + "{2}: {3}", key, m_region.Name, (count - offset), ex); throw; } count++; //if ((count % 1000) == 0) //{ // Util.Log("PutsTask::DoTask: Intermediate: Ran for 1000 iterations."); //} } //Util.Log("PutsTask::DoTask: Ran for {0} iterations.", count); Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Int32 localcnt = m_cnt; Int32 size = m_maps.Count; Int32 count = 0; Int32 i = 0; while (i < size) { count += m_maps[i].Count; foreach (KeyValuePair<TKey, TVal> item in m_maps[i]) { TKey key = (TKey)(object)item.Key; DeltaTestImpl value = item.Value as DeltaTestImpl; ; Util.BBSet("ToDeltaBB", key.ToString(), value.GetToDeltaCounter()); } i++; } Util.BBSet("MapCount", "size", count); Util.BBSet("DeltaBB", "UPDATECOUNT", m_update); } } public class CreateTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_create; private Int32 m_cnt; #endregion public CreateTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_create = 0; m_cnt = 0; } public override void DoTask(int iters, object data) { Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); IDictionary<TKey, TVal> hmoc = new Dictionary<TKey, TVal>(); lock (m_maps) { m_maps.Add(hmoc); } int offset = Util.Rand(m_MaxKeys); int count = offset; Util.Log("CreateTask::DoTask: starting {0} iterations.", iters); while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; TKey key = default(TKey); try { key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); TVal obj = (TVal)(object)(new DeltaTestImpl(0, "delta")); m_region.Add(key, obj); Interlocked.Increment(ref m_create); (m_maps[localcnt]).Add(key, obj); } catch (Exception ex) { Util.Log(Util.LogLevel.Error, "Exception while creating key[{0}] for region {1} in iteration " + "{2}: {3}", key, m_region.Name, (count - offset), ex); throw; } count++; } Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Util.BBSet("DeltaBB", "CREATECOUNT", m_create); Util.BBSet("DeltaBB", "DESTROYCOUNT", 0); } } public class EntryTask<TKey, TVal> : ClientTask { #region Private members private IRegion<TKey, TVal> m_region; private int m_MaxKeys; private List<IDictionary<TKey, TVal>> m_maps; private Int32 m_create; private Int32 m_update; private Int32 m_destroy; private Int32 m_invalidate; private Int32 m_cnt; bool m_isDestroy; private object CLASS_LOCK = new object(); #endregion public EntryTask(IRegion<TKey, TVal> region, int keyCnt, List<IDictionary<TKey, TVal>> maps) : base() { m_region = region; m_MaxKeys = keyCnt; m_maps = maps; m_create = 0; m_update = 0; m_destroy = 0; m_invalidate = 0; m_cnt = 0; m_isDestroy = true; } DeltaTestImpl getLatestDelta(TKey key, Int32 localcnt, bool isCreate) { DeltaTestImpl oldValue = (m_maps[localcnt])[key] as DeltaTestImpl; if (oldValue == null) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("oldDelta cannot be null"); } DeltaTestImpl obj = new DeltaTestImpl(oldValue.GetIntVar() + 1, "delta"); if (!isCreate) { obj.SetIntVar(oldValue.GetIntVar() + 1); } return obj; } public override void DoTask(int iters, object data) { Int32 localcnt = m_cnt; Interlocked.Increment(ref m_cnt); IDictionary<TKey, TVal> hmoc = new Dictionary<TKey, TVal>(); lock (m_maps) { m_maps.Add(hmoc); } int offset = Util.Rand(m_MaxKeys); int count = offset; TKey key = default(TKey); Util.Log("EntryTask::DoTask: starting {0} iterations.", iters); while (Running && (iters-- != 0)) { int idx = count % m_MaxKeys; key = (TKey)(object)("AAAAAA" + localcnt + idx.ToString("D10")); string opcode = FwkTest<TKey, TVal>.CurrentTest.GetStringValue("entryOps"); if (opcode == null) opcode = "no-opcode"; if (opcode == "put") { lock (CLASS_LOCK) { DeltaTestImpl newValue = null; if (m_region.ContainsKey(key)) { DeltaTestImpl oldValue = m_region[key] as DeltaTestImpl; if (oldValue == null) { newValue = getLatestDelta(key, localcnt, false); m_region[key] = (TVal)(object)newValue; } else { newValue = new DeltaTestImpl(oldValue); newValue.SetIntVar(oldValue.GetIntVar() + 1); m_region[key] = (TVal)(object)newValue; } Interlocked.Increment(ref m_update); //Util.BBSet("ToDeltaBB", key.ToString(), newValue.GetToDeltaCounter()); } else { newValue = getLatestDelta(key, localcnt, true); m_region.Add(key, (TVal)(object)newValue); Interlocked.Increment(ref m_create); } //(m_maps[localcnt]).Add(key, newValue); m_maps[localcnt][key] = (TVal)(object)newValue; } } else if (opcode == "destroy") { DeltaTestImpl oldValue = null; if (m_region.ContainsKey(key)) { if ((oldValue = m_region[key] as DeltaTestImpl) == null) { if (m_isDestroy) { m_region.Remove(key); (m_maps[localcnt]).Remove(key); } } else { m_maps[localcnt][key] = (TVal)(object)oldValue; m_region.Remove(key); //(m_maps[localcnt]).Remove(key); } Interlocked.Increment(ref m_destroy); } } else if (opcode == "invalidate") { DeltaTestImpl oldValue = null; if (m_region.ContainsKey(key)) { if ((oldValue = m_region[key] as DeltaTestImpl) != null) { m_maps[localcnt].Add(key, (TVal)(object)oldValue); m_region.Invalidate(key); Interlocked.Increment(ref m_invalidate); m_maps[localcnt].Add(key, default(TVal)); } } } } Interlocked.Add(ref m_iters, count - offset); } public void dumpToBB() { Int32 localcnt = m_cnt; Int32 size = m_maps.Count; Int32 count = 0; Int32 i = 0; while(i < size) { count += m_maps[i].Count; foreach (KeyValuePair<TKey, TVal> item in m_maps[i]) { TKey key = (TKey)(object)item.Key; DeltaTestImpl value = item.Value as DeltaTestImpl; Util.BBSet("ToDeltaBB", key.ToString(), value.GetToDeltaCounter()); } i++; } Util.BBSet("MapCount", "size", count); Int32 createCnt = (Int32)Util.BBGet("DeltaBB", "CREATECOUNT"); Util.BBSet("DeltaBB", "CREATECOUNT", createCnt + m_create); Util.BBSet("DeltaBB", "UPDATECOUNT", m_update); Util.BBSet("DeltaBB", "DESTROYCOUNT", m_destroy); } } public class DeltaTest<TKey, TVal> : FwkTest<TKey, TVal> { protected TKey[] m_keysA; protected int m_maxKeys; protected int m_keyIndexBegin; protected TVal[] m_cValues; protected int m_maxValues; protected const string ClientCount = "clientCount"; protected const string TimedInterval = "timedInterval"; protected const string DistinctKeys = "distinctKeys"; protected const string NumThreads = "numThreads"; protected const string ValueSizes = "valueSizes"; protected const string OpsSecond = "opsSecond"; protected const string KeyType = "keyType"; protected const string KeySize = "keySize"; protected const string KeyIndexBegin = "keyIndexBegin"; protected const string RegisterKeys = "registerKeys"; protected const string RegisterRegex = "registerRegex"; protected const string UnregisterRegex = "unregisterRegex"; protected const string ExpectedCount = "expectedCount"; protected const string InterestPercent = "interestPercent"; protected const string KeyStart = "keyStart"; protected const string KeyEnd = "keyEnd"; protected char m_keyType = 'i'; protected static List<IDictionary<TKey, TVal>> mapList = new List<IDictionary<TKey, TVal>>(); private static bool isObjectRegistered = false; protected void ClearKeys() { if (m_keysA != null) { for (int i = 0; i < m_keysA.Length; i++) { if (m_keysA[i] != null) { //m_keysA[i].Dispose(); m_keysA[i] = default(TKey); } } m_keysA = null; m_maxKeys = 0; } } protected int InitKeys(bool useDefault) { string typ = GetStringValue(KeyType); // int is only value to use char newType = (typ == null || typ.Length == 0) ? 's' : typ[0]; int low = GetUIntValue(KeyIndexBegin); low = (low > 0) ? low : 0; int numKeys = GetUIntValue(DistinctKeys); // check distinct keys first if (numKeys <= 0) { if (useDefault) { numKeys = 5000; } else { //FwkSevere("Failed to initialize keys with numKeys: {0}", numKeys); return numKeys; } } int high = numKeys + low; FwkInfo("InitKeys:: numKeys: {0}; low: {1}", numKeys, low); if ((newType == m_keyType) && (numKeys == m_maxKeys) && (m_keyIndexBegin == low)) { return numKeys; } ClearKeys(); m_maxKeys = numKeys; m_keyIndexBegin = low; m_keyType = newType; if (m_keyType == 'i') { InitIntKeys(low, high); } else { int keySize = GetUIntValue(KeySize); keySize = (keySize > 0) ? keySize : 10; string keyBase = new string('A', keySize); InitStrKeys(low, high, keyBase); } for (int j = 0; j < numKeys; j++) { int randIndx = Util.Rand(numKeys); if (randIndx != j) { TKey tmp = m_keysA[j]; m_keysA[j] = m_keysA[randIndx]; m_keysA[randIndx] = tmp; } } return m_maxKeys; } protected int InitKeys() { return InitKeys(true); } protected void InitStrKeys(int low, int high, string keyBase) { m_keysA = (TKey[])(object)new String[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)(keyBase + i.ToString("D10")); } } protected void InitIntKeys(int low, int high) { m_keysA = (TKey[])(object)new Int32[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)i; } } protected IRegion<TKey,TVal> GetRegion() { return GetRegion(null); } protected IRegion<TKey, TVal> GetRegion(string regionName) { IRegion<TKey, TVal> region; if (regionName == null) { region = GetRootRegion(); if (region == null) { IRegion<TKey, TVal>[] rootRegions = CacheHelper<TKey, TVal>.DCache.RootRegions<TKey, TVal>(); if (rootRegions != null && rootRegions.Length > 0) { region = rootRegions[Util.Rand(rootRegions.Length)]; } } } else { region = CacheHelper<TKey, TVal>.GetRegion(regionName); } return region; } public DeltaTest() { //FwkInfo("In DeltaTest()"); } public static ICacheListener<TKey, TVal> CreateDeltaValidationCacheListener() { return new DeltaClientValidationListener<TKey, TVal>(); } public virtual void DoCreateRegion() { FwkInfo("In DoCreateRegion()"); try { if (!isObjectRegistered) { CacheHelper<TKey, TVal>.DCache.TypeRegistry.RegisterTypeGeneric(DeltaTestImpl.CreateDeserializable); CacheHelper<TKey, TVal>.DCache.TypeRegistry.RegisterTypeGeneric(TestObject1.CreateDeserializable); isObjectRegistered = true; } IRegion<TKey, TVal> region = CreateRootRegion(); if (region == null) { FwkException("DoCreateRegion() could not create region."); } FwkInfo("DoCreateRegion() Created region '{0}'", region.Name); } catch (Exception ex) { FwkException("DoCreateRegion() Caught Exception: {0}", ex); } FwkInfo("DoCreateRegion() complete."); } public virtual void DoCreatePool() { FwkInfo("In DoCreatePool()"); try { CreatePool(); } catch (Exception ex) { FwkException("DoCreatePool() Caught Exception: {0}", ex); } FwkInfo("DoCreatePool() complete."); } public void DoRegisterAllKeys() { FwkInfo("In DoRegisterAllKeys()"); try { IRegion<TKey, TVal> region = GetRegion(); FwkInfo("DoRegisterAllKeys() region name is {0}", region.Name); bool isDurable = GetBoolValue("isDurableReg"); ResetKey("getInitialValues"); bool isGetInitialValues = GetBoolValue("getInitialValues"); region.GetSubscriptionService().RegisterAllKeys(isDurable, isGetInitialValues); } catch (Exception ex) { FwkException("DoRegisterAllKeys() Caught Exception: {0}", ex); } FwkInfo("DoRegisterAllKeys() complete."); } public void DoPuts() { FwkInfo("In DoPuts()"); try { IRegion<TKey, TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; // Loop over key set sizes ResetKey(DistinctKeys); int numKeys; while ((numKeys = InitKeys(false)) > 0) { // keys loop // Loop over value sizes ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { PutTask<TKey, TVal> puts = new PutTask<TKey, TVal>(region, numKeys / numThreads, mapList, true); FwkInfo("Running timed task "); try { RunTask(puts, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoPuts() Timed run timed out."); } puts.dumpToBB(); Thread.Sleep(3000); // Put a marker of inactivity in the stats } Thread.Sleep(3000); // Put a marker of inactivity in the stats } // keys loop } catch (Exception ex) { FwkException("DoPuts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoPuts() complete."); } public void DoPopulateRegion() { FwkInfo("In DoPopulateRegion()"); try { IRegion<TKey, TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = InitKeys(); ResetKey(NumThreads); int numThreads = GetUIntValue(NumThreads); CreateTask<TKey, TVal> creates = new CreateTask<TKey, TVal>(region, (numKeys / numThreads), mapList); FwkInfo("Populating region."); RunTask(creates, numThreads, (numKeys / numThreads), -1, -1, null); creates.dumpToBB(); } catch (Exception ex) { FwkException("DoPopulateRegion() Caught Exception: {0}", ex); } FwkInfo("DoPopulateRegion() complete."); } public void DoEntryOperation() { FwkInfo("In DoEntryOperation"); try { IRegion<TKey, TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; { timedInterval = 5000; } int maxTime = 10 * timedInterval; // Loop over key set sizes ResetKey(DistinctKeys); int numKeys = GetUIntValue(DistinctKeys); ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { EntryTask<TKey, TVal> entrytask = new EntryTask<TKey, TVal>(region, numKeys / numThreads, mapList); FwkInfo("Running timed task "); try { RunTask(entrytask, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoPuts() Timed run timed out."); } Thread.Sleep(3000); entrytask.dumpToBB(); } } catch (Exception ex) { FwkException("DoEntryOperation() Caught Exception: {0}", ex); } FwkInfo("DoEntryOperation() complete."); } public void DoCloseCache() { FwkInfo("DoCloseCache() Closing cache and disconnecting from" + " distributed system."); CacheHelper<TKey, TVal>.Close(); } public void DoValidateDeltaTest() { FwkInfo("DoValidateDeltaTest() called."); try { IRegion<TKey, TVal> region = GetRegion(); region.GetLocalView().DestroyRegion(); TKey key = default(TKey); Int32 expectedAfterCreateEvent = (Int32)Util.BBGet("DeltaBB", "CREATECOUNT"); Int32 expectedAfterUpdateEvent = (Int32)Util.BBGet("DeltaBB", "UPDATECOUNT"); Int32 expectedAfterDestroyEvent = (Int32)Util.BBGet("DeltaBB", "DESTROYCOUNT"); long eventAfterCreate = (long)Util.BBGet("DeltaBB", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name); long eventAfterUpdate = (long)Util.BBGet("DeltaBB", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name); long eventAfterDestroy = (long)Util.BBGet("DeltaBB", "AFTER_DESTROY_COUNT_" + Util.ClientId + "_" + region.Name); FwkInfo("DoValidateDeltaTest() -- eventAfterCreate {0} ,eventAfterUpdate {1} ,eventAfterDestroy {2}", eventAfterCreate, eventAfterUpdate, eventAfterDestroy); FwkInfo("DoValidateDeltaTest() -- expectedAfterCreateEvent {0} ,expectedAfterUpdateEvent {1}, expectedAfterDestroyEvent {2} ", expectedAfterCreateEvent, expectedAfterUpdateEvent, expectedAfterDestroyEvent); if (expectedAfterCreateEvent == eventAfterCreate && expectedAfterUpdateEvent == eventAfterUpdate && expectedAfterDestroyEvent == eventAfterDestroy) { DeltaClientValidationListener<TKey, TVal> cs = (region.Attributes.CacheListener) as DeltaClientValidationListener<TKey, TVal>; IDictionary<TKey, Int64> map = cs.getMap(); Int32 mapCount = map.Count; Int32 toDeltaMapCount = (Int32)Util.BBGet("MapCount", "size"); if (mapCount == toDeltaMapCount) { foreach (KeyValuePair<TKey, Int64> item in map) { key = (TKey)(object)item.Key; Int64 value = item.Value; long fromDeltaCount = (long)value; long toDeltaCount = (long)Util.BBGet("ToDeltaBB", key.ToString()); if (toDeltaCount == fromDeltaCount) { FwkInfo("DoValidateDeltaTest() Delta Count Validation success with fromDeltaCount: {0} = toDeltaCount: {1}", fromDeltaCount, toDeltaCount); } } FwkInfo("DoValidateDeltaTest() Validation success."); } else { FwkException("Validation Failed() as fromDeltaMapCount: {0} is not equal to toDeltaMapCount: {1}",mapCount,toDeltaMapCount); } } else { FwkException("Validation Failed()for Region: {0} Expected were expectedAfterCreateEvent {1} expectedAfterUpdateEvent {2} expectedAfterDestroyEvent {3} eventAfterCreate {4}, eventAfterUpdate {5} ", region.Name, expectedAfterCreateEvent, expectedAfterUpdateEvent,expectedAfterDestroyEvent, eventAfterCreate, eventAfterUpdate ,eventAfterDestroy); } } catch (Exception ex) { FwkException("DoValidateDeltaTest() Caught Exception: {0}", ex); FwkInfo("DoValidateDeltaTest() complete."); } } } }//DeltaTest end
// 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 System.Text; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.Windows.Design.Host; namespace Microsoft.PythonTools.Designer { class WpfEventBindingProvider : EventBindingProvider { private Project.PythonFileNode _pythonFileNode; public WpfEventBindingProvider(Project.PythonFileNode pythonFileNode) { _pythonFileNode = pythonFileNode; } public override bool AddEventHandler(EventDescription eventDescription, string objectName, string methodName) { // we return false here which causes the event handler to always be wired up via XAML instead of via code. return false; } public override bool AllowClassNameForMethodName() { return true; } public override void AppendStatements(EventDescription eventDescription, string methodName, string statements, int relativePosition) { throw new NotImplementedException(); } public override string CodeProviderLanguage { get { return "Python"; } } public override bool CreateMethod(EventDescription eventDescription, string methodName, string initialStatements) { // build the new method handler var view = _pythonFileNode.GetTextView(); var textBuffer = _pythonFileNode.GetTextBuffer(); PythonAst ast; var classDef = GetClassForEvents(out ast); if (classDef != null) { int end = classDef.Body.EndIndex; // insert after the newline at the end of the last statement of the class def if (textBuffer.CurrentSnapshot[end] == '\r') { if (end + 1 < textBuffer.CurrentSnapshot.Length && textBuffer.CurrentSnapshot[end + 1] == '\n') { end += 2; } else { end++; } } else if (textBuffer.CurrentSnapshot[end] == '\n') { end++; } using (var edit = textBuffer.CreateEdit()) { var text = BuildMethod( eventDescription, methodName, new string(' ', classDef.Body.GetStart(ast).Column - 1), view.Options.IsConvertTabsToSpacesEnabled() ? view.Options.GetIndentSize() : -1); edit.Insert(end, text); edit.Apply(); return true; } } return false; } private ClassDefinition GetClassForEvents() { PythonAst ast; return GetClassForEvents(out ast); } private ClassDefinition GetClassForEvents(out PythonAst ast) { ast = null; var analysis = _pythonFileNode.GetProjectEntry() as IPythonProjectEntry; if (analysis != null) { // TODO: Wait for up to date analysis ast = analysis.WaitForCurrentTree(); var suiteStmt = ast.Body as SuiteStatement; foreach (var stmt in suiteStmt.Statements) { var classDef = stmt as ClassDefinition; // TODO: Make sure this is the right class if (classDef != null) { return classDef; } } } return null; } private static string BuildMethod(EventDescription eventDescription, string methodName, string indentation, int tabSize) { StringBuilder text = new StringBuilder(); text.AppendLine(indentation); text.Append(indentation); text.Append("def "); text.Append(methodName); text.Append('('); text.Append("self"); foreach (var param in eventDescription.Parameters) { text.Append(", "); text.Append(param.Name); } text.AppendLine("):"); if (tabSize < 0) { text.Append(indentation); text.Append("\tpass"); } else { text.Append(indentation); text.Append(' ', tabSize); text.Append("pass"); } text.AppendLine(); return text.ToString(); } public override string CreateUniqueMethodName(string objectName, EventDescription eventDescription) { var name = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", objectName, eventDescription.Name); int count = 0; while (IsExistingMethodName(eventDescription, name)) { name = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}{2}", objectName, eventDescription.Name, ++count); } return name; } public override IEnumerable<string> GetCompatibleMethods(EventDescription eventDescription) { var classDef = GetClassForEvents(); SuiteStatement suite = classDef.Body as SuiteStatement; if (suite != null) { int requiredParamCount = eventDescription.Parameters.Count() + 1; foreach (var methodCandidate in suite.Statements) { FunctionDefinition funcDef = methodCandidate as FunctionDefinition; if (funcDef != null) { // Given that event handlers can be given any arbitrary // name, it is important to not rely on the default naming // to detect compatible methods. Instead we look at the // event parameters. We don't have param types in Python, // so really the only thing that can be done is look at // the method parameter count, which should be one more than // the event parameter count (to account for the self param). if (funcDef.Parameters.Count == requiredParamCount) { yield return funcDef.Name; } } } } } public override IEnumerable<string> GetMethodHandlers(EventDescription eventDescription, string objectName) { return new string[0]; } public override bool IsExistingMethodName(EventDescription eventDescription, string methodName) { return FindMethod(methodName) != null; } private FunctionDefinition FindMethod(string methodName) { var classDef = GetClassForEvents(); SuiteStatement suite = classDef.Body as SuiteStatement; if (suite != null) { foreach (var methodCandidate in suite.Statements) { FunctionDefinition funcDef = methodCandidate as FunctionDefinition; if (funcDef != null) { if (funcDef.Name == methodName) { return funcDef; } } } } return null; } public override bool RemoveEventHandler(EventDescription eventDescription, string objectName, string methodName) { var method = FindMethod(methodName); if (method != null) { var view = _pythonFileNode.GetTextView(); var textBuffer = _pythonFileNode.GetTextBuffer(); // appending a method adds 2 extra newlines, we want to remove those if those are still // present so that adding a handler and then removing it leaves the buffer unchanged. using (var edit = textBuffer.CreateEdit()) { int start = method.StartIndex - 1; // eat the newline we insert before the method while (start >= 0) { var curChar = edit.Snapshot[start]; if (!Char.IsWhiteSpace(curChar)) { break; } else if (curChar == ' ' || curChar == '\t') { start--; continue; } else if (curChar == '\n') { if (start != 0) { if (edit.Snapshot[start - 1] == '\r') { start--; } } start--; break; } else if (curChar == '\r') { start--; break; } start--; } // eat the newline we insert at the end of the method int end = method.EndIndex; while (end < edit.Snapshot.Length) { if (edit.Snapshot[end] == '\n') { end++; break; } else if (edit.Snapshot[end] == '\r') { if (end < edit.Snapshot.Length - 1 && edit.Snapshot[end + 1] == '\n') { end += 2; } else { end++; } break; } else if (edit.Snapshot[end] == ' ' || edit.Snapshot[end] == '\t') { end++; continue; } else { break; } } // delete the method and the extra whitespace that we just calculated. edit.Delete(Span.FromBounds(start + 1, end)); edit.Apply(); } return true; } return false; } public override bool RemoveHandlesForName(string elementName) { throw new NotImplementedException(); } public override bool RemoveMethod(EventDescription eventDescription, string methodName) { throw new NotImplementedException(); } public override void SetClassName(string className) { } public override bool ShowMethod(EventDescription eventDescription, string methodName) { var method = FindMethod(methodName); if (method != null) { var view = _pythonFileNode.GetTextView(); view.Caret.MoveTo(new VisualStudio.Text.SnapshotPoint(view.TextSnapshot, method.StartIndex)); view.Caret.EnsureVisible(); return true; } return false; } public override void ValidateMethodName(EventDescription eventDescription, string methodName) { } } }
/* * Copyright (c) 2006-2008, 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.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; using OpenMetaverse.Packets; namespace OpenMetaverse { #region Enums /// <summary> /// Map layer request type /// </summary> public enum GridLayerType : uint { /// <summary>Objects and terrain are shown</summary> Objects = 0, /// <summary>Only the terrain is shown, no objects</summary> Terrain = 1, /// <summary>Overlay showing land for sale and for auction</summary> LandForSale = 2 } /// <summary> /// Type of grid item, such as telehub, event, populator location, etc. /// </summary> public enum GridItemType : uint { /// <summary>Telehub</summary> Telehub = 1, /// <summary>PG rated event</summary> PgEvent = 2, /// <summary>Mature rated event</summary> MatureEvent = 3, /// <summary>Popular location</summary> Popular = 4, /// <summary>Locations of avatar groups in a region</summary> AgentLocations = 6, /// <summary>Land for sale</summary> LandForSale = 7, /// <summary>Classified ad</summary> Classified = 8, /// <summary>Adult rated event</summary> AdultEvent = 9, /// <summary>Adult land for sale</summary> AdultLandForSale = 10 } #endregion Enums #region Structs /// <summary> /// Information about a region on the grid map /// </summary> public struct GridRegion { /// <summary>Sim X position on World Map</summary> public int X; /// <summary>Sim Y position on World Map</summary> public int Y; /// <summary>Sim Name (NOTE: In lowercase!)</summary> public string Name; /// <summary></summary> public SimAccess Access; /// <summary>Appears to always be zero (None)</summary> public RegionFlags RegionFlags; /// <summary>Sim's defined Water Height</summary> public byte WaterHeight; /// <summary></summary> public byte Agents; /// <summary>UUID of the World Map image</summary> public UUID MapImageID; /// <summary>Unique identifier for this region, a combination of the X /// and Y position</summary> public ulong RegionHandle; /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return String.Format("{0} ({1}/{2}), Handle: {3}, MapImage: {4}, Access: {5}, Flags: {6}", Name, X, Y, RegionHandle, MapImageID, Access, RegionFlags); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj is GridRegion) return Equals((GridRegion)obj); else return false; } private bool Equals(GridRegion region) { return (this.X == region.X && this.Y == region.Y); } } /// <summary> /// Visual chunk of the grid map /// </summary> public struct GridLayer { public int Bottom; public int Left; public int Top; public int Right; public UUID ImageID; public bool ContainsRegion(int x, int y) { return (x >= Left && x <= Right && y >= Bottom && y <= Top); } } #endregion Structs #region Map Item Classes /// <summary> /// Base class for Map Items /// </summary> public abstract class MapItem { /// <summary>The Global X position of the item</summary> public uint GlobalX; /// <summary>The Global Y position of the item</summary> public uint GlobalY; /// <summary>Get the Local X position of the item</summary> public uint LocalX { get { return GlobalX % 256; } } /// <summary>Get the Local Y position of the item</summary> public uint LocalY { get { return GlobalY % 256; } } /// <summary>Get the Handle of the region</summary> public ulong RegionHandle { get { return Utils.UIntsToLong((uint)(GlobalX - (GlobalX % 256)), (uint)(GlobalY - (GlobalY % 256))); } } } /// <summary> /// Represents an agent or group of agents location /// </summary> public class MapAgentLocation : MapItem { public int AvatarCount; public string Identifier; } /// <summary> /// Represents a Telehub location /// </summary> public class MapTelehub : MapItem { } /// <summary> /// Represents a non-adult parcel of land for sale /// </summary> public class MapLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents an Adult parcel of land for sale /// </summary> public class MapAdultLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents a PG Event /// </summary> public class MapPGEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents a Mature event /// </summary> public class MapMatureEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents an Adult event /// </summary> public class MapAdultEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } #endregion Grid Item Classes /// <summary> /// Manages grid-wide tasks such as the world map /// </summary> public class GridManager { #region Delegates /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<CoarseLocationUpdateEventArgs> m_CoarseLocationUpdate; /// <summary>Raises the CoarseLocationUpdate event</summary> /// <param name="e">A CoarseLocationUpdateEventArgs object containing the /// data sent by simulator</param> protected virtual void OnCoarseLocationUpdate(CoarseLocationUpdateEventArgs e) { EventHandler<CoarseLocationUpdateEventArgs> handler = m_CoarseLocationUpdate; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_CoarseLocationUpdateLock = new object(); /// <summary>Raised when the simulator sends a <see cref="CoarseLocationUpdatePacket"/> /// containing the location of agents in the simulator</summary> public event EventHandler<CoarseLocationUpdateEventArgs> CoarseLocationUpdate { add { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate += value; } } remove { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridRegionEventArgs> m_GridRegion; /// <summary>Raises the GridRegion event</summary> /// <param name="e">A GridRegionEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridRegion(GridRegionEventArgs e) { EventHandler<GridRegionEventArgs> handler = m_GridRegion; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridRegionLock = new object(); /// <summary>Raised when the simulator sends a Region Data in response to /// a Map request</summary> public event EventHandler<GridRegionEventArgs> GridRegion { add { lock (m_GridRegionLock) { m_GridRegion += value; } } remove { lock (m_GridRegionLock) { m_GridRegion -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridLayerEventArgs> m_GridLayer; /// <summary>Raises the GridLayer event</summary> /// <param name="e">A GridLayerEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridLayer(GridLayerEventArgs e) { EventHandler<GridLayerEventArgs> handler = m_GridLayer; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridLayerLock = new object(); /// <summary>Raised when the simulator sends GridLayer object containing /// a map tile coordinates and texture information</summary> public event EventHandler<GridLayerEventArgs> GridLayer { add { lock (m_GridLayerLock) { m_GridLayer += value; } } remove { lock (m_GridLayerLock) { m_GridLayer -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridItemsEventArgs> m_GridItems; /// <summary>Raises the GridItems event</summary> /// <param name="e">A GridItemEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridItems(GridItemsEventArgs e) { EventHandler<GridItemsEventArgs> handler = m_GridItems; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridItemsLock = new object(); /// <summary>Raised when the simulator sends GridItems object containing /// details on events, land sales at a specific location</summary> public event EventHandler<GridItemsEventArgs> GridItems { add { lock (m_GridItemsLock) { m_GridItems += value; } } remove { lock (m_GridItemsLock) { m_GridItems -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<RegionHandleReplyEventArgs> m_RegionHandleReply; /// <summary>Raises the RegionHandleReply event</summary> /// <param name="e">A RegionHandleReplyEventArgs object containing the /// data sent by simulator</param> protected virtual void OnRegionHandleReply(RegionHandleReplyEventArgs e) { EventHandler<RegionHandleReplyEventArgs> handler = m_RegionHandleReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_RegionHandleReplyLock = new object(); /// <summary>Raised in response to a Region lookup</summary> public event EventHandler<RegionHandleReplyEventArgs> RegionHandleReply { add { lock (m_RegionHandleReplyLock) { m_RegionHandleReply += value; } } remove { lock (m_RegionHandleReplyLock) { m_RegionHandleReply -= value; } } } #endregion Delegates /// <summary>Unknown</summary> public float SunPhase { get { return sunPhase; } } /// <summary>Current direction of the sun</summary> public Vector3 SunDirection { get { return sunDirection; } } /// <summary>Current angular velocity of the sun</summary> public Vector3 SunAngVelocity { get { return sunAngVelocity; } } /// <summary>Current world time</summary> public DateTime WorldTime { get { return WorldTime; } } /// <summary>A dictionary of all the regions, indexed by region name</summary> internal Dictionary<string, GridRegion> Regions = new Dictionary<string, GridRegion>(); /// <summary>A dictionary of all the regions, indexed by region handle</summary> internal Dictionary<ulong, GridRegion> RegionsByHandle = new Dictionary<ulong, GridRegion>(); private GridClient Client; private float sunPhase; private Vector3 sunDirection; private Vector3 sunAngVelocity; /// <summary> /// Constructor /// </summary> /// <param name="client">Instance of GridClient object to associate with this GridManager instance</param> public GridManager(GridClient client) { Client = client; //Client.Network.RegisterCallback(PacketType.MapLayerReply, MapLayerReplyHandler); Client.Network.RegisterCallback(PacketType.MapBlockReply, MapBlockReplyHandler); Client.Network.RegisterCallback(PacketType.MapItemReply, MapItemReplyHandler); Client.Network.RegisterCallback(PacketType.SimulatorViewerTimeMessage, SimulatorViewerTimeMessageHandler); Client.Network.RegisterCallback(PacketType.CoarseLocationUpdate, CoarseLocationHandler, false); Client.Network.RegisterCallback(PacketType.RegionIDAndHandleReply, RegionHandleReplyHandler); } /// <summary> /// /// </summary> /// <param name="layer"></param> public void RequestMapLayer(GridLayerType layer) { Uri url = Client.Network.CurrentSim.Caps.CapabilityURI("MapLayer"); if (url != null) { OSDMap body = new OSDMap(); body["Flags"] = OSD.FromInteger((int)layer); CapsClient request = new CapsClient(url); request.OnComplete += new CapsClient.CompleteCallback(MapLayerResponseHandler); request.BeginGetResponse(body, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } } /// <summary> /// Request a map layer /// </summary> /// <param name="regionName">The name of the region</param> /// <param name="layer">The type of layer</param> public void RequestMapRegion(string regionName, GridLayerType layer) { MapNameRequestPacket request = new MapNameRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.EstateID = 0; // Filled in on the sim request.AgentData.Godlike = false; // Filled in on the sim request.NameData.Name = Utils.StringToBytes(regionName); Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="layer"></param> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> /// <param name="returnNonExistent"></param> public void RequestMapBlocks(GridLayerType layer, ushort minX, ushort minY, ushort maxX, ushort maxY, bool returnNonExistent) { MapBlockRequestPacket request = new MapBlockRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Flags |= (uint)(returnNonExistent ? 0x10000 : 0); request.AgentData.EstateID = 0; // Filled in at the simulator request.AgentData.Godlike = false; // Filled in at the simulator request.PositionData.MinX = minX; request.PositionData.MinY = minY; request.PositionData.MaxX = maxX; request.PositionData.MaxY = maxY; Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> /// <param name="timeoutMS"></param> /// <returns></returns> public List<MapItem> MapItems(ulong regionHandle, GridItemType item, GridLayerType layer, int timeoutMS) { List<MapItem> itemList = null; AutoResetEvent itemsEvent = new AutoResetEvent(false); EventHandler<GridItemsEventArgs> callback = delegate(object sender, GridItemsEventArgs e) { if (e.Type == GridItemType.AgentLocations) { itemList = e.Items; itemsEvent.Set(); } }; GridItems += callback; RequestMapItems(regionHandle, item, layer); itemsEvent.WaitOne(timeoutMS, false); GridItems -= callback; return itemList; } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> public void RequestMapItems(ulong regionHandle, GridItemType item, GridLayerType layer) { MapItemRequestPacket request = new MapItemRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Godlike = false; // Filled in on the sim request.AgentData.EstateID = 0; // Filled in on the sim request.RequestData.ItemType = (uint)item; request.RequestData.RegionHandle = regionHandle; Client.Network.SendPacket(request); } /// <summary> /// Request data for all mainland (Linden managed) simulators /// </summary> public void RequestMainlandSims(GridLayerType layer) { RequestMapBlocks(layer, 0, 0, 65535, 65535, false); } /// <summary> /// Request the region handle for the specified region UUID /// </summary> /// <param name="regionID">UUID of the region to look up</param> public void RequestRegionHandle(UUID regionID) { RegionHandleRequestPacket request = new RegionHandleRequestPacket(); request.RequestBlock = new RegionHandleRequestPacket.RequestBlockBlock(); request.RequestBlock.RegionID = regionID; Client.Network.SendPacket(request); } /// <summary> /// Get grid region information using the region name, this function /// will block until it can find the region or gives up /// </summary> /// <param name="name">Name of sim you're looking for</param> /// <param name="layer">Layer that you are requesting</param> /// <param name="region">Will contain a GridRegion for the sim you're /// looking for if successful, otherwise an empty structure</param> /// <returns>True if the GridRegion was successfully fetched, otherwise /// false</returns> public bool GetGridRegion(string name, GridLayerType layer, out GridRegion region) { if (String.IsNullOrEmpty(name)) { Logger.Log("GetGridRegion called with a null or empty region name", Helpers.LogLevel.Error, Client); region = new GridRegion(); return false; } if (Regions.ContainsKey(name)) { // We already have this GridRegion structure region = Regions[name]; return true; } else { AutoResetEvent regionEvent = new AutoResetEvent(false); EventHandler<GridRegionEventArgs> callback = delegate(object sender, GridRegionEventArgs e) { if (e.Region.Name == name) regionEvent.Set(); }; GridRegion += callback; RequestMapRegion(name, layer); regionEvent.WaitOne(Client.Settings.MAP_REQUEST_TIMEOUT, false); GridRegion -= callback; if (Regions.ContainsKey(name)) { // The region was found after our request region = Regions[name]; return true; } else { Logger.Log("Couldn't find region " + name, Helpers.LogLevel.Warning, Client); region = new GridRegion(); return false; } } } protected void MapLayerResponseHandler(CapsClient client, OSD result, Exception error) { OSDMap body = (OSDMap)result; OSDArray layerData = (OSDArray)body["LayerData"]; if (m_GridLayer != null) { for (int i = 0; i < layerData.Count; i++) { OSDMap thisLayerData = (OSDMap)layerData[i]; GridLayer layer; layer.Bottom = thisLayerData["Bottom"].AsInteger(); layer.Left = thisLayerData["Left"].AsInteger(); layer.Top = thisLayerData["Top"].AsInteger(); layer.Right = thisLayerData["Right"].AsInteger(); layer.ImageID = thisLayerData["ImageID"].AsUUID(); OnGridLayer(new GridLayerEventArgs(layer)); } } if (body.ContainsKey("MapBlocks")) { // TODO: At one point this will become activated Logger.Log("Got MapBlocks through CAPS, please finish this function!", Helpers.LogLevel.Error, Client); } } /// <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 MapBlockReplyHandler(object sender, PacketReceivedEventArgs e) { MapBlockReplyPacket map = (MapBlockReplyPacket)e.Packet; foreach (MapBlockReplyPacket.DataBlock block in map.Data) { if (block.X != 0 && block.Y != 0) { GridRegion region; region.X = block.X; region.Y = block.Y; region.Name = Utils.BytesToString(block.Name); // RegionFlags seems to always be zero here? region.RegionFlags = (RegionFlags)block.RegionFlags; region.WaterHeight = block.WaterHeight; region.Agents = block.Agents; region.Access = (SimAccess)block.Access; region.MapImageID = block.MapImageID; region.RegionHandle = Utils.UIntsToLong((uint)(region.X * 256), (uint)(region.Y * 256)); lock (Regions) { Regions[region.Name] = region; RegionsByHandle[region.RegionHandle] = region; } if (m_GridRegion != null) { OnGridRegion(new GridRegionEventArgs(region)); } } } } /// <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 MapItemReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_GridItems != null) { MapItemReplyPacket reply = (MapItemReplyPacket)e.Packet; GridItemType type = (GridItemType)reply.RequestData.ItemType; List<MapItem> items = new List<MapItem>(); for (int i = 0; i < reply.Data.Length; i++) { string name = Utils.BytesToString(reply.Data[i].Name); switch (type) { case GridItemType.AgentLocations: MapAgentLocation location = new MapAgentLocation(); location.GlobalX = reply.Data[i].X; location.GlobalY = reply.Data[i].Y; location.Identifier = name; location.AvatarCount = reply.Data[i].Extra; items.Add(location); break; case GridItemType.Classified: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.LandForSale: MapLandForSale landsale = new MapLandForSale(); landsale.GlobalX = reply.Data[i].X; landsale.GlobalY = reply.Data[i].Y; landsale.ID = reply.Data[i].ID; landsale.Name = name; landsale.Size = reply.Data[i].Extra; landsale.Price = reply.Data[i].Extra2; items.Add(landsale); break; case GridItemType.MatureEvent: MapMatureEvent matureEvent = new MapMatureEvent(); matureEvent.GlobalX = reply.Data[i].X; matureEvent.GlobalY = reply.Data[i].Y; matureEvent.Description = name; matureEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(matureEvent); break; case GridItemType.PgEvent: MapPGEvent PGEvent = new MapPGEvent(); PGEvent.GlobalX = reply.Data[i].X; PGEvent.GlobalY = reply.Data[i].Y; PGEvent.Description = name; PGEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(PGEvent); break; case GridItemType.Popular: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.Telehub: MapTelehub teleHubItem = new MapTelehub(); teleHubItem.GlobalX = reply.Data[i].X; teleHubItem.GlobalY = reply.Data[i].Y; items.Add(teleHubItem); break; case GridItemType.AdultLandForSale: MapAdultLandForSale adultLandsale = new MapAdultLandForSale(); adultLandsale.GlobalX = reply.Data[i].X; adultLandsale.GlobalY = reply.Data[i].Y; adultLandsale.ID = reply.Data[i].ID; adultLandsale.Name = name; adultLandsale.Size = reply.Data[i].Extra; adultLandsale.Price = reply.Data[i].Extra2; items.Add(adultLandsale); break; case GridItemType.AdultEvent: MapAdultEvent adultEvent = new MapAdultEvent(); adultEvent.GlobalX = reply.Data[i].X; adultEvent.GlobalY = reply.Data[i].Y; adultEvent.Description = Utils.BytesToString(reply.Data[i].Name); adultEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(adultEvent); break; default: Logger.Log("Unknown map item type " + type, Helpers.LogLevel.Warning, Client); break; } } OnGridItems(new GridItemsEventArgs(type, items)); } } /// <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 SimulatorViewerTimeMessageHandler(object sender, PacketReceivedEventArgs e) { SimulatorViewerTimeMessagePacket time = (SimulatorViewerTimeMessagePacket)e.Packet; sunPhase = time.TimeInfo.SunPhase; sunDirection = time.TimeInfo.SunDirection; sunAngVelocity = time.TimeInfo.SunAngVelocity; // TODO: Does anyone have a use for the time stuff? } /// <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 CoarseLocationHandler(object sender, PacketReceivedEventArgs e) { CoarseLocationUpdatePacket coarse = (CoarseLocationUpdatePacket)e.Packet; // populate a dictionary from the packet, for local use Dictionary<UUID, Vector3> coarseEntries = new Dictionary<UUID, Vector3>(); for (int i = 0; i < coarse.AgentData.Length; i++) { if(coarse.Location.Length > 0) coarseEntries[coarse.AgentData[i].AgentID] = new Vector3((int)coarse.Location[i].X, (int)coarse.Location[i].Y, (int)coarse.Location[i].Z * 4); // the friend we are tracking on radar if (i == coarse.Index.Prey) e.Simulator.preyID = coarse.AgentData[i].AgentID; } // find stale entries (people who left the sim) List<UUID> removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return !coarseEntries.ContainsKey(findID); }); // anyone who was not listed in the previous update List<UUID> newEntries = new List<UUID>(); lock (e.Simulator.avatarPositions.Dictionary) { // remove stale entries foreach(UUID trackedID in removedEntries) e.Simulator.avatarPositions.Dictionary.Remove(trackedID); // add or update tracked info, and record who is new foreach (KeyValuePair<UUID, Vector3> entry in coarseEntries) { if (!e.Simulator.avatarPositions.Dictionary.ContainsKey(entry.Key)) newEntries.Add(entry.Key); e.Simulator.avatarPositions.Dictionary[entry.Key] = entry.Value; } } if (m_CoarseLocationUpdate != null) { ThreadPool.QueueUserWorkItem(delegate(object o) { OnCoarseLocationUpdate(new CoarseLocationUpdateEventArgs(e.Simulator, newEntries, removedEntries)); }); } } /// <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 RegionHandleReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_RegionHandleReply != null) { RegionIDAndHandleReplyPacket reply = (RegionIDAndHandleReplyPacket)e.Packet; OnRegionHandleReply(new RegionHandleReplyEventArgs(reply.ReplyBlock.RegionID, reply.ReplyBlock.RegionHandle)); } } } #region EventArgs classes public class CoarseLocationUpdateEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly List<UUID> m_NewEntries; private readonly List<UUID> m_RemovedEntries; public Simulator Simulator { get { return m_Simulator; } } public List<UUID> NewEntries { get { return m_NewEntries; } } public List<UUID> RemovedEntries { get { return m_RemovedEntries; } } public CoarseLocationUpdateEventArgs(Simulator simulator, List<UUID> newEntries, List<UUID> removedEntries) { this.m_Simulator = simulator; this.m_NewEntries = newEntries; this.m_RemovedEntries = removedEntries; } } public class GridRegionEventArgs : EventArgs { private readonly GridRegion m_Region; public GridRegion Region { get { return m_Region; } } public GridRegionEventArgs(GridRegion region) { this.m_Region = region; } } public class GridLayerEventArgs : EventArgs { private readonly GridLayer m_Layer; public GridLayer Layer { get { return m_Layer; } } public GridLayerEventArgs(GridLayer layer) { this.m_Layer = layer; } } public class GridItemsEventArgs : EventArgs { private readonly GridItemType m_Type; private readonly List<MapItem> m_Items; public GridItemType Type { get { return m_Type; } } public List<MapItem> Items { get { return m_Items; } } public GridItemsEventArgs(GridItemType type, List<MapItem> items) { this.m_Type = type; this.m_Items = items; } } public class RegionHandleReplyEventArgs : EventArgs { private readonly UUID m_RegionID; private readonly ulong m_RegionHandle; public UUID RegionID { get { return m_RegionID; } } public ulong RegionHandle { get { return m_RegionHandle; } } public RegionHandleReplyEventArgs(UUID regionID, ulong regionHandle) { this.m_RegionID = regionID; this.m_RegionHandle = regionHandle; } } #endregion }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; if (Input.GetMouseButtonDown (0)) { Debug.Log ("Working?"); RaycastHit hitInfo = new RaycastHit (); bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo); if (hit) { Debug.Log ("hit?"); if (hitInfo.transform.gameObject.tag == "Exit") { Debug.Log ("Why not quiting?"); Application.Quit (); } } } } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace FA.ApiClient.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [StructLayout(LayoutKind.Sequential)] public struct Double : IComparable, IFormattable, IComparable<Double>, IEquatable<Double>, IConvertible { private double _value; // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; // Note Epsilon should be a double whose hex representation is 0x1 // on little endian machines. public const double Epsilon = 4.9406564584124654E-324; public const double NegativeInfinity = (double)-1.0 / (double)(0.0); public const double PositiveInfinity = (double)1.0 / (double)(0.0); public const double NaN = (double)0.0 / (double)0.0; // 0x8000000000000000 is exactly same as -0.0. We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal static double NegativeZero = Int64BitsToDouble(unchecked((long)0x8000000000000000)); private static unsafe double Int64BitsToDouble(long value) { return *((double*)&value); } [Pure] public static unsafe bool IsInfinity(double d) { return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } [Pure] public static bool IsPositiveInfinity(double d) { //Jit will generate inlineable code with this if (d == double.PositiveInfinity) { return true; } else { return false; } } [Pure] public static bool IsNegativeInfinity(double d) { //Jit will generate inlineable code with this if (d == double.NegativeInfinity) { return true; } else { return false; } } [Pure] internal static unsafe bool IsNegative(double d) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; } [Pure] public static unsafe bool IsNaN(double d) { return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L; } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Double) { double d = (double)value; if (_value < d) return -1; if (_value > d) return 1; if (_value == d) return 0; // At least one of the values is NaN. if (IsNaN(_value)) return (IsNaN(d) ? 0 : -1); else return 1; } throw new ArgumentException(SR.Arg_MustBeDouble); } public int CompareTo(Double value) { if (_value < value) return -1; if (_value > value) return 1; if (_value == value) return 0; // At least one of the values is NaN. if (IsNaN(_value)) return (IsNaN(value) ? 0 : -1); else return 1; } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals(Object obj) { if (!(obj is Double)) { return false; } double temp = ((Double)obj)._value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == _value) { return true; } return IsNaN(temp) && IsNaN(_value); } [NonVersionable] public static bool operator ==(Double left, Double right) { return left == right; } [NonVersionable] public static bool operator !=(Double left, Double right) { return left != right; } [NonVersionable] public static bool operator <(Double left, Double right) { return left < right; } [NonVersionable] public static bool operator >(Double left, Double right) { return left > right; } [NonVersionable] public static bool operator <=(Double left, Double right) { return left <= right; } [NonVersionable] public static bool operator >=(Double left, Double right) { return left >= right; } public bool Equals(Double obj) { if (obj == _value) { return true; } return IsNaN(obj) && IsNaN(_value); } //The hashcode for a double is the absolute value of the integer representation //of that double. // public unsafe override int GetHashCode() { double d = _value; if (d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(_value, null, null); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(_value, format, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(_value, null, provider); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatDouble(_value, format, provider); } public static double Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, null); } public static double Parse(String s, NumberStyles style) { Decimal.ValidateParseStyleFloatingPoint(style); return Parse(s, style, null); } public static double Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static double Parse(String s, NumberStyles style, IFormatProvider provider) { Decimal.ValidateParseStyleFloatingPoint(style); return FormatProvider.ParseDouble(s, style, provider); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static bool TryParse(String s, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) { Decimal.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } bool success = FormatProvider.TryParseDouble(s, style, provider, out result); if (!success) { String sTrim = s.Trim(); if (FormatProvider.IsPositiveInfinity(sTrim, provider)) { result = PositiveInfinity; } else if (FormatProvider.IsNegativeInfinity(sTrim, provider)) { result = NegativeInfinity; } else if (FormatProvider.IsNaNSymbol(sTrim, provider)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } double IConvertible.ToDouble(IFormatProvider provider) { return _value; } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLoption = Interop.Http.CURLoption; using CurlProtocols = Interop.Http.CurlProtocols; using CURLProxyType = Interop.Http.curl_proxytype; using SafeCurlHandle = Interop.Http.SafeCurlHandle; using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle; using SafeCallbackHandle = Interop.Http.SafeCallbackHandle; using SeekCallback = Interop.Http.SeekCallback; using ReadWriteCallback = Interop.Http.ReadWriteCallback; using ReadWriteFunction = Interop.Http.ReadWriteFunction; using SslCtxCallback = Interop.Http.SslCtxCallback; using DebugCallback = Interop.Http.DebugCallback; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { /// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary> private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage> { /// <summary>Maximum content length where we'll use COPYPOSTFIELDS to let libcurl dup the content.</summary> private const int InMemoryPostContentLimit = 32 * 1024; // arbitrary limit; could be tweaked in the future based on experimentation /// <summary>Debugging flag used to enable CURLOPT_VERBOSE to dump to stderr when not redirecting it to the event source.</summary> private static readonly bool s_curlDebugLogging = Environment.GetEnvironmentVariable("CURLHANDLER_DEBUG_VERBOSE") == "true"; internal readonly CurlHandler _handler; internal readonly MultiAgent _associatedMultiAgent; internal readonly HttpRequestMessage _requestMessage; internal readonly CurlResponseMessage _responseMessage; internal readonly CancellationToken _cancellationToken; internal Stream _requestContentStream; internal long? _requestContentStreamStartingPosition; internal bool _inMemoryPostContent; internal SafeCurlHandle _easyHandle; private SafeCurlSListHandle _requestHeaders; internal SendTransferState _sendTransferState; internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference; private SafeCallbackHandle _callbackHandle; public EasyRequest(CurlHandler handler, MultiAgent agent, HttpRequestMessage requestMessage, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(handler != null, $"Expected non-null {nameof(handler)}"); Debug.Assert(agent != null, $"Expected non-null {nameof(agent)}"); Debug.Assert(requestMessage != null, $"Expected non-null {nameof(requestMessage)}"); _handler = handler; _associatedMultiAgent = agent; _requestMessage = requestMessage; _cancellationToken = cancellationToken; _responseMessage = new CurlResponseMessage(this); } /// <summary> /// Initialize the underlying libcurl support for this EasyRequest. /// This is separated out of the constructor so that we can take into account /// any additional configuration needed based on the request message /// after the EasyRequest is configured and so that error handling /// can be better handled in the caller. /// </summary> internal void InitializeCurl() { // Create the underlying easy handle SafeCurlHandle easyHandle = Interop.Http.EasyCreate(); if (easyHandle.IsInvalid) { throw new OutOfMemoryException(); } _easyHandle = easyHandle; EventSourceTrace("Configuring request."); // Before setting any other options, turn on curl's debug tracing // if desired. CURLOPT_VERBOSE may also be set subsequently if // EventSource tracing is enabled. if (s_curlDebugLogging) { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); } // Before actually configuring the handle based on the state of the request, // do any necessary cleanup of the request object. SanitizeRequestMessage(); // Configure the handle SetUrl(); SetNetworkingOptions(); SetMultithreading(); SetTimeouts(); SetRedirection(); SetVerb(); SetVersion(); SetDecompressionOptions(); SetProxyOptions(_requestMessage.RequestUri); SetCredentialsOptions(_handler._useDefaultCredentials ? GetDefaultCredentialAndAuth() : _handler.GetCredentials(_requestMessage.RequestUri)); SetCookieOption(_requestMessage.RequestUri); SetRequestHeaders(); SetSslOptions(); EventSourceTrace("Done configuring request."); } public void EnsureResponseMessagePublished() { // If the response message hasn't been published yet, do any final processing of it before it is. if (!Task.IsCompleted) { EventSourceTrace("Publishing response message"); // On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length // headers are removed from the response. Do the same thing here. DecompressionMethods dm = _handler.AutomaticDecompression; if (dm != DecompressionMethods.None) { HttpContentHeaders contentHeaders = _responseMessage.Content.Headers; IEnumerable<string> encodings; if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings)) { foreach (string encoding in encodings) { if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) || ((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase))) { contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding); contentHeaders.Remove(HttpKnownHeaderNames.ContentLength); break; } } } } } // Now ensure it's published. bool completedTask = TrySetResult(_responseMessage); Debug.Assert(completedTask || Task.IsCompletedSuccessfully, "If the task was already completed, it should have been completed successfully; " + "we shouldn't be completing as successful after already completing as failed."); // If we successfully transitioned it to be completed, we also handed off lifetime ownership // of the response to the owner of the task. Transition our reference on the EasyRequest // to be weak instead of strong, so that we don't forcibly keep it alive. if (completedTask) { Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper"); _selfStrongToWeakReference.MakeWeak(); } } public void CleanupAndFailRequest(Exception error) { try { Cleanup(); } catch (Exception exc) { // This would only happen in an aggregious case, such as a Stream failing to seek when // it claims to be able to, but in case something goes very wrong, make sure we don't // lose the exception information. error = new AggregateException(error, exc); } finally { FailRequest(error); } } public void FailRequest(Exception error) { Debug.Assert(error != null, "Expected non-null exception"); EventSourceTrace("Failing request: {0}", error); var oce = error as OperationCanceledException; if (oce != null) { TrySetCanceled(oce.CancellationToken); } else { if (error is InvalidOperationException || error is IOException || error is CurlException || error == null) { error = CreateHttpRequestException(error); } TrySetException(error); } // There's not much we can reasonably assert here about the result of TrySet*. // It's possible that the task wasn't yet completed (e.g. a failure while initiating the request), // it's possible that the task was already completed as success (e.g. a failure sending back the response), // and it's possible that the task was already completed as failure (e.g. we handled the exception and // faulted the task, but then tried to fault it again while finishing processing in the main loop). // Make sure the exception is available on the response stream so that it's propagated // from any attempts to read from the stream. _responseMessage.ResponseStream.SignalComplete(error); } public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up { // Don't dispose of the ResponseMessage.ResponseStream as it may still be in use // by code reading data stored in the stream. Also don't dispose of the request content // stream; that'll be handled by the disposal of the request content by the HttpClient, // and doing it here prevents reuse by an intermediate handler sitting between the client // and this handler. // However, if we got an original position for the request stream, we seek back to that position, // for the corner case where the stream does get reused before it's disposed by the HttpClient // (if the same request object is used multiple times from an intermediate handler, we'll be using // ReadAsStreamAsync, which on the same request object will return the same stream object, which // we've already advanced). if (_requestContentStream != null && _requestContentStream.CanSeek) { Debug.Assert(_requestContentStreamStartingPosition.HasValue, "The stream is seekable, but we don't have a starting position?"); _requestContentStream.Position = _requestContentStreamStartingPosition.GetValueOrDefault(); } // Dispose of the underlying easy handle. We're no longer processing it. _easyHandle?.Dispose(); // Dispose of the request headers if we had any. We had to keep this handle // alive as long as the easy handle was using it. We didn't need to do any // ref counting on the safe handle, though, as the only processing happens // in Process, which ensures the handle will be rooted while libcurl is // doing any processing that assumes it's valid. _requestHeaders?.Dispose(); // Dispose native callback resources _callbackHandle?.Dispose(); // Release any send transfer state, which will return its buffer to the pool _sendTransferState?.Dispose(); } private void SanitizeRequestMessage() { // Make sure Transfer-Encoding and Content-Length make sense together. if (_requestMessage.Content != null) { SetChunkedModeForSend(_requestMessage); } } private void SetUrl() { Uri requestUri = _requestMessage.RequestUri; long scopeId; if (IsLinkLocal(requestUri, out scopeId)) { // Uri.AbsoluteUri doesn't include the ScopeId/ZoneID, so if it is link-local, // we separately pass the scope to libcurl. EventSourceTrace("ScopeId: {0}", scopeId); SetCurlOption(CURLoption.CURLOPT_ADDRESS_SCOPE, scopeId); } EventSourceTrace("Url: {0}", requestUri); string idnHost = requestUri.IdnHost; string url = requestUri.Host == idnHost ? requestUri.AbsoluteUri : new UriBuilder(requestUri) { Host = idnHost }.Uri.AbsoluteUri; SetCurlOption(CURLoption.CURLOPT_URL, url); SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS)); } private static bool IsLinkLocal(Uri url, out long scopeId) { IPAddress ip; if (IPAddress.TryParse(url.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal) { scopeId = ip.ScopeId; return true; } scopeId = 0; return false; } private void SetNetworkingOptions() { // Disable the TCP Nagle algorithm. It's disabled by default starting with libcurl 7.50.2, // and when enabled has a measurably negative impact on latency in key scenarios // (e.g. POST'ing small-ish data). SetCurlOption(CURLoption.CURLOPT_TCP_NODELAY, 1L); } private void SetMultithreading() { SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L); } private void SetTimeouts() { // Set timeout limit on the connect phase. SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, int.MaxValue); // Override the default DNS cache timeout. libcurl defaults to a 1 minute // timeout, but we extend that to match the Windows timeout of 10 minutes. const int DnsCacheTimeoutSeconds = 10 * 60; SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds); } private void SetRedirection() { if (!_handler._automaticRedirection) { return; } SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L); CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ? CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols); SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections); EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections); } /// <summary> /// When a Location header is received along with a 3xx status code, it's an indication /// that we're likely to redirect. Prepare the easy handle in case we do. /// </summary> internal void SetPossibleRedirectForLocationHeader(string location) { // Reset cookies in case we redirect. Below we'll set new cookies for the // new location if we have any. if (_handler._useCookies) { SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero); } // Parse the location string into a relative or absolute Uri, then combine that // with the current request Uri to get the new location. var updatedCredentials = default(KeyValuePair<NetworkCredential, CURLAUTH>); Uri newUri; if (Uri.TryCreate(_requestMessage.RequestUri, location.Trim(), out newUri)) { // Just as with WinHttpHandler, for security reasons, we drop the server credential if it is // anything other than a CredentialCache. We allow credentials in a CredentialCache since they // are specifically tied to URIs. updatedCredentials = _handler._useDefaultCredentials ? GetDefaultCredentialAndAuth() : GetCredentials(newUri, _handler.Credentials as CredentialCache, s_orderedAuthTypes); // Reset proxy - it is possible that the proxy has different credentials for the new URI SetProxyOptions(newUri); // Set up new cookies if (_handler._useCookies) { SetCookieOption(newUri); } } // Set up the new credentials, either for the new Uri if we were able to get it, // or to empty creds if we couldn't. SetCredentialsOptions(updatedCredentials); // Set the headers again. This is a workaround for libcurl's limitation in handling // headers with empty values. SetRequestHeaders(); } private void SetContentLength(CURLoption lengthOption) { Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE); if (_requestMessage.Content == null) { // Tell libcurl there's no data to be sent. SetCurlOption(lengthOption, 0L); return; } long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength; if (contentLengthOpt != null) { long contentLength = contentLengthOpt.GetValueOrDefault(); if (contentLength <= int.MaxValue) { // Tell libcurl how much data we expect to send. SetCurlOption(lengthOption, contentLength); } else { // Similarly, tell libcurl how much data we expect to send. However, // as the amount is larger than a 32-bit value, switch to the "_LARGE" // equivalent libcurl options. SetCurlOption( lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE, contentLength); } EventSourceTrace("Set content length: {0}", contentLength); return; } // There is content but we couldn't determine its size. Don't set anything. } private void SetVerb() { EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method); if (_requestMessage.Method == HttpMethod.Put) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); SetContentLength(CURLoption.CURLOPT_INFILESIZE); } else if (_requestMessage.Method == HttpMethod.Head) { SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else if (_requestMessage.Method == HttpMethod.Post) { SetCurlOption(CURLoption.CURLOPT_POST, 1L); // Set the content length if we have one available. We must set POSTFIELDSIZE before setting // COPYPOSTFIELDS, as the setting of COPYPOSTFIELDS uses the size to know how much data to read // out; if POSTFIELDSIZE is not done before, COPYPOSTFIELDS will look for a null terminator, and // we don't necessarily have one. SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE); // For most content types and most HTTP methods, we use a callback that lets libcurl // get data from us if/when it wants it. However, as an optimization, for POSTs that // use content already known to be entirely in memory, we hand that data off to libcurl // ahead of time. This not only saves on costs associated with all of the async transfer // between the content and libcurl, it also lets libcurl do larger writes that can, for // example, enable fewer packets to be sent on the wire. var inMemContent = _requestMessage.Content as ByteArrayContent; ArraySegment<byte> contentSegment; if (inMemContent != null && inMemContent.TryGetBuffer(out contentSegment) && contentSegment.Count <= InMemoryPostContentLimit) // skip if we'd be forcing libcurl to allocate/copy a large buffer { // Only pre-provide the content if the content still has its ContentLength // and if that length matches the segment. If it doesn't, something has been overridden, // and we should rely on reading from the content stream to get the data. long? contentLength = inMemContent.Headers.ContentLength; if (contentLength.HasValue && contentLength.GetValueOrDefault() == contentSegment.Count) { _inMemoryPostContent = true; // Debug double-check array segment; this should all have been validated by the ByteArrayContent Debug.Assert(contentSegment.Array != null, "Expected non-null byte content array"); Debug.Assert(contentSegment.Count >= 0, $"Expected non-negative byte content count {contentSegment.Count}"); Debug.Assert(contentSegment.Offset >= 0, $"Expected non-negative byte content offset {contentSegment.Offset}"); Debug.Assert(contentSegment.Array.Length - contentSegment.Offset >= contentSegment.Count, $"Expected offset {contentSegment.Offset} + count {contentSegment.Count} to be within array length {contentSegment.Array.Length}"); // Hand the data off to libcurl with COPYPOSTFIELDS for it to copy out the data. (The alternative // is to use POSTFIELDS, which would mean we'd need to pin the array in the ByteArrayContent for the // duration of the request. Often with a ByteArrayContent, the data will be small and the copy cheap.) unsafe { fixed (byte* inMemContentPtr = contentSegment.Array) { SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, new IntPtr(inMemContentPtr + contentSegment.Offset)); EventSourceTrace("Set post fields rather than using send content callback"); } } } } } else if (_requestMessage.Method == HttpMethod.Trace) { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); if (_requestMessage.Content != null) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); SetContentLength(CURLoption.CURLOPT_INFILESIZE); } } } private void SetVersion() { Version v = _requestMessage.Version; if (v != null) { // Try to use the requested version, if a known version was explicitly requested. // If an unknown version was requested, we simply use libcurl's default. var curlVersion = (v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 : (v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 : (v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 : Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE; if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE) { // Ask libcurl to use the specified version if possible. CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion); if (c == CURLcode.CURLE_OK) { // Success. The requested version will be used. EventSourceTrace("HTTP version: {0}", v); } else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL) { // The requested version is unsupported. Fall back to using the default version chosen by libcurl. EventSourceTrace("Unsupported protocol: {0}", v); } else { // Some other error. Fail. ThrowIfCURLEError(c); } } } } private void SetDecompressionOptions() { if (!_handler.SupportsAutomaticDecompression) { return; } DecompressionMethods autoDecompression = _handler.AutomaticDecompression; bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0; bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0; if (gzip || deflate) { string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate : gzip ? EncodingNameGzip : EncodingNameDeflate; SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding); EventSourceTrace<string>("Encoding: {0}", encoding); } } internal void SetProxyOptions(Uri requestUri) { if (!_handler._useProxy) { // Explicitly disable the use of a proxy. This will prevent libcurl from using // any proxy, including ones set via environment variable. SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("UseProxy false, disabling proxy"); return; } if (_handler.Proxy == null) { // UseProxy was true, but Proxy was null. Let libcurl do its default handling, // which includes checking the http_proxy environment variable. EventSourceTrace("UseProxy true, Proxy null, using default proxy"); // Since that proxy set in an environment variable might require a username and password, // use the default proxy credentials if there are any. Currently only NetworkCredentials // are used, as we can't query by the proxy Uri, since we don't know it. SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential); return; } // Custom proxy specified. Uri proxyUri; try { // Should we bypass a proxy for this URI? if (_handler.Proxy.IsBypassed(requestUri)) { SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy"); return; } // Get the proxy Uri for this request. proxyUri = _handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { EventSourceTrace("GetProxy returned null, using default."); return; } } catch (PlatformNotSupportedException) { // WebRequest.DefaultWebProxy throws PlatformNotSupportedException, // in which case we should use the default rather than the custom proxy. EventSourceTrace("PlatformNotSupportedException from proxy, using default"); return; } // Configure libcurl with the gathered proxy information // uri.AbsoluteUri/ToString() omit IPv6 scope IDs. SerializationInfoString ensures these details // are included, but does not properly handle international hosts. As a workaround we check whether // the host is a link-local IP address, and based on that either return the SerializationInfoString // or the AbsoluteUri. (When setting the request Uri itself, we instead use CURLOPT_ADDRESS_SCOPE to // set the scope id and the url separately, avoiding these issues and supporting versions of libcurl // prior to v7.37 that don't support parsing scope IDs out of the url's host. As similar feature // doesn't exist for proxies.) IPAddress ip; string proxyUrl = IPAddress.TryParse(proxyUri.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal ? proxyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped) : proxyUri.AbsoluteUri; EventSourceTrace<string>("Proxy: {0}", proxyUrl); SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP); SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUrl); SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials( proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes); SetProxyCredentials(credentialScheme.Key); } private void SetProxyCredentials(NetworkCredential credentials) { if (credentials == CredentialCache.DefaultCredentials) { EventSourceTrace("DefaultCredentials set for proxy. Skipping."); } else if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } // Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode // them in order to allow, for example, a colon in the username. string credentialText = string.IsNullOrEmpty(credentials.Domain) ? WebUtility.UrlEncode(credentials.UserName) + ":" + WebUtility.UrlEncode(credentials.Password) : string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain)); EventSourceTrace("Proxy credentials set."); SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair) { if (credentialSchemePair.Key == null) { EventSourceTrace("Credentials cleared."); SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero); SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero); return; } NetworkCredential credentials = credentialSchemePair.Key; CURLAUTH authScheme = credentialSchemePair.Value; string userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : credentials.Domain + "\\" + credentials.UserName; SetCurlOption(CURLoption.CURLOPT_USERNAME, userName); SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme); if (credentials.Password != null) { SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password); } EventSourceTrace("Credentials set."); } private static KeyValuePair<NetworkCredential, CURLAUTH> GetDefaultCredentialAndAuth() => new KeyValuePair<NetworkCredential, CURLAUTH>(CredentialCache.DefaultNetworkCredentials, CURLAUTH.Negotiate); internal void SetCookieOption(Uri uri) { if (!_handler._useCookies) { return; } string cookieValues = _handler.CookieContainer.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookieValues)) { SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues); EventSourceTrace<string>("Cookies: {0}", cookieValues); } } internal void SetRequestHeaders() { var slist = new SafeCurlSListHandle(); bool suppressContentType; if (_requestMessage.Content != null) { // Add content request headers AddRequestHeaders(_requestMessage.Content.Headers, slist); suppressContentType = _requestMessage.Content.Headers.ContentType == null; } else { suppressContentType = true; } if (suppressContentType) { // Remove the Content-Type header libcurl adds by default. ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType)); } // Add request headers AddRequestHeaders(_requestMessage.Headers, slist); // Since libcurl always adds a Transfer-Encoding header, we need to explicitly block // it if caller specifically does not want to set the header if (_requestMessage.Headers.TransferEncodingChunked.HasValue && !_requestMessage.Headers.TransferEncodingChunked.Value) { ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding)); } // Since libcurl adds an Expect header if it sees enough post data, we need to explicitly block // it unless the caller has explicitly opted-in to it. if (!_requestMessage.Headers.ExpectContinue.GetValueOrDefault()) { ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoExpect)); } if (!slist.IsInvalid) { SafeCurlSListHandle prevList = _requestHeaders; _requestHeaders = slist; SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist); prevList?.Dispose(); } else { slist.Dispose(); } } private void SetSslOptions() { // SSL Options should be set regardless of the type of the original request, // in case an http->https redirection occurs. // // While this does slow down the theoretical best path of the request the code // to decide that we need to register the callback is more complicated than, and // potentially more expensive than, just always setting the callback. SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions); } internal bool ServerCertificateValidationCallbackAcceptsAll => ReferenceEquals( _handler.ServerCertificateCustomValidationCallback, HttpClientHandler.DangerousAcceptAnyServerCertificateValidator); internal void SetCurlCallbacks( IntPtr easyGCHandle, ReadWriteCallback receiveHeadersCallback, ReadWriteCallback sendCallback, SeekCallback seekCallback, ReadWriteCallback receiveBodyCallback, DebugCallback debugCallback) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } // Add callback for processing headers Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Header, receiveHeadersCallback, easyGCHandle, ref _callbackHandle); ThrowOOMIfInvalid(_callbackHandle); // If we're sending data as part of the request and it wasn't already added as // in-memory data, add callbacks for sending request data. if (!_inMemoryPostContent && _requestMessage.Content != null) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Read, sendCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); Interop.Http.RegisterSeekCallback( _easyHandle, seekCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); } // If we're expecting any data in response, add a callback for receiving body data if (_requestMessage.Method != HttpMethod.Head) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Write, receiveBodyCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); } if (NetEventSource.IsEnabled) { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); CURLcode curlResult = Interop.Http.RegisterDebugCallback( _easyHandle, debugCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); if (curlResult != CURLcode.CURLE_OK) { EventSourceTrace("Failed to register debug callback."); } } } internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } return Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle); } private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle) { foreach (KeyValuePair<string, IEnumerable<string>> header in headers) { if (string.Equals(header.Key, HttpKnownHeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase)) { // avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE continue; } string headerKeyAndValue; string[] values = header.Value as string[]; Debug.Assert(values != null, "Implementation detail, but expected Value to be a string[]"); if (values != null && values.Length < 2) { // 0 or 1 values headerKeyAndValue = values.Length == 0 || string.IsNullOrEmpty(values[0]) ? header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent header.Key + ": " + values[0]; } else { // Either Values wasn't a string[], or it had 2 or more items. Both are handled by GetHeaderString. string headerValue = headers.GetHeaderString(header.Key); headerKeyAndValue = string.IsNullOrEmpty(headerValue) ? header.Key + ";" : // semicolon needed by libcurl; see above header.Key + ": " + headerValue; } ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue)); } } internal void SetCurlOption(CURLoption option, string value) { ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, long value) { ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, IntPtr value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, SafeHandle value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } private static void ThrowOOMIfFalse(bool appendResult) { if (!appendResult) { ThrowOOM(); } } private static void ThrowOOMIfInvalid(SafeHandle handle) { if (handle.IsInvalid) { ThrowOOM(); } } private static void ThrowOOM() { throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false)); } internal sealed class SendTransferState : IDisposable { internal byte[] Buffer { get; private set; } internal int Offset { get; set; } internal int Count { get; set; } internal Task<int> Task { get; private set; } public SendTransferState(int bufferLength) { Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}"); Buffer = ArrayPool<byte>.Shared.Rent(bufferLength); } public void Dispose() { byte[] b = Buffer; if (b != null) { Buffer = null; ArrayPool<byte>.Shared.Return(b); } } public void SetTaskOffsetCount(Task<int> task, int offset, int count) { Debug.Assert(offset >= 0, "Offset should never be negative"); Debug.Assert(count >= 0, "Count should never be negative"); Debug.Assert(offset <= count, "Offset should never be greater than count"); Task = task; Offset = offset; Count = count; } } internal void StoreLastEffectiveUri() { IntPtr urlCharPtr; // do not free; will point to libcurl private memory CURLcode urlResult = Interop.Http.EasyGetInfoPointer(_easyHandle, Interop.Http.CURLINFO.CURLINFO_EFFECTIVE_URL, out urlCharPtr); if (urlResult == CURLcode.CURLE_OK && urlCharPtr != IntPtr.Zero) { string url = Marshal.PtrToStringAnsi(urlCharPtr); if (url != _requestMessage.RequestUri.OriginalString) { Uri finalUri; if (Uri.TryCreate(url, UriKind.Absolute, out finalUri)) { _requestMessage.RequestUri = finalUri; } } return; } Debug.Fail("Expected to be able to get the last effective Uri from libcurl"); } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName); } } } }
namespace IdentityBase.EntityFramework.Stores { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityBase.EntityFramework.DbContexts; using IdentityBase.EntityFramework.Mappers; using IdentityBase.Models; using IdentityBase.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using ServiceBase; using ServiceBase.Collections; using ServiceBase.Extensions; using UserAccountEntity = Entities.UserAccount; // TODO: make use of value type System.Security.Claims.ClaimValueTypes // while create UserClaim // http://www.npgsql.org/doc/faq.html public class UserAccountStore : IUserAccountStore { private readonly UserAccountDbContext _context; private readonly ILogger<UserAccountStore> _logger; public UserAccountStore( UserAccountDbContext context, ILogger<UserAccountStore> logger) { this._context = context ?? throw new ArgumentNullException(nameof(context)); this._logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task DeleteByIdAsync(Guid id) { UserAccountEntity entity = this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefault(x => x.Id == id); if (entity != null) { this._context.Remove(entity); await this._context.SaveChangesAsync(); this._logger.LogDebug( "{id} found and deleted in database: {userAccountFound}", id, true); } else { this._logger.LogDebug( "{id} found in database: {userAccountFound}", id, false); } } public async Task<UserAccount> LoadByEmailAsync(string email) { UserAccountEntity entity = await this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefaultAsync(x => x.Email .Equals(email, StringComparison.OrdinalIgnoreCase)); UserAccount model = entity?.ToModel(); this._logger.LogDebug( "{email} found in database: {userAccountFound}", email, model != null); return model; } /*public async Task<UserAccount> LoadByEmailWithExternalAsync( string email) { UserAccountEntity entity = await this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefaultAsync(x => x.Email .Equals(email, StringComparison.OrdinalIgnoreCase) || x.Accounts.Any(c => c.Email .Equals(email, StringComparison.OrdinalIgnoreCase))); UserAccount model = entity?.ToModel(); this._logger.LogDebug( "{email} found in database: {userAccountFound}", email, model != null); return model; }*/ public async Task<UserAccount> LoadByExternalProviderAsync( string provider, string subject) { UserAccountEntity entity = await this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefaultAsync(x => x.Accounts.Any(c => c.Provider.Equals( provider, StringComparison.OrdinalIgnoreCase)) && x.Accounts.Any(c => c.Subject.Equals( subject, StringComparison.OrdinalIgnoreCase))); UserAccount model = entity?.ToModel(); this._logger.LogDebug( "{provider}, {subject} found in database: {userAccountFound}", provider, subject, model != null); return model; } public async Task<UserAccount> LoadByIdAsync(Guid id) { UserAccountEntity entity = await this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefaultAsync(x => x.Id == id); UserAccount model = entity?.ToModel(); this._logger.LogDebug( "{id} found in database: {userAccountFound}", id, model != null); return model; } public async Task<UserAccount> LoadByVerificationKeyAsync(string key) { UserAccountEntity entity = await this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .FirstOrDefaultAsync(x => x.VerificationKey == key); UserAccount model = entity?.ToModel(); this._logger.LogDebug( "{key} found in database: {userAccountFound}", key, model != null); return model; } public async Task<UserAccount> WriteAsync(UserAccount userAccount) { if (userAccount == null) { throw new ArgumentNullException(nameof(userAccount)); } UserAccountEntity entity = this._context.UserAccounts .Include(x => x.Accounts) .Include(x => x.Claims) .SingleOrDefault(x => x.Id == userAccount.Id); if (entity == null) { this._logger.LogDebug( "{userAccountId} not found in database", userAccount.Id); entity = this._context.UserAccounts .Add(userAccount.ToEntity()).Entity; } else { this._logger.LogDebug( "{userAccountId} found in database", userAccount.Id); // Update parent UserAccountEntity entityUpdated = userAccount.ToEntity(); this._context.Entry(entity) .CurrentValues.SetValues(entityUpdated); this.UpdateExternalAccounts(entity, entityUpdated); this.UpdateUserAccountClaims(entity, entityUpdated); } await this._context.SaveChangesAsync(); return entity.ToModel(); } private void UpdateExternalAccounts( UserAccountEntity entity, UserAccountEntity entityUpdated) { var (removed, added, updated) = entity.Accounts.Diff(entityUpdated.Accounts); foreach (var item in removed) { this._context.ExternalAccounts.Remove(item); entity.Accounts.Remove(item); } foreach (var item in added) { this._context.ExternalAccounts.Add(item); entity.Accounts.Add(item); } foreach (var item in updated) { this._context.Entry( entity.Accounts.FirstOrDefault(c => c.Equals(item)) ).CurrentValues.SetValues(item); } } private void UpdateUserAccountClaims( UserAccountEntity entity, UserAccountEntity entityUpdated) { var (removed, added, updated) = entity.Claims.Diff(entityUpdated.Claims); foreach (var item in removed) { this._context.UserAccountClaims.Remove(item); entity.Claims.Remove(item); } foreach (var item in added) { this._context.UserAccountClaims.Add(item); entity.Claims.Add(item); } foreach (var item in updated) { this._context.Entry( entity.Claims.FirstOrDefault(c => c.Equals(item)) ).CurrentValues.SetValues(item); } } //public Task<ExternalAccount> WriteExternalAccountAsync( // ExternalAccount externalAccount) //{ // var userAccountId = externalAccount.UserAccount != null ? // externalAccount.UserAccount.Id : externalAccount.UserAccountId; // var userAccountEntity = this._context.UserAccounts // .SingleOrDefault(x => x.Id == userAccountId); // // if (userAccountEntity == null) // { // this._logger.LogError( // "{existingUserAccountId} not found in database", // // userAccountId); // return null; // } // // var externalAccountEntity = this._context.ExternalAccounts // .SingleOrDefault(x => // x.Provider == externalAccount.Provider && // x.Subject == externalAccount.Subject); // // if (externalAccountEntity == null) // { // this._logger.LogDebug("{0} {1} not found in database", // externalAccount.Provider, externalAccount.Subject); // // externalAccountEntity = externalAccount.ToEntity(); // this._context.ExternalAccounts.Add(externalAccountEntity); // } // else // { // this._logger.LogDebug("{0} {1} found in database", // externalAccountEntity.Provider, // externalAccountEntity.Subject); // // externalAccount.UpdateEntity(externalAccountEntity); // } // // try // { // this._context.SaveChanges(); // return Task.FromResult(externalAccountEntity.ToModel()); // } // catch (Exception ex) // { // this._logger.LogError(0, ex, "Exception storing external account"); // } // // return Task.FromResult<ExternalAccount>(null); //} public async Task<PagedList<UserAccount>> LoadInvitedUserAccountsAsync( int take, int skip = 0, Guid? invitedBy = null) { IQueryable<UserAccountEntity> baseQuery = this._context .UserAccounts .Where(c => c.CreationKind == (int)CreationKind.Invitation); if (invitedBy.HasValue) { baseQuery = baseQuery.Where(c => c.CreatedBy == invitedBy); } PagedList<UserAccount> result = new PagedList<UserAccount> { Skip = skip, Take = take, Total = baseQuery.Count(), Items = await baseQuery .Include(x => x.Accounts) .Include(x => x.Claims) .OrderByDescending(c => c.CreatedAt) .Skip(skip) .Take(take) .Select(s => s.ToModel()).ToArrayAsync(), Sort = new List<SortInfo> { new SortInfo("CreatedAt".Camelize(), SortDirection.Descending) } }; //_logger.LogDebug("{email} found in database: {userAccountFound}", // email, // model != null); return result; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto_defs/messages/Wallet.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace VirtualWallet.Proto.Messages { /// <summary>Holder for reflection information generated from proto_defs/messages/Wallet.proto</summary> public static partial class WalletReflection { #region Descriptor /// <summary>File descriptor for proto_defs/messages/Wallet.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static WalletReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBwcm90b19kZWZzL21lc3NhZ2VzL1dhbGxldC5wcm90bxIcVmlydHVhbFdh", "bGxldC5Qcm90by5NZXNzYWdlcxogcHJvdG9fZGVmcy9tZXNzYWdlcy9QZXJz", "b24ucHJvdG8i5gEKBldhbGxldBIPCgdiYWxhbmNlGAEgASgEEj0KBHR5cGUY", "AiABKA4yLy5WaXJ0dWFsV2FsbGV0LlByb3RvLk1lc3NhZ2VzLldhbGxldC5X", "YWxsZXRUeXBlEjQKBnBlcnNvbhgDIAEoCzIkLlZpcnR1YWxXYWxsZXQuUHJv", "dG8uTWVzc2FnZXMuUGVyc29uEhcKD3N1YnNjcmliZXJfY29kZRgEIAEoCSI9", "CgpXYWxsZXRUeXBlEgwKCENVU1RPTUVSEAASCQoFU1RPUkUQARIKCgZERUFM", "RVIQAhIKCgZCUk9LRVIQA2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::VirtualWallet.Proto.Messages.PersonReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Messages.Wallet), global::VirtualWallet.Proto.Messages.Wallet.Parser, new[]{ "Balance", "Type", "Person", "SubscriberCode" }, null, new[]{ typeof(global::VirtualWallet.Proto.Messages.Wallet.Types.WalletType) }, null) })); } #endregion } #region Messages public sealed partial class Wallet : pb::IMessage<Wallet> { private static readonly pb::MessageParser<Wallet> _parser = new pb::MessageParser<Wallet>(() => new Wallet()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Wallet> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::VirtualWallet.Proto.Messages.WalletReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Wallet() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Wallet(Wallet other) : this() { balance_ = other.balance_; type_ = other.type_; Person = other.person_ != null ? other.Person.Clone() : null; subscriberCode_ = other.subscriberCode_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Wallet Clone() { return new Wallet(this); } /// <summary>Field number for the "balance" field.</summary> public const int BalanceFieldNumber = 1; private ulong balance_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Balance { get { return balance_; } set { balance_ = value; } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private global::VirtualWallet.Proto.Messages.Wallet.Types.WalletType type_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::VirtualWallet.Proto.Messages.Wallet.Types.WalletType Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "person" field.</summary> public const int PersonFieldNumber = 3; private global::VirtualWallet.Proto.Messages.Person person_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::VirtualWallet.Proto.Messages.Person Person { get { return person_; } set { person_ = value; } } /// <summary>Field number for the "subscriber_code" field.</summary> public const int SubscriberCodeFieldNumber = 4; private string subscriberCode_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SubscriberCode { get { return subscriberCode_; } set { subscriberCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Wallet); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Wallet other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Balance != other.Balance) return false; if (Type != other.Type) return false; if (!object.Equals(Person, other.Person)) return false; if (SubscriberCode != other.SubscriberCode) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Balance != 0UL) hash ^= Balance.GetHashCode(); if (Type != 0) hash ^= Type.GetHashCode(); if (person_ != null) hash ^= Person.GetHashCode(); if (SubscriberCode.Length != 0) hash ^= SubscriberCode.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Balance != 0UL) { output.WriteRawTag(8); output.WriteUInt64(Balance); } if (Type != 0) { output.WriteRawTag(16); output.WriteEnum((int) Type); } if (person_ != null) { output.WriteRawTag(26); output.WriteMessage(Person); } if (SubscriberCode.Length != 0) { output.WriteRawTag(34); output.WriteString(SubscriberCode); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Balance != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Balance); } if (Type != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (person_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Person); } if (SubscriberCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SubscriberCode); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Wallet other) { if (other == null) { return; } if (other.Balance != 0UL) { Balance = other.Balance; } if (other.Type != 0) { Type = other.Type; } if (other.person_ != null) { if (person_ == null) { person_ = new global::VirtualWallet.Proto.Messages.Person(); } Person.MergeFrom(other.Person); } if (other.SubscriberCode.Length != 0) { SubscriberCode = other.SubscriberCode; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Balance = input.ReadUInt64(); break; } case 16: { type_ = (global::VirtualWallet.Proto.Messages.Wallet.Types.WalletType) input.ReadEnum(); break; } case 26: { if (person_ == null) { person_ = new global::VirtualWallet.Proto.Messages.Person(); } input.ReadMessage(person_); break; } case 34: { SubscriberCode = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Wallet message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum WalletType { [pbr::OriginalName("CUSTOMER")] Customer = 0, [pbr::OriginalName("STORE")] Store = 1, [pbr::OriginalName("DEALER")] Dealer = 2, [pbr::OriginalName("BROKER")] Broker = 3, } } #endregion } #endregion } #endregion Designer generated code
// // Copyright (c) 2004-2016 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. // #if !__IOS__ && !WINDOWS_PHONE && !__ANDROID__ namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; #if WCF_SUPPORTED using System.ServiceModel; using System.ServiceModel.Channels; #endif using System.Threading; #if SILVERLIGHT using System.Windows; using System.Windows.Threading; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.LogReceiverService; /// <summary> /// Sends log messages to a NLog Receiver Service (using WCF or Web Services). /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso> [Target("LogReceiverService")] public class LogReceiverWebServiceTarget : Target { private LogEventInfoBuffer buffer; private bool inCall; /// <summary> /// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class. /// </summary> public LogReceiverWebServiceTarget() { this.Parameters = new List<MethodCallParameter>(); this.buffer = new LogEventInfoBuffer(10000, false, 10000); } /// <summary> /// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class. /// </summary> /// <param name="name">Name of the target.</param> public LogReceiverWebServiceTarget(string name) : this() { this.Name = name; } /// <summary> /// Gets or sets the endpoint address. /// </summary> /// <value>The endpoint address.</value> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] public virtual string EndpointAddress { get; set; } #if WCF_SUPPORTED /// <summary> /// Gets or sets the name of the endpoint configuration in WCF configuration file. /// </summary> /// <value>The name of the endpoint configuration.</value> /// <docgen category='Connection Options' order='10' /> public string EndpointConfigurationName { get; set; } /// <summary> /// Gets or sets a value indicating whether to use binary message encoding. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool UseBinaryEncoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) /// </summary> /// <docgen category='Connection Options' order='10' /> public bool UseOneWayContract { get; set; } #endif /// <summary> /// Gets or sets the client ID. /// </summary> /// <value>The client ID.</value> /// <docgen category='Payload Options' order='10' /> public Layout ClientId { get; set; } /// <summary> /// Gets the list of parameters. /// </summary> /// <value>The parameters.</value> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList<MethodCallParameter> Parameters { get; private set; } /// <summary> /// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Called when log events are being sent (test hook). /// </summary> /// <param name="events">The events.</param> /// <param name="asyncContinuations">The async continuations.</param> /// <returns>True if events should be sent, false to stop processing them.</returns> protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { return true; } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(ArraySegment<AsyncLogEventInfo> logEvents) { // if web service call is being processed, buffer new events and return // lock is being held here if (this.inCall) { for(int x=0;x<logEvents.Count;x++) { var ev = logEvents.Array[x]; this.buffer.Append(ev); } return; } var networkLogEvents = this.TranslateLogEvents(logEvents); var arr = new AsyncLogEventInfo[logEvents.Count]; Array.Copy(logEvents.Array, logEvents.Offset, arr, 0, logEvents.Count); this.Send(networkLogEvents, arr); } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { this.SendBufferedEvents(); asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value) { int stringIndex; if (!stringTable.TryGetValue(value, out stringIndex)) { stringIndex = context.Strings.Count; stringTable.Add(value, stringIndex); context.Strings.Add(value); } return stringIndex; } private NLogEvents TranslateLogEvents(ArraySegment<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 0 && !LogManager.ThrowExceptions) { InternalLogger.Error("LogEvents array is empty, sending empty event..."); return new NLogEvents(); } string clientID = string.Empty; if (this.ClientId != null) { clientID = this.ClientId.Render(logEvents.Array[0].LogEvent); } var networkLogEvents = new NLogEvents { ClientName = clientID, LayoutNames = new StringCollection(), Strings = new StringCollection(), BaseTimeUtc = logEvents.Array[0].LogEvent.TimeStamp.ToUniversalTime().Ticks }; var stringTable = new Dictionary<string, int>(); for (int i = 0; i < this.Parameters.Count; ++i) { networkLogEvents.LayoutNames.Add(this.Parameters[i].Name); } if (this.IncludeEventProperties) { for (int i = 0; i < logEvents.Count; ++i) { var ev = logEvents.Array[i].LogEvent; // add all event-level property names in 'LayoutNames' collection. foreach (var prop in ev.Properties) { string propName = prop.Key as string; if (propName != null) { if (!networkLogEvents.LayoutNames.Contains(propName)) { networkLogEvents.LayoutNames.Add(propName); } } } } } networkLogEvents.Events = new NLogEvent[logEvents.Count]; for (int i = 0; i < logEvents.Count; ++i) { networkLogEvents.Events[i] = this.TranslateEvent(logEvents.Array[i].LogEvent, networkLogEvents, stringTable); } return networkLogEvents; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")] private void Send(NLogEvents events, AsyncLogEventInfo[] asyncContinuations) { if (!this.OnSend(events, asyncContinuations)) { return; } #if WCF_SUPPORTED var client = CreateLogReceiver(); client.ProcessLogMessagesCompleted += (sender, e) => { // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(e.Error); } // send any buffered events this.SendBufferedEvents(); }; this.inCall = true; #if SILVERLIGHT if (!Deployment.Current.Dispatcher.CheckAccess()) { Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events)); } else { client.ProcessLogMessagesAsync(events); } #else client.ProcessLogMessagesAsync(events); #endif #else var client = new SoapLogReceiverClient(this.EndpointAddress); this.inCall = true; client.BeginProcessLogMessages( events, result => { Exception exception = null; try { client.EndProcessLogMessages(result); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } exception = ex; } // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(exception); } // send any buffered events this.SendBufferedEvents(); }, null); #endif } #if WCF_SUPPORTED /// <summary> /// Creating a new instance of WcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> [Obsolete("Ths may be removed in a future release. Use CreateLogReceiver.")] protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient() { WcfLogReceiverClient client; if (string.IsNullOrEmpty(this.EndpointConfigurationName)) { // endpoint not specified - use BasicHttpBinding Binding binding; if (this.UseBinaryEncoding) { binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); } else { binding = new BasicHttpBinding(); } client = new WcfLogReceiverClient(UseOneWayContract, binding, new EndpointAddress(this.EndpointAddress)); } else { client = new WcfLogReceiverClient(UseOneWayContract, this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress)); } client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted; return client; } /// <summary> /// Creating a new instance of IWcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> /// <remarks>virtual is used by endusers</remarks> protected virtual IWcfLogReceiverClient CreateLogReceiver() { #pragma warning disable 612, 618 return this.CreateWcfLogReceiverClient(); #pragma warning restore 612, 618 } private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs) { var client = sender as WcfLogReceiverClient; if (client != null && client.State == CommunicationState.Opened) { client.CloseCommunicationObject(); } } #endif private void SendBufferedEvents() { lock (this.SyncRoot) { // clear inCall flag AsyncLogEventInfo[] bufferedEvents = this.buffer.GetEventsAndClear(); if (bufferedEvents.Length > 0) { var networkLogEvents = this.TranslateLogEvents(new ArraySegment<AsyncLogEventInfo>(bufferedEvents)); this.Send(networkLogEvents, bufferedEvents); } else { // nothing in the buffer, clear in-call flag this.inCall = false; } } } private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable) { var nlogEvent = new NLogEvent(); nlogEvent.Id = eventInfo.SequenceID; nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage); nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal; nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName); nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc; for (int i = 0; i < this.Parameters.Count; ++i) { var param = this.Parameters[i]; var value = param.Layout.Render(eventInfo); int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } // layout names beyond Parameters.Count are per-event property names. for (int i = this.Parameters.Count; i < context.LayoutNames.Count; ++i) { string value; object propertyValue; if (eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue)) { value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture); } else { value = string.Empty; } int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } if (eventInfo.Exception != null) { nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString())); } return nlogEvent; } } } #endif
/* * Copyright (c) 2006, Clutch, Inc. * Original Author: Jeff Cesnik * 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.Net; using System.Net.Sockets; using System.Threading; using log4net; using OpenSim.Framework; using OpenSim.Framework.Monitoring; namespace OpenMetaverse { /// <summary> /// Base UDP server /// </summary> public abstract class OpenSimUDPBase { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This method is called when an incoming packet is received /// </summary> /// <param name="buffer">Incoming packet buffer</param> public abstract void PacketReceived(UDPPacketBuffer buffer); /// <summary>UDP port to bind to in server mode</summary> protected int m_udpPort; /// <summary>Local IP address to bind to in server mode</summary> protected IPAddress m_localBindAddress; /// <summary>UDP socket, used in either client or server mode</summary> private Socket m_udpSocket; /// <summary> /// Are we to use object pool(s) to reduce memory churn when receiving data? /// </summary> public bool UsePools { get; protected set; } /// <summary> /// Pool to use for handling data. May be null if UsePools = false; /// </summary> protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; } /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary> public bool IsRunningInbound { get; private set; } /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary> /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks> public bool IsRunningOutbound { get; private set; } /// <summary> /// Number of UDP receives. /// </summary> public int UdpReceives { get; private set; } /// <summary> /// Number of UDP sends /// </summary> public int UdpSends { get; private set; } /// <summary> /// Number of receives over which to establish a receive time average. /// </summary> private readonly static int s_receiveTimeSamples = 500; /// <summary> /// Current number of samples taken to establish a receive time average. /// </summary> private int m_currentReceiveTimeSamples; /// <summary> /// Cumulative receive time for the sample so far. /// </summary> private int m_receiveTicksInCurrentSamplePeriod; /// <summary> /// The average time taken for each require receive in the last sample. /// </summary> public float AverageReceiveTicksForLastSamplePeriod { get; private set; } public int Port { get { return m_udpPort; } } #region PacketDropDebugging /// <summary> /// For debugging purposes only... random number generator for dropping /// outbound packets. /// </summary> private Random m_dropRandomGenerator = new Random(); /// <summary> /// For debugging purposes only... parameters for a simplified /// model of packet loss with bursts, overall drop rate should /// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability) /// which is about 1% for parameters 0.0015 and 0.15 /// </summary> private double m_dropProbability = 0.0030; private double m_dropLengthProbability = 0.15; private bool m_dropState = false; /// <summary> /// For debugging purposes only... parameters to control the time /// duration over which packet loss bursts can occur, if no packets /// have been sent for m_dropResetTicks milliseconds, then reset the /// state of the packet dropper to its default. /// </summary> private int m_dropLastTick = 0; private int m_dropResetTicks = 500; /// <summary> /// Debugging code used to simulate dropped packets with bursts /// </summary> private bool DropOutgoingPacket() { double rnum = m_dropRandomGenerator.NextDouble(); // if the connection has been idle for awhile (more than m_dropResetTicks) then // reset the state to the default state, don't continue a burst int curtick = Util.EnvironmentTickCount(); if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks) m_dropState = false; m_dropLastTick = curtick; // if we are dropping packets, then the probability of dropping // this packet is the probability that we stay in the burst if (m_dropState) { m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false; } else { m_dropState = (rnum < m_dropProbability) ? true : false; } return m_dropState; } #endregion PacketDropDebugging /// <summary> /// Default constructor /// </summary> /// <param name="bindAddress">Local IP address to bind the server to</param> /// <param name="port">Port to listening for incoming UDP packets on</param> /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param> public OpenSimUDPBase(IPAddress bindAddress, int port) { m_localBindAddress = bindAddress; m_udpPort = port; // for debugging purposes only, initializes the random number generator // used for simulating packet loss // m_dropRandomGenerator = new Random(); } ~OpenSimUDPBase() { if(m_udpSocket !=null) try { m_udpSocket.Close(); } catch { } } /// <summary> /// Start inbound UDP packet handling. /// </summary> /// <param name="recvBufferSize">The size of the receive buffer for /// the UDP socket. This value is passed up to the operating system /// and used in the system networking stack. Use zero to leave this /// value as the default</param> /// <param name="asyncPacketHandling">Set this to true to start /// receiving more packets while current packet handler callbacks are /// still running. Setting this to false will complete each packet /// callback before the next packet is processed</param> /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag /// on the socket to get newer versions of Windows to behave in a sane /// manner (not throwing an exception when the remote side resets the /// connection). This call is ignored on Mono where the flag is not /// necessary</remarks> public virtual void StartInbound(int recvBufferSize) { if (!IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop"); const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { if (m_udpSocket.Ttl < 128) { m_udpSocket.Ttl = 128; } } catch (SocketException) { m_log.Debug("[UDPBASE]: Failed to increase default TTL"); } try { // This udp socket flag is not supported under mono, // so we'll catch the exception and continue // Try does not protect some mono versions on mac if(Util.IsWindows()) { m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set"); } else { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } } catch { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment // we never want two regions to listen on the same port as they cannot demultiplex each other's messages, // leading to a confusing bug. // By default, Windows does not allow two sockets to bind to the same port. // // Unfortunately, this also causes a crashed sim to leave the socket in a state // where it appears to be in use but is really just hung from the old process // crashing rather than closing it. While this protects agains misconfiguration, // allowing crashed sims to be started up again right away, rather than having to // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016 // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (recvBufferSize != 0) m_udpSocket.ReceiveBufferSize = recvBufferSize; m_udpSocket.Bind(ipep); if (m_udpPort == 0) m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port; IsRunningInbound = true; // kick off an async receive. The Start() method will return, the // actual receives will occur asynchronously and will be caught in // AsyncEndRecieve(). AsyncBeginReceive(); } } /// <summary> /// Start outbound UDP packet handling. /// </summary> public virtual void StartOutbound() { m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop"); IsRunningOutbound = true; } public virtual void StopInbound() { if (IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop"); IsRunningInbound = false; m_udpSocket.Close(); } } public virtual void StopOutbound() { m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop"); IsRunningOutbound = false; } public virtual bool EnablePools() { if (!UsePools) { Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500); UsePools = true; return true; } return false; } public virtual bool DisablePools() { if (UsePools) { UsePools = false; // We won't null out the pool to avoid a race condition with code that may be in the middle of using it. return true; } return false; } private void AsyncBeginReceive() { UDPPacketBuffer buf; // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation. // if (UsePools) // buf = Pool.GetObject(); // else buf = new UDPPacketBuffer(); if (IsRunningInbound) { try { // kick off an async read m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionReset) { m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort); bool salvaged = false; while (!salvaged) { try { m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); salvaged = true; } catch (SocketException) { } catch (ObjectDisposedException) { return; } } m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort); } } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } } } private void AsyncEndReceive(IAsyncResult iar) { // Asynchronous receive operations will complete here through the call // to AsyncBeginReceive if (IsRunningInbound) { UdpReceives++; try { // get the buffer that was created in AsyncBeginReceive // this is the received data UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; int startTick = Util.EnvironmentTickCount(); // get the length of data actually read from the socket, store it with the // buffer buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); // call the abstract method PacketReceived(), passing the buffer that // has just been filled from the socket read. PacketReceived(buffer); // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler) // then a particular stat may be inaccurate due to a race condition. We won't worry about this // since this should be rare and won't cause a runtime problem. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples) { AverageReceiveTicksForLastSamplePeriod = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples; m_receiveTicksInCurrentSamplePeriod = 0; m_currentReceiveTimeSamples = 0; } else { m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick); m_currentReceiveTimeSamples++; } } catch (SocketException se) { m_log.Error( string.Format( "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ", UdpReceives, se.ErrorCode), se); } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } finally { // if (UsePools) // Pool.ReturnObject(buffer); AsyncBeginReceive(); } } } public void AsyncBeginSend(UDPPacketBuffer buf) { // if (IsRunningOutbound) // { // This is strictly for debugging purposes to simulate dropped // packets when testing throttles & retransmission code // if (DropOutgoingPacket()) // return; try { m_udpSocket.BeginSendTo( buf.Data, 0, buf.DataLength, SocketFlags.None, buf.RemoteEndPoint, AsyncEndSend, buf); } catch (SocketException) { } catch (ObjectDisposedException) { } // } } void AsyncEndSend(IAsyncResult result) { try { // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState; m_udpSocket.EndSendTo(result); UdpSends++; } catch (SocketException) { } catch (ObjectDisposedException) { } } public void SyncSend(UDPPacketBuffer buf) { try { m_udpSocket.SendTo( buf.Data, 0, buf.DataLength, SocketFlags.None, buf.RemoteEndPoint ); UdpSends++; } catch (SocketException e) { m_log.Warn("[UDPBASE]: sync send SocketException {0} " + e.Message); } catch (ObjectDisposedException) { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ElasticPoolsOperations operations. /// </summary> public partial interface IElasticPoolsOperations { /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or /// created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ElasticPool>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ElasticPool>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a list of elastic pools in a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ElasticPool>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns elastic pool activities. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool for which to get the current activity. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ElasticPoolActivity>>> ListActivityWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns activity on databases inside of an elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<ElasticPoolDatabaseActivity>>> ListDatabaseActivityWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a database inside of an elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='databaseName'> /// The name of the database to be retrieved. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Database>> GetDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a list of databases in an elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<Database>>> ListDatabasesWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or /// created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ElasticPool>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Copyright 2011 Matthew Beardmore * * 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; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Nini.Config; using Aurora.DataManager; using OpenMetaverse; using OpenSim.Services.Interfaces; using OpenSim.Services.LLLoginService; namespace Aurora.Modules.Ban { #region Grid BanCheck public class LoginBanCheck : ILoginModule { #region Declares BanCheck m_module; public string Name { get { return GetType().Name; } } #endregion #region ILoginModule Members public void Initialize(ILoginService service, IConfigSource source, IRegistryCore registry) { m_module = new BanCheck(source, registry.RequestModuleInterface<IUserAccountService>()); } public LoginResponse Login(Hashtable request, UserAccount account, IAgentInfo agentInfo, string authType, string password, out object data) { data = null; string ip = ""; string version = ""; string platform = ""; string mac = ""; string id0 = ""; if (request != null) { ip = request.ContainsKey("ip") ? (string)request["ip"] : ""; version = request.ContainsKey("version") ? (string)request["version"] : ""; platform = request.ContainsKey("platform") ? (string)request["platform"] : ""; mac = request.ContainsKey("mac") ? (string)request["mac"] : ""; id0 = request.ContainsKey("id0") ? (string)request["id0"] : ""; } string message; if(!m_module.CheckUser(account.PrincipalID, ip, version, platform, mac, id0, out message)) { return new LLFailedLoginResponse(LoginResponseEnum.Indeterminant, message, false); } return null; } #endregion } #endregion #region BanCheck base public class BanCheck { #region Declares private IPresenceInfo presenceInfo = null; private AllowLevel GrieferAllowLevel = AllowLevel.AllowCleanOnly; private IUserAccountService m_accountService = null; private List<string> m_bannedViewers = new List<string>(); private List<string> m_allowedViewers = new List<string>(); private bool m_useIncludeList = false; private bool m_debug = false; private bool m_checkOnLogin = false; private bool m_checkOnTimer = true; private bool m_enabled = false; private Aurora.Framework.ListCombiningTimedSaving<PresenceInfo> _checkForSimilaritiesLater = new ListCombiningTimedSaving<PresenceInfo>(); #endregion #region Enums public enum AllowLevel : int { AllowCleanOnly = 0, AllowSuspected = 1, AllowKnown = 2 } #endregion #region Constructor public BanCheck (IConfigSource source, IUserAccountService UserAccountService) { IConfig config = source.Configs["GrieferProtection"]; if (config == null) return; m_enabled = config.GetBoolean ("Enabled", true); if (!m_enabled) return; string bannedViewers = config.GetString("ViewersToBan", ""); m_bannedViewers = Util.ConvertToList(bannedViewers); string allowedViewers = config.GetString("ViewersToAllow", ""); m_allowedViewers = Util.ConvertToList(allowedViewers); m_useIncludeList = config.GetBoolean("UseAllowListInsteadOfBanList", false); m_checkOnLogin = config.GetBoolean ("CheckForSimilaritiesOnLogin", m_checkOnLogin); m_checkOnTimer = config.GetBoolean ("CheckForSimilaritiesOnTimer", m_checkOnTimer); if (m_checkOnTimer) _checkForSimilaritiesLater.Start(5, CheckForSimilaritiesMultiple); GrieferAllowLevel = (AllowLevel)Enum.Parse (typeof (AllowLevel), config.GetString ("GrieferAllowLevel", "AllowKnown")); presenceInfo = Aurora.DataManager.DataManager.RequestPlugin<IPresenceInfo> (); m_accountService = UserAccountService; if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand( "show user info", "show user info [UUID] or [First] [Last]", "Info on a given user", UserInfo); MainConsole.Instance.Commands.AddCommand( "set user info", "set user info [UUID] or [First] [Last] [Flags]", "Sets the info of the given user [Flags]: Clean, Suspected, Known, Banned", SetUserInfo); MainConsole.Instance.Commands.AddCommand( "block user", "block user [UUID] or [Name]", "Blocks a given user from connecting anymore", BlockUser); MainConsole.Instance.Commands.AddCommand( "ban user", "ban user [UUID] or [Name]", "Blocks a given user from connecting anymore", BlockUser); MainConsole.Instance.Commands.AddCommand( "unblock user", "unblock user [UUID] or [Name]", "Removes the block for logging in on a given user", UnBlockUser); MainConsole.Instance.Commands.AddCommand( "unban user", "unban user [UUID] or [Name]", "Removes the block for logging in on a given user", UnBlockUser); } } #endregion #region Private and Protected members private void CheckForSimilaritiesMultiple(UUID agentID, List<PresenceInfo> info) { foreach(PresenceInfo i in info) presenceInfo.Check(i, m_useIncludeList ? m_allowedViewers : m_bannedViewers, m_useIncludeList); } private void CheckForSimilarities(PresenceInfo info) { presenceInfo.Check(info, m_useIncludeList ? m_allowedViewers : m_bannedViewers, m_useIncludeList); } private PresenceInfo UpdatePresenceInfo(UUID AgentID, PresenceInfo oldInfo, string ip, string version, string platform, string mac, string id0) { PresenceInfo info = new PresenceInfo(); info.AgentID = AgentID; if(!string.IsNullOrEmpty(ip)) info.LastKnownIP = ip; if (!string.IsNullOrEmpty(version)) info.LastKnownViewer = version; if (!string.IsNullOrEmpty(platform)) info.Platform = platform; if (!string.IsNullOrEmpty(mac)) info.LastKnownMac = mac; if (!string.IsNullOrEmpty(id0)) info.LastKnownID0 = id0; if (!oldInfo.KnownID0s.Contains(info.LastKnownID0)) oldInfo.KnownID0s.Add(info.LastKnownID0); if (!oldInfo.KnownIPs.Contains(info.LastKnownIP)) oldInfo.KnownIPs.Add(info.LastKnownIP); if (!oldInfo.KnownMacs.Contains(info.LastKnownMac)) oldInfo.KnownMacs.Add(info.LastKnownMac); if (!oldInfo.KnownViewers.Contains(info.LastKnownViewer)) oldInfo.KnownViewers.Add(info.LastKnownViewer); info.KnownViewers = oldInfo.KnownViewers; info.KnownMacs = oldInfo.KnownMacs; info.KnownIPs = oldInfo.KnownIPs; info.KnownID0s = oldInfo.KnownID0s; info.KnownAlts = oldInfo.KnownAlts; info.Flags = oldInfo.Flags; presenceInfo.UpdatePresenceInfo(info); return info; } private PresenceInfo GetInformation(UUID AgentID) { PresenceInfo oldInfo = presenceInfo.GetPresenceInfo(AgentID); if (oldInfo == null) { PresenceInfo info = new PresenceInfo(); info.AgentID = AgentID; info.Flags = PresenceInfo.PresenceInfoFlags.Clean; presenceInfo.UpdatePresenceInfo(info); oldInfo = presenceInfo.GetPresenceInfo(AgentID); } return oldInfo; } protected void UserInfo(string[] cmdparams) { if (cmdparams.Length < 4) { MainConsole.Instance.Info("Wrong number of parameters for show user info"); return; } UUID AgentID; PresenceInfo info; if (!UUID.TryParse(cmdparams[3], out AgentID)) { UserAccount account = m_accountService.GetUserAccount(null, Util.CombineParams(cmdparams, 3)); if (account == null) { MainConsole.Instance.Warn("Cannot find user."); return; } AgentID = account.PrincipalID; } info = GetInformation(AgentID); if (info == null) { MainConsole.Instance.Warn("Cannot find user."); return; } DisplayUserInfo(info); } protected void BlockUser(string[] cmdparams) { if (cmdparams.Length < 3) { MainConsole.Instance.Info("Wrong number of parameters for block user"); return; } UUID AgentID; PresenceInfo info; if (!UUID.TryParse(cmdparams[2], out AgentID)) { UserAccount account = m_accountService.GetUserAccount(null, Util.CombineParams(cmdparams, 2)); if (account == null) { MainConsole.Instance.Warn("Cannot find user."); return; } AgentID = account.PrincipalID; } info = GetInformation(AgentID); if (info == null) { MainConsole.Instance.Warn("Cannot find user."); return; } if (MainConsole.Instance.Prompt("Do you want to have this only be a temporary ban?", "no", new List<string>() { "yes", "no" }).ToLower() == "yes") { var conn = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>(); IAgentInfo agentInfo = conn.GetAgent(AgentID); float days = float.Parse(MainConsole.Instance.Prompt("How long (in days) should this ban last?", "5.0")); agentInfo.Flags |= IAgentFlags.TempBan; agentInfo.OtherAgentInformation["TemperaryBanInfo"] = DateTime.Now.AddDays(days); conn.UpdateAgent(agentInfo); } else { info.Flags |= PresenceInfo.PresenceInfoFlags.Banned; presenceInfo.UpdatePresenceInfo(info); } MainConsole.Instance.Fatal("User blocked from logging in"); } protected void UnBlockUser(string[] cmdparams) { if (cmdparams.Length < 3) { MainConsole.Instance.Info("Wrong number of parameters for block user"); return; } UUID AgentID; PresenceInfo info; if (!UUID.TryParse(cmdparams[2], out AgentID)) { UserAccount account = m_accountService.GetUserAccount(null, Util.CombineParams(cmdparams, 2)); if (account == null) { MainConsole.Instance.Warn("Cannot find user."); return; } AgentID = account.PrincipalID; } info = GetInformation(AgentID); if (info == null) { MainConsole.Instance.Warn("Cannot find user."); return; } info.Flags = PresenceInfo.PresenceInfoFlags.Clean; presenceInfo.UpdatePresenceInfo(info); var conn = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>(); IAgentInfo agentInfo = conn.GetAgent(AgentID); agentInfo.Flags &= IAgentFlags.TempBan; agentInfo.Flags &= IAgentFlags.PermBan; conn.UpdateAgent(agentInfo); MainConsole.Instance.Fatal("User block removed"); } protected void SetUserInfo(string[] cmdparams) { if (cmdparams.Length < 5) { MainConsole.Instance.Info("Wrong number of parameters for set user info"); return; } UUID AgentID; PresenceInfo info; int Num = 4; if (!UUID.TryParse(cmdparams[3], out AgentID)) { UserAccount account = m_accountService.GetUserAccount(null, Util.CombineParams(cmdparams, 3, 5)); if (account == null) { MainConsole.Instance.Warn("Cannot find user."); return; } AgentID = account.PrincipalID; Num += 1; } info = GetInformation(AgentID); if (info == null) { MainConsole.Instance.Warn("Cannot find user."); return; } try { info.Flags = (PresenceInfo.PresenceInfoFlags)Enum.Parse(typeof(PresenceInfo.PresenceInfoFlags), cmdparams[Num]); } catch { MainConsole.Instance.Warn("Please choose a valid flag: Clean, Suspected, Known, Banned"); return; } MainConsole.Instance.Info("Set Flags for " + info.AgentID.ToString() + " to " + info.Flags.ToString()); presenceInfo.UpdatePresenceInfo(info); } private void DisplayUserInfo(PresenceInfo info) { UserAccount account = m_accountService.GetUserAccount(null, info.AgentID); if (account != null) MainConsole.Instance.Info("User Info for " + account.Name); else MainConsole.Instance.Info("User Info for " + info.AgentID); MainConsole.Instance.Info(" AgentID: " + info.AgentID); MainConsole.Instance.Info(" Flags: " + info.Flags); MainConsole.Instance.Info(" ID0: " + info.LastKnownID0); MainConsole.Instance.Info(" IP: " + info.LastKnownIP); //MainConsole.Instance.Info(" Mac: " + info.LastKnownMac); MainConsole.Instance.Info(" Viewer: " + info.LastKnownViewer); MainConsole.Instance.Info(" Platform: " + info.Platform); if (info.KnownAlts.Count > 0) { MainConsole.Instance.Info(" Known Alt Accounts: "); foreach (var acc in info.KnownAlts) { account = m_accountService.GetUserAccount(null, UUID.Parse(acc)); if (account != null) MainConsole.Instance.Info(" " + account.Name); else MainConsole.Instance.Info(" " + acc); } } } private bool CheckClient(UUID AgentID, out string message) { message = ""; PresenceInfo info = GetInformation(AgentID); if (m_checkOnLogin) CheckForSimilarities(info); else _checkForSimilaritiesLater.Add(AgentID, info); if (!CheckThreatLevel(info, out message)) return false; return CheckViewer(info, out message); } private bool CheckViewer(PresenceInfo info, out string reason) { //Check for banned viewers if (IsViewerBanned(info.LastKnownViewer)) { reason = "Viewer is banned"; return false; } //Overkill, and perm-bans people who only log in with a bad viewer once //foreach (string mac in info.KnownMacs) { if (info.LastKnownMac.Contains("000")) { //Ban this asshole reason = "Viewer is blocked (MAC)"; return false; } } //foreach (string id0 in info.KnownID0s) { if (info.LastKnownID0.Contains("000")) { //Ban this asshole reason = "Viewer is blocked (IO)"; return false; } } reason = ""; return true; } public bool IsViewerBanned(string name) { if (m_useIncludeList) { if (!m_allowedViewers.Contains(name)) return true; } else { if (m_bannedViewers.Contains(name)) return true; } return false; } private bool CheckThreatLevel(PresenceInfo info, out string message) { message = ""; if ((info.Flags & PresenceInfo.PresenceInfoFlags.Banned) == PresenceInfo.PresenceInfoFlags.Banned) { message = "Banned agent."; return false; } if (GrieferAllowLevel == AllowLevel.AllowKnown) return true; //Allow all else if (GrieferAllowLevel == AllowLevel.AllowCleanOnly) { //Allow people with only clean flag or suspected alt if ((info.Flags & PresenceInfo.PresenceInfoFlags.Suspected) == PresenceInfo.PresenceInfoFlags.Suspected || (info.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known || (info.Flags & PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown || (info.Flags & PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown || (info.Flags & PresenceInfo.PresenceInfoFlags.Banned) == PresenceInfo.PresenceInfoFlags.Banned) { message = "Not a Clean agent and have been denied access."; return false; } } else if (GrieferAllowLevel == AllowLevel.AllowSuspected) { //Block all alts of knowns, and suspected alts of knowns if ((info.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known || (info.Flags & PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown || (info.Flags & PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown || (info.Flags & PresenceInfo.PresenceInfoFlags.Banned) == PresenceInfo.PresenceInfoFlags.Banned) { message = "Not a Clean agent and have been denied access."; return false; } } return true; } #endregion #region Public members public bool CheckUser(UUID AgentID, string ip, string version, string platform, string mac, string id0, out string message) { message = ""; if (!m_enabled) return true; PresenceInfo oldInfo = GetInformation(AgentID); oldInfo = UpdatePresenceInfo(AgentID, oldInfo, ip, version, platform, mac, id0); if (m_debug) DisplayUserInfo(oldInfo); return CheckClient(AgentID, out message); } public void SetUserLevel(UUID AgentID, PresenceInfo.PresenceInfoFlags presenceInfoFlags) { if (!m_enabled) return; //Get PresenceInfo info = GetInformation(AgentID); //Set the flags info.Flags = presenceInfoFlags; //Save presenceInfo.UpdatePresenceInfo(info); } #endregion } #endregion #region IP block check public class IPBanCheck : ILoginModule { #region Declares private List<IPAddress> IPBans = new List<IPAddress>(); private List<string> IPRangeBans = new List<string>(); public string Name { get { return GetType().Name; } } #endregion #region ILoginModule Members public void Initialize(ILoginService service, IConfigSource source, IRegistryCore registry) { IConfig config = source.Configs["GrieferProtection"]; if (config != null) { List<string> iPBans = Util.ConvertToList(config.GetString("IPBans", "")); foreach (string ip in iPBans) { IPAddress ipa; if(IPAddress.TryParse(ip, out ipa)) IPBans.Add(ipa); } IPRangeBans = Util.ConvertToList(config.GetString("IPRangeBans", "")); } } public LoginResponse Login(Hashtable request, UserAccount account, IAgentInfo agentInfo, string authType, string password, out object data) { data = null; string ip = request != null && request.ContainsKey("ip") ? (string)request["ip"] : "127.0.0.1"; ip = ip.Split(':')[0];//Remove the port IPAddress userIP = IPAddress.Parse(ip); if (IPBans.Contains(userIP)) return new LLFailedLoginResponse(LoginResponseEnum.Indeterminant, "Your account cannot be accessed on this computer.", false); foreach (string ipRange in IPRangeBans) { string[] split = ipRange.Split('-'); if (split.Length != 2) continue; IPAddress low = IPAddress.Parse(ip); IPAddress high = IPAddress.Parse(ip); NetworkUtils.IPAddressRange range = new NetworkUtils.IPAddressRange(low, high); if (range.IsInRange(userIP)) return new LLFailedLoginResponse(LoginResponseEnum.Indeterminant, "Your account cannot be accessed on this computer.", false); } return null; } #endregion } #endregion }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using System.IO; using System.Threading.Tasks; using OpenTK; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using OpenTK.Graphics; using osu.Framework.Input; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Framework.Logging; using osu.Game.Beatmaps.IO; using osu.Game.Overlays.Notifications; namespace osu.Game.Overlays.Direct { public abstract class DirectPanel : Container { public readonly BeatmapSetInfo SetInfo; protected Box BlackBackground; private const double hover_transition_time = 400; private Container content; private APIAccess api; private ProgressBar progressBar; private BeatmapManager beatmaps; private NotificationOverlay notifications; protected override Container<Drawable> Content => content; protected DirectPanel(BeatmapSetInfo setInfo) { SetInfo = setInfo; } private readonly EdgeEffectParameters edgeEffectNormal = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 1f), Radius = 2f, Colour = Color4.Black.Opacity(0.25f), }; private readonly EdgeEffectParameters edgeEffectHovered = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 5f), Radius = 10f, Colour = Color4.Black.Opacity(0.3f), }; [BackgroundDependencyLoader(permitNulls: true)] private void load(APIAccess api, BeatmapManager beatmaps, OsuColour colours, NotificationOverlay notifications) { this.api = api; this.beatmaps = beatmaps; this.notifications = notifications; AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, EdgeEffect = edgeEffectNormal, Children = new[] { // temporary blackness until the actual background loads. BlackBackground = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, CreateBackground(), progressBar = new ProgressBar { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Height = 0, Alpha = 0, BackgroundColour = Color4.Black.Opacity(0.7f), FillColour = colours.Blue, Depth = -1, }, } }); } protected override bool OnHover(InputState state) { content.TweenEdgeEffectTo(edgeEffectHovered, hover_transition_time, Easing.OutQuint); content.MoveToY(-4, hover_transition_time, Easing.OutQuint); return base.OnHover(state); } protected override void OnHoverLost(InputState state) { content.TweenEdgeEffectTo(edgeEffectNormal, hover_transition_time, Easing.OutQuint); content.MoveToY(0, hover_transition_time, Easing.OutQuint); base.OnHoverLost(state); } // this should eventually be moved to a more central place, like BeatmapManager. private DownloadBeatmapSetRequest downloadRequest; protected void StartDownload() { if (api == null) return; // we already have an active download running. if (downloadRequest != null) { content.MoveToX(-5, 50, Easing.OutSine).Then() .MoveToX(5, 100, Easing.InOutSine).Then() .MoveToX(-5, 100, Easing.InOutSine).Then() .MoveToX(0, 50, Easing.InSine).Then(); return; } if (!api.LocalUser.Value.IsSupporter) { notifications.Post(new SimpleNotification { Icon = FontAwesome.fa_superpowers, Text = "You gotta be a supporter to download for now 'yo" }); return; } progressBar.FadeIn(400, Easing.OutQuint); progressBar.ResizeHeightTo(4, 400, Easing.OutQuint); progressBar.Current.Value = 0; ProgressNotification downloadNotification = new ProgressNotification { Text = $"Downloading {SetInfo.Metadata.Artist} - {SetInfo.Metadata.Title}", }; downloadRequest = new DownloadBeatmapSetRequest(SetInfo); downloadRequest.Failure += e => { progressBar.Current.Value = 0; progressBar.FadeOut(500); downloadNotification.State = ProgressNotificationState.Completed; Logger.Error(e, "Failed to get beatmap download information"); downloadRequest = null; }; downloadRequest.Progress += (current, total) => { float progress = (float)current / total; progressBar.Current.Value = progress; downloadNotification.State = ProgressNotificationState.Active; downloadNotification.Progress = progress; }; downloadRequest.Success += data => { progressBar.Current.Value = 1; progressBar.FadeOut(500); downloadNotification.State = ProgressNotificationState.Completed; using (var stream = new MemoryStream(data)) using (var archive = new OszArchiveReader(stream)) beatmaps.Import(archive); }; downloadNotification.CancelRequested += () => { downloadRequest.Cancel(); downloadRequest = null; return true; }; notifications.Post(downloadNotification); // don't run in the main api queue as this is a long-running task. Task.Run(() => downloadRequest.Perform(api)); } public class DownloadBeatmapSetRequest : APIDownloadRequest { private readonly BeatmapSetInfo beatmapSet; public DownloadBeatmapSetRequest(BeatmapSetInfo beatmapSet) { this.beatmapSet = beatmapSet; } protected override string Target => $@"beatmapsets/{beatmapSet.OnlineBeatmapSetID}/download"; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(200, Easing.Out); } protected List<DifficultyIcon> GetDifficultyIcons() { var icons = new List<DifficultyIcon>(); foreach (var b in SetInfo.Beatmaps) icons.Add(new DifficultyIcon(b)); return icons; } protected Drawable CreateBackground() => new DelayedLoadWrapper(new BeatmapSetCover(SetInfo) { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, OnLoadComplete = d => { d.FadeInFromZero(400, Easing.Out); BlackBackground.Delay(400).FadeOut(); }, }) { RelativeSizeAxes = Axes.Both, TimeBeforeLoad = 300 }; public class Statistic : FillFlowContainer { private readonly SpriteText text; private int value; public int Value { get { return value; } set { this.value = value; text.Text = Value.ToString(@"N0"); } } public Statistic(FontAwesome icon, int value = 0) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; AutoSizeAxes = Axes.Both; Direction = FillDirection.Horizontal; Spacing = new Vector2(5f, 0f); Children = new Drawable[] { text = new OsuSpriteText { Font = @"Exo2.0-SemiBoldItalic", }, new SpriteIcon { Icon = icon, Shadow = true, Size = new Vector2(14), Margin = new MarginPadding { Top = 1 }, }, }; Value = value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace CSScripting { /// <summary> /// Various PATH extensions /// </summary> public static class PathExtensions { /// <summary> /// Copies the file. /// </summary> /// <param name="src">The source path to the file.</param> /// <param name="dest">The destination path to the file.</param> /// <param name="ignoreErrors">if set to <c>true</c> [ignore errors].</param> public static void FileCopy(this string src, string dest, bool ignoreErrors = false) { try { File.Copy(src, dest, true); } catch { if (!ignoreErrors) throw; } } /// <summary> /// Changes the extension of the file. /// </summary> /// <param name="path">The path.</param> /// <param name="extension">The extension.</param> /// <returns>A new path</returns> public static string ChangeExtension(this string path, string extension) => Path.ChangeExtension(path, extension); /// <summary> /// Gets the extension. /// </summary> /// <param name="path">The path.</param> /// <returns>File extension</returns> public static string GetExtension(this string path) => Path.GetExtension(path); /// <summary> /// Gets the file name part of the full path. /// </summary> /// <param name="path">The path.</param> /// <returns>The method result.</returns> public static string GetFileName(this string path) => Path.GetFileName(path); /// <summary> /// Checks if the directory exists. /// </summary> /// <param name="path">The path.</param> /// <returns>The result of the test.</returns> public static bool DirExists(this string path) => path.IsNotEmpty() ? Directory.Exists(path) : false; /// <summary> /// Gets the full path. /// </summary> /// <param name="path">The path.</param> /// <returns>The path</returns> public static string GetFullPath(this string path) => Path.GetFullPath(path); /// <summary> /// Determines whether the path is directory. /// </summary> /// <param name="path">The path.</param> /// <returns> /// <c>true</c> if the specified path is dir; otherwise, <c>false</c>. /// </returns> public static bool IsDir(this string path) => Directory.Exists(path); /// <summary> /// Determines whether the specified path string is valid (does not contain invalid characters). /// </summary> /// <param name="path">The path.</param> /// <returns> /// <c>true</c> if the path is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValidPath(this string path) => path.IndexOfAny(Path.GetInvalidPathChars()) == -1; /// <summary> /// A more convenient API version of <see cref="Path.Combine(string[])"/>. /// </summary> /// <param name="path">The path.</param> /// <param name="parts">The parts.</param> /// <returns>A new path.</returns> public static string PathJoin(this string path, params object[] parts) { var allParts = new[] { path ?? "" }.Concat(parts.Select(x => x?.ToString() ?? "")); return Path.Combine(allParts.ToArray()); } /// <summary> /// Gets the special folder path. /// </summary> /// <param name="folder">The folder.</param> /// <returns>A folder path.</returns> public static string GetPath(this Environment.SpecialFolder folder) { return Environment.GetFolderPath(folder); } internal static bool IsWritable(this string path) { var testFile = path.PathJoin(Guid.NewGuid().ToString()); try { File.WriteAllText(testFile, ""); return true; } catch { return false; } finally { try { testFile.DeleteIfExists(); } catch { } } } internal static string DeleteIfExists(this string path, bool recursive = false) { if (Directory.Exists(path)) Directory.Delete(path, recursive); else if (File.Exists(path)) File.Delete(path); return path; } /// <summary> /// Ensures the directory exists. /// </summary> /// <param name="path">The path.</param> /// <param name="rethrow">if set to <c>true</c> [rethrow].</param> /// <returns>Path of the created/existing directory </returns> public static string EnsureDir(this string path, bool rethrow = true) { try { Directory.CreateDirectory(path); return path; } catch { if (rethrow) throw; } return null; } /// <summary> /// Ensures the parent directory of the file exists. /// </summary> /// <param name="file">The file path.</param> /// <param name="rethrow">if set to <c>true</c> [rethrow].</param> /// <returns>Path of the file</returns> public static string EnsureFileDir(this string file, bool rethrow = true) { try { file.GetDirName().EnsureDir(); return file; } catch { if (rethrow) throw; } return null; } /// <summary> /// Deletes the directory and its all content. /// </summary> /// <param name="path">The path.</param> /// <param name="handleExceptions">if set to <c>true</c> [handle exceptions].</param> /// <returns>The original directory path</returns> public static string DeleteDir(this string path, bool handleExceptions = false) { if (Directory.Exists(path)) { try { void del_dir(string d) { try { Directory.Delete(d); } catch (Exception) { Thread.Sleep(1); Directory.Delete(d); } } var dirs = new Queue<string>(); dirs.Enqueue(path); while (dirs.Any()) { var dir = dirs.Dequeue(); foreach (var file in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) File.Delete(file); Directory.GetDirectories(dir, "*", SearchOption.AllDirectories) .ForEach(dirs.Enqueue); } var emptyDirs = Directory.GetDirectories(path, "*", SearchOption.AllDirectories) .Reverse(); emptyDirs.ForEach(del_dir); del_dir(path); } catch { if (!handleExceptions) throw; } } return path; } /// <summary> /// Checks if the file exists. /// </summary> /// <param name="path">The path.</param> /// <returns>The result of the test.</returns> public static bool FileExists(this string path) { try { return path.IsNotEmpty() ? File.Exists(path) : false; } catch { return false; } } /// <summary> /// Gets the directory name from the path. /// </summary> /// <param name="path">The path.</param> /// <returns>The directory path.</returns> public static string GetDirName(this string path) => path == null ? null : Path.GetDirectoryName(path); /// <summary> /// Changes the name of the file. /// </summary> /// <param name="path">The path.</param> /// <param name="fileName">Name of the file.</param> /// <returns>A new path.</returns> public static string ChangeFileName(this string path, string fileName) => path.GetDirName().PathJoin(fileName); /// <summary> /// Gets the file name without the extension. /// </summary> /// <param name="path">The path.</param> /// <returns>File name</returns> public static string GetFileNameWithoutExtension(this string path) => Path.GetFileNameWithoutExtension(path); /// <summary> /// Normalizes directory separators in the given path by ensuring the separators are compatible with the target file system. /// </summary> /// <param name="path">The path.</param> /// <returns>A new normalized path.</returns> public static string PathNormaliseSeparators(this string path) { return path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } /// <summary> /// Gets the subdirectories of the specified directory path. /// </summary> /// <param name="path">The path.</param> /// <param name="mask">The mask.</param> /// <returns>A list of the discovered directories.</returns> public static string[] PathGetDirs(this string path, string mask) { return Directory.GetDirectories(path, mask); } #if !class_lib public static bool IsDirSectionSeparator(this string text) { return text != null && text.StartsWith(csscript.Settings.dirs_section_prefix) && text.StartsWith(csscript.Settings.dirs_section_suffix); } #endif } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; namespace ClosedXML.Excel.Drawings { [DebuggerDisplay("{Name}")] internal class XLPicture : IXLPicture { private static IDictionary<XLPictureFormat, ImageFormat> FormatMap; private readonly IXLWorksheet _worksheet; private Int32 height; private Int32 width; static XLPicture() { var properties = typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public); FormatMap = Enum.GetValues(typeof(XLPictureFormat)) .Cast<XLPictureFormat>() .Where(pf => properties.Any(pi => pi.Name.Equals(pf.ToString(), StringComparison.OrdinalIgnoreCase))) .ToDictionary( pf => pf, pf => properties.Single(pi => pi.Name.Equals(pf.ToString(), StringComparison.OrdinalIgnoreCase)).GetValue(null, null) as ImageFormat ); } internal XLPicture(IXLWorksheet worksheet, Stream stream) : this(worksheet) { if (stream == null) throw new ArgumentNullException(nameof(stream)); this.ImageStream = new MemoryStream(); { stream.Position = 0; stream.CopyTo(ImageStream); ImageStream.Seek(0, SeekOrigin.Begin); using (var bitmap = new Bitmap(ImageStream)) { if (FormatMap.Values.Select(f => f.Guid).Contains(bitmap.RawFormat.Guid)) this.Format = FormatMap.Single(f => f.Value.Guid.Equals(bitmap.RawFormat.Guid)).Key; DeduceDimensionsFromBitmap(bitmap); } ImageStream.Seek(0, SeekOrigin.Begin); } } internal XLPicture(IXLWorksheet worksheet, Stream stream, XLPictureFormat format) : this(worksheet) { if (stream == null) throw new ArgumentNullException(nameof(stream)); this.Format = format; this.ImageStream = new MemoryStream(); { stream.Position = 0; stream.CopyTo(ImageStream); ImageStream.Seek(0, SeekOrigin.Begin); using (var bitmap = new Bitmap(ImageStream)) { if (FormatMap.ContainsKey(this.Format)) { if (FormatMap[this.Format].Guid != bitmap.RawFormat.Guid) throw new ArgumentException("The picture format in the stream and the parameter don't match"); } DeduceDimensionsFromBitmap(bitmap); } ImageStream.Seek(0, SeekOrigin.Begin); } } internal XLPicture(IXLWorksheet worksheet, Bitmap bitmap) : this(worksheet) { if (bitmap == null) throw new ArgumentNullException(nameof(bitmap)); this.ImageStream = new MemoryStream(); bitmap.Save(ImageStream, bitmap.RawFormat); ImageStream.Seek(0, SeekOrigin.Begin); DeduceDimensionsFromBitmap(bitmap); var formats = FormatMap.Where(f => f.Value.Guid.Equals(bitmap.RawFormat.Guid)); if (!formats.Any() || formats.Count() > 1) throw new ArgumentException("Unsupported or unknown image format in bitmap"); this.Format = formats.Single().Key; } private XLPicture(IXLWorksheet worksheet) { if (worksheet == null) throw new ArgumentNullException(nameof(worksheet)); this._worksheet = worksheet; this.Placement = XLPicturePlacement.MoveAndSize; this.Markers = new Dictionary<XLMarkerPosition, IXLMarker>() { [XLMarkerPosition.TopLeft] = null, [XLMarkerPosition.BottomRight] = null }; } public IXLAddress BottomRightCellAddress { get { return Markers[XLMarkerPosition.BottomRight].Address; } private set { if (!value.Worksheet.Equals(this._worksheet)) throw new ArgumentOutOfRangeException(nameof(value.Worksheet)); this.Markers[XLMarkerPosition.BottomRight] = new XLMarker(value); } } public XLPictureFormat Format { get; private set; } public Int32 Height { get { return height; } set { if (this.Placement == XLPicturePlacement.MoveAndSize) throw new ArgumentException("To set the height, the placement should be FreeFloating or Move"); height = value; } } public MemoryStream ImageStream { get; private set; } public Int32 Left { get { return Markers[XLMarkerPosition.TopLeft]?.Offset.X ?? 0; } set { if (this.Placement != XLPicturePlacement.FreeFloating) throw new ArgumentException("To set the left-hand offset, the placement should be FreeFloating"); Markers[XLMarkerPosition.TopLeft] = new XLMarker(_worksheet.Cell(1, 1).Address, new Point(value, this.Top)); } } public String Name { get; set; } public Int32 OriginalHeight { get; private set; } public Int32 OriginalWidth { get; private set; } public XLPicturePlacement Placement { get; set; } public Int32 Top { get { return Markers[XLMarkerPosition.TopLeft]?.Offset.Y ?? 0; } set { if (this.Placement != XLPicturePlacement.FreeFloating) throw new ArgumentException("To set the top offset, the placement should be FreeFloating"); Markers[XLMarkerPosition.TopLeft] = new XLMarker(_worksheet.Cell(1, 1).Address, new Point(this.Left, value)); } } public IXLAddress TopLeftCellAddress { get { return Markers[XLMarkerPosition.TopLeft].Address; } private set { if (!value.Worksheet.Equals(this._worksheet)) throw new ArgumentOutOfRangeException(nameof(value.Worksheet)); this.Markers[XLMarkerPosition.TopLeft] = new XLMarker(value); } } public Int32 Width { get { return width; } set { if (this.Placement == XLPicturePlacement.MoveAndSize) throw new ArgumentException("To set the width, the placement should be FreeFloating or Move"); width = value; } } public IXLWorksheet Worksheet { get { return _worksheet; } } internal IDictionary<XLMarkerPosition, IXLMarker> Markers { get; private set; } internal String RelId { get; set; } public void Dispose() { this.ImageStream.Dispose(); } public Point GetOffset(XLMarkerPosition position) { return Markers[position].Offset; } public IXLPicture MoveTo(Int32 left, Int32 top) { this.Placement = XLPicturePlacement.FreeFloating; this.Left = left; this.Top = top; return this; } public IXLPicture MoveTo(IXLAddress cell) { return MoveTo(cell, 0, 0); } public IXLPicture MoveTo(IXLAddress cell, Int32 xOffset, Int32 yOffset) { return MoveTo(cell, new Point(xOffset, yOffset)); } public IXLPicture MoveTo(IXLAddress cell, Point offset) { if (cell == null) throw new ArgumentNullException(nameof(cell)); this.Placement = XLPicturePlacement.Move; this.TopLeftCellAddress = cell; this.Markers[XLMarkerPosition.TopLeft].Offset = offset; return this; } public IXLPicture MoveTo(IXLAddress fromCell, IXLAddress toCell) { return MoveTo(fromCell, 0, 0, toCell, 0, 0); } public IXLPicture MoveTo(IXLAddress fromCell, Int32 fromCellXOffset, Int32 fromCellYOffset, IXLAddress toCell, Int32 toCellXOffset, Int32 toCellYOffset) { return MoveTo(fromCell, new Point(fromCellXOffset, fromCellYOffset), toCell, new Point(toCellXOffset, toCellYOffset)); } public IXLPicture MoveTo(IXLAddress fromCell, Point fromOffset, IXLAddress toCell, Point toOffset) { if (fromCell == null) throw new ArgumentNullException(nameof(fromCell)); if (toCell == null) throw new ArgumentNullException(nameof(toCell)); this.Placement = XLPicturePlacement.MoveAndSize; this.TopLeftCellAddress = fromCell; this.Markers[XLMarkerPosition.TopLeft].Offset = fromOffset; this.BottomRightCellAddress = toCell; this.Markers[XLMarkerPosition.BottomRight].Offset = toOffset; return this; } public IXLPicture Scale(Double factor, Boolean relativeToOriginal = false) { return this.ScaleHeight(factor, relativeToOriginal).ScaleWidth(factor, relativeToOriginal); } public IXLPicture ScaleHeight(Double factor, Boolean relativeToOriginal = false) { this.Height = Convert.ToInt32((relativeToOriginal ? this.OriginalHeight : this.Height) * factor); return this; } public IXLPicture ScaleWidth(Double factor, Boolean relativeToOriginal = false) { this.Width = Convert.ToInt32((relativeToOriginal ? this.OriginalWidth : this.Width) * factor); return this; } public IXLPicture WithPlacement(XLPicturePlacement value) { this.Placement = value; return this; } public IXLPicture WithSize(Int32 width, Int32 height) { this.Width = width; this.Height = height; return this; } private static ImageFormat FromMimeType(string mimeType) { var guid = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))?.FormatID; if (!guid.HasValue) return null; var property = typeof(System.Drawing.Imaging.ImageFormat).GetProperties(BindingFlags.Public | BindingFlags.Static) .FirstOrDefault(pi => (pi.GetValue(null, null) as ImageFormat).Guid.Equals(guid.Value)); if (property == null) return null; return (property.GetValue(null, null) as ImageFormat); } private static string GetMimeType(Image i) { var imgguid = i.RawFormat.Guid; foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders()) { if (codec.FormatID == imgguid) return codec.MimeType; } return "image/unknown"; } private void DeduceDimensionsFromBitmap(Bitmap bitmap) { this.OriginalWidth = bitmap.Width; this.OriginalHeight = bitmap.Height; this.width = bitmap.Width; this.height = bitmap.Height; } } }
// 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 Microsoft.Build.Framework; using Newtonsoft.Json; using NuGet.RuntimeModel; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class GenerateRuntimeGraph : PackagingTask { /// <summary> /// A set of RuntimeGroups that can be used to generate a runtime graph /// Identity: the base string for the RID, without version architecture, or qualifiers. /// Parent: the base string for the parent of this RID. This RID will be imported by the baseRID, architecture-specific, /// and qualifier-specific RIDs (with the latter two appending appropriate architecture and qualifiers). /// Versions: A list of strings delimited by semi-colons that represent the versions for this RID. /// TreatVersionsAsCompatible: Default is true. When true, version-specific RIDs will import the previous /// version-specific RID in the Versions list, with the first version importing the version-less RID. /// When false all version-specific RIDs will import the version-less RID (bypassing previous version-specific RIDs) /// OmitVersionDelimiter: Default is false. When true no characters will separate the base RID and version (EG: win7). /// When false a '.' will separate the base RID and version (EG: osx.10.12). /// ApplyVersionsToParent: Default is false. When true, version-specific RIDs will import version-specific Parent RIDs /// similar to is done for architecture and qualifier (see Parent above). /// Architectures: A list of strings delimited by semi-colons that represent the architectures for this RID. /// AdditionalQualifiers: A list of strings delimited by semi-colons that represent the additional qualifiers for this RID. /// Additional qualifers do not stack, each only applies to the qualifier-less RIDs (so as not to cause combinatorial /// exponential growth of RIDs). /// /// The following options can be used under special circumstances but break the normal precedence rules we try to establish /// by generating the RID graph from common logic. These options make it possible to create a RID fallback chain that doesn't /// match the rest of the RIDs and therefore is hard for developers/package authors to reason about. /// Only use these options for cases where you know what you are doing and have carefully reviewed the resulting RID fallbacks /// using the CompatibliltyMap. /// OmitRIDs: A list of strings delimited by semi-colons that represent RIDs calculated from this RuntimeGroup that should /// be omitted from the RuntimeGraph. These RIDs will not be referenced nor defined. /// OmitRIDDefinitions: A list of strings delimited by semi-colons that represent RIDs calculated from this RuntimeGroup /// that should be omitted from the RuntimeGraph. These RIDs will not be defined by this RuntimeGroup, but will be /// referenced: useful in case some other RuntimeGroup (or runtime.json template) defines them. /// OmitRIDReferences: A list of strings delimited by semi-colons that represent RIDs calculated from this RuntimeGroup /// that should be omitted from the RuntimeGraph. These RIDs will be defined but not referenced by this RuntimeGroup. /// </summary> public ITaskItem[] RuntimeGroups { get; set; } /// <summary> /// Optional source Runtime.json to use as a starting point when merging additional RuntimeGroups /// </summary> public string SourceRuntimeJson { get; set; } /// <summary> /// Where to write the final runtime.json /// </summary> public string RuntimeJson { get; set; } /// <summary> /// When defined, specifies the file to write compatibility precedence for each RID in the graph. /// </summary> public string CompatibilityMap { get; set; } /// <summary> /// True to write the generated runtime.json to RuntimeJson and compatibility map to CompatibilityMap, otherwise files are read and diffed /// with generated versions and an error is emitted if they differ. /// Setting UpdateRuntimeFiles will overwrite files even when the file is marked ReadOnly. /// </summary> public bool UpdateRuntimeFiles { get; set; } /// <summary> /// When defined, specifies the file to write a DGML representation of the runtime graph. /// </summary> public string RuntimeDirectedGraph { get; set; } public override bool Execute() { if (RuntimeGroups != null && RuntimeGroups.Any() && RuntimeJson == null) { Log.LogError($"{nameof(RuntimeJson)} argument must be specified when {nameof(RuntimeGroups)} is specified."); return false; } RuntimeGraph runtimeGraph; if (!String.IsNullOrEmpty(SourceRuntimeJson)) { if (!File.Exists(SourceRuntimeJson)) { Log.LogError($"{nameof(SourceRuntimeJson)} did not exist at {SourceRuntimeJson}."); return false; } runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(SourceRuntimeJson); } else { runtimeGraph = new RuntimeGraph(); } foreach (var runtimeGroup in RuntimeGroups.NullAsEmpty().Select(i => new RuntimeGroup(i))) { runtimeGraph = SafeMerge(runtimeGraph, runtimeGroup); } ValidateImports(runtimeGraph); if (!String.IsNullOrEmpty(RuntimeJson)) { if (UpdateRuntimeFiles) { EnsureWritable(RuntimeJson); JsonRuntimeFormat.WriteRuntimeGraph(RuntimeJson, runtimeGraph); } else { // validate that existing file matches generated file if (!File.Exists(RuntimeJson)) { Log.LogError($"{nameof(RuntimeJson)} did not exist at {RuntimeJson} and {nameof(UpdateRuntimeFiles)} was not specified."); } else { var existingRuntimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(RuntimeJson); if (!existingRuntimeGraph.Equals(runtimeGraph)) { Log.LogError($"The generated {nameof(RuntimeJson)} differs from {RuntimeJson} and {nameof(UpdateRuntimeFiles)} was not specified. Please specify {nameof(UpdateRuntimeFiles)}=true to commit the changes."); } } } } if (!String.IsNullOrEmpty(CompatibilityMap)) { var compatibilityMap = GetCompatibilityMap(runtimeGraph); if (UpdateRuntimeFiles) { EnsureWritable(CompatibilityMap); WriteCompatibilityMap(compatibilityMap, CompatibilityMap); } else { // validate that existing file matches generated file if (!File.Exists(CompatibilityMap)) { Log.LogError($"{nameof(CompatibilityMap)} did not exist at {CompatibilityMap} and {nameof(UpdateRuntimeFiles)} was not specified."); } else { var existingCompatibilityMap = ReadCompatibilityMap(CompatibilityMap); if (!CompatibilityMapEquals(existingCompatibilityMap, compatibilityMap)) { Log.LogError($"The generated {nameof(CompatibilityMap)} differs from {CompatibilityMap} and {nameof(UpdateRuntimeFiles)} was not specified. Please specify {nameof(UpdateRuntimeFiles)}=true to commit the changes."); } } } } if (!String.IsNullOrEmpty(RuntimeDirectedGraph)) { WriteRuntimeGraph(runtimeGraph, RuntimeDirectedGraph); } return !Log.HasLoggedErrors; } private void EnsureWritable(string file) { if (File.Exists(file)) { var existingAttributes = File.GetAttributes(file); if ((existingAttributes & FileAttributes.ReadOnly) != 0) { File.SetAttributes(file, existingAttributes &= ~FileAttributes.ReadOnly); } } } private RuntimeGraph SafeMerge(RuntimeGraph existingGraph, RuntimeGroup runtimeGroup) { var runtimeGraph = runtimeGroup.GetRuntimeGraph(); foreach (var existingRuntimeDescription in existingGraph.Runtimes.Values) { RuntimeDescription newRuntimeDescription; if (runtimeGraph.Runtimes.TryGetValue(existingRuntimeDescription.RuntimeIdentifier, out newRuntimeDescription)) { // overlapping RID, ensure that the imports match (same ordering and content) if (!existingRuntimeDescription.InheritedRuntimes.SequenceEqual(newRuntimeDescription.InheritedRuntimes)) { Log.LogError($"RuntimeGroup {runtimeGroup.BaseRID} defines RID {newRuntimeDescription.RuntimeIdentifier} with imports {String.Join(";", newRuntimeDescription.InheritedRuntimes)} which differ from existing imports {String.Join(";", existingRuntimeDescription.InheritedRuntimes)}. You may avoid this by specifying {nameof(RuntimeGroup.OmitRIDDefinitions)} metadata with {newRuntimeDescription.RuntimeIdentifier}."); } } } return RuntimeGraph.Merge(existingGraph, runtimeGraph); } private void ValidateImports(RuntimeGraph runtimeGraph) { foreach (var runtimeDescription in runtimeGraph.Runtimes.Values) { foreach (var import in runtimeDescription.InheritedRuntimes) { if (!runtimeGraph.Runtimes.ContainsKey(import)) { Log.LogError($"Runtime {runtimeDescription.RuntimeIdentifier} imports {import} which is not defined."); } } } } class RuntimeGroup { private const string rootRID = "any"; private const char VersionDelimiter = '.'; private const char ArchitectureDelimiter = '-'; private const char QualifierDelimiter = '-'; public RuntimeGroup(ITaskItem item) { BaseRID = item.ItemSpec; Parent = item.GetString(nameof(Parent)); Versions = item.GetStrings(nameof(Versions)); TreatVersionsAsCompatible = item.GetBoolean(nameof(TreatVersionsAsCompatible), true); OmitVersionDelimiter = item.GetBoolean(nameof(OmitVersionDelimiter)); ApplyVersionsToParent = item.GetBoolean(nameof(ApplyVersionsToParent)); Architectures = item.GetStrings(nameof(Architectures)); AdditionalQualifiers = item.GetStrings(nameof(AdditionalQualifiers)); OmitRIDs = new HashSet<string>(item.GetStrings(nameof(OmitRIDs))); OmitRIDDefinitions = new HashSet<string>(item.GetStrings(nameof(OmitRIDDefinitions))); OmitRIDReferences = new HashSet<string>(item.GetStrings(nameof(OmitRIDReferences))); } public string BaseRID { get; } public string Parent { get; } public IEnumerable<string> Versions { get; } public bool TreatVersionsAsCompatible { get; } public bool OmitVersionDelimiter { get; } public bool ApplyVersionsToParent { get; } public IEnumerable<string> Architectures { get; } public IEnumerable<string> AdditionalQualifiers { get; } public ICollection<string> OmitRIDs { get; } public ICollection<string> OmitRIDDefinitions { get; } public ICollection<string> OmitRIDReferences { get; } private class RIDMapping { public RIDMapping(RID runtimeIdentifier) { RuntimeIdentifier = runtimeIdentifier; Imports = Enumerable.Empty<RID>(); } public RIDMapping(RID runtimeIdentifier, IEnumerable<RID> imports) { RuntimeIdentifier = runtimeIdentifier; Imports = imports; } public RID RuntimeIdentifier { get; } public IEnumerable<RID> Imports { get; } } private class RID { public string BaseRID { get; set; } public string VersionDelimiter { get; set; } public string Version { get; set; } public string ArchitectureDelimiter { get; set; } public string Architecture { get; set; } public string QualifierDelimiter { get; set; } public string Qualifier { get; set; } public override string ToString() { StringBuilder builder = new StringBuilder(BaseRID); if (HasVersion()) { builder.Append(VersionDelimiter); builder.Append(Version); } if (HasArchitecture()) { builder.Append(ArchitectureDelimiter); builder.Append(Architecture); } if (HasQualifier()) { builder.Append(QualifierDelimiter); builder.Append(Qualifier); } return builder.ToString(); } public bool HasVersion() { return Version != null; } public bool HasArchitecture() { return Architecture != null; } public bool HasQualifier() { return Qualifier != null; } } private RID CreateRuntime(string baseRid, string version = null, string architecture = null, string qualifier = null) { return new RID() { BaseRID = baseRid, VersionDelimiter = OmitVersionDelimiter ? String.Empty : VersionDelimiter.ToString(), Version = version, ArchitectureDelimiter = ArchitectureDelimiter.ToString(), Architecture = architecture, QualifierDelimiter = QualifierDelimiter.ToString(), Qualifier = qualifier }; } private IEnumerable<RIDMapping> GetRIDMappings() { // base => // Parent yield return Parent == null ? new RIDMapping(CreateRuntime(BaseRID)) : new RIDMapping(CreateRuntime(BaseRID), new[] { CreateRuntime(Parent) }); foreach (var architecture in Architectures) { // base + arch => // base, // parent + arch var imports = new List<RID>() { CreateRuntime(BaseRID) }; if (!IsNullOrRoot(Parent)) { imports.Add(CreateRuntime(Parent, architecture: architecture)); } yield return new RIDMapping(CreateRuntime(BaseRID, architecture: architecture), imports); } string lastVersion = null; foreach (var version in Versions) { // base + version => // base + lastVersion, // parent + version (optionally) var imports = new List<RID>() { CreateRuntime(BaseRID, version: lastVersion) }; if (ApplyVersionsToParent) { imports.Add(CreateRuntime(Parent, version: version)); } yield return new RIDMapping(CreateRuntime(BaseRID, version: version), imports); foreach (var architecture in Architectures) { // base + version + architecture => // base + version, // base + lastVersion + architecture, // parent + version + architecture (optionally) var archImports = new List<RID>() { CreateRuntime(BaseRID, version: version), CreateRuntime(BaseRID, version: lastVersion, architecture: architecture) }; if (ApplyVersionsToParent) { archImports.Add(CreateRuntime(Parent, version: version, architecture: architecture)); } yield return new RIDMapping(CreateRuntime(BaseRID, version: version, architecture: architecture), archImports); } if (TreatVersionsAsCompatible) { lastVersion = version; } } foreach (var qualifier in AdditionalQualifiers) { // base + qual => // base, // parent + qual yield return new RIDMapping(CreateRuntime(BaseRID, qualifier: qualifier), new[] { CreateRuntime(BaseRID), IsNullOrRoot(Parent) ? CreateRuntime(qualifier) : CreateRuntime(Parent, qualifier:qualifier) }); foreach (var architecture in Architectures) { // base + arch + qualifier => // base + qualifier, // base + arch // parent + arch + qualifier var imports = new List<RID>() { CreateRuntime(BaseRID, qualifier: qualifier), CreateRuntime(BaseRID, architecture: architecture) }; if (!IsNullOrRoot(Parent)) { imports.Add(CreateRuntime(Parent, architecture: architecture, qualifier: qualifier)); } yield return new RIDMapping(CreateRuntime(BaseRID, architecture: architecture, qualifier: qualifier), imports); } lastVersion = null; foreach (var version in Versions) { // base + version + qualifier => // base + version, // base + lastVersion + qualifier // parent + version + qualifier (optionally) var imports = new List<RID>() { CreateRuntime(BaseRID, version: version), CreateRuntime(BaseRID, version: lastVersion, qualifier: qualifier) }; if (ApplyVersionsToParent) { imports.Add(CreateRuntime(Parent, version: version, qualifier: qualifier)); } yield return new RIDMapping(CreateRuntime(BaseRID, version: version, qualifier: qualifier), imports); foreach (var architecture in Architectures) { // base + version + architecture + qualifier => // base + version + qualifier, // base + version + architecture, // base + version, // base + lastVersion + architecture + qualifier, // parent + version + architecture + qualifier (optionally) var archImports = new List<RID>() { CreateRuntime(BaseRID, version: version, qualifier: qualifier), CreateRuntime(BaseRID, version: version, architecture: architecture), CreateRuntime(BaseRID, version: version), CreateRuntime(BaseRID, version: lastVersion, architecture: architecture, qualifier: qualifier) }; if (ApplyVersionsToParent) { imports.Add(CreateRuntime(Parent, version: version, architecture: architecture, qualifier: qualifier)); } yield return new RIDMapping(CreateRuntime(BaseRID, version: version, architecture: architecture, qualifier: qualifier), archImports); } if (TreatVersionsAsCompatible) { lastVersion = version; } } } } private bool IsNullOrRoot(string rid) { return rid == null || rid == rootRID; } public IEnumerable<RuntimeDescription> GetRuntimeDescriptions() { foreach (var mapping in GetRIDMappings()) { var rid = mapping.RuntimeIdentifier.ToString(); if (OmitRIDs.Contains(rid) || OmitRIDDefinitions.Contains(rid)) { continue; } var imports = mapping.Imports .Select(i => i.ToString()) .Where(i => !OmitRIDs.Contains(i) && !OmitRIDReferences.Contains(i)) .ToArray(); yield return new RuntimeDescription(rid, imports); } } public RuntimeGraph GetRuntimeGraph() { return new RuntimeGraph(GetRuntimeDescriptions()); } } private static IDictionary<string, IEnumerable<string>> GetCompatibilityMap(RuntimeGraph graph) { Dictionary<string, IEnumerable<string>> compatibilityMap = new Dictionary<string, IEnumerable<string>>(); foreach (var rid in graph.Runtimes.Keys.OrderBy(rid => rid, StringComparer.Ordinal)) { compatibilityMap.Add(rid, graph.ExpandRuntime(rid)); } return compatibilityMap; } private static IDictionary<string, IEnumerable<string>> ReadCompatibilityMap(string mapFile) { var serializer = new JsonSerializer(); using (var file = File.OpenText(mapFile)) using (var jsonTextReader = new JsonTextReader(file)) { return serializer.Deserialize<IDictionary<string, IEnumerable<string>>>(jsonTextReader); } } private static void WriteCompatibilityMap(IDictionary<string, IEnumerable<string>> compatibilityMap, string mapFile) { var serializer = new JsonSerializer() { Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string directory = Path.GetDirectoryName(mapFile); if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (var file = File.CreateText(mapFile)) { serializer.Serialize(file, compatibilityMap); } } private static bool CompatibilityMapEquals(IDictionary<string, IEnumerable<string>> left, IDictionary<string, IEnumerable<string>> right) { if (left.Count != right.Count) { return false; } foreach (var leftPair in left) { IEnumerable<string> rightValue; if (!right.TryGetValue(leftPair.Key, out rightValue)) { return false; } if (!rightValue.SequenceEqual(leftPair.Value)) { return false; } } return true; } private static XNamespace s_dgmlns = @"http://schemas.microsoft.com/vs/2009/dgml"; private static void WriteRuntimeGraph(RuntimeGraph graph, string dependencyGraphFilePath) { var doc = new XDocument(new XElement(s_dgmlns + "DirectedGraph")); var nodesElement = new XElement(s_dgmlns + "Nodes"); var linksElement = new XElement(s_dgmlns + "Links"); doc.Root.Add(nodesElement); doc.Root.Add(linksElement); var nodeIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var runtimeDescription in graph.Runtimes.Values) { nodesElement.Add(new XElement(s_dgmlns + "Node", new XAttribute("Id", runtimeDescription.RuntimeIdentifier))); foreach (var import in runtimeDescription.InheritedRuntimes) { linksElement.Add(new XElement(s_dgmlns + "Link", new XAttribute("Source", runtimeDescription.RuntimeIdentifier), new XAttribute("Target", import))); } } using (var file = File.Create(dependencyGraphFilePath)) { doc.Save(file); } } } }
// 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 Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class LoadFromFileTests { [Fact] public static void TestIssuer() { using (X509Certificate2 c = LoadCertificateFromFile()) { string issuer = c.Issuer; Assert.Equal( "CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", issuer); } } [Fact] public static void TestSubject() { using (X509Certificate2 c = LoadCertificateFromFile()) { string subject = c.Subject; Assert.Equal( "CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", subject); } } [Fact] public static void TestSerial() { string expectedSerialHex = "33000000B011AF0A8BD03B9FDD0001000000B0"; byte[] expectedSerial = "B00000000100DD9F3BD08B0AAF11B000000033".HexToByteArray(); using (X509Certificate2 c = LoadCertificateFromFile()) { byte[] serial = c.GetSerialNumber(); Assert.Equal(expectedSerial, serial); string serialHex = c.GetSerialNumberString(); Assert.Equal(expectedSerialHex, serialHex); serialHex = c.SerialNumber; Assert.Equal(expectedSerialHex, serialHex); } } [Fact] public static void TestThumbprint() { string expectedThumbPrintHex = "108E2BA23632620C427C570B6D9DB51AC31387FE"; byte[] expectedThumbPrint = expectedThumbPrintHex.HexToByteArray(); using (X509Certificate2 c = LoadCertificateFromFile()) { byte[] thumbPrint = c.GetCertHash(); Assert.Equal(expectedThumbPrint, thumbPrint); string thumbPrintHex = c.GetCertHashString(); Assert.Equal(expectedThumbPrintHex, thumbPrintHex); } } #if HAVE_THUMBPRINT_OVERLOADS [Theory] [InlineData("SHA1", false)] [InlineData("SHA1", true)] [InlineData("SHA256", false)] [InlineData("SHA256", true)] [InlineData("SHA384", false)] [InlineData("SHA384", true)] [InlineData("SHA512", false)] [InlineData("SHA512", true)] public static void TestThumbprint(string hashAlgName, bool viaSpan) { string expectedThumbprintHex; switch (hashAlgName) { case "SHA1": expectedThumbprintHex = "108E2BA23632620C427C570B6D9DB51AC31387FE"; break; case "SHA256": expectedThumbprintHex = "73FCF982974387FB164C91D0168FE8C3B957DE6526AE239AAD32825C5A63D2A4"; break; case "SHA384": expectedThumbprintHex = "E6DCEF0840DAB43E1DBE9BE23142182BD05106AB25F7043BDE6A551928DFB4C7082791B86A5FB5E77B0F43DD92B7A3E5"; break; case "SHA512": expectedThumbprintHex = "8435635A12915A1A9C28BC2BCE7C3CAD08EB723FE276F13CD37D1C3B21416994" + "0661A27B419882DBA643B23A557CA9EBC03ACC3D7EE3D4D591AB4BA0E553B945"; break; default: throw new ArgumentOutOfRangeException(nameof(hashAlgName)); } HashAlgorithmName alg = new HashAlgorithmName(hashAlgName); using (X509Certificate2 c = LoadCertificateFromFile()) { if (viaSpan) { const int WriteOffset = 3; const byte FillByte = 0x55; int expectedSize = expectedThumbprintHex.Length / 2; byte[] thumbPrint = new byte[expectedSize + 10]; thumbPrint.AsSpan().Fill(FillByte); Span<byte> writeDest = thumbPrint.AsSpan(WriteOffset); int bytesWritten; // Too small. Assert.False(c.TryGetCertHash(alg, writeDest.Slice(0, expectedSize - 1), out bytesWritten)); Assert.Equal(0, bytesWritten); // Still all 0x55s. Assert.Equal(new string('5', thumbPrint.Length * 2), thumbPrint.ByteArrayToHex()); // Large enough (+7) Assert.True(c.TryGetCertHash(alg, writeDest, out bytesWritten)); Assert.Equal(expectedSize, bytesWritten); Assert.Equal(expectedThumbprintHex, writeDest.Slice(0, bytesWritten).ByteArrayToHex()); Assert.Equal(FillByte, thumbPrint[expectedSize + WriteOffset]); // Try again with a perfectly sized value thumbPrint.AsSpan().Fill(FillByte); Assert.True(c.TryGetCertHash(alg, writeDest.Slice(0, expectedSize), out bytesWritten)); Assert.Equal(expectedSize, bytesWritten); Assert.Equal(expectedThumbprintHex, writeDest.Slice(0, bytesWritten).ByteArrayToHex()); Assert.Equal(FillByte, thumbPrint[expectedSize + WriteOffset]); } else { byte[] thumbPrint = c.GetCertHash(alg); Assert.Equal(expectedThumbprintHex, thumbPrint.ByteArrayToHex()); string thumbPrintHex = c.GetCertHashString(alg); Assert.Equal(expectedThumbprintHex, thumbPrintHex); } } } #endif [Fact] public static void TestGetFormat() { using (X509Certificate2 c = LoadCertificateFromFile()) { string format = c.GetFormat(); Assert.Equal("X509", format); // Only one format is supported so this is very predictable api... } } [Fact] public static void TestGetKeyAlgorithm() { using (X509Certificate2 c = LoadCertificateFromFile()) { string keyAlgorithm = c.GetKeyAlgorithm(); Assert.Equal("1.2.840.113549.1.1.1", keyAlgorithm); } } [Fact] public static void TestGetKeyAlgorithmParameters() { string expected = "0500"; using (X509Certificate2 c = LoadCertificateFromFile()) { byte[] keyAlgorithmParameters = c.GetKeyAlgorithmParameters(); Assert.Equal(expected.HexToByteArray(), keyAlgorithmParameters); string keyAlgorithmParametersString = c.GetKeyAlgorithmParametersString(); Assert.Equal(expected, keyAlgorithmParametersString); } } [Fact] public static void TestGetPublicKey() { string expectedPublicKeyHex = "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001"; byte[] expectedPublicKey = expectedPublicKeyHex.HexToByteArray(); using (X509Certificate2 c = LoadCertificateFromFile()) { byte[] publicKey = c.GetPublicKey(); Assert.Equal(expectedPublicKey, publicKey); string publicKeyHex = c.GetPublicKeyString(); Assert.Equal(expectedPublicKeyHex, publicKeyHex, true); } } [Fact] [ActiveIssue(2910, TestPlatforms.AnyUnix)] public static void TestLoadSignedFile() { // X509Certificate2 can also extract the certificate from a signed file. string path = Path.Combine("TestData", "Windows6.1-KB3004361-x64.msu"); if (!File.Exists(path)) throw new Exception(string.Format("Test infrastructure failure: Expected to find file \"{0}\".", path)); using (X509Certificate2 c = new X509Certificate2(path)) { string issuer = c.Issuer; Assert.Equal( "CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", issuer); #pragma warning disable 0618 Assert.Equal( "C=US, S=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Code Signing PCA", c.GetIssuerName()); #pragma warning restore 0618 string subject = c.Subject; Assert.Equal( "CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US", subject); #pragma warning disable 0618 Assert.Equal( "C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=MOPR, CN=Microsoft Corporation", c.GetName()); #pragma warning restore 0618 string expectedThumbprintHash = "67B1757863E3EFF760EA9EBB02849AF07D3A8080"; byte[] expectedThumbprint = expectedThumbprintHash.HexToByteArray(); byte[] actualThumbprint = c.GetCertHash(); Assert.Equal(expectedThumbprint, actualThumbprint); string actualThumbprintHash = c.GetCertHashString(); Assert.Equal(expectedThumbprintHash, actualThumbprintHash); } } private static X509Certificate2 LoadCertificateFromFile() { string path = Path.Combine("TestData", "MS.cer"); if (!File.Exists(path)) throw new Exception(string.Format("Test infrastructure failure: Expected to find file \"{0}\".", path)); byte[] data = File.ReadAllBytes(path); Assert.Equal(TestData.MsCertificate, data); return new X509Certificate2(path); } } }
/// <summary> /// Copyright 2013 The Loon Authors /// Licensed under the Apache License, Version 2.0 (the "License"); you may not /// use this file except in compliance with the License. You may obtain a copy of /// the License at /// http://www.apache.org/licenses/LICENSE-2.0 /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT /// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the /// License for the specific language governing permissions and limitations under /// the License. /// </summary> /// using Loon.Core.Geom; using Loon.Utils; namespace Loon.Physics { public class PBody { internal AABB aabb; internal float ang; internal float angVel; internal float correctAngVel; internal Vector2f correctVel; internal bool fix; internal float i; internal float invI; internal float invM; internal float m; internal PTransformer mAng; internal int numShapes; internal Vector2f pos; internal bool rem; internal PShape[] shapes; internal Vector2f vel; internal PPhysWorld w; internal object tag; public PBody(float angle, bool fixate, PShape[] ss) { pos = new Vector2f(); vel = new Vector2f(); correctVel = new Vector2f(); mAng = new PTransformer(); aabb = new AABB(); ang = angle; numShapes = ss.Length; shapes = new PShape[1024]; for (int i_0 = 0; i_0 < numShapes; i_0++) { shapes[i_0] = ss[i_0]; shapes[i_0]._parent = this; if (shapes[i_0]._type == PShapeType.CONCAVE_SHAPE) { PConcavePolygonShape cp = (PConcavePolygonShape) shapes[i_0]; for (int j = 0; j < cp.numConvexes; j++) { cp.convexes[j]._parent = this; } } } fix = fixate; CalcMassData(); } public void AddShape(PShape s) { if (w != null) { w.AddShape(s); } shapes[numShapes] = s; s._localPos.SubLocal(pos); s._parent = this; if (s._type == PShapeType.CONCAVE_SHAPE) { PConcavePolygonShape cp = (PConcavePolygonShape) s; for (int i_0 = 0; i_0 < cp.numConvexes; i_0++) { cp.convexes[i_0]._parent = this; } } numShapes++; CalcMassData(); } public void ApplyForce(float fx, float fy) { if (fix) { return; } else { vel.x += fx * invM; vel.y += fy * invM; return; } } public void ApplyImpulse(float fx, float fy, float px, float py) { if (fix) { return; } else { vel.x += fx * invM; vel.y += fy * invM; px -= pos.x; py -= pos.y; angVel += (px * fy - py * fx) * invI; return; } } public void ApplyTorque(float torque) { if (fix) { return; } else { angVel += torque * invI; return; } } internal void CalcMassData() { CorrectCenterOfGravity(); if (!fix) { m = i = 0.0F; for (int j = 0; j < numShapes; j++) { m += shapes[j].mm * shapes[j]._dens; i += shapes[j].ii * shapes[j]._dens; i += (shapes[j]._localPos.x * shapes[j]._localPos.x + shapes[j]._localPos.y * shapes[j]._localPos.y) * shapes[j].mm * shapes[j]._dens; } invM = 1.0F / m; invI = 1.0F / i; } else { m = invM = 0.0F; i = invI = 0.0F; } } internal void CorrectCenterOfGravity() { float cy; float cx = cy = 0.0F; float total = 0.0F; for (int j = 0; j < numShapes; j++) { total += shapes[j].mm * shapes[j]._dens; cx += shapes[j]._localPos.x * shapes[j].mm * shapes[j]._dens; cy += shapes[j]._localPos.y * shapes[j].mm * shapes[j]._dens; } if (numShapes > 0) { total = 1.0F / total; cx *= total; cy *= total; } pos.x += cx; pos.y += cy; for (int j_0 = 0; j_0 < numShapes; j_0++) { shapes[j_0]._localPos.x -= cx; shapes[j_0]._localPos.y -= cy; } } public float GetAngularVelocity() { return angVel; } public Vector2f getPosition() { return pos; } public PShape[] GetShapes() { PShape[] result = new PShape[numShapes]; System.Array.Copy((shapes),0,(result),0,numShapes); return result; } public int Size() { return numShapes; } public PShape[] Inner_shapes() { return shapes; } public Vector2f getVelocity() { return vel; } public bool IsFixate() { return fix; } private float Max(float v1, float v2) { return (v1 <= v2) ? v2 : v1; } private float Min(float v1, float v2) { return (v1 >= v2) ? v2 : v1; } internal void PositionCorrection(float torque) { if (fix) { return; } else { correctAngVel += torque * invI; return; } } internal void PositionCorrection(float fx, float fy, float px, float py) { if (fix) { return; } else { correctVel.x += fx * invM; correctVel.y += fy * invM; px -= pos.x; py -= pos.y; correctAngVel += (px * fy - py * fx) * invI; return; } } public void Remove() { this.rem = true; } public void RemoveShape(PShape s) { for (int i_0 = 0; i_0 < numShapes; i_0++) { if (shapes[i_0] != s) { continue; } s._rem = true; s._parent = null; s._localPos.AddLocal(pos); if (i_0 != numShapes - 1) { System.Array.Copy((shapes),i_0 + 1,(shapes),i_0,numShapes - i_0 - 1); } break; } numShapes--; CalcMassData(); } public void SetAngularVelocity(float v) { angVel = v; } public void SetFixate(bool fixate) { if (fix == fixate) { return; } else { fix = fixate; CalcMassData(); return; } } public void SetVelocity(float vx, float vy) { vel.Set(vx, vy); } internal void Update() { float twoPI = MathUtils.TWO_PI; ang = (ang + twoPI) % twoPI; mAng.SetRotate(ang); for (int i_0 = 0; i_0 < numShapes; i_0++) { PShape s = shapes[i_0]; s._pos.Set(s._localPos.x, s._localPos.y); mAng.MulEqual(s._pos); s._pos.AddLocal(pos); s._localAng = (s._localAng + twoPI) % twoPI; s._ang = ang + s._localAng; s._mAng.SetRotate(s._ang); s.Update(); s.CalcAABB(); s._sapAABB.Update(); if (i_0 == 0) { aabb.Set(s._aabb.minX, s._aabb.minY, s._aabb.maxX, s._aabb.maxY); } else { aabb.Set(Min(aabb.minX, s._aabb.minX), Min(aabb.minY, s._aabb.minY), Max(aabb.maxX, s._aabb.maxX), Max(aabb.maxY, s._aabb.maxY)); } } } public object GetTag() { return tag; } public void SetTag(object tag_0) { this.tag = tag_0; } } }
// 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.ComponentModel.Composition; using System.Windows.Media; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.NodejsTools.Repl { [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveErrorFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Error"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveErrorFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xee, 00, 00); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveBlackFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Black"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveBlackFormatDefinition() { DisplayName = Name; ForegroundColor = Colors.Black; } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkRedFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkRed"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkRedFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xd4, 0, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkGreenFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkGreen"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkGreenFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0x8a, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkYellowFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkYellow"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkYellowFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x98, 0x70, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkBlueFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkBlue"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkBlueFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0x57, 0xff); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkMagentaFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkMagenta"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkMagentaFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xbb, 0x00, 0xbb); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkCyanFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkCyan"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkCyanFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0x7f, 0x7f); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveGrayFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Gray"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveGrayFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x76, 0x76, 0x76); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveDarkGrayFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - DarkGray"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveDarkGrayFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x69, 0x69, 0x69); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveRedFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Red"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveRedFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xEE, 0, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveGreenFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Green"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveGreenFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0x80, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveYellowFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Yellow"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveYellowFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xff, 0xff, 0); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] [Order(After = Priority.Default, Before = Priority.High)] internal class InteractiveBlueFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Blue"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveBlueFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0x00, 0xff); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveMagentaFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Magenta"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveMagentaFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xd1, 0x00, 0xd1); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveCyanFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - Cyan"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveCyanFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0x00, 0xff, 0xff); } } [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Name)] [Name(Name)] [UserVisible(true)] internal class InteractiveWhiteFormatDefinition : ClassificationFormatDefinition { public const string Name = "Node.js Interactive - White"; [Export] [Name(Name)] [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] internal static ClassificationTypeDefinition Definition = null; // Set via MEF public InteractiveWhiteFormatDefinition() { DisplayName = Name; ForegroundColor = Color.FromRgb(0xff, 0xff, 0xff); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 #pragma warning disable 56523 using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Globalization; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.PowerShell; using Microsoft.PowerShell.Commands; using DWORD = System.UInt32; namespace Microsoft.PowerShell { /// <summary> /// Defines the different Execution Policies supported by the /// PSAuthorizationManager class. /// </summary> public enum ExecutionPolicy { /// Unrestricted - No files must be signed. If a file originates from the /// internet, Monad provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Unrestricted = 0, /// RemoteSigned - Only .msh and .mshxml files originating from the internet /// must be digitally signed. If remote, signed, and executed, Monad /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. RemoteSigned = 1, /// AllSigned - All .msh and .mshxml files must be digitally signed. If /// signed and executed, Monad prompts to determine if files from the /// signing publisher should be run or not. AllSigned = 2, /// Restricted - All .msh files are blocked. Mshxml files must be digitally /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. Restricted = 3, /// Bypass - No files must be signed, and internet origin is not verified Bypass = 4, /// Undefined - Not specified at this scope Undefined = 5, /// <summary> /// Default - The most restrictive policy available. /// </summary> Default = Restricted } /// <summary> /// Defines the available configuration scopes for an execution /// policy. They are in the following priority, with successive /// elements overriding the items that precede them: /// LocalMachine -> CurrentUser -> Runspace. /// </summary> public enum ExecutionPolicyScope { /// Execution policy is retrieved from the /// PSExecutionPolicyPreference environment variable. Process = 0, /// Execution policy is retrieved from the HKEY_CURRENT_USER /// registry hive for the current ShellId. CurrentUser = 1, /// Execution policy is retrieved from the HKEY_LOCAL_MACHINE /// registry hive for the current ShellId. LocalMachine = 2, /// Execution policy is retrieved from the current user's /// group policy setting. UserPolicy = 3, /// Execution policy is retrieved from the machine-wide /// group policy setting. MachinePolicy = 4 } } namespace System.Management.Automation.Internal { /// <summary> /// The SAFER policy associated with this file. /// </summary> internal enum SaferPolicy { /// Explicitly allowed through an Allow rule ExplicitlyAllowed = 0, /// Allowed because it has not been explicitly disallowed Allowed = 1, /// Disallowed by a rule or policy. Disallowed = 2 } /// <summary> /// Security Support APIs. /// </summary> public static class SecuritySupport { #region execution policy internal static ExecutionPolicyScope[] ExecutionPolicyScopePreferences { get { return new ExecutionPolicyScope[] { ExecutionPolicyScope.MachinePolicy, ExecutionPolicyScope.UserPolicy, ExecutionPolicyScope.Process, ExecutionPolicyScope.CurrentUser, ExecutionPolicyScope.LocalMachine }; } } internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId) { #if UNIX throw new PlatformNotSupportedException(); #else string executionPolicy = "Restricted"; switch (policy) { case ExecutionPolicy.Restricted: executionPolicy = "Restricted"; break; case ExecutionPolicy.AllSigned: executionPolicy = "AllSigned"; break; case ExecutionPolicy.RemoteSigned: executionPolicy = "RemoteSigned"; break; case ExecutionPolicy.Unrestricted: executionPolicy = "Unrestricted"; break; case ExecutionPolicy.Bypass: executionPolicy = "Bypass"; break; } // Set the execution policy switch (scope) { case ExecutionPolicyScope.Process: if (policy == ExecutionPolicy.Undefined) executionPolicy = null; Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); break; case ExecutionPolicyScope.CurrentUser: // They want to remove it if (policy == ExecutionPolicy.Undefined) { PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); } else { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); } break; case ExecutionPolicyScope.LocalMachine: // They want to remove it if (policy == ExecutionPolicy.Undefined) { PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); } else { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); } break; } #endif } internal static ExecutionPolicy GetExecutionPolicy(string shellId) { foreach (ExecutionPolicyScope scope in ExecutionPolicyScopePreferences) { ExecutionPolicy policy = GetExecutionPolicy(shellId, scope); if (policy != ExecutionPolicy.Undefined) return policy; } return ExecutionPolicy.Restricted; } private static bool? _hasGpScriptParent; /// <summary> /// A value indicating that the current process was launched by GPScript.exe /// Used to determine execution policy when group policies are in effect. /// </summary> /// <remarks> /// This is somewhat expensive to determine and does not change within the lifetime of the current process /// </remarks> private static bool HasGpScriptParent { get { if (!_hasGpScriptParent.HasValue) { _hasGpScriptParent = IsCurrentProcessLaunchedByGpScript(); } return _hasGpScriptParent.Value; } } private static bool IsCurrentProcessLaunchedByGpScript() { Process currentProcess = Process.GetCurrentProcess(); string gpScriptPath = IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.System), "gpscript.exe"); bool foundGpScriptParent = false; try { while (currentProcess != null) { if (string.Equals(gpScriptPath, currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) { foundGpScriptParent = true; break; } else { currentProcess = PsUtils.GetParentProcess(currentProcess); } } } catch (System.ComponentModel.Win32Exception) { // If you attempt to retrieve the MainModule of a 64-bit process // from a WOW64 (32-bit) process, the Win32 API has a fatal // flaw that causes this to return the error: // "Only part of a ReadProcessMemory or WriteProcessMemory // request was completed." // In this case, we just catch the exception and eat it. // The implication is that logon / logoff scripts that somehow // launch the Wow64 version of PowerShell will be subject // to the execution policy deployed by Group Policy (where // our goal here is to not have the Group Policy execution policy // affect logon / logoff scripts. } return foundGpScriptParent; } internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPolicyScope scope) { #if UNIX return ExecutionPolicy.Unrestricted; #else switch (scope) { case ExecutionPolicyScope.Process: { string policy = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference"); if (!string.IsNullOrEmpty(policy)) return ParseExecutionPolicy(policy); else return ExecutionPolicy.Undefined; } case ExecutionPolicyScope.CurrentUser: case ExecutionPolicyScope.LocalMachine: { string policy = GetLocalPreferenceValue(shellId, scope); if (!string.IsNullOrEmpty(policy)) return ParseExecutionPolicy(policy); else return ExecutionPolicy.Undefined; } // TODO: Group Policy is only supported on Full systems, but !LINUX && CORECLR // will run there as well, so I don't think we should remove it. case ExecutionPolicyScope.UserPolicy: case ExecutionPolicyScope.MachinePolicy: { string groupPolicyPreference = GetGroupPolicyValue(shellId, scope); // Be sure we aren't being called by Group Policy // itself. A group policy should never block a logon / // logoff script. if (string.IsNullOrEmpty(groupPolicyPreference) || HasGpScriptParent) { return ExecutionPolicy.Undefined; } return ParseExecutionPolicy(groupPolicyPreference); } } return ExecutionPolicy.Restricted; #endif } internal static ExecutionPolicy ParseExecutionPolicy(string policy) { if (string.Equals(policy, "Bypass", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Bypass; } else if (string.Equals(policy, "Unrestricted", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Unrestricted; } else if (string.Equals(policy, "RemoteSigned", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.RemoteSigned; } else if (string.Equals(policy, "AllSigned", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.AllSigned; } else if (string.Equals(policy, "Restricted", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Restricted; } else { return ExecutionPolicy.Default; } } internal static string GetExecutionPolicy(ExecutionPolicy policy) { switch (policy) { case ExecutionPolicy.Bypass: return "Bypass"; case ExecutionPolicy.Unrestricted: return "Unrestricted"; case ExecutionPolicy.RemoteSigned: return "RemoteSigned"; case ExecutionPolicy.AllSigned: return "AllSigned"; case ExecutionPolicy.Restricted: return "Restricted"; default: return "Restricted"; } } /// <summary> /// Returns true if file has product binary signature. /// </summary> /// <param name="file">Name of file to check.</param> /// <returns>True when file has product binary signature.</returns> public static bool IsProductBinary(string file) { if (string.IsNullOrEmpty(file) || (!IO.File.Exists(file))) { return false; } // Check if it is in the product folder, if not, skip checking the catalog // and any other checks. var isUnderProductFolder = Utils.IsUnderProductFolder(file); if (!isUnderProductFolder) { return false; } #if UNIX // There is no signature support on non-Windows platforms (yet), when // execution reaches here, we are sure the file is under product folder return true; #else // Check the file signature Signature fileSignature = SignatureHelper.GetSignature(file, null); if ((fileSignature != null) && (fileSignature.IsOSBinary)) { return true; } // WTGetSignatureInfo is used to verify catalog signature. // On Win7, catalog API is not available. // On OneCore SKUs like NanoServer/IoT, the API has a bug that makes it not able to find the // corresponding catalog file for a given product file, so it doesn't work properly. // In these cases, we just trust the 'isUnderProductFolder' check. if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value) { // When execution reaches here, we are sure the file is under product folder return true; } return false; #endif } /// <summary> /// Returns the value of the Execution Policy as retrieved /// from group policy. /// </summary> /// <returns>NULL if it is not defined at this level.</returns> private static string GetGroupPolicyValue(string shellId, ExecutionPolicyScope scope) { ConfigScope[] scopeKey = null; switch (scope) { case ExecutionPolicyScope.MachinePolicy: scopeKey = Utils.SystemWideOnlyConfig; break; case ExecutionPolicyScope.UserPolicy: scopeKey = Utils.CurrentUserOnlyConfig; break; } var scriptExecutionSetting = Utils.GetPolicySetting<ScriptExecution>(scopeKey); if (scriptExecutionSetting != null) { if (scriptExecutionSetting.EnableScripts == false) { // Script execution is explicitly disabled return "Restricted"; } else if (scriptExecutionSetting.EnableScripts == true) { // Script execution is explicitly enabled return scriptExecutionSetting.ExecutionPolicy; } } return null; } /// <summary> /// Returns the value of the Execution Policy as retrieved /// from the local preference. /// </summary> /// <returns>NULL if it is not defined at this level.</returns> private static string GetLocalPreferenceValue(string shellId, ExecutionPolicyScope scope) { switch (scope) { // 1: Look up the current-user preference case ExecutionPolicyScope.CurrentUser: return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.CurrentUser, shellId); // 2: Look up the system-wide preference case ExecutionPolicyScope.LocalMachine: return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.AllUsers, shellId); } return null; } #endregion execution policy private static bool _saferIdentifyLevelApiSupported = true; /// <summary> /// Get the pass / fail result of calling the SAFER API. /// </summary> /// <param name="path">The path to the file in question.</param> /// <param name="handle">A file handle to the file in question, if available.</param> [ArchitectureSensitive] [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle) { SaferPolicy status = SaferPolicy.Allowed; if (!_saferIdentifyLevelApiSupported) { return status; } SAFER_CODE_PROPERTIES codeProperties = new SAFER_CODE_PROPERTIES(); IntPtr hAuthzLevel; // Prepare the code properties struct. codeProperties.cbSize = (uint)Marshal.SizeOf(typeof(SAFER_CODE_PROPERTIES)); codeProperties.dwCheckFlags = ( NativeConstants.SAFER_CRITERIA_IMAGEPATH | NativeConstants.SAFER_CRITERIA_IMAGEHASH | NativeConstants.SAFER_CRITERIA_AUTHENTICODE); codeProperties.ImagePath = path; if (handle != null) { codeProperties.hImageFileHandle = handle.DangerousGetHandle(); } // turn off WinVerifyTrust UI codeProperties.dwWVTUIChoice = NativeConstants.WTD_UI_NONE; // Identify the level associated with the code if (NativeMethods.SaferIdentifyLevel(1, ref codeProperties, out hAuthzLevel, NativeConstants.SRP_POLICY_SCRIPT)) { // We found an Authorization Level applicable to this application. IntPtr hRestrictedToken = IntPtr.Zero; try { if (!NativeMethods.SaferComputeTokenFromLevel( hAuthzLevel, // Safer Level IntPtr.Zero, // Test current process' token ref hRestrictedToken, // target token NativeConstants.SAFER_TOKEN_NULL_IF_EQUAL, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); if ((lastError == NativeConstants.ERROR_ACCESS_DISABLED_BY_POLICY) || (lastError == NativeConstants.ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY)) { status = SaferPolicy.Disallowed; } else { throw new System.ComponentModel.Win32Exception(); } } else { if (hRestrictedToken == IntPtr.Zero) { // This is not necessarily the "fully trusted" level, // it means that the thread token is complies with the requested level status = SaferPolicy.Allowed; } else { status = SaferPolicy.Disallowed; NativeMethods.CloseHandle(hRestrictedToken); } } } finally { NativeMethods.SaferCloseLevel(hAuthzLevel); } } else { int lastError = Marshal.GetLastWin32Error(); if (lastError == NativeConstants.FUNCTION_NOT_SUPPORTED) { _saferIdentifyLevelApiSupported = false; } else { throw new System.ComponentModel.Win32Exception(lastError); } } return status; } /// <summary> /// Throw if file does not exist. /// </summary> /// <param name="filePath">Path to file.</param> /// <returns>Does not return a value.</returns> internal static void CheckIfFileExists(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException(filePath); } } /// <summary> /// Check to see if the specified cert is suitable to be /// used as a code signing cert. /// </summary> /// <param name="c">Certificate object.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertIsGoodForSigning(X509Certificate2 c) { if (!c.HasPrivateKey) { return false; } return CertHasOid(c, CertificateFilterInfo.CodeSigningOid); } /// <summary> /// Check to see if the specified cert is suitable to be /// used as an encryption cert for PKI encryption. Note /// that this cert doesn't require the private key. /// </summary> /// <param name="c">Certificate object.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertIsGoodForEncryption(X509Certificate2 c) { return ( CertHasOid(c, CertificateFilterInfo.DocumentEncryptionOid) && (CertHasKeyUsage(c, X509KeyUsageFlags.DataEncipherment) || CertHasKeyUsage(c, X509KeyUsageFlags.KeyEncipherment))); } /// <summary> /// Check to see if the specified cert is expiring by the time. /// </summary> /// <param name="c">Certificate object.</param> /// <param name="expiring">Certificate expire time.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertExpiresByTime(X509Certificate2 c, DateTime expiring) { return c.NotAfter < expiring; } private static bool CertHasOid(X509Certificate2 c, string oid) { foreach (var extension in c.Extensions) { if (extension is X509EnhancedKeyUsageExtension ext) { foreach (Oid ekuOid in ext.EnhancedKeyUsages) { if (ekuOid.Value == oid) { return true; } } break; } } return false; } private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsage) { foreach (X509Extension extension in c.Extensions) { X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage) { return true; } break; } } return false; } /// <summary> /// Get the EKUs of a cert. /// </summary> /// <param name="cert">Certificate object.</param> /// <returns>A collection of cert eku strings.</returns> [ArchitectureSensitive] internal static Collection<string> GetCertEKU(X509Certificate2 cert) { Collection<string> ekus = new Collection<string>(); IntPtr pCert = cert.Handle; int structSize = 0; IntPtr dummy = IntPtr.Zero; if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0, dummy, out structSize)) { if (structSize > 0) { IntPtr ekuBuffer = Marshal.AllocHGlobal(structSize); try { if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0, ekuBuffer, out structSize)) { Security.NativeMethods.CERT_ENHKEY_USAGE ekuStruct = Marshal.PtrToStructure<Security.NativeMethods.CERT_ENHKEY_USAGE>(ekuBuffer); IntPtr ep = ekuStruct.rgpszUsageIdentifier; IntPtr ekuptr; for (int i = 0; i < ekuStruct.cUsageIdentifier; i++) { ekuptr = Marshal.ReadIntPtr(ep, i * Marshal.SizeOf(ep)); string eku = Marshal.PtrToStringAnsi(ekuptr); ekus.Add(eku); } } else { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } } finally { Marshal.FreeHGlobal(ekuBuffer); } } } else { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } return ekus; } /// <summary> /// Convert an int to a DWORD. /// </summary> /// <param name="n">Signed int number.</param> /// <returns>DWORD.</returns> internal static DWORD GetDWORDFromInt(int n) { UInt32 result = BitConverter.ToUInt32(BitConverter.GetBytes(n), 0); return (DWORD)result; } /// <summary> /// Convert a DWORD to int. /// </summary> /// <param name="n">Number.</param> /// <returns>Int.</returns> internal static int GetIntFromDWORD(DWORD n) { Int64 n64 = n - 0x100000000L; return (int)n64; } } /// <summary> /// Information used for filtering a set of certs. /// </summary> internal sealed class CertificateFilterInfo { internal CertificateFilterInfo() { } /// <summary> /// Gets or sets purpose of a certificate. /// </summary> internal CertificatePurpose Purpose { get; set; } = CertificatePurpose.NotSpecified; /// <summary> /// Gets or sets SSL Server Authentication. /// </summary> internal bool SSLServerAuthentication { get; set; } /// <summary> /// Gets or sets DNS name of a certificate. /// </summary> internal WildcardPattern DnsName { get; set; } /// <summary> /// Gets or sets EKU OID list of a certificate. /// </summary> internal List<WildcardPattern> Eku { get; set; } /// <summary> /// Gets or sets validity time for a certificate. /// </summary> internal DateTime Expiring { get; set; } = DateTime.MinValue; internal const string CodeSigningOid = "1.3.6.1.5.5.7.3.3"; internal const string OID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; // The OID arc 1.3.6.1.4.1.311.80 is assigned to PowerShell. If we need // new OIDs, we can assign them under this branch. internal const string DocumentEncryptionOid = "1.3.6.1.4.1.311.80.1"; } } namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the valid purposes by which /// we can filter certificates. /// </summary> internal enum CertificatePurpose { /// <summary> /// Certificates where a purpose has not been specified. /// </summary> NotSpecified = 0, /// <summary> /// Certificates that can be used to sign /// code and scripts. /// </summary> CodeSigning = 0x1, /// <summary> /// Certificates that can be used to encrypt /// data. /// </summary> DocumentEncryption = 0x2, /// <summary> /// Certificates that can be used for any /// purpose. /// </summary> All = 0xffff } } namespace System.Management.Automation { using System.Security.Cryptography.Pkcs; /// <summary> /// Utility class for CMS (Cryptographic Message Syntax) related operations. /// </summary> internal static class CmsUtils { internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipients, SessionState sessionState, out ErrorRecord error) { error = null; if ((contentBytes == null) || (contentBytes.Length == 0)) { return string.Empty; } // After review with the crypto board, NIST_AES256_CBC is more appropriate // than .NET's default 3DES. Also, when specified, uses szOID_RSAES_OAEP for key // encryption to prevent padding attacks. const string szOID_NIST_AES256_CBC = "2.16.840.1.101.3.4.1.42"; ContentInfo content = new ContentInfo(contentBytes); EnvelopedCms cms = new EnvelopedCms(content, new AlgorithmIdentifier( Oid.FromOidValue(szOID_NIST_AES256_CBC, OidGroup.EncryptionAlgorithm))); CmsRecipientCollection recipientCollection = new CmsRecipientCollection(); foreach (CmsMessageRecipient recipient in recipients) { // Resolve the recipient, if it hasn't been done yet. if ((recipient.Certificates != null) && (recipient.Certificates.Count == 0)) { recipient.Resolve(sessionState, ResolutionPurpose.Encryption, out error); } if (error != null) { return null; } foreach (X509Certificate2 certificate in recipient.Certificates) { recipientCollection.Add(new CmsRecipient(certificate)); } } cms.Encrypt(recipientCollection); byte[] encodedBytes = cms.Encode(); string encodedContent = CmsUtils.GetAsciiArmor(encodedBytes); return encodedContent; } internal static readonly string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; internal static readonly string END_CMS_SIGIL = "-----END CMS-----"; internal static readonly string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; internal static readonly string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; /// <summary> /// Adds Ascii armour to a byte stream in Base64 format. /// </summary> /// <param name="bytes">The bytes to encode.</param> internal static string GetAsciiArmor(byte[] bytes) { StringBuilder output = new StringBuilder(); output.AppendLine(BEGIN_CMS_SIGIL); string encodedString = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); output.AppendLine(encodedString); output.Append(END_CMS_SIGIL); return output.ToString(); } /// <summary> /// Removes Ascii armour from a byte stream. /// </summary> /// <param name="actualContent">The Ascii armored content.</param> /// <param name="beginMarker">The marker of the start of the Base64 content.</param> /// <param name="endMarker">The marker of the end of the Base64 content.</param> /// <param name="startIndex">The beginning of where the Ascii armor was detected.</param> /// <param name="endIndex">The end of where the Ascii armor was detected.</param> internal static byte[] RemoveAsciiArmor(string actualContent, string beginMarker, string endMarker, out int startIndex, out int endIndex) { byte[] messageBytes = null; startIndex = -1; endIndex = -1; startIndex = actualContent.IndexOf(beginMarker, StringComparison.OrdinalIgnoreCase); if (startIndex < 0) { return null; } endIndex = actualContent.IndexOf(endMarker, startIndex, StringComparison.OrdinalIgnoreCase) + endMarker.Length; if (endIndex < endMarker.Length) { return null; } int startContent = startIndex + beginMarker.Length; int endContent = endIndex - endMarker.Length; string encodedContent = actualContent.Substring(startContent, endContent - startContent); encodedContent = System.Text.RegularExpressions.Regex.Replace(encodedContent, "\\s", string.Empty); messageBytes = Convert.FromBase64String(encodedContent); return messageBytes; } } /// <summary> /// Represents a message recipient for the Cms cmdlets. /// </summary> public class CmsMessageRecipient { /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> internal CmsMessageRecipient() { } /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> /// <param name="identifier"> /// The identifier of the CmsMessageRecipient. /// Can be either: /// - The path to a file containing the certificate /// - The path to a directory containing the certificate /// - The thumbprint of the certificate, used to find the certificate in the certificate store /// - The Subject name of the recipient, used to find the certificate in the certificate store /// </param> public CmsMessageRecipient(string identifier) { _identifier = identifier; this.Certificates = new X509Certificate2Collection(); } private readonly string _identifier; /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> /// <param name="certificate">The certificate to use.</param> public CmsMessageRecipient(X509Certificate2 certificate) { _pendingCertificate = certificate; this.Certificates = new X509Certificate2Collection(); } private readonly X509Certificate2 _pendingCertificate; /// <summary> /// Gets the certificate associated with this recipient. /// </summary> public X509Certificate2Collection Certificates { get; internal set; } /// <summary> /// Resolves the provided identifier into a collection of certificates. /// </summary> /// <param name="sessionState">A reference to an instance of Powershell's SessionState class.</param> /// <param name="purpose">The purpose for which this identifier is being resolved (Encryption / Decryption.</param> /// <param name="error">The error generated (if any) for this resolution.</param> public void Resolve(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { error = null; // Process the certificate if that was supplied exactly if (_pendingCertificate != null) { ProcessResolvedCertificates( purpose, new X509Certificate2Collection(_pendingCertificate), out error); if ((error != null) || (Certificates.Count != 0)) { return; } } if (_identifier != null) { // First try to resolve assuming that the cert was Base64 encoded. ResolveFromBase64Encoding(purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } // Then try to resolve by path. ResolveFromPath(sessionState, purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } // Then by cert store ResolveFromStoreById(purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } } // Generate an error if no cert was found (and this is an encryption attempt). // If it is only decryption, then the system will always look in the 'My' store anyways, so // don't generate an error if they used wildcards. If they did not use wildcards, // then generate an error because they were expecting something specific. if ((purpose == ResolutionPurpose.Encryption) || (!WildcardPattern.ContainsWildcardCharacters(_identifier))) { error = new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, SecuritySupportStrings.NoCertificateFound, _identifier)), "NoCertificateFound", ErrorCategory.ObjectNotFound, _identifier); } return; } private void ResolveFromBase64Encoding(ResolutionPurpose purpose, out ErrorRecord error) { error = null; int startIndex, endIndex; byte[] messageBytes = null; try { messageBytes = CmsUtils.RemoveAsciiArmor(_identifier, CmsUtils.BEGIN_CERTIFICATE_SIGIL, CmsUtils.END_CERTIFICATE_SIGIL, out startIndex, out endIndex); } catch (FormatException) { // Not Base-64 encoded return; } // Didn't have the sigil if (messageBytes == null) { return; } var certificatesToProcess = new X509Certificate2Collection(); try { X509Certificate2 newCertificate = new X509Certificate2(messageBytes); certificatesToProcess.Add(newCertificate); } catch (Exception) { // User call-out, catch-all OK // Wasn't certificate data return; } // Now validate the certificate ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { error = null; ProviderInfo pathProvider = null; Collection<string> resolvedPaths = null; try { resolvedPaths = sessionState.Path.GetResolvedProviderPathFromPSPath(_identifier, out pathProvider); } catch (SessionStateException) { // If we got an ItemNotFound / etc., then this didn't represent a valid path. } // If we got a resolved path, try to load certs from that path. if ((resolvedPaths != null) && (resolvedPaths.Count != 0)) { // Ensure the path is from the file system provider if (!string.Equals(pathProvider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) { error = new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, SecuritySupportStrings.CertificatePathMustBeFileSystemPath, _identifier)), "CertificatePathMustBeFileSystemPath", ErrorCategory.ObjectNotFound, pathProvider); return; } // If this is a directory, add all certificates in it. This will be the primary // scenario for decryption via Group Protected PFX files // (http://social.technet.microsoft.com/wiki/contents/articles/13922.certificate-pfx-export-and-import-using-ad-ds-account-protection.aspx) List<string> pathsToAdd = new List<string>(); List<string> pathsToRemove = new List<string>(); foreach (string resolvedPath in resolvedPaths) { if (System.IO.Directory.Exists(resolvedPath)) { // It would be nice to limit this to *.pfx, *.cer, etc., but // the crypto APIs support extracting certificates from arbitrary file types. pathsToAdd.AddRange(System.IO.Directory.GetFiles(resolvedPath)); pathsToRemove.Add(resolvedPath); } } // Update resolved paths foreach (string path in pathsToAdd) { resolvedPaths.Add(path); } foreach (string path in pathsToRemove) { resolvedPaths.Remove(path); } var certificatesToProcess = new X509Certificate2Collection(); foreach (string path in resolvedPaths) { X509Certificate2 certificate = null; try { certificate = new X509Certificate2(path); } catch (Exception) { // User call-out, catch-all OK continue; } certificatesToProcess.Add(certificate); } ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } } private void ResolveFromStoreById(ResolutionPurpose purpose, out ErrorRecord error) { error = null; WildcardPattern subjectNamePattern = WildcardPattern.Get(_identifier, WildcardOptions.IgnoreCase); try { var certificatesToProcess = new X509Certificate2Collection(); using (var storeCU = new X509Store("my", StoreLocation.CurrentUser)) { storeCU.Open(OpenFlags.ReadOnly); X509Certificate2Collection storeCerts = storeCU.Certificates; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (var storeLM = new X509Store("my", StoreLocation.LocalMachine)) { storeLM.Open(OpenFlags.ReadOnly); storeCerts.AddRange(storeLM.Certificates); } } certificatesToProcess.AddRange(storeCerts.Find(X509FindType.FindByThumbprint, _identifier, validOnly: false)); if (certificatesToProcess.Count == 0) { foreach (var cert in storeCerts) { if (subjectNamePattern.IsMatch(cert.Subject) || subjectNamePattern.IsMatch(cert.GetNameInfo(X509NameType.SimpleName, forIssuer: false))) { certificatesToProcess.Add(cert); } } } ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } } catch (SessionStateException) { } } private void ProcessResolvedCertificates(ResolutionPurpose purpose, X509Certificate2Collection certificatesToProcess, out ErrorRecord error) { error = null; HashSet<string> processedThumbprints = new HashSet<string>(); foreach (X509Certificate2 certificate in certificatesToProcess) { if (!SecuritySupport.CertIsGoodForEncryption(certificate)) { // If they specified a specific cert, generate an error if it isn't good // for encryption. if (!WildcardPattern.ContainsWildcardCharacters(_identifier)) { error = new ErrorRecord( new ArgumentException( string.Format( CultureInfo.InvariantCulture, SecuritySupportStrings.CertificateCannotBeUsedForEncryption, certificate.Thumbprint, CertificateFilterInfo.DocumentEncryptionOid)), "CertificateCannotBeUsedForEncryption", ErrorCategory.InvalidData, certificate); return; } else { continue; } } // When decrypting, only look for certs that have the private key if (purpose == ResolutionPurpose.Decryption) { if (!certificate.HasPrivateKey) { continue; } } if (processedThumbprints.Contains(certificate.Thumbprint)) { continue; } else { processedThumbprints.Add(certificate.Thumbprint); } if (purpose == ResolutionPurpose.Encryption) { // Only let wildcards expand to one recipient. Otherwise, data // may be encrypted to the wrong person on accident. if (Certificates.Count > 0) { error = new ErrorRecord( new ArgumentException( string.Format( CultureInfo.InvariantCulture, SecuritySupportStrings.IdentifierMustReferenceSingleCertificate, _identifier, arg1: "To")), "IdentifierMustReferenceSingleCertificate", ErrorCategory.LimitsExceeded, certificatesToProcess); Certificates.Clear(); return; } } Certificates.Add(certificate); } } } /// <summary> /// Defines the purpose for resolution of a CmsMessageRecipient. /// </summary> public enum ResolutionPurpose { /// <summary> /// This message recipient is intended to be used for message encryption. /// </summary> Encryption, /// <summary> /// This message recipient is intended to be used for message decryption. /// </summary> Decryption } internal static class AmsiUtils { internal static int Init() { Diagnostics.Assert(s_amsiContext == IntPtr.Zero, "Init should be called just once"); lock (s_amsiLockObject) { string appName; try { appName = string.Concat("PowerShell_", Environment.ProcessPath, "_", PSVersionInfo.ProductVersion); } catch (Exception) { // Fall back to 'Process.ProcessName' in case 'Environment.ProcessPath' throws exception. Process currentProcess = Process.GetCurrentProcess(); appName = string.Concat("PowerShell_", currentProcess.ProcessName, ".exe_", PSVersionInfo.ProductVersion); } AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; var hr = AmsiNativeMethods.AmsiInitialize(appName, ref s_amsiContext); if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; } return hr; } } /// <summary> /// Scans a string buffer for malware using the Antimalware Scan Interface (AMSI). /// Caller is responsible for calling AmsiCloseSession when a "session" (script) /// is complete, and for calling AmsiUninitialize when the runspace is being torn down. /// </summary> /// <param name="content">The string to be scanned.</param> /// <param name="sourceMetadata">Information about the source (filename, etc.).</param> /// <returns>AMSI_RESULT_DETECTED if malware was detected in the sample.</returns> internal static AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string sourceMetadata) { #if UNIX return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; #else return WinScanContent(content, sourceMetadata, warmUp: false); #endif } internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, string sourceMetadata, bool warmUp) { if (string.IsNullOrEmpty(sourceMetadata)) { sourceMetadata = string.Empty; } const string EICAR_STRING = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"; if (InternalTestHooks.UseDebugAmsiImplementation) { if (content.Contains(EICAR_STRING, StringComparison.Ordinal)) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED; } } // If we had a previous initialization failure, just return the neutral result. if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } lock (s_amsiLockObject) { if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } try { int hr = 0; // Initialize AntiMalware Scan Interface, if not already initialized. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") if (s_amsiContext == IntPtr.Zero) { hr = Init(); if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } // Initialize the session, if one isn't already started. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") if (s_amsiSession == IntPtr.Zero) { hr = AmsiNativeMethods.AmsiOpenSession(s_amsiContext, ref s_amsiSession); AmsiInitialized = true; if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } if (warmUp) { // We are warming up the AMSI component in console startup, and that means we initialize AMSI // and create a AMSI session, but don't really scan anything. return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_CLEAN; // Run AMSI content scan unsafe { fixed (char* buffer = content) { var buffPtr = new IntPtr(buffer); hr = AmsiNativeMethods.AmsiScanBuffer( s_amsiContext, buffPtr, (uint)(content.Length * sizeof(char)), sourceMetadata, s_amsiSession, ref result); } } if (!Utils.Succeeded(hr)) { // If we got a failure, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } return result; } catch (DllNotFoundException) { s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } } internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) { if (AmsiInitialized && !AmsiUninitializeCalled) { Uninitialize(); } } [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiContext = IntPtr.Zero; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiSession = IntPtr.Zero; private static bool s_amsiInitFailed = false; private static readonly object s_amsiLockObject = new object(); /// <summary> /// Reset the AMSI session (used to track related script invocations) /// </summary> internal static void CloseSession() { #if !UNIX WinCloseSession(); #endif } internal static void WinCloseSession() { if (!s_amsiInitFailed) { if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { lock (s_amsiLockObject) { // Clean up the session if one was open. if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { AmsiNativeMethods.AmsiCloseSession(s_amsiContext, s_amsiSession); s_amsiSession = IntPtr.Zero; } } } } } /// <summary> /// Uninitialize the AMSI interface. /// </summary> internal static void Uninitialize() { #if !UNIX WinUninitialize(); #endif } internal static void WinUninitialize() { AmsiUninitializeCalled = true; if (!s_amsiInitFailed) { lock (s_amsiLockObject) { if (s_amsiContext != IntPtr.Zero) { CloseSession(); // Unregister the event handler. AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; // Uninitialize the AMSI interface. AmsiCleanedUp = true; AmsiNativeMethods.AmsiUninitialize(s_amsiContext); s_amsiContext = IntPtr.Zero; } } } } public static bool AmsiUninitializeCalled = false; public static bool AmsiInitialized = false; public static bool AmsiCleanedUp = false; internal static class AmsiNativeMethods { internal enum AMSI_RESULT { /// AMSI_RESULT_CLEAN -> 0 AMSI_RESULT_CLEAN = 0, /// AMSI_RESULT_NOT_DETECTED -> 1 AMSI_RESULT_NOT_DETECTED = 1, /// Certain policies set by administrator blocked this content on this machine AMSI_RESULT_BLOCKED_BY_ADMIN_BEGIN = 0x4000, AMSI_RESULT_BLOCKED_BY_ADMIN_END = 0x4fff, /// AMSI_RESULT_DETECTED -> 32768 AMSI_RESULT_DETECTED = 32768, } /// Return Type: HRESULT->LONG->int ///appName: LPCWSTR->WCHAR* ///amsiContext: HAMSICONTEXT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiInitialize", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiInitialize( [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string appName, ref System.IntPtr amsiContext); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiUninitialize", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiUninitialize(System.IntPtr amsiContext); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiOpenSession", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiOpenSession(System.IntPtr amsiContext, ref System.IntPtr amsiSession); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION->HAMSISESSION__* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiCloseSession", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiCloseSession(System.IntPtr amsiContext, System.IntPtr amsiSession); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///buffer: PVOID->void* ///length: ULONG->unsigned int ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanBuffer", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanBuffer( System.IntPtr amsiContext, System.IntPtr buffer, uint length, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///string: LPCWSTR->WCHAR* ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanString", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanString( System.IntPtr amsiContext, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string @string, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); } } } #pragma warning restore 56523
// 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.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_InvalidParametersAndStrangeFiles : ZipFileTestBase { private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, string Message) where TException : Exception { try { Assert.Throws<TException>(() => { using (ZipArchive archive = constructor()) { } }); } catch (Exception e) { Console.WriteLine(string.Format("{0}: {1}", Message, e.ToString())); throw; } } [Fact] public static async Task InvalidInstanceMethods() { Stream zipFile = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(zipFile, ZipArchiveMode.Update)) { //non-existent entry Assert.True(null == archive.GetEntry("nonExistentEntry")); //"Should return null on non-existent entry name" //null/empty string Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); //"Should throw on null entry name" ZipArchiveEntry entry = archive.GetEntry("first.txt"); //null/empty string AssertExtensions.Throws<ArgumentException>("entryName", () => archive.CreateEntry("")); //"Should throw on empty entry name" Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); //"should throw on null entry name" } } [Fact] public static void InvalidConstructors() { //out of range enum values ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(-1)), "Out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(4)), "out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(10)), "Out of range enum"); //null/closed stream ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Read), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Create), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Update), "Null/closed stream"); MemoryStream ms = new MemoryStream(); ms.Dispose(); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Read), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Create), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Update), "Disposed Base Stream"); //non-seekable to update using (LocalMemoryStream nonReadable = new LocalMemoryStream(), nonWriteable = new LocalMemoryStream(), nonSeekable = new LocalMemoryStream()) { nonReadable.SetCanRead(false); nonWriteable.SetCanWrite(false); nonSeekable.SetCanSeek(false); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Read), "Non readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Create), "Non-writable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Update), "Non-readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Update), "Non-writable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonSeekable, ZipArchiveMode.Update), "Non-seekable stream"); } } [Theory] [InlineData("LZMA.zip")] [InlineData("invalidDeflate.zip")] public static async Task ZipArchiveEntry_InvalidUpdate(string zipname) { string filename = bad(zipname); Stream updatedCopy = await StreamHelpers.CreateTempCopyStream(filename); string name; long length, compressedLength; DateTimeOffset lastWriteTime; using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update, true)) { ZipArchiveEntry e = archive.Entries[0]; name = e.FullName; lastWriteTime = e.LastWriteTime; length = e.Length; compressedLength = e.CompressedLength; Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } //make sure that update mode preserves that unreadable file using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; Assert.Equal(name, e.FullName); //"Name isn't the same" Assert.Equal(lastWriteTime, e.LastWriteTime); //"LastWriteTime not the same" Assert.Equal(length, e.Length); //"Length isn't the same" Assert.Equal(compressedLength, e.CompressedLength); //"CompressedLength isn't the same" Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } } [Theory] [InlineData("CDoffsetOutOfBounds.zip")] [InlineData("EOCDmissing.zip")] public static async Task ZipArchive_InvalidStream(string zipname) { string filename = bad(zipname); using (var stream = await StreamHelpers.CreateTempCopyStream(filename)) Assert.Throws<InvalidDataException>(() => new ZipArchive(stream, ZipArchiveMode.Read)); } [Theory] [InlineData("CDoffsetInBoundsWrong.zip")] [InlineData("numberOfEntriesDifferent.zip")] public static async Task ZipArchive_InvalidEntryTable(string zipname) { string filename = bad(zipname); using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read)) Assert.Throws<InvalidDataException>(() => archive.Entries[0]); } [Theory] [InlineData("compressedSizeOutOfBounds.zip", true)] [InlineData("localFileHeaderSignatureWrong.zip", true)] [InlineData("localFileOffsetOutOfBounds.zip", true)] [InlineData("LZMA.zip", true)] [InlineData("invalidDeflate.zip", false)] public static async Task ZipArchive_InvalidEntry(string zipname, bool throwsOnOpen) { string filename = bad(zipname); using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read)) { ZipArchiveEntry e = archive.Entries[0]; if (throwsOnOpen) { Assert.Throws<InvalidDataException>(() => e.Open()); //"should throw on open" } else { using (Stream s = e.Open()) { Assert.Throws<InvalidDataException>(() => s.ReadByte()); //"Unreadable stream" } } } } [Fact] public static async Task ZipArchiveEntry_InvalidLastWriteTime_Read() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream( bad("invaliddate.zip")), ZipArchiveMode.Read)) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); //"Date isn't correct on invalid date" } } [Fact] public static void ZipArchiveEntry_InvalidLastWriteTime_Write() { using (ZipArchive archive = new ZipArchive(new MemoryStream(), ZipArchiveMode.Create)) { ZipArchiveEntry entry = archive.CreateEntry("test"); Assert.Throws<ArgumentOutOfRangeException>(() => { //"should throw on bad date" entry.LastWriteTime = new DateTimeOffset(1979, 12, 3, 5, 6, 2, new TimeSpan()); }); Assert.Throws<ArgumentOutOfRangeException>(() => { //"Should throw on bad date" entry.LastWriteTime = new DateTimeOffset(2980, 12, 3, 5, 6, 2, new TimeSpan()); }); } } [Theory] [InlineData("extradata/extraDataLHandCDentryAndArchiveComments.zip", "verysmall", true)] [InlineData("extradata/extraDataThenZip64.zip", "verysmall", true)] [InlineData("extradata/zip64ThenExtraData.zip", "verysmall", true)] [InlineData("dataDescriptor.zip", "normalWithoutBinary", false)] [InlineData("filenameTimeAndSizesDifferentInLH.zip", "verysmall", false)] public static async Task StrangeFiles(string zipFile, string zipFolder, bool requireExplicit) { IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(strange(zipFile)), zfolder(zipFolder), ZipArchiveMode.Update, requireExplicit, checkTimes: true); } /// <summary> /// This test tiptoes the buffer boundaries to ensure that the size of a read buffer doesn't /// cause any bytes to be left in ZLib's buffer. /// </summary> [Fact] public static void ZipWithLargeSparseFile() { string zipname = strange("largetrailingwhitespacedeflation.zip"); string entryname = "A/B/C/D"; using (FileStream stream = File.Open(zipname, FileMode.Open, FileAccess.Read)) using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) { ZipArchiveEntry entry = archive.GetEntry(entryname); long size = entry.Length; for (int bufferSize = 1; bufferSize <= size; bufferSize++) { using (Stream entryStream = entry.Open()) { byte[] b = new byte[bufferSize]; int read = 0, count = 0; while ((read = entryStream.Read(b, 0, bufferSize)) > 0) { count += read; } Assert.Equal(size, count); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Orders; using Nop.Services.Catalog; using Nop.Services.Common; using Nop.Services.Customers; using Nop.Services.Directory; using Nop.Services.Events; using Nop.Services.Helpers; using Nop.Services.Localization; using Nop.Services.Security; using Nop.Services.Stores; namespace Nop.Services.Orders { /// <summary> /// Shopping cart service /// </summary> public partial class ShoppingCartService : IShoppingCartService { #region Fields private readonly IRepository<ShoppingCartItem> _sciRepository; private readonly IWorkContext _workContext; private readonly IStoreContext _storeContext; private readonly ICurrencyService _currencyService; private readonly IProductService _productService; private readonly ILocalizationService _localizationService; private readonly IProductAttributeParser _productAttributeParser; private readonly ICheckoutAttributeService _checkoutAttributeService; private readonly ICheckoutAttributeParser _checkoutAttributeParser; private readonly IPriceFormatter _priceFormatter; private readonly ICustomerService _customerService; private readonly ShoppingCartSettings _shoppingCartSettings; private readonly IEventPublisher _eventPublisher; private readonly IPermissionService _permissionService; private readonly IAclService _aclService; private readonly IStoreMappingService _storeMappingService; private readonly IGenericAttributeService _genericAttributeService; private readonly IProductAttributeService _productAttributeService; private readonly IDateTimeHelper _dateTimeHelper; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="sciRepository">Shopping cart repository</param> /// <param name="workContext">Work context</param> /// <param name="storeContext">Store context</param> /// <param name="currencyService">Currency service</param> /// <param name="productService">Product settings</param> /// <param name="localizationService">Localization service</param> /// <param name="productAttributeParser">Product attribute parser</param> /// <param name="checkoutAttributeService">Checkout attribute service</param> /// <param name="checkoutAttributeParser">Checkout attribute parser</param> /// <param name="priceFormatter">Price formatter</param> /// <param name="customerService">Customer service</param> /// <param name="shoppingCartSettings">Shopping cart settings</param> /// <param name="eventPublisher">Event publisher</param> /// <param name="permissionService">Permission service</param> /// <param name="aclService">ACL service</param> /// <param name="storeMappingService">Store mapping service</param> /// <param name="genericAttributeService">Generic attribute service</param> /// <param name="productAttributeService">Product attribute service</param> /// <param name="dateTimeHelper">Datetime helper</param> public ShoppingCartService(IRepository<ShoppingCartItem> sciRepository, IWorkContext workContext, IStoreContext storeContext, ICurrencyService currencyService, IProductService productService, ILocalizationService localizationService, IProductAttributeParser productAttributeParser, ICheckoutAttributeService checkoutAttributeService, ICheckoutAttributeParser checkoutAttributeParser, IPriceFormatter priceFormatter, ICustomerService customerService, ShoppingCartSettings shoppingCartSettings, IEventPublisher eventPublisher, IPermissionService permissionService, IAclService aclService, IStoreMappingService storeMappingService, IGenericAttributeService genericAttributeService, IProductAttributeService productAttributeService, IDateTimeHelper dateTimeHelper) { this._sciRepository = sciRepository; this._workContext = workContext; this._storeContext = storeContext; this._currencyService = currencyService; this._productService = productService; this._localizationService = localizationService; this._productAttributeParser = productAttributeParser; this._checkoutAttributeService = checkoutAttributeService; this._checkoutAttributeParser = checkoutAttributeParser; this._priceFormatter = priceFormatter; this._customerService = customerService; this._shoppingCartSettings = shoppingCartSettings; this._eventPublisher = eventPublisher; this._permissionService = permissionService; this._aclService = aclService; this._storeMappingService = storeMappingService; this._genericAttributeService = genericAttributeService; this._productAttributeService = productAttributeService; this._dateTimeHelper = dateTimeHelper; } #endregion #region Methods /// <summary> /// Delete shopping cart item /// </summary> /// <param name="shoppingCartItem">Shopping cart item</param> /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param> /// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param> public virtual void DeleteShoppingCartItem(ShoppingCartItem shoppingCartItem, bool resetCheckoutData = true, bool ensureOnlyActiveCheckoutAttributes = false) { if (shoppingCartItem == null) throw new ArgumentNullException("shoppingCartItem"); var customer = shoppingCartItem.Customer; var storeId = shoppingCartItem.StoreId; //reset checkout data if (resetCheckoutData) { _customerService.ResetCheckoutData(shoppingCartItem.Customer, shoppingCartItem.StoreId); } //delete item _sciRepository.Delete(shoppingCartItem); //reset "HasShoppingCartItems" property used for performance optimization customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0; _customerService.UpdateCustomer(customer); //validate checkout attributes if (ensureOnlyActiveCheckoutAttributes && //only for shopping cart items (ignore wishlist) shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart) { var cart = customer.ShoppingCartItems .Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(storeId) .ToList(); var checkoutAttributesXml = customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, storeId); checkoutAttributesXml = _checkoutAttributeParser.EnsureOnlyActiveAttributes(checkoutAttributesXml, cart); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CheckoutAttributes, checkoutAttributesXml, storeId); } //event notification _eventPublisher.EntityDeleted(shoppingCartItem); } /// <summary> /// Deletes expired shopping cart items /// </summary> /// <param name="olderThanUtc">Older than date and time</param> /// <returns>Number of deleted items</returns> public virtual int DeleteExpiredShoppingCartItems(DateTime olderThanUtc) { var query = from sci in _sciRepository.Table where sci.UpdatedOnUtc < olderThanUtc select sci; var cartItems = query.ToList(); foreach (var cartItem in cartItems) _sciRepository.Delete(cartItem); return cartItems.Count; } /// <summary> /// Validates required products (products which require some other products to be added to the cart) /// </summary> /// <param name="customer">Customer</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="storeId">Store identifier</param> /// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param> /// <returns>Warnings</returns> public virtual IList<string> GetRequiredProductWarnings(Customer customer, ShoppingCartType shoppingCartType, Product product, int storeId, bool automaticallyAddRequiredProductsIfEnabled) { if (customer == null) throw new ArgumentNullException("customer"); if (product == null) throw new ArgumentNullException("product"); var cart = customer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == shoppingCartType) .LimitPerStore(storeId) .ToList(); var warnings = new List<string>(); if (product.RequireOtherProducts) { var requiredProducts = new List<Product>(); foreach (var id in product.ParseRequiredProductIds()) { var rp = _productService.GetProductById(id); if (rp != null) requiredProducts.Add(rp); } foreach (var rp in requiredProducts) { //ensure that product is in the cart bool alreadyInTheCart = false; foreach (var sci in cart) { if (sci.ProductId == rp.Id) { alreadyInTheCart = true; break; } } //not in the cart if (!alreadyInTheCart) { if (product.AutomaticallyAddRequiredProducts) { //add to cart (if possible) if (automaticallyAddRequiredProductsIfEnabled) { //pass 'false' for 'automaticallyAddRequiredProductsIfEnabled' to prevent circular references var addToCartWarnings = AddToCart(customer: customer, product: rp, shoppingCartType: shoppingCartType, storeId: storeId, automaticallyAddRequiredProductsIfEnabled: false); if (addToCartWarnings.Count > 0) { //a product wasn't atomatically added for some reasons //don't display specific errors from 'addToCartWarnings' variable //display only generic error warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name))); } } else { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name))); } } else { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name))); } } } } return warnings; } /// <summary> /// Validates a product for standard properties /// </summary> /// <param name="customer">Customer</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerEnteredPrice">Customer entered price</param> /// <param name="quantity">Quantity</param> /// <returns>Warnings</returns> public virtual IList<string> GetStandardWarnings(Customer customer, ShoppingCartType shoppingCartType, Product product, string attributesXml, decimal customerEnteredPrice, int quantity) { if (customer == null) throw new ArgumentNullException("customer"); if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); //deleted if (product.Deleted) { warnings.Add(_localizationService.GetResource("ShoppingCart.ProductDeleted")); return warnings; } //published if (!product.Published) { warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished")); } //we can add only simple products if (product.ProductType != ProductType.SimpleProduct) { warnings.Add("This is not simple product"); } //ACL if (!_aclService.Authorize(product, customer)) { warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished")); } //Store mapping if (!_storeMappingService.Authorize(product, _storeContext.CurrentStore.Id)) { warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished")); } //disabled "add to cart" button if (shoppingCartType == ShoppingCartType.ShoppingCart && product.DisableBuyButton) { warnings.Add(_localizationService.GetResource("ShoppingCart.BuyingDisabled")); } //disabled "add to wishlist" button if (shoppingCartType == ShoppingCartType.Wishlist && product.DisableWishlistButton) { warnings.Add(_localizationService.GetResource("ShoppingCart.WishlistDisabled")); } //call for price if (shoppingCartType == ShoppingCartType.ShoppingCart && product.CallForPrice) { warnings.Add(_localizationService.GetResource("Products.CallForPrice")); } //customer entered price if (product.CustomerEntersPrice) { if (customerEnteredPrice < product.MinimumCustomerEnteredPrice || customerEnteredPrice > product.MaximumCustomerEnteredPrice) { decimal minimumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MinimumCustomerEnteredPrice, _workContext.WorkingCurrency); decimal maximumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MaximumCustomerEnteredPrice, _workContext.WorkingCurrency); warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CustomerEnteredPrice.RangeError"), _priceFormatter.FormatPrice(minimumCustomerEnteredPrice, false, false), _priceFormatter.FormatPrice(maximumCustomerEnteredPrice, false, false))); } } //quantity validation var hasQtyWarnings = false; if (quantity < product.OrderMinimumQuantity) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MinimumQuantity"), product.OrderMinimumQuantity)); hasQtyWarnings = true; } if (quantity > product.OrderMaximumQuantity) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumQuantity"), product.OrderMaximumQuantity)); hasQtyWarnings = true; } var allowedQuantities = product.ParseAllowedQuantities(); if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(quantity)) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities))); } var validateOutOfStock = shoppingCartType == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist; if (validateOutOfStock && !hasQtyWarnings) { switch (product.ManageInventoryMethod) { case ManageInventoryMethod.DontManageStock: { //do nothing } break; case ManageInventoryMethod.ManageStock: { if (product.BackorderMode == BackorderMode.NoBackorders) { int maximumQuantityCanBeAdded = product.GetTotalStockQuantity(); if (maximumQuantityCanBeAdded < quantity) { if (maximumQuantityCanBeAdded <= 0) warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock")); else warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded)); } } } break; case ManageInventoryMethod.ManageStockByAttributes: { var combination = _productAttributeParser.FindProductAttributeCombination(product, attributesXml); if (combination != null) { //combination exists //let's check stock level if (!combination.AllowOutOfStockOrders && combination.StockQuantity < quantity) { int maximumQuantityCanBeAdded = combination.StockQuantity; if (maximumQuantityCanBeAdded <= 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock")); } else { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded)); } } } else { //combination doesn't exist if (product.AllowAddingOnlyExistingAttributeCombinations) { //maybe, is it better to display something like "No such product/combination" message? warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock")); } } } break; default: break; } } //availability dates bool availableStartDateError = false; if (product.AvailableStartDateTimeUtc.HasValue) { DateTime now = DateTime.UtcNow; DateTime availableStartDateTime = DateTime.SpecifyKind(product.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc); if (availableStartDateTime.CompareTo(now) > 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable")); availableStartDateError = true; } } if (product.AvailableEndDateTimeUtc.HasValue && !availableStartDateError) { DateTime now = DateTime.UtcNow; DateTime availableEndDateTime = DateTime.SpecifyKind(product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc); if (availableEndDateTime.CompareTo(now) < 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable")); } } return warnings; } /// <summary> /// Validates shopping cart item attributes /// </summary> /// <param name="customer">Customer</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="quantity">Quantity</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="ignoreNonCombinableAttributes">A value indicating whether we should ignore non-combinable attributes</param> /// <returns>Warnings</returns> public virtual IList<string> GetShoppingCartItemAttributeWarnings(Customer customer, ShoppingCartType shoppingCartType, Product product, int quantity = 1, string attributesXml = "", bool ignoreNonCombinableAttributes = false) { if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); //ensure it's our attributes var attributes1 = _productAttributeParser.ParseProductAttributeMappings(attributesXml); if (ignoreNonCombinableAttributes) { attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList(); } foreach (var attribute in attributes1) { if (attribute.Product != null) { if (attribute.Product.Id != product.Id) { warnings.Add("Attribute error"); } } else { warnings.Add("Attribute error"); return warnings; } } //validate required product attributes (whether they're chosen/selected/entered) var attributes2 = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id); if (ignoreNonCombinableAttributes) { attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList(); } //validate conditional attributes only (if specified) attributes2 = attributes2.Where(x => { var conditionMet = _productAttributeParser.IsConditionMet(x, attributesXml); return !conditionMet.HasValue || conditionMet.Value; }).ToList(); foreach (var a2 in attributes2) { if (a2.IsRequired) { bool found = false; //selected product attributes foreach (var a1 in attributes1) { if (a1.Id == a2.Id) { var attributeValuesStr = _productAttributeParser.ParseValues(attributesXml, a1.Id); foreach (string str1 in attributeValuesStr) { if (!String.IsNullOrEmpty(str1.Trim())) { found = true; break; } } } } //if not found if (!found) { var notFoundWarning = !string.IsNullOrEmpty(a2.TextPrompt) ? a2.TextPrompt : string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.ProductAttribute.GetLocalized(a => a.Name)); warnings.Add(notFoundWarning); } } if (a2.AttributeControlType == AttributeControlType.ReadonlyCheckboxes) { //customers cannot edit read-only attributes var allowedReadOnlyValueIds = _productAttributeService.GetProductAttributeValues(a2.Id) .Where(x => x.IsPreSelected) .Select(x => x.Id) .ToArray(); var selectedReadOnlyValueIds = _productAttributeParser.ParseProductAttributeValues(attributesXml) .Where(x => x.ProductAttributeMappingId == a2.Id) .Select(x => x.Id) .ToArray(); if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds)) { warnings.Add("You cannot change read-only values"); } } } //validation rules foreach (var pam in attributes2) { if (!pam.ValidationRulesAllowed()) continue; //minimum length if (pam.ValidationMinLength.HasValue) { if (pam.AttributeControlType == AttributeControlType.TextBox || pam.AttributeControlType == AttributeControlType.MultilineTextbox) { var valuesStr = _productAttributeParser.ParseValues(attributesXml, pam.Id); var enteredText = valuesStr.FirstOrDefault(); int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length; if (pam.ValidationMinLength.Value > enteredTextLength) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), pam.ProductAttribute.GetLocalized(a => a.Name), pam.ValidationMinLength.Value)); } } } //maximum length if (pam.ValidationMaxLength.HasValue) { if (pam.AttributeControlType == AttributeControlType.TextBox || pam.AttributeControlType == AttributeControlType.MultilineTextbox) { var valuesStr = _productAttributeParser.ParseValues(attributesXml, pam.Id); var enteredText = valuesStr.FirstOrDefault(); int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length; if (pam.ValidationMaxLength.Value < enteredTextLength) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), pam.ProductAttribute.GetLocalized(a => a.Name), pam.ValidationMaxLength.Value)); } } } } if (warnings.Count > 0) return warnings; //validate bundled products var attributeValues = _productAttributeParser.ParseProductAttributeValues(attributesXml); foreach (var attributeValue in attributeValues) { if (attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct) { if (ignoreNonCombinableAttributes && attributeValue.ProductAttributeMapping.IsNonCombinable()) continue; //associated product (bundle) var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId); if (associatedProduct != null) { var totalQty = quantity * attributeValue.Quantity; var associatedProductWarnings = GetShoppingCartItemWarnings(customer, shoppingCartType, associatedProduct, _storeContext.CurrentStore.Id, "", decimal.Zero, null, null, totalQty, false); foreach (var associatedProductWarning in associatedProductWarnings) { var attributeName = attributeValue.ProductAttributeMapping.ProductAttribute.GetLocalized(a => a.Name); var attributeValueName = attributeValue.GetLocalized(a => a.Name); warnings.Add(string.Format( _localizationService.GetResource("ShoppingCart.AssociatedAttributeWarning"), attributeName, attributeValueName, associatedProductWarning)); } } else { warnings.Add(string.Format("Associated product cannot be loaded - {0}", attributeValue.AssociatedProductId)); } } } return warnings; } /// <summary> /// Validates shopping cart item (gift card) /// </summary> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Warnings</returns> public virtual IList<string> GetShoppingCartItemGiftCardWarnings(ShoppingCartType shoppingCartType, Product product, string attributesXml) { if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); //gift cards if (product.IsGiftCard) { string giftCardRecipientName; string giftCardRecipientEmail; string giftCardSenderName; string giftCardSenderEmail; string giftCardMessage; _productAttributeParser.GetGiftCardAttribute(attributesXml, out giftCardRecipientName, out giftCardRecipientEmail, out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage); if (String.IsNullOrEmpty(giftCardRecipientName)) warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientNameError")); if (product.GiftCardType == GiftCardType.Virtual) { //validate for virtual gift cards only if (String.IsNullOrEmpty(giftCardRecipientEmail) || !CommonHelper.IsValidEmail(giftCardRecipientEmail)) warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientEmailError")); } if (String.IsNullOrEmpty(giftCardSenderName)) warnings.Add(_localizationService.GetResource("ShoppingCart.SenderNameError")); if (product.GiftCardType == GiftCardType.Virtual) { //validate for virtual gift cards only if (String.IsNullOrEmpty(giftCardSenderEmail) || !CommonHelper.IsValidEmail(giftCardSenderEmail)) warnings.Add(_localizationService.GetResource("ShoppingCart.SenderEmailError")); } } return warnings; } /// <summary> /// Validates shopping cart item for rental products /// </summary> /// <param name="product">Product</param> /// <param name="rentalStartDate">Rental start date</param> /// <param name="rentalEndDate">Rental end date</param> /// <returns>Warnings</returns> public virtual IList<string> GetRentalProductWarnings(Product product, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null) { if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); if (!product.IsRental) return warnings; if (!rentalStartDate.HasValue) { warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.EnterStartDate")); return warnings; } if (!rentalEndDate.HasValue) { warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.EnterEndDate")); return warnings; } if (rentalStartDate.Value.CompareTo(rentalEndDate.Value) > 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.StartDateLessEndDate")); return warnings; } //allowed start date should be the future date //we should compare rental start date with a store local time //but we what if a store works in distinct timezones? how we should handle it? skip it for now //we also ignore hours (anyway not supported yet) //today DateTime nowDtInStoreTimeZone = _dateTimeHelper.ConvertToUserTime(DateTime.Now, TimeZoneInfo.Local, _dateTimeHelper.DefaultStoreTimeZone); var todayDt = new DateTime(nowDtInStoreTimeZone.Year, nowDtInStoreTimeZone.Month, nowDtInStoreTimeZone.Day); DateTime todayDtUtc = _dateTimeHelper.ConvertToUtcTime(todayDt, _dateTimeHelper.DefaultStoreTimeZone); //dates are entered in store timezone (e.g. like in hotels) DateTime startDateUtc = _dateTimeHelper.ConvertToUtcTime(rentalStartDate.Value, _dateTimeHelper.DefaultStoreTimeZone); //but we what if dates should be entered in a customer timezone? //DateTime startDateUtc = _dateTimeHelper.ConvertToUtcTime(rentalStartDate.Value, _dateTimeHelper.CurrentTimeZone); if (todayDtUtc.CompareTo(startDateUtc) > 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.StartDateShouldBeFuture")); return warnings; } return warnings; } /// <summary> /// Validates shopping cart item /// </summary> /// <param name="customer">Customer</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="storeId">Store identifier</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerEnteredPrice">Customer entered price</param> /// <param name="rentalStartDate">Rental start date</param> /// <param name="rentalEndDate">Rental end date</param> /// <param name="quantity">Quantity</param> /// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param> /// <param name="getStandardWarnings">A value indicating whether we should validate a product for standard properties</param> /// <param name="getAttributesWarnings">A value indicating whether we should validate product attributes</param> /// <param name="getGiftCardWarnings">A value indicating whether we should validate gift card properties</param> /// <param name="getRequiredProductWarnings">A value indicating whether we should validate required products (products which require other products to be added to the cart)</param> /// <param name="getRentalWarnings">A value indicating whether we should validate rental properties</param> /// <returns>Warnings</returns> public virtual IList<string> GetShoppingCartItemWarnings(Customer customer, ShoppingCartType shoppingCartType, Product product, int storeId, string attributesXml, decimal customerEnteredPrice, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true, bool getStandardWarnings = true, bool getAttributesWarnings = true, bool getGiftCardWarnings = true, bool getRequiredProductWarnings = true, bool getRentalWarnings = true) { if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); //standard properties if (getStandardWarnings) warnings.AddRange(GetStandardWarnings(customer, shoppingCartType, product, attributesXml, customerEnteredPrice, quantity)); //selected attributes if (getAttributesWarnings) warnings.AddRange(GetShoppingCartItemAttributeWarnings(customer, shoppingCartType, product, quantity, attributesXml)); //gift cards if (getGiftCardWarnings) warnings.AddRange(GetShoppingCartItemGiftCardWarnings(shoppingCartType, product, attributesXml)); //required products if (getRequiredProductWarnings) warnings.AddRange(GetRequiredProductWarnings(customer, shoppingCartType, product, storeId, automaticallyAddRequiredProductsIfEnabled)); //rental products if (getRentalWarnings) warnings.AddRange(GetRentalProductWarnings(product, rentalStartDate, rentalEndDate)); return warnings; } /// <summary> /// Validates whether this shopping cart is valid /// </summary> /// <param name="shoppingCart">Shopping cart</param> /// <param name="checkoutAttributesXml">Checkout attributes in XML format</param> /// <param name="validateCheckoutAttributes">A value indicating whether to validate checkout attributes</param> /// <returns>Warnings</returns> public virtual IList<string> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart, string checkoutAttributesXml, bool validateCheckoutAttributes) { var warnings = new List<string>(); bool hasStandartProducts = false; bool hasRecurringProducts = false; foreach (var sci in shoppingCart) { var product = sci.Product; if (product == null) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CannotLoadProduct"), sci.ProductId)); return warnings; } if (product.IsRecurring) hasRecurringProducts = true; else hasStandartProducts = true; } //don't mix standard and recurring products if (hasStandartProducts && hasRecurringProducts) warnings.Add(_localizationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts")); //recurring cart validation if (hasRecurringProducts) { int cycleLength; RecurringProductCyclePeriod cyclePeriod; int totalCycles; string cyclesError = shoppingCart.GetRecurringCycleInfo(_localizationService, out cycleLength, out cyclePeriod, out totalCycles); if (!string.IsNullOrEmpty(cyclesError)) { warnings.Add(cyclesError); return warnings; } } //validate checkout attributes if (validateCheckoutAttributes) { //selected attributes var attributes1 = _checkoutAttributeParser.ParseCheckoutAttributes(checkoutAttributesXml); //existing checkout attributes var attributes2 = _checkoutAttributeService.GetAllCheckoutAttributes(_storeContext.CurrentStore.Id, !shoppingCart.RequiresShipping()); foreach (var a2 in attributes2) { if (a2.IsRequired) { bool found = false; //selected checkout attributes foreach (var a1 in attributes1) { if (a1.Id == a2.Id) { var attributeValuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, a1.Id); foreach (string str1 in attributeValuesStr) if (!String.IsNullOrEmpty(str1.Trim())) { found = true; break; } } } //if not found if (!found) { if (!string.IsNullOrEmpty(a2.GetLocalized(a => a.TextPrompt))) warnings.Add(a2.GetLocalized(a => a.TextPrompt)); else warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetLocalized(a => a.Name))); } } } //now validation rules //minimum length foreach (var ca in attributes2) { if (ca.ValidationMinLength.HasValue) { if (ca.AttributeControlType == AttributeControlType.TextBox || ca.AttributeControlType == AttributeControlType.MultilineTextbox) { var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, ca.Id); var enteredText = valuesStr.FirstOrDefault(); int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length; if (ca.ValidationMinLength.Value > enteredTextLength) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMinLength.Value)); } } } //maximum length if (ca.ValidationMaxLength.HasValue) { if (ca.AttributeControlType == AttributeControlType.TextBox || ca.AttributeControlType == AttributeControlType.MultilineTextbox) { var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, ca.Id); var enteredText = valuesStr.FirstOrDefault(); int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length; if (ca.ValidationMaxLength.Value < enteredTextLength) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMaxLength.Value)); } } } } } return warnings; } /// <summary> /// Finds a shopping cart item in the cart /// </summary> /// <param name="shoppingCart">Shopping cart</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerEnteredPrice">Price entered by a customer</param> /// <param name="rentalStartDate">Rental start date</param> /// <param name="rentalEndDate">Rental end date</param> /// <returns>Found shopping cart item</returns> public virtual ShoppingCartItem FindShoppingCartItemInTheCart(IList<ShoppingCartItem> shoppingCart, ShoppingCartType shoppingCartType, Product product, string attributesXml = "", decimal customerEnteredPrice = decimal.Zero, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null) { if (shoppingCart == null) throw new ArgumentNullException("shoppingCart"); if (product == null) throw new ArgumentNullException("product"); foreach (var sci in shoppingCart.Where(a => a.ShoppingCartType == shoppingCartType)) { if (sci.ProductId == product.Id) { //attributes bool attributesEqual = _productAttributeParser.AreProductAttributesEqual(sci.AttributesXml, attributesXml, false); //gift cards bool giftCardInfoSame = true; if (sci.Product.IsGiftCard) { string giftCardRecipientName1; string giftCardRecipientEmail1; string giftCardSenderName1; string giftCardSenderEmail1; string giftCardMessage1; _productAttributeParser.GetGiftCardAttribute(attributesXml, out giftCardRecipientName1, out giftCardRecipientEmail1, out giftCardSenderName1, out giftCardSenderEmail1, out giftCardMessage1); string giftCardRecipientName2; string giftCardRecipientEmail2; string giftCardSenderName2; string giftCardSenderEmail2; string giftCardMessage2; _productAttributeParser.GetGiftCardAttribute(sci.AttributesXml, out giftCardRecipientName2, out giftCardRecipientEmail2, out giftCardSenderName2, out giftCardSenderEmail2, out giftCardMessage2); if (giftCardRecipientName1.ToLowerInvariant() != giftCardRecipientName2.ToLowerInvariant() || giftCardSenderName1.ToLowerInvariant() != giftCardSenderName2.ToLowerInvariant()) giftCardInfoSame = false; } //price is the same (for products which require customers to enter a price) bool customerEnteredPricesEqual = true; if (sci.Product.CustomerEntersPrice) //TODO should we use RoundingHelper.RoundPrice here? customerEnteredPricesEqual = Math.Round(sci.CustomerEnteredPrice, 2) == Math.Round(customerEnteredPrice, 2); //rental products bool rentalInfoEqual = true; if (sci.Product.IsRental) { rentalInfoEqual = sci.RentalStartDateUtc == rentalStartDate && sci.RentalEndDateUtc == rentalEndDate; } //found? if (attributesEqual && giftCardInfoSame && customerEnteredPricesEqual && rentalInfoEqual) return sci; } } return null; } /// <summary> /// Add a product to shopping cart /// </summary> /// <param name="customer">Customer</param> /// <param name="product">Product</param> /// <param name="shoppingCartType">Shopping cart type</param> /// <param name="storeId">Store identifier</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerEnteredPrice">The price enter by a customer</param> /// <param name="rentalStartDate">Rental start date</param> /// <param name="rentalEndDate">Rental end date</param> /// <param name="quantity">Quantity</param> /// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param> /// <returns>Warnings</returns> public virtual IList<string> AddToCart(Customer customer, Product product, ShoppingCartType shoppingCartType, int storeId, string attributesXml = null, decimal customerEnteredPrice = decimal.Zero, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true) { if (customer == null) throw new ArgumentNullException("customer"); if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); if (shoppingCartType == ShoppingCartType.ShoppingCart && !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart, customer)) { warnings.Add("Shopping cart is disabled"); return warnings; } if (shoppingCartType == ShoppingCartType.Wishlist && !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist, customer)) { warnings.Add("Wishlist is disabled"); return warnings; } if (customer.IsSearchEngineAccount()) { warnings.Add("Search engine can't add to cart"); return warnings; } if (quantity <= 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.QuantityShouldPositive")); return warnings; } //reset checkout info _customerService.ResetCheckoutData(customer, storeId); var cart = customer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == shoppingCartType) .LimitPerStore(storeId) .ToList(); var shoppingCartItem = FindShoppingCartItemInTheCart(cart, shoppingCartType, product, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate); if (shoppingCartItem != null) { //update existing shopping cart item int newQuantity = shoppingCartItem.Quantity + quantity; warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product, storeId, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, newQuantity, automaticallyAddRequiredProductsIfEnabled)); if (warnings.Count == 0) { shoppingCartItem.AttributesXml = attributesXml; shoppingCartItem.Quantity = newQuantity; shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow; _customerService.UpdateCustomer(customer); //event notification _eventPublisher.EntityUpdated(shoppingCartItem); } } else { //new shopping cart item warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product, storeId, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, quantity, automaticallyAddRequiredProductsIfEnabled)); if (warnings.Count == 0) { //maximum items validation switch (shoppingCartType) { case ShoppingCartType.ShoppingCart: { if (cart.Count >= _shoppingCartSettings.MaximumShoppingCartItems) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumShoppingCartItems"), _shoppingCartSettings.MaximumShoppingCartItems)); return warnings; } } break; case ShoppingCartType.Wishlist: { if (cart.Count >= _shoppingCartSettings.MaximumWishlistItems) { warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumWishlistItems"), _shoppingCartSettings.MaximumWishlistItems)); return warnings; } } break; default: break; } DateTime now = DateTime.UtcNow; shoppingCartItem = new ShoppingCartItem { ShoppingCartType = shoppingCartType, StoreId = storeId, Product = product, AttributesXml = attributesXml, CustomerEnteredPrice = customerEnteredPrice, Quantity = quantity, RentalStartDateUtc = rentalStartDate, RentalEndDateUtc = rentalEndDate, CreatedOnUtc = now, UpdatedOnUtc = now }; customer.ShoppingCartItems.Add(shoppingCartItem); _customerService.UpdateCustomer(customer); //updated "HasShoppingCartItems" property used for performance optimization customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0; _customerService.UpdateCustomer(customer); //event notification _eventPublisher.EntityInserted(shoppingCartItem); } } return warnings; } /// <summary> /// Updates the shopping cart item /// </summary> /// <param name="customer">Customer</param> /// <param name="shoppingCartItemId">Shopping cart item identifier</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerEnteredPrice">New customer entered price</param> /// <param name="rentalStartDate">Rental start date</param> /// <param name="rentalEndDate">Rental end date</param> /// <param name="quantity">New shopping cart item quantity</param> /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param> /// <returns>Warnings</returns> public virtual IList<string> UpdateShoppingCartItem(Customer customer, int shoppingCartItemId, string attributesXml, decimal customerEnteredPrice, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool resetCheckoutData = true) { if (customer == null) throw new ArgumentNullException("customer"); var warnings = new List<string>(); var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId); if (shoppingCartItem != null) { if (resetCheckoutData) { //reset checkout data _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId); } if (quantity > 0) { //check warnings warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartItem.ShoppingCartType, shoppingCartItem.Product, shoppingCartItem.StoreId, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, quantity, false)); if (warnings.Count == 0) { //if everything is OK, then update a shopping cart item shoppingCartItem.Quantity = quantity; shoppingCartItem.AttributesXml = attributesXml; shoppingCartItem.CustomerEnteredPrice = customerEnteredPrice; shoppingCartItem.RentalStartDateUtc = rentalStartDate; shoppingCartItem.RentalEndDateUtc = rentalEndDate; shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow; _customerService.UpdateCustomer(customer); //event notification _eventPublisher.EntityUpdated(shoppingCartItem); } } else { //delete a shopping cart item DeleteShoppingCartItem(shoppingCartItem, resetCheckoutData, true); } } return warnings; } /// <summary> /// Migrate shopping cart /// </summary> /// <param name="fromCustomer">From customer</param> /// <param name="toCustomer">To customer</param> /// <param name="includeCouponCodes">A value indicating whether to coupon codes (discount and gift card) should be also re-applied</param> public virtual void MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes) { if (fromCustomer == null) throw new ArgumentNullException("fromCustomer"); if (toCustomer == null) throw new ArgumentNullException("toCustomer"); if (fromCustomer.Id == toCustomer.Id) return; //the same customer //shopping cart items var fromCart = fromCustomer.ShoppingCartItems.ToList(); for (int i = 0; i < fromCart.Count; i++) { var sci = fromCart[i]; AddToCart(toCustomer, sci.Product, sci.ShoppingCartType, sci.StoreId, sci.AttributesXml, sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false); } for (int i = 0; i < fromCart.Count; i++) { var sci = fromCart[i]; DeleteShoppingCartItem(sci); } //migrate gift card and discount coupon codes if (includeCouponCodes) { //discount var discountCouponCode = fromCustomer.GetAttribute<string>(SystemCustomerAttributeNames.DiscountCouponCode); if (!String.IsNullOrEmpty(discountCouponCode)) _genericAttributeService.SaveAttribute(toCustomer, SystemCustomerAttributeNames.DiscountCouponCode, discountCouponCode); //gift card foreach (var gcCode in fromCustomer.ParseAppliedGiftCardCouponCodes()) toCustomer.ApplyGiftCardCouponCode(gcCode); //save customer _customerService.UpdateCustomer(toCustomer); } } #endregion } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestRpcInteropLite { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables #endregion #region Extensions internal static readonly object Descriptor; static UnitTestRpcInteropLite() { Descriptor = null; } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class SearchRequest : pb::GeneratedMessageLite<SearchRequest, SearchRequest.Builder> { private SearchRequest() { } private static readonly SearchRequest defaultInstance = new SearchRequest().MakeReadOnly(); private static readonly string[] _searchRequestFieldNames = new string[] { "Criteria" }; private static readonly uint[] _searchRequestFieldTags = new uint[] { 10 }; public static SearchRequest DefaultInstance { get { return defaultInstance; } } public override SearchRequest DefaultInstanceForType { get { return DefaultInstance; } } protected override SearchRequest ThisMessage { get { return this; } } public const int CriteriaFieldNumber = 1; private pbc::PopsicleList<string> criteria_ = new pbc::PopsicleList<string>(); public scg::IList<string> CriteriaList { get { return pbc::Lists.AsReadOnly(criteria_); } } public int CriteriaCount { get { return criteria_.Count; } } public string GetCriteria(int index) { return criteria_[index]; } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _searchRequestFieldNames; if (criteria_.Count > 0) { output.WriteStringArray(1, field_names[0], criteria_); } } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; { int dataSize = 0; foreach (string element in CriteriaList) { dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); } size += dataSize; size += 1 * criteria_.Count; } memoizedSerializedSize = size; return size; } #region Lite runtime methods public override int GetHashCode() { int hash = GetType().GetHashCode(); foreach(string i in criteria_) hash ^= i.GetHashCode(); return hash; } public override bool Equals(object obj) { SearchRequest other = obj as SearchRequest; if (other == null) return false; if(criteria_.Count != other.criteria_.Count) return false; for(int ix=0; ix < criteria_.Count; ix++) if(!criteria_[ix].Equals(other.criteria_[ix])) return false; return true; } public override void PrintTo(global::System.IO.TextWriter writer) { PrintField("Criteria", criteria_, writer); } #endregion public static SearchRequest ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SearchRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SearchRequest ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SearchRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SearchRequest ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SearchRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static SearchRequest ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static SearchRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static SearchRequest ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SearchRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private SearchRequest MakeReadOnly() { criteria_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(SearchRequest prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilderLite<SearchRequest, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(SearchRequest cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private SearchRequest result; private SearchRequest PrepareBuilder() { if (resultIsReadOnly) { SearchRequest original = result; result = new SearchRequest(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override SearchRequest MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override SearchRequest DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.SearchRequest.DefaultInstance; } } public override SearchRequest BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessageLite other) { if (other is SearchRequest) { return MergeFrom((SearchRequest) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(SearchRequest other) { if (other == global::Google.ProtocolBuffers.TestProtos.SearchRequest.DefaultInstance) return this; PrepareBuilder(); if (other.criteria_.Count != 0) { result.criteria_.Add(other.criteria_); } return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_searchRequestFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _searchRequestFieldTags[field_ordinal]; else { ParseUnknownField(input, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { return this; } ParseUnknownField(input, extensionRegistry, tag, field_name); break; } case 10: { input.ReadStringArray(tag, field_name, result.criteria_); break; } } } return this; } public pbc::IPopsicleList<string> CriteriaList { get { return PrepareBuilder().criteria_; } } public int CriteriaCount { get { return result.CriteriaCount; } } public string GetCriteria(int index) { return result.GetCriteria(index); } public Builder SetCriteria(int index, string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.criteria_[index] = value; return this; } public Builder AddCriteria(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.criteria_.Add(value); return this; } public Builder AddRangeCriteria(scg::IEnumerable<string> values) { PrepareBuilder(); result.criteria_.Add(values); return this; } public Builder ClearCriteria() { PrepareBuilder(); result.criteria_.Clear(); return this; } } static SearchRequest() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInteropLite.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class SearchResponse : pb::GeneratedMessageLite<SearchResponse, SearchResponse.Builder> { private SearchResponse() { } private static readonly SearchResponse defaultInstance = new SearchResponse().MakeReadOnly(); private static readonly string[] _searchResponseFieldNames = new string[] { "results" }; private static readonly uint[] _searchResponseFieldTags = new uint[] { 10 }; public static SearchResponse DefaultInstance { get { return defaultInstance; } } public override SearchResponse DefaultInstanceForType { get { return DefaultInstance; } } protected override SearchResponse ThisMessage { get { return this; } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ResultItem : pb::GeneratedMessageLite<ResultItem, ResultItem.Builder> { private ResultItem() { } private static readonly ResultItem defaultInstance = new ResultItem().MakeReadOnly(); private static readonly string[] _resultItemFieldNames = new string[] { "name", "url" }; private static readonly uint[] _resultItemFieldTags = new uint[] { 18, 10 }; public static ResultItem DefaultInstance { get { return defaultInstance; } } public override ResultItem DefaultInstanceForType { get { return DefaultInstance; } } protected override ResultItem ThisMessage { get { return this; } } public const int UrlFieldNumber = 1; private bool hasUrl; private string url_ = ""; public bool HasUrl { get { return hasUrl; } } public string Url { get { return url_; } } public const int NameFieldNumber = 2; private bool hasName; private string name_ = ""; public bool HasName { get { return hasName; } } public string Name { get { return name_; } } public override bool IsInitialized { get { if (!hasUrl) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _resultItemFieldNames; if (hasUrl) { output.WriteString(1, field_names[1], Url); } if (hasName) { output.WriteString(2, field_names[0], Name); } } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasUrl) { size += pb::CodedOutputStream.ComputeStringSize(1, Url); } if (hasName) { size += pb::CodedOutputStream.ComputeStringSize(2, Name); } memoizedSerializedSize = size; return size; } #region Lite runtime methods public override int GetHashCode() { int hash = GetType().GetHashCode(); if (hasUrl) hash ^= url_.GetHashCode(); if (hasName) hash ^= name_.GetHashCode(); return hash; } public override bool Equals(object obj) { ResultItem other = obj as ResultItem; if (other == null) return false; if (hasUrl != other.hasUrl || (hasUrl && !url_.Equals(other.url_))) return false; if (hasName != other.hasName || (hasName && !name_.Equals(other.name_))) return false; return true; } public override void PrintTo(global::System.IO.TextWriter writer) { PrintField("url", hasUrl, url_, writer); PrintField("name", hasName, name_, writer); } #endregion public static ResultItem ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ResultItem ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ResultItem ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ResultItem ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ResultItem ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ResultItem ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ResultItem ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ResultItem ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ResultItem ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ResultItem ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ResultItem MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(ResultItem prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilderLite<ResultItem, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ResultItem cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ResultItem result; private ResultItem PrepareBuilder() { if (resultIsReadOnly) { ResultItem original = result; result = new ResultItem(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ResultItem MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override ResultItem DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance; } } public override ResultItem BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessageLite other) { if (other is ResultItem) { return MergeFrom((ResultItem) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ResultItem other) { if (other == global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance) return this; PrepareBuilder(); if (other.HasUrl) { Url = other.Url; } if (other.HasName) { Name = other.Name; } return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_resultItemFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _resultItemFieldTags[field_ordinal]; else { ParseUnknownField(input, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { return this; } ParseUnknownField(input, extensionRegistry, tag, field_name); break; } case 10: { result.hasUrl = input.ReadString(ref result.url_); break; } case 18: { result.hasName = input.ReadString(ref result.name_); break; } } } return this; } public bool HasUrl { get { return result.hasUrl; } } public string Url { get { return result.Url; } set { SetUrl(value); } } public Builder SetUrl(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUrl = true; result.url_ = value; return this; } public Builder ClearUrl() { PrepareBuilder(); result.hasUrl = false; result.url_ = ""; return this; } public bool HasName { get { return result.hasName; } } public string Name { get { return result.Name; } set { SetName(value); } } public Builder SetName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasName = true; result.name_ = value; return this; } public Builder ClearName() { PrepareBuilder(); result.hasName = false; result.name_ = ""; return this; } } static ResultItem() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInteropLite.Descriptor, null); } } } #endregion public const int ResultsFieldNumber = 1; private pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> results_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem>(); public scg::IList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> ResultsList { get { return results_; } } public int ResultsCount { get { return results_.Count; } } public global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem GetResults(int index) { return results_[index]; } public override bool IsInitialized { get { foreach (global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem element in ResultsList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _searchResponseFieldNames; if (results_.Count > 0) { output.WriteMessageArray(1, field_names[0], results_); } } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; foreach (global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem element in ResultsList) { size += pb::CodedOutputStream.ComputeMessageSize(1, element); } memoizedSerializedSize = size; return size; } #region Lite runtime methods public override int GetHashCode() { int hash = GetType().GetHashCode(); foreach(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem i in results_) hash ^= i.GetHashCode(); return hash; } public override bool Equals(object obj) { SearchResponse other = obj as SearchResponse; if (other == null) return false; if(results_.Count != other.results_.Count) return false; for(int ix=0; ix < results_.Count; ix++) if(!results_[ix].Equals(other.results_[ix])) return false; return true; } public override void PrintTo(global::System.IO.TextWriter writer) { PrintField("results", results_, writer); } #endregion public static SearchResponse ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SearchResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SearchResponse ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SearchResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SearchResponse ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SearchResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static SearchResponse ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static SearchResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static SearchResponse ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SearchResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private SearchResponse MakeReadOnly() { results_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(SearchResponse prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilderLite<SearchResponse, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(SearchResponse cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private SearchResponse result; private SearchResponse PrepareBuilder() { if (resultIsReadOnly) { SearchResponse original = result; result = new SearchResponse(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override SearchResponse MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override SearchResponse DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance; } } public override SearchResponse BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessageLite other) { if (other is SearchResponse) { return MergeFrom((SearchResponse) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(SearchResponse other) { if (other == global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance) return this; PrepareBuilder(); if (other.results_.Count != 0) { result.results_.Add(other.results_); } return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_searchResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _searchResponseFieldTags[field_ordinal]; else { ParseUnknownField(input, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { return this; } ParseUnknownField(input, extensionRegistry, tag, field_name); break; } case 10: { input.ReadMessageArray(tag, field_name, result.results_, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.DefaultInstance, extensionRegistry); break; } } } return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> ResultsList { get { return PrepareBuilder().results_; } } public int ResultsCount { get { return result.ResultsCount; } } public global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem GetResults(int index) { return result.GetResults(index); } public Builder SetResults(int index, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.results_[index] = value; return this; } public Builder SetResults(int index, global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.results_[index] = builderForValue.Build(); return this; } public Builder AddResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.results_.Add(value); return this; } public Builder AddResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.results_.Add(builderForValue.Build()); return this; } public Builder AddRangeResults(scg::IEnumerable<global::Google.ProtocolBuffers.TestProtos.SearchResponse.Types.ResultItem> values) { PrepareBuilder(); result.results_.Add(values); return this; } public Builder ClearResults() { PrepareBuilder(); result.results_.Clear(); return this; } } static SearchResponse() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInteropLite.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class RefineSearchRequest : pb::GeneratedMessageLite<RefineSearchRequest, RefineSearchRequest.Builder> { private RefineSearchRequest() { } private static readonly RefineSearchRequest defaultInstance = new RefineSearchRequest().MakeReadOnly(); private static readonly string[] _refineSearchRequestFieldNames = new string[] { "Criteria", "previous_results" }; private static readonly uint[] _refineSearchRequestFieldTags = new uint[] { 10, 18 }; public static RefineSearchRequest DefaultInstance { get { return defaultInstance; } } public override RefineSearchRequest DefaultInstanceForType { get { return DefaultInstance; } } protected override RefineSearchRequest ThisMessage { get { return this; } } public const int CriteriaFieldNumber = 1; private pbc::PopsicleList<string> criteria_ = new pbc::PopsicleList<string>(); public scg::IList<string> CriteriaList { get { return pbc::Lists.AsReadOnly(criteria_); } } public int CriteriaCount { get { return criteria_.Count; } } public string GetCriteria(int index) { return criteria_[index]; } public const int PreviousResultsFieldNumber = 2; private bool hasPreviousResults; private global::Google.ProtocolBuffers.TestProtos.SearchResponse previousResults_; public bool HasPreviousResults { get { return hasPreviousResults; } } public global::Google.ProtocolBuffers.TestProtos.SearchResponse PreviousResults { get { return previousResults_ ?? global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance; } } public override bool IsInitialized { get { if (!hasPreviousResults) return false; if (!PreviousResults.IsInitialized) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _refineSearchRequestFieldNames; if (criteria_.Count > 0) { output.WriteStringArray(1, field_names[0], criteria_); } if (hasPreviousResults) { output.WriteMessage(2, field_names[1], PreviousResults); } } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; { int dataSize = 0; foreach (string element in CriteriaList) { dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); } size += dataSize; size += 1 * criteria_.Count; } if (hasPreviousResults) { size += pb::CodedOutputStream.ComputeMessageSize(2, PreviousResults); } memoizedSerializedSize = size; return size; } #region Lite runtime methods public override int GetHashCode() { int hash = GetType().GetHashCode(); foreach(string i in criteria_) hash ^= i.GetHashCode(); if (hasPreviousResults) hash ^= previousResults_.GetHashCode(); return hash; } public override bool Equals(object obj) { RefineSearchRequest other = obj as RefineSearchRequest; if (other == null) return false; if(criteria_.Count != other.criteria_.Count) return false; for(int ix=0; ix < criteria_.Count; ix++) if(!criteria_[ix].Equals(other.criteria_[ix])) return false; if (hasPreviousResults != other.hasPreviousResults || (hasPreviousResults && !previousResults_.Equals(other.previousResults_))) return false; return true; } public override void PrintTo(global::System.IO.TextWriter writer) { PrintField("Criteria", criteria_, writer); PrintField("previous_results", hasPreviousResults, previousResults_, writer); } #endregion public static RefineSearchRequest ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static RefineSearchRequest ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static RefineSearchRequest ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static RefineSearchRequest ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static RefineSearchRequest ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static RefineSearchRequest ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static RefineSearchRequest ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static RefineSearchRequest ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static RefineSearchRequest ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static RefineSearchRequest ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private RefineSearchRequest MakeReadOnly() { criteria_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(RefineSearchRequest prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilderLite<RefineSearchRequest, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(RefineSearchRequest cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private RefineSearchRequest result; private RefineSearchRequest PrepareBuilder() { if (resultIsReadOnly) { RefineSearchRequest original = result; result = new RefineSearchRequest(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override RefineSearchRequest MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override RefineSearchRequest DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.DefaultInstance; } } public override RefineSearchRequest BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessageLite other) { if (other is RefineSearchRequest) { return MergeFrom((RefineSearchRequest) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(RefineSearchRequest other) { if (other == global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.DefaultInstance) return this; PrepareBuilder(); if (other.criteria_.Count != 0) { result.criteria_.Add(other.criteria_); } if (other.HasPreviousResults) { MergePreviousResults(other.PreviousResults); } return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_refineSearchRequestFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _refineSearchRequestFieldTags[field_ordinal]; else { ParseUnknownField(input, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { return this; } ParseUnknownField(input, extensionRegistry, tag, field_name); break; } case 10: { input.ReadStringArray(tag, field_name, result.criteria_); break; } case 18: { global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder subBuilder = global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder(); if (result.hasPreviousResults) { subBuilder.MergeFrom(PreviousResults); } input.ReadMessage(subBuilder, extensionRegistry); PreviousResults = subBuilder.BuildPartial(); break; } } } return this; } public pbc::IPopsicleList<string> CriteriaList { get { return PrepareBuilder().criteria_; } } public int CriteriaCount { get { return result.CriteriaCount; } } public string GetCriteria(int index) { return result.GetCriteria(index); } public Builder SetCriteria(int index, string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.criteria_[index] = value; return this; } public Builder AddCriteria(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.criteria_.Add(value); return this; } public Builder AddRangeCriteria(scg::IEnumerable<string> values) { PrepareBuilder(); result.criteria_.Add(values); return this; } public Builder ClearCriteria() { PrepareBuilder(); result.criteria_.Clear(); return this; } public bool HasPreviousResults { get { return result.hasPreviousResults; } } public global::Google.ProtocolBuffers.TestProtos.SearchResponse PreviousResults { get { return result.PreviousResults; } set { SetPreviousResults(value); } } public Builder SetPreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasPreviousResults = true; result.previousResults_ = value; return this; } public Builder SetPreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasPreviousResults = true; result.previousResults_ = builderForValue.Build(); return this; } public Builder MergePreviousResults(global::Google.ProtocolBuffers.TestProtos.SearchResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasPreviousResults && result.previousResults_ != global::Google.ProtocolBuffers.TestProtos.SearchResponse.DefaultInstance) { result.previousResults_ = global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder(result.previousResults_).MergeFrom(value).BuildPartial(); } else { result.previousResults_ = value; } result.hasPreviousResults = true; return this; } public Builder ClearPreviousResults() { PrepareBuilder(); result.hasPreviousResults = false; result.previousResults_ = null; return this; } } static RefineSearchRequest() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestRpcInteropLite.Descriptor, null); } } #endregion #region Services public partial interface ISearchService { global::Google.ProtocolBuffers.TestProtos.SearchResponse Search(global::Google.ProtocolBuffers.TestProtos.SearchRequest searchRequest); global::Google.ProtocolBuffers.TestProtos.SearchResponse RefineSearch(global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest refineSearchRequest); } [global::System.CLSCompliant(false)] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public partial class SearchService : ISearchService, pb::IRpcDispatch, global::System.IDisposable { private readonly bool dispose; private readonly pb::IRpcDispatch dispatch; public SearchService(pb::IRpcDispatch dispatch) : this(dispatch, true) { } public SearchService(pb::IRpcDispatch dispatch, bool dispose) { pb::ThrowHelper.ThrowIfNull(this.dispatch = dispatch, "dispatch"); this.dispose = dispose && dispatch is global::System.IDisposable; } public void Dispose() { if (dispose) ((global::System.IDisposable)dispatch).Dispose(); } TMessage pb::IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response) { return dispatch.CallMethod(method, request, response); } public global::Google.ProtocolBuffers.TestProtos.SearchResponse Search(global::Google.ProtocolBuffers.TestProtos.SearchRequest searchRequest) { return dispatch.CallMethod("Search", searchRequest, global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder()); } public global::Google.ProtocolBuffers.TestProtos.SearchResponse RefineSearch(global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest refineSearchRequest) { return dispatch.CallMethod("RefineSearch", refineSearchRequest, global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder()); } [global::System.CLSCompliant(false)] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable { private readonly bool dispose; private readonly ISearchService implementation; public Dispatch(ISearchService implementation) : this(implementation, true) { } public Dispatch(ISearchService implementation, bool dispose) { pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, "implementation"); this.dispose = dispose && implementation is global::System.IDisposable; } public void Dispose() { if (dispose) ((global::System.IDisposable)implementation).Dispose(); } public TMessage CallMethod<TMessage, TBuilder>(string methodName, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response) where TMessage : pb::IMessageLite<TMessage, TBuilder> where TBuilder : pb::IBuilderLite<TMessage, TBuilder> { switch(methodName) { case "Search": return response.MergeFrom(implementation.Search((global::Google.ProtocolBuffers.TestProtos.SearchRequest)request)).Build(); case "RefineSearch": return response.MergeFrom(implementation.RefineSearch((global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest)request)).Build(); default: throw pb::ThrowHelper.CreateMissingMethod(typeof(ISearchService), methodName); } } } [global::System.CLSCompliant(false)] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable { private readonly bool dispose; private readonly pb::IRpcDispatch implementation; public ServerStub(ISearchService implementation) : this(implementation, true) { } public ServerStub(ISearchService implementation, bool dispose) : this(new Dispatch(implementation, dispose), dispose) { } public ServerStub(pb::IRpcDispatch implementation) : this(implementation, true) { } public ServerStub(pb::IRpcDispatch implementation, bool dispose) { pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, "implementation"); this.dispose = dispose && implementation is global::System.IDisposable; } public void Dispose() { if (dispose) ((global::System.IDisposable)implementation).Dispose(); } public pb::IMessageLite CallMethod(string methodName, pb::ICodedInputStream input, pb::ExtensionRegistry registry) { switch(methodName) { case "Search": return implementation.CallMethod(methodName, global::Google.ProtocolBuffers.TestProtos.SearchRequest.ParseFrom(input, registry), global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder()); case "RefineSearch": return implementation.CallMethod(methodName, global::Google.ProtocolBuffers.TestProtos.RefineSearchRequest.ParseFrom(input, registry), global::Google.ProtocolBuffers.TestProtos.SearchResponse.CreateBuilder()); default: throw pb::ThrowHelper.CreateMissingMethod(typeof(ISearchService), methodName); } } } } #endregion } #endregion Designer generated code
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// <para>Describes the properties of an environment.</para> /// </summary> public class TerminateEnvironmentResult { private string environmentName; private string environmentId; private string applicationName; private string versionLabel; private string solutionStackName; private string templateName; private string description; private string endpointURL; private string cNAME; private DateTime? dateCreated; private DateTime? dateUpdated; private string status; private string health; private EnvironmentResourcesDescription resources; /// <summary> /// The name of this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>4 - 23</description> /// </item> /// </list> /// </para> /// </summary> public string EnvironmentName { get { return this.environmentName; } set { this.environmentName = value; } } /// <summary> /// Sets the EnvironmentName property /// </summary> /// <param name="environmentName">The value to set for the EnvironmentName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithEnvironmentName(string environmentName) { this.environmentName = environmentName; return this; } // Check to see if EnvironmentName property is set internal bool IsSetEnvironmentName() { return this.environmentName != null; } /// <summary> /// The ID of this environment. /// /// </summary> public string EnvironmentId { get { return this.environmentId; } set { this.environmentId = value; } } /// <summary> /// Sets the EnvironmentId property /// </summary> /// <param name="environmentId">The value to set for the EnvironmentId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithEnvironmentId(string environmentId) { this.environmentId = environmentId; return this; } // Check to see if EnvironmentId property is set internal bool IsSetEnvironmentId() { return this.environmentId != null; } /// <summary> /// The name of the application associated with this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string ApplicationName { get { return this.applicationName; } set { this.applicationName = value; } } /// <summary> /// Sets the ApplicationName property /// </summary> /// <param name="applicationName">The value to set for the ApplicationName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithApplicationName(string applicationName) { this.applicationName = applicationName; return this; } // Check to see if ApplicationName property is set internal bool IsSetApplicationName() { return this.applicationName != null; } /// <summary> /// The application version deployed in this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string VersionLabel { get { return this.versionLabel; } set { this.versionLabel = value; } } /// <summary> /// Sets the VersionLabel property /// </summary> /// <param name="versionLabel">The value to set for the VersionLabel property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithVersionLabel(string versionLabel) { this.versionLabel = versionLabel; return this; } // Check to see if VersionLabel property is set internal bool IsSetVersionLabel() { return this.versionLabel != null; } /// <summary> /// The name of the <c>SolutionStack</c> deployed with this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string SolutionStackName { get { return this.solutionStackName; } set { this.solutionStackName = value; } } /// <summary> /// Sets the SolutionStackName property /// </summary> /// <param name="solutionStackName">The value to set for the SolutionStackName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithSolutionStackName(string solutionStackName) { this.solutionStackName = solutionStackName; return this; } // Check to see if SolutionStackName property is set internal bool IsSetSolutionStackName() { return this.solutionStackName != null; } /// <summary> /// The name of the configuration template used to originally launch this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string TemplateName { get { return this.templateName; } set { this.templateName = value; } } /// <summary> /// Sets the TemplateName property /// </summary> /// <param name="templateName">The value to set for the TemplateName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithTemplateName(string templateName) { this.templateName = templateName; return this; } // Check to see if TemplateName property is set internal bool IsSetTemplateName() { return this.templateName != null; } /// <summary> /// Describes this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 200</description> /// </item> /// </list> /// </para> /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// The URL to the LoadBalancer for this environment. /// /// </summary> public string EndpointURL { get { return this.endpointURL; } set { this.endpointURL = value; } } /// <summary> /// Sets the EndpointURL property /// </summary> /// <param name="endpointURL">The value to set for the EndpointURL property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithEndpointURL(string endpointURL) { this.endpointURL = endpointURL; return this; } // Check to see if EndpointURL property is set internal bool IsSetEndpointURL() { return this.endpointURL != null; } /// <summary> /// The URL to the CNAME for this environment. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// </list> /// </para> /// </summary> public string CNAME { get { return this.cNAME; } set { this.cNAME = value; } } /// <summary> /// Sets the CNAME property /// </summary> /// <param name="cNAME">The value to set for the CNAME property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithCNAME(string cNAME) { this.cNAME = cNAME; return this; } // Check to see if CNAME property is set internal bool IsSetCNAME() { return this.cNAME != null; } /// <summary> /// The creation date for this environment. /// /// </summary> public DateTime DateCreated { get { return this.dateCreated ?? default(DateTime); } set { this.dateCreated = value; } } /// <summary> /// Sets the DateCreated property /// </summary> /// <param name="dateCreated">The value to set for the DateCreated property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithDateCreated(DateTime dateCreated) { this.dateCreated = dateCreated; return this; } // Check to see if DateCreated property is set internal bool IsSetDateCreated() { return this.dateCreated.HasValue; } /// <summary> /// The last modified date for this environment. /// /// </summary> public DateTime DateUpdated { get { return this.dateUpdated ?? default(DateTime); } set { this.dateUpdated = value; } } /// <summary> /// Sets the DateUpdated property /// </summary> /// <param name="dateUpdated">The value to set for the DateUpdated property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithDateUpdated(DateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } // Check to see if DateUpdated property is set internal bool IsSetDateUpdated() { return this.dateUpdated.HasValue; } /// <summary> /// The current operational status of the environment: <ul> <li> <c>Launching</c>: Environment is in the process of initial deployment. </li> /// <li> <c>Updating</c>: Environment is in the process of updating its configuration settings or application version. </li> <li> <c>Ready</c>: /// Environment is available to have an action performed on it, such as update or terminate. </li> <li> <c>Terminating</c>: Environment is in /// the shut-down process. </li> <li> <c>Terminated</c>: Environment is not running. </li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>Launching, Updating, Ready, Terminating, Terminated</description> /// </item> /// </list> /// </para> /// </summary> public string Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Sets the Status property /// </summary> /// <param name="status">The value to set for the Status property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithStatus(string status) { this.status = status; return this; } // Check to see if Status property is set internal bool IsSetStatus() { return this.status != null; } /// <summary> /// Describes the health status of the environment. AWS Elastic Beanstalk indicates the failure levels for a running environment: <enumValues> /// <value name="Red"> <c>Red</c> : Indicates the environment is not working. </value> <value name="Yellow"> <c>Yellow</c>: Indicates that /// something is wrong, the application might not be available, but the instances appear running. </value> <value name="Green"> <c>Green</c>: /// Indicates the environment is healthy and fully functional. </value> </enumValues> <ul> <li> <c>Red</c>: Indicates the environment is not /// responsive. Occurs when three or more consecutive failures occur for an environment. </li> <li> <c>Yellow</c>: Indicates that something is /// wrong. Occurs when two consecutive failures occur for an environment. </li> <li> <c>Green</c>: Indicates the environment is healthy and /// fully functional. </li> <li> <c>Grey</c>: Default health for a new environment. The environment is not fully launched and health checks have /// not started or health checks are suspended during an <c>UpdateEnvironment</c> or <c>RestartEnvironement</c> request. </li> </ul> Default: /// <c>Grey</c> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>Green, Yellow, Red, Grey</description> /// </item> /// </list> /// </para> /// </summary> public string Health { get { return this.health; } set { this.health = value; } } /// <summary> /// Sets the Health property /// </summary> /// <param name="health">The value to set for the Health property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithHealth(string health) { this.health = health; return this; } // Check to see if Health property is set internal bool IsSetHealth() { return this.health != null; } /// <summary> /// The description of the AWS resources used by this environment. /// /// </summary> public EnvironmentResourcesDescription Resources { get { return this.resources; } set { this.resources = value; } } /// <summary> /// Sets the Resources property /// </summary> /// <param name="resources">The value to set for the Resources property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TerminateEnvironmentResult WithResources(EnvironmentResourcesDescription resources) { this.resources = resources; return this; } // Check to see if Resources property is set internal bool IsSetResources() { return this.resources != null; } } }
// // Copyright (c) 2004-2021 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.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Reflection; using System.Text; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 using System.Transactions; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; #if !NETSTANDARD using System.Configuration; using ConfigurationManager = System.Configuration.ConfigurationManager; #endif /// <summary> /// Writes log messages to the database using an ADO.NET provider. /// </summary> /// <remarks> /// <para> /// Note .NET Core application cannot load connectionstrings from app.config / web.config. Instead use ${configsetting} /// </para> /// <a href="https://github.com/nlog/nlog/wiki/Database-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso> /// <example> /// <para> /// The configuration is dependent on the database type, because /// there are different methods of specifying connection string, SQL /// command and command parameters. /// </para> /// <para>MS SQL Server using System.Data.SqlClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" /> /// <para>Oracle using System.Data.OracleClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" /> /// <para>Oracle using System.Data.OleDBClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" /> /// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para> /// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" /> /// </example> [Target("Database")] public class DatabaseTarget : Target, IInstallable { private IDbConnection _activeConnection; private string _activeConnectionString; /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> public DatabaseTarget() { InstallDdlCommands = new List<DatabaseCommandInfo>(); UninstallDdlCommands = new List<DatabaseCommandInfo>(); DBProvider = "sqlserver"; DBHost = "."; #if !NETSTANDARD ConnectionStringsSettings = ConfigurationManager.ConnectionStrings; #endif CommandType = CommandType.Text; } /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public DatabaseTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the name of the database provider. /// </summary> /// <remarks> /// <para> /// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are: /// </para> /// <ul> /// <li><c>System.Data.SqlClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li> /// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="https://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li> /// <li><c>System.Data.OracleClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li> /// <li><c>Oracle.DataAccess.Client</c> - <see href="https://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li> /// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li> /// <li><c>Npgsql</c> - <see href="https://www.npgsql.org/">Npgsql driver for PostgreSQL</see></li> /// <li><c>MySql.Data.MySqlClient</c> - <see href="https://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li> /// </ul> /// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para> /// <para> /// Alternatively the parameter value can be be a fully qualified name of the provider /// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens: /// </para> /// <ul> /// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li> /// <li><c>oledb</c> - OLEDB Data Provider</li> /// <li><c>odbc</c> - ODBC Data Provider</li> /// </ul> /// </remarks> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] [DefaultValue("sqlserver")] public string DBProvider { get; set; } #if !NETSTANDARD /// <summary> /// Gets or sets the name of the connection string (as specified in <see href="https://msdn.microsoft.com/en-us/library/bf7sd233.aspx">&lt;connectionStrings&gt; configuration section</see>. /// </summary> /// <docgen category='Connection Options' order='50' /> public string ConnectionStringName { get; set; } #endif /// <summary> /// Gets or sets the connection string. When provided, it overrides the values /// specified in DBHost, DBUserName, DBPassword, DBDatabase. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout ConnectionString { get; set; } /// <summary> /// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. /// </summary> /// <docgen category='Installation Options' order='100' /> public Layout InstallConnectionString { get; set; } /// <summary> /// Gets the installation DDL commands. /// </summary> /// <docgen category='Installation Options' order='100' /> [ArrayParameter(typeof(DatabaseCommandInfo), "install-command")] public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; } /// <summary> /// Gets the uninstallation DDL commands. /// </summary> /// <docgen category='Installation Options' order='100' /> [ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")] public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; } /// <summary> /// Gets or sets a value indicating whether to keep the /// database connection open between the log events. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(false)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets the database host name. If the ConnectionString is not provided /// this value will be used to construct the "Server=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBHost { get; set; } /// <summary> /// Gets or sets the database user name. If the ConnectionString is not provided /// this value will be used to construct the "User ID=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBUserName { get; set; } /// <summary> /// Gets or sets the database password. If the ConnectionString is not provided /// this value will be used to construct the "Password=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBPassword { get => _dbPassword; set { _dbPassword = value; if (value is SimpleLayout simpleLayout && simpleLayout.IsFixedText) _dbPasswordFixed = EscapeValueForConnectionString(simpleLayout.OriginalText); else _dbPasswordFixed = null; } } private Layout _dbPassword; private string _dbPasswordFixed; /// <summary> /// Gets or sets the database name. If the ConnectionString is not provided /// this value will be used to construct the "Database=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBDatabase { get; set; } /// <summary> /// Gets or sets the text of the SQL command to be run on each log level. /// </summary> /// <remarks> /// Typically this is a SQL INSERT statement or a stored procedure call. /// It should use the database-specific parameters (marked as <c>@parameter</c> /// for SQL server or <c>:parameter</c> for Oracle, other data providers /// have their own notation) and not the layout renderers, /// because the latter is prone to SQL injection attacks. /// The layout renderers should be specified as &lt;parameter /&gt; elements instead. /// </remarks> /// <docgen category='SQL Statement' order='10' /> [RequiredParameter] public Layout CommandText { get; set; } /// <summary> /// Gets or sets the type of the SQL command to be run on each log level. /// </summary> /// <remarks> /// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure". /// When using the value StoredProcedure, the commandText-property would /// normally be the name of the stored procedure. TableDirect method is not supported in this context. /// </remarks> /// <docgen category='SQL Statement' order='11' /> [DefaultValue(CommandType.Text)] public CommandType CommandType { get; set; } /// <summary> /// Gets the collection of parameters. Each item contains a mapping /// between NLog layout and a database named or positional parameter. /// </summary> /// <docgen category='SQL Statement' order='14' /> [ArrayParameter(typeof(DatabaseParameterInfo), "parameter")] public IList<DatabaseParameterInfo> Parameters { get; } = new List<DatabaseParameterInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbConnection instance /// </summary> /// <docgen category='Connection Options' order='50' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "connectionproperty")] public IList<DatabaseObjectPropertyInfo> ConnectionProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbCommand instance /// </summary> /// <docgen category='Connection Options' order='50' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "commandproperty")] public IList<DatabaseObjectPropertyInfo> CommandProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Configures isolated transaction batch writing. If supported by the database, then it will improve insert performance. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public System.Data.IsolationLevel? IsolationLevel { get; set; } #if !NETSTANDARD internal DbProviderFactory ProviderFactory { get; set; } // this is so we can mock the connection string without creating sub-processes internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; } #endif internal Type ConnectionType { get; private set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { RunInstallCommands(installationContext, InstallDdlCommands); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { RunInstallCommands(installationContext, UninstallDdlCommands); } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return null; } internal IDbConnection OpenConnection(string connectionString, LogEventInfo logEventInfo) { IDbConnection connection; #if !NETSTANDARD if (ProviderFactory != null) { connection = ProviderFactory.CreateConnection(); } else #endif { connection = (IDbConnection)Activator.CreateInstance(ConnectionType); } if (connection is null) { throw new NLogRuntimeException("Creation of connection failed"); } connection.ConnectionString = connectionString; if (ConnectionProperties?.Count > 0) { ApplyDatabaseObjectProperties(connection, ConnectionProperties, logEventInfo ?? LogEventInfo.CreateNullEvent()); } connection.Open(); return connection; } private void ApplyDatabaseObjectProperties(object databaseObject, IList<DatabaseObjectPropertyInfo> objectProperties, LogEventInfo logEventInfo) { for (int i = 0; i < objectProperties.Count; ++i) { var propertyInfo = objectProperties[i]; try { var propertyValue = propertyInfo.RenderValue(logEventInfo); if (!propertyInfo.SetPropertyValue(databaseObject, propertyValue)) { InternalLogger.Warn("{0}: Failed to lookup property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType()); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to assign value for property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType()); if (LogManager.ThrowExceptions) throw; } } } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs is null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim())) { ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim()); } providerName = cs.ProviderName?.Trim() ?? string.Empty; } #endif if (ConnectionString != null) { providerName = InitConnectionString(providerName); } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { providerName = GetProviderNameFromDbProviderFactories(providerName); } if (!string.IsNullOrEmpty(providerName)) { foundProvider = InitProviderFactory(providerName); } #endif if (!foundProvider) { try { SetConnectionType(); if (ConnectionType is null) { InternalLogger.Warn("{0}: No ConnectionType created from DBProvider={1}", this, DBProvider); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create ConnectionType from DBProvider={1}", this, DBProvider); throw; } } } private string InitConnectionString(string providerName) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString()?.Trim() ?? string.Empty; } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse '{1}' ConnectionString", this, ConnectionStringName); else #endif InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse ConnectionString", this); } return providerName; } #if !NETSTANDARD private bool InitProviderFactory(string providerName) { bool foundProvider; try { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: DbProviderFactories failed to get factory from ProviderName={1}", this, providerName); throw; } return foundProvider; } private string GetProviderNameFromDbProviderFactories(string providerName) { string dbProvider = DBProvider?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(dbProvider)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase)) { providerName = invariantname; break; } } } return providerName; } #endif /// <summary> /// Set the <see cref="ConnectionType"/> to use it for opening connections to the database. /// </summary> private void SetConnectionType() { switch (DBProvider.ToUpperInvariant()) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": #if NETSTANDARD { try { var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient")); ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true); } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Failed to load assembly 'Microsoft.Data.SqlClient'. Falling back to 'System.Data.SqlClient'.", this); var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); } break; } case "SYSTEM.DATA.SQLCLIENT": { var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #else case "SYSTEM.DATA.SQLCLIENT": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #endif case "MICROSOFT.DATA.SQLCLIENT": { var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient")); ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true); break; } #if !NETSTANDARD case "OLEDB": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.OleDb.OleDbConnection", true, true); break; } #endif case "ODBC": case "SYSTEM.DATA.ODBC": { #if NETSTANDARD var assembly = Assembly.Load(new AssemblyName("System.Data.Odbc")); #else var assembly = typeof(IDbConnection).GetAssembly(); #endif ConnectionType = assembly.GetType("System.Data.Odbc.OdbcConnection", true, true); break; } default: ConnectionType = Type.GetType(DBProvider, true, true); break; } } /// <inheritdoc/> protected override void CloseTarget() { base.CloseTarget(); InternalLogger.Trace("{0}: Close connection because of CloseTarget", this); CloseConnection(); } /// <summary> /// Writes the specified logging event to the database. It creates /// a new database command, prepares parameters for it by calculating /// layouts and executes the command. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { try { WriteLogEventSuppressTransactionScope(logEvent, BuildConnectionString(logEvent)); } finally { if (!KeepConnection) { InternalLogger.Trace("{0}: Close connection (KeepConnection = false).", this); CloseConnection(); } } } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { var buckets = GroupInBuckets(logEvents); if (buckets.Count == 1) { var firstBucket = System.Linq.Enumerable.First(buckets); WriteLogEventsToDatabase(firstBucket.Value, firstBucket.Key); } else { foreach (var bucket in buckets) WriteLogEventsToDatabase(bucket.Value, bucket.Key); } } private ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>> GroupInBuckets(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 0) { #if !NET35 && !NET45 return Array.Empty<KeyValuePair<string, IList<AsyncLogEventInfo>>>(); #else return new KeyValuePair<string, IList<AsyncLogEventInfo>>[0]; #endif } string firstConnectionString = BuildConnectionString(logEvents[0].LogEvent); IDictionary<string, IList<AsyncLogEventInfo>> dictionary = null; for (int i = 1; i < logEvents.Count; ++i) { var connectionString = BuildConnectionString(logEvents[i].LogEvent); if (dictionary is null) { if (connectionString == firstConnectionString) continue; var firstBucket = new List<AsyncLogEventInfo>(i); for (int j = 0; j < i; ++j) firstBucket.Add(logEvents[j]); dictionary = new Dictionary<string, IList<AsyncLogEventInfo>>(StringComparer.Ordinal) { { firstConnectionString, firstBucket } }; } if (!dictionary.TryGetValue(connectionString, out var bucket)) bucket = dictionary[connectionString] = new List<AsyncLogEventInfo>(); bucket.Add(logEvents[i]); } return (ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>>)dictionary ?? new KeyValuePair<string, IList<AsyncLogEventInfo>>[] { new KeyValuePair<string, IList<AsyncLogEventInfo>>(firstConnectionString, logEvents) }; } private void WriteLogEventsToDatabase(IList<AsyncLogEventInfo> logEvents, string connectionString) { try { if (IsolationLevel.HasValue && logEvents.Count > 1) { WriteLogEventsWithTransactionScope(logEvents, connectionString); } else { WriteLogEventsSuppressTransactionScope(logEvents, connectionString); } } finally { if (!KeepConnection) { InternalLogger.Trace("{0}: Close connection because of KeepConnection=false", this); CloseConnection(); } } } private void WriteLogEventsSuppressTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString) { for (int i = 0; i < logEvents.Count; i++) { try { WriteLogEventSuppressTransactionScope(logEvents[i].LogEvent, connectionString); logEvents[i].Continuation(null); } catch (Exception exception) { if (LogManager.ThrowExceptions) throw; logEvents[i].Continuation(exception); } } } private void WriteLogEventsWithTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvents.Count > 0 ? logEvents[0].LogEvent : null); var dbTransaction = _activeConnection.BeginTransaction(IsolationLevel.Value); try { for (int i = 0; i < logEvents.Count; ++i) { ExecuteDbCommandWithParameters(logEvents[i].LogEvent, _activeConnection, dbTransaction); } dbTransaction?.Commit(); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } dbTransaction?.Dispose(); // Can throw error on dispose, so no using transactionScope.Complete(); //not really needed as there is no transaction at all. } catch { try { if (dbTransaction?.Connection != null) { dbTransaction?.Rollback(); } dbTransaction?.Dispose(); } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error during rollback of batch writing {1} logevents to database.", this, logEvents.Count); if (LogManager.ThrowExceptions) throw; } throw; } } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error when batch writing {1} logevents to database.", this, logEvents.Count); if (LogManager.ThrowExceptions) throw; InternalLogger.Trace("{0}: Close connection because of error", this); CloseConnection(); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(exception); } } } private void WriteLogEventSuppressTransactionScope(LogEventInfo logEvent, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvent); ExecuteDbCommandWithParameters(logEvent, _activeConnection, null); transactionScope.Complete(); //not really needed as there is no transaction at all. } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error when writing to database.", this); if (LogManager.ThrowExceptions) throw; InternalLogger.Trace("{0}: Close connection because of error", this); CloseConnection(); throw; } } /// <summary> /// Write logEvent to database /// </summary> private void ExecuteDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, IDbTransaction dbTransaction) { using (IDbCommand command = CreateDbCommand(logEvent, dbConnection)) { if (dbTransaction != null) command.Transaction = dbTransaction; int result = command.ExecuteNonQuery(); InternalLogger.Trace("{0}: Finished execution, result = {1}", this, result); } } internal IDbCommand CreateDbCommand(LogEventInfo logEvent, IDbConnection dbConnection) { var commandText = RenderLogEvent(CommandText, logEvent); InternalLogger.Trace("{0}: Executing {1}: {2}", this, CommandType, commandText); return CreateDbCommandWithParameters(logEvent, dbConnection, CommandType, commandText, Parameters); } private IDbCommand CreateDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, CommandType commandType, string dbCommandText, IList<DatabaseParameterInfo> databaseParameterInfos) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandType = commandType; if (CommandProperties?.Count > 0) { ApplyDatabaseObjectProperties(dbCommand, CommandProperties, logEvent); } dbCommand.CommandText = dbCommandText; for (int i = 0; i < databaseParameterInfos.Count; ++i) { var parameterInfo = databaseParameterInfos[i]; var dbParameter = CreateDatabaseParameter(dbCommand, parameterInfo); var dbParameterValue = GetDatabaseParameterValue(logEvent, parameterInfo); dbParameter.Value = dbParameterValue; dbCommand.Parameters.Add(dbParameter); InternalLogger.Trace(" DatabaseTarget: Parameter: '{0}' = '{1}' ({2})", dbParameter.ParameterName, dbParameter.Value, dbParameter.DbType); } return dbCommand; } /// <summary> /// Build the connectionstring from the properties. /// </summary> /// <remarks> /// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>, /// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/> /// </remarks> /// <param name="logEvent">Event to render the layout inside the properties.</param> /// <returns></returns> protected string BuildConnectionString(LogEventInfo logEvent) { if (ConnectionString != null) { return RenderLogEvent(ConnectionString, logEvent); } var sb = new StringBuilder(); sb.Append("Server="); sb.Append(RenderLogEvent(DBHost, logEvent)); sb.Append(";"); var dbUserName = RenderLogEvent(DBUserName, logEvent); if (string.IsNullOrEmpty(dbUserName)) { sb.Append("Trusted_Connection=SSPI;"); } else { sb.Append("User id="); sb.Append(dbUserName); sb.Append(";Password="); var password = _dbPasswordFixed ?? EscapeValueForConnectionString(_dbPassword.Render(logEvent)); sb.Append(password); sb.Append(";"); } var dbDatabase = RenderLogEvent(DBDatabase, logEvent); if (!string.IsNullOrEmpty(dbDatabase)) { sb.Append("Database="); sb.Append(dbDatabase); } return sb.ToString(); } /// <summary> /// Escape quotes and semicolons. /// See https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms722656(v=vs.85)#setting-values-that-use-reserved-characters /// </summary> private static string EscapeValueForConnectionString(string value) { if (string.IsNullOrEmpty(value)) return value; const char singleQuote = '\''; if (value.IndexOf(singleQuote) == 0 && (value.LastIndexOf(singleQuote) == value.Length - 1)) { // already escaped return value; } const char doubleQuote = '\"'; if (value.IndexOf(doubleQuote) == 0 && (value.LastIndexOf(doubleQuote) == value.Length - 1)) { // already escaped return value; } var containsSingle = value.IndexOf(singleQuote) >= 0; var containsDouble = value.IndexOf(doubleQuote) >= 0; if (containsSingle || containsDouble || value.IndexOf(';') >= 0) { if (!containsSingle) { return singleQuote + value + singleQuote; } if (!containsDouble) { return doubleQuote + value + doubleQuote; } // both single and double var escapedValue = value.Replace("\"", "\"\""); return doubleQuote + escapedValue + doubleQuote; } return value; } private void EnsureConnectionOpen(string connectionString, LogEventInfo logEventInfo) { if (_activeConnection != null && _activeConnectionString != connectionString) { InternalLogger.Trace("{0}: Close connection because of opening new.", this); CloseConnection(); } if (_activeConnection != null) { return; } InternalLogger.Trace("{0}: Open connection.", this); _activeConnection = OpenConnection(connectionString, logEventInfo); _activeConnectionString = connectionString; } private void CloseConnection() { try { var activeConnection = _activeConnection; if (activeConnection != null) { activeConnection.Close(); activeConnection.Dispose(); } } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Error while closing connection.", this); } finally { _activeConnectionString = null; _activeConnection = null; } } private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { var connectionString = GetConnectionStringFromCommand(commandInfo, logEvent); // Set ConnectionType if it has not been initialized already if (ConnectionType is null) { SetConnectionType(); } EnsureConnectionOpen(connectionString, logEvent); string commandText = RenderLogEvent(commandInfo.Text, logEvent); installationContext.Trace("DatabaseTarget(Name={0}) - Executing {1} '{2}'", Name, commandInfo.CommandType, commandText); using (IDbCommand command = CreateDbCommandWithParameters(logEvent, _activeConnection, commandInfo.CommandType, commandText, commandInfo.Parameters)) { try { command.ExecuteNonQuery(); } catch (Exception exception) { if (LogManager.ThrowExceptions) throw; if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } } finally { InternalLogger.Trace("{0}: Close connection after install.", this); CloseConnection(); } } private string GetConnectionStringFromCommand(DatabaseCommandInfo commandInfo, LogEventInfo logEvent) { string connectionString; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it connectionString = RenderLogEvent(commandInfo.ConnectionString, logEvent); } else if (InstallConnectionString != null) { // next, try InstallConnectionString connectionString = RenderLogEvent(InstallConnectionString, logEvent); } else { // if it's not defined, fall back to regular connection string connectionString = BuildConnectionString(logEvent); } return connectionString; } /// <summary> /// Create database parameter /// </summary> /// <param name="command">Current command.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected virtual IDbDataParameter CreateDatabaseParameter(IDbCommand command, DatabaseParameterInfo parameterInfo) { IDbDataParameter dbParameter = command.CreateParameter(); dbParameter.Direction = ParameterDirection.Input; if (parameterInfo.Name != null) { dbParameter.ParameterName = parameterInfo.Name; } if (parameterInfo.Size != 0) { dbParameter.Size = parameterInfo.Size; } if (parameterInfo.Precision != 0) { dbParameter.Precision = parameterInfo.Precision; } if (parameterInfo.Scale != 0) { dbParameter.Scale = parameterInfo.Scale; } try { if (!parameterInfo.SetDbType(dbParameter)) { InternalLogger.Warn(" DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); } } catch (Exception ex) { InternalLogger.Error(ex, " DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); if (LogManager.ThrowExceptions) throw; } return dbParameter; } /// <summary> /// Extract parameter value from the logevent /// </summary> /// <param name="logEvent">Current logevent.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected internal virtual object GetDatabaseParameterValue(LogEventInfo logEvent, DatabaseParameterInfo parameterInfo) { var value = parameterInfo.RenderValue(logEvent); if (parameterInfo.AllowDbNull && string.Empty.Equals(value)) return DBNull.Value; else return value; } #if NETSTANDARD1_3 || NETSTANDARD1_5 /// <summary> /// Fake transaction /// /// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949 /// </summary> private sealed class TransactionScope : IDisposable { private readonly TransactionScopeOption _suppress; public TransactionScope(TransactionScopeOption suppress) { _suppress = suppress; } public void Complete() { // Fake scope for compatibility, so nothing to do } public void Dispose() { // Fake scope for compatibility, so nothing to do } } /// <summary> /// Fake option /// </summary> private enum TransactionScopeOption { Required, RequiresNew, Suppress, } #endif } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Commander.Tests { /// <summary> /// Provides a fluent interface for asserting the raising of exceptions. /// </summary> /// <typeparam name="TException">The type of exception to assert.</typeparam> public static class Exception<TException> where TException : Exception { /// <summary> /// Asserts that the exception is thrown when the specified action is executed. /// </summary> /// <param name="action">The action to execute.</param> /// <returns></returns> public static TException ShouldBeThrownBy(Action action) { return ShouldBeThrownBy(action, null); } /// <summary> /// Asserts that the exception is thrown when the specified action is executed. /// </summary> /// <param name="action">The action to execute.</param> /// <param name="postCatchAction">The action to execute after the exception has been caught.</param> /// <returns></returns> public static TException ShouldBeThrownBy(Action action, Action<Exception> postCatchAction) { TException exception = null; try { action(); } catch (Exception e) { exception = e.ShouldBeOfType<TException>(); if(postCatchAction != null) { postCatchAction(e); } } exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action."); return exception; } /// <summary> /// Asserts that the exception was thrown when the specified action is executed by /// scanning the exception chain. /// </summary> /// <param name="action">The action to execute.</param> /// <returns></returns> public static TException ShouldExistInExceptionChainAfter(Action action) { TException exception = null; try { action(); } catch (Exception e) { exception = ScanExceptionChain(e); } return exception; } /// <summary> /// Scans the specified exception chain and asserts the existence of the target exception. /// </summary> /// <param name="chainLink">Exception chain to scan.</param> /// <returns></returns> private static TException ScanExceptionChain(Exception chainLink) { TException exception; if((exception = chainLink as TException) != null) { return exception; } if(chainLink.InnerException == null) { Assert.Fail("An exception was expected, but not thrown by the given action."); } return ScanExceptionChain(chainLink.InnerException); } } public static class SpecificationExtensions { public static void ShouldHave<T>(this IEnumerable<T> values, Func<T, bool> func) { values.FirstOrDefault(func).ShouldNotBeNull(); } public static void ShouldBeFalse(this bool condition) { Assert.IsFalse(condition); } public static void ShouldBeTrue(this bool condition) { Assert.IsTrue(condition); } public static void ShouldBeTrueBecause(this bool condition, string reason, params object[] args) { Assert.IsTrue(condition, reason, args); } public static object ShouldEqual(this object actual, object expected) { Assert.AreEqual(expected, actual); return expected; } public static object ShouldEqual(this string actual, object expected) { Assert.AreEqual((expected != null) ? expected.ToString() : null, actual); return expected; } public static void ShouldMatch(this string actual, string pattern) { #pragma warning disable 612,618 Assert.That(actual, Text.Matches(pattern)); #pragma warning restore 612,618 } public static XmlElement AttributeShouldEqual(this XmlElement element, string attributeName, object expected) { Assert.IsNotNull(element, "The Element is null"); string actual = element.GetAttribute(attributeName); Assert.AreEqual(expected, actual); return element; } public static XmlElement AttributeShouldEqual(this XmlNode node, string attributeName, object expected) { var element = node as XmlElement; Assert.IsNotNull(element, "The Element is null"); string actual = element.GetAttribute(attributeName); Assert.AreEqual(expected, actual); return element; } public static XmlElement ShouldHaveChild(this XmlElement element, string xpath) { var child = element.SelectSingleNode(xpath) as XmlElement; Assert.IsNotNull(child, "Should have a child element matching " + xpath); return child; } public static XmlElement DoesNotHaveAttribute(this XmlElement element, string attributeName) { Assert.IsNotNull(element, "The Element is null"); Assert.IsFalse(element.HasAttribute(attributeName), "Element should not have an attribute named " + attributeName); return element; } public static object ShouldNotEqual(this object actual, object expected) { Assert.AreNotEqual(expected, actual); return expected; } public static void ShouldBeNull(this object anObject) { Assert.IsNull(anObject); } public static void ShouldNotBeNull(this object anObject) { Assert.IsNotNull(anObject); } public static void ShouldNotBeNull(this object anObject, string message) { Assert.IsNotNull(anObject, message); } public static object ShouldBeTheSameAs(this object actual, object expected) { Assert.AreSame(expected, actual); return expected; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { Assert.AreNotSame(expected, actual); return expected; } public static T ShouldBeOfType<T>(this object actual) { actual.ShouldNotBeNull(); actual.ShouldBeOfType(typeof(T)); return (T)actual; } public static T As<T>(this object actual) { actual.ShouldNotBeNull(); actual.ShouldBeOfType(typeof(T)); return (T)actual; } public static object ShouldBeOfType(this object actual, Type expected) { #pragma warning disable 612,618 Assert.IsInstanceOfType(expected, actual); #pragma warning restore 612,618 return actual; } public static void ShouldNotBeOfType(this object actual, Type expected) { #pragma warning disable 612,618 Assert.IsNotInstanceOfType(expected, actual); #pragma warning restore 612,618 } public static void ShouldContain(this IList actual, object expected) { Assert.Contains(expected, actual); } public static void ShouldContain<T>(this IEnumerable<T> actual, T expected) { if (actual.Count(t => t.Equals(expected)) == 0) { Assert.Fail("The item '{0}' was not found in the sequence.", expected); } } public static void ShouldNotBeEmpty<T>(this IEnumerable<T> actual) { Assert.Greater(actual.Count(), 0, "The list should have at least one element"); } public static void ShouldNotContain<T>(this IEnumerable<T> actual, T expected) { if (actual.Count(t => t.Equals(expected)) > 0) { Assert.Fail("The item was found in the sequence it should not be in."); } } public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected) { actual.ShouldNotBeNull(); expected.ShouldNotBeNull(); actual.Count.ShouldEqual(expected.Count); for (int i = 0; i < actual.Count; i++) { actual[i].ShouldEqual(expected[i]); } } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected) { ShouldHaveTheSameElementsAs(actual, (IEnumerable<T>)expected); } public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected) { IList actualList = (actual is IList) ? (IList)actual : actual.ToList(); IList expectedList = (expected is IList) ? (IList)expected : expected.ToList(); ShouldHaveTheSameElementsAs(actualList, expectedList); } public static void ShouldHaveTheSameElementKeysAs<ELEMENT, KEY>(this IEnumerable<ELEMENT> actual, IEnumerable expected, Func<ELEMENT, KEY> keySelector) { actual.ShouldNotBeNull(); expected.ShouldNotBeNull(); ELEMENT[] actualArray = actual.ToArray(); object[] expectedArray = expected.Cast<object>().ToArray(); actualArray.Length.ShouldEqual(expectedArray.Length); for (int i = 0; i < actual.Count(); i++) { keySelector(actualArray[i]).ShouldEqual(expectedArray[i]); } } public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { Assert.Greater(arg1, arg2); return arg2; } public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2) { Assert.Less(arg1, arg2); return arg2; } public static void ShouldBeEmpty(this ICollection collection) { Assert.IsEmpty(collection); } public static void ShouldBeEmpty(this string aString) { Assert.IsEmpty(aString); } public static void ShouldNotBeEmpty(this ICollection collection) { Assert.IsNotEmpty(collection); } public static void ShouldNotBeEmpty(this string aString) { Assert.IsNotEmpty(aString); } public static void ShouldContain(this string actual, string expected) { StringAssert.Contains(expected, actual); } public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected) { actual.Count().ShouldBeGreaterThan(0); T result = actual.FirstOrDefault(expected); Assert.That(result, Is.Not.EqualTo(default(T)), "Expected item was not found in the actual sequence"); } public static void ShouldNotContain(this string actual, string expected) { Assert.That(actual, new NotConstraint(new SubstringConstraint(expected))); } public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { StringAssert.AreEqualIgnoringCase(expected, actual); return expected; } public static void ShouldEndWith(this string actual, string expected) { StringAssert.EndsWith(expected, actual); } public static void ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { StringAssert.Contains(expected, exception.Message); } public static Exception ShouldBeThrownBy(this Type exceptionType, Action action) { Exception exception = null; try { action(); } catch (Exception e) { Assert.AreEqual(exceptionType, e.GetType()); exception = e; } if (exception == null) { Assert.Fail(String.Format("Expected {0} to be thrown.", exceptionType.FullName)); } return exception; } public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected) { TimeSpan timeSpan = actual - expected; Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3); } public static IEnumerable<T> ShouldHaveCount<T>(this IEnumerable<T> actual, int expected) { actual.Count().ShouldEqual(expected); return actual; } } }
using System; using System.Collections.Generic; using System.Reflection; public delegate void EventHandler<T>(); public class ViableCallable { public void Run<T1, T2, T3>(C1<T1, T2> x1, C1<T1[], T2> x2, dynamic dyn, T3 t3) { // Viable callables: {C2,C3,C4,C5,C6,C7}.M() x1.M(default(T1), 8); // Viable callables: {C2,C3,C4,C5,C6,C7}.{get_Prop(),set_Prop()} x1.Prop = x1.Prop; // Viable callables: {C2,C3,C4,C5,C6,C7}.{get_Item(),set_Item()} x1[default(T2)] = x1[default(T2)]; // Viable callables: {C2,C3,C4,C5,C6,C7}.{add_Event(),remove_Event()} x1.Event += () => { }; x1.Event -= () => { }; // Viable callables: {C4,C6}.M() (not C7.M(), as C7<T[]> is not constructed for any T) x2.M(new T1[0], false); // Viable callables: {C4,C6}.{get_Prop(),set_Prop()} x2.Prop = x2.Prop; // Viable callables: {C4,C6}.{get_Item(),set_Item()} x2[default(T2)] = x2[default(T2)]; // Viable callables: {C4,C6}.{add_Event(),remove_Event()} x2.Event += () => { }; x2.Event -= () => { }; // Viable callables: {C2,C6}.M() C1<string, int> x3 = Mock<C1<string, int>>(); x3.M("abc", 42); // Viable callables: {C2,C6}.{get_Prop(),set_Prop()} x3.Prop = x3.Prop; // Viable callables: {C2,C6}.{get_Item(),set_Item()} x3[0] = x3[0]; // Viable callables: {C2,C6}.{add_Event(),remove_Event()} x3.Event += () => { }; x3.Event -= () => { }; // Viable callables: {C2,C3,C6}.M() C1<string, decimal> x4 = Mock<C1<string, decimal>>(); x4.M("abc", 42d); // Viable callables: {C2,C3,C6}.{get_Prop(),set_Prop()} x4.Prop = x4.Prop; // Viable callables: {C2,C3,C6}.{get_Item(),set_Item()} x4[0M] = x4[0M]; // Viable callables: {C2,C3,C6}.{add_Event(),remove_Event()} x4.Event += () => { }; x4.Event -= () => { }; // Viable callables: {C4,C6}.M() C1<int[], bool> x5 = Mock<C1<int[], bool>>(); x5.M<object>(new int[] { 42 }, null); // Viable callables: {C4,C6}.{get_Prop(),set_Prop()} x5.Prop = x5.Prop; // Viable callables: {C4,C6}.{get_Item(),set_Item()} x5[false] = x5[false]; // Viable callables: {C4,C6}.{add_Event(),remove_Event()} x5.Event += () => { }; x5.Event -= () => { }; // Viable callables: {C2,C5,C6}.M() C1<string, bool> x6 = Mock<C1<string, bool>>(); x6.M<object>("", null); // Viable callables: {C2,C5,C6}.{get_Prop(),set_Prop()} x6.Prop = x6.Prop; // Viable callables: {C2,C5,C6}.{get_Item(),set_Item()} x6[false] = x6[false]; // Viable callables: {C2,C5,C6}.{add_Event(),remove_Event()} x6.Event += () => { }; x6.Event -= () => { }; // Viable callables: C6.M() C1<T1, bool> x7 = new C6<T1, bool>(); x7.M(default(T1), ""); // Viable callables: C6.{get_Prop(),set_Prop()} x7.Prop = x7.Prop; // Viable callables: C6.{get_Item(),set_Item()} x7[false] = x7[false]; // Viable callables: C6.{add_Event(),remove_Event()} x7.Event += () => { }; x7.Event -= () => { }; // Viable callables: {C8,C9}.M() dynamic d = Mock<C8>(); d.M(Mock<IEnumerable<C4<string>>>()); // Viable callables: {C8,C9}.{get_Prop(),set_Prop()} d.Prop1 = d.Prop1; // Viable callables: {C8,C9}.{get_Item(),set_Item()} d[0] = d[0]; // Viable callables: (none) d.M(Mock<IEnumerable<C4<int>>>()); // Viable callables: C5.M() d = 42; C5.M(d); // Viable callables: C5.set_Prop2() d = ""; C5.Prop2 = d; // Viable callables: C5.{add_Event(),remove_Event()} d = (EventHandler<string>)(() => { }); C5.Event2 += d; C5.Event2 -= d; // Viable callables: (none) d = ""; C5.M(d); // Viable callables: (none) d = 0; C5.Prop2 = d; // Viable callables: (none) C5.Event2 += d; C5.Event2 -= d; // Viable callables: C8.M2() d = new decimal[] { 0M }; C8.M2<decimal>(d); // Viable callables: C8.M2() d = new string[] { "" }; C8.M2<string>(d); // Viable callables: (none) d = ""; C8.M2<object>(d); // Viable callables: C6.M() d = new C6<T1, byte>(); d.M(default(T1), ""); // Viable callables: C6.{get_Prop(),set_Prop()} d.Prop = d.Prop; // Viable callables: C6.{get_Item(),set_Item()} d[(byte)0] = d[(byte)0]; // Viable callables: C6.{add_Event(),remove_Event()} d.Event += (EventHandler<string>)(() => { }); d.Event -= (EventHandler<string>)(() => { }); // Viable callables: C8.M3(), C9.M3() d = Mock<C8>(); d.M3(); d.M3(0); d.M3(0, 0.0); // Viable callables: {C8,C9,C10}.M3() dyn.M3(); dyn.M3(0); dyn.M3(0, 0.0); // Viable callables: {C8,C9,C10}.{get_Prop1(),set_Prop1()} dyn.Prop1 = dyn.Prop1; // Viable callables: {C2,C3,C6,C7,C8,C9,C10}.{get_Item(),set_Item()} dyn[0] = dyn[0]; // Viable callables: {C2,C3,C5,C6,C7,C8,C9}.{add_Event(),remove_Event()} dyn.Event += (EventHandler<string>)(() => { }); dyn.Event -= (EventHandler<string>)(() => { }); // Viable callables: C8.M4() dyn.M4(0, Mock<IList<string>>()); dyn.M4(0, new string[] { "" }); // Viable callables: C10.set_Prop1() dyn.Prop1 = false; // Viable callables: (none) dyn.M4(-1, new string[] { "" }); dyn.M4(0, new int[] { 0 }); // Viable callables: (none) dyn.Prop1 = 0; // Viable callables: {C2,C6}.{get_Item(),set_Item()} dyn[""] = dyn[""]; // Operator calls using dynamic types: all target int operators d = 0; d = d + 1; d = 0; d = 1 - d; d = 0; d = d + t3; // mixed with a type parameter // Operator calls using reflection: targets C10 addition operator var c = new C10(); typeof(C10).InvokeMember("op_Addition", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] { c, c }); // Property call using reflection: targets C10 property getter/setter typeof(C10).InvokeMember("get_Prop3", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[0]); typeof(C10).InvokeMember("set_Prop3", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] { "" }); // Indexer call using reflection: targets C10 indexer getter/setter typeof(C10).InvokeMember("get_Item", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object[] { 0 }); typeof(C10).InvokeMember("set_Item", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object[] { 0, true }); // Event handler call using reflection: targets C10 event adder/remover EventHandler<bool> e = () => { }; typeof(C10).InvokeMember("add_Event", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object[] { e }); typeof(C10).InvokeMember("remove_Event", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object[] { e }); } public static T Mock<T>() { throw new Exception(); } void CreateTypeInstance() { new C2<bool>(); new C2<int>(); new C2<decimal>(); new C4<int>(); new C6<string, bool>(); new C6<string, int>(); new C6<string, decimal>(); new C6<int[], bool>(); new C7<bool>(); // Need to reference built-in operators for them to be extracted if (2 + 3 - 1 > 0) ; // No construction of C8/C9; reflection/dynamic calls should not rely on existence of types } } public abstract class C1<T1, T2> { public abstract T2 M<T3>(T1 x, T3 y); public abstract T1 Prop { get; set; } public abstract T1 this[T2 x] { get; set; } public abstract event EventHandler<T1> Event; public void Run(T1 x) { // Viable callables: C2.M(), C3.M(), C4.M(), C5.M(), C6.M(), C7.M() M(x, 8); } } public class C2<T> : C1<string, T> { public override T M<T3>(string x, T3 y) { throw new Exception(); } public override string Prop { get; set; } public override string this[T x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<string> Event { add { } remove { } } } public class C3 : C1<string, decimal> { public override decimal M<T3>(string x, T3 y) { throw new Exception(); } public override string Prop { get; set; } public override string this[decimal x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<string> Event { add { } remove { } } } public class C4<T> : C1<T[], bool> { public override bool M<T3>(T[] x, T3 y) { throw new Exception(); } public override T[] Prop { get; set; } public override T[] this[bool x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<T[]> Event { add { } remove { } } } public class C5 : C1<string, bool> { public override bool M<T3>(string x, T3 y) { throw new Exception(); } public static void M(int x) { } public override string Prop { get; set; } public static string Prop2 { get; set; } public override string this[bool x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<string> Event { add { } remove { } } public static event EventHandler<string> Event2 { add { } remove { } } } public class C6<T1, T2> : C1<T1, T2> { public override T2 M<T3>(T1 x, T3 y) { throw new Exception(); } public override T1 Prop { get; set; } public override T1 this[T2 x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<T1> Event { add { } remove { } } public void Run(T1 x) { // Viable callables: C6.M(), C7.M() M(x, 8); // Viable callables: C6.M(), C7.M() this.M(x, 8); } } public class C7<T1> : C6<T1, byte> { public override byte M<T3>(T1 x, T3 y) { throw new Exception(); } public override T1 Prop { get; set; } public override T1 this[byte x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<T1> Event { add { } remove { } } public void Run(T1 x) { // Viable callables: C7.M() M(x, 8); // Viable callables: C7.M() this.M(x, 8); // Viable callables: C6.M() base.M(x, 8); } } public class C8 { public virtual void M(IEnumerable<C1<string[], bool>> x) { } public static void M2<T>(T[] x) { } public void M3(params double[] x) { } public void M4(byte b, IEnumerable<string> s) { } public virtual string Prop1 { get; set; } public static string Prop2 { get; set; } public string Prop3 { get; set; } public virtual string this[int x] { get { throw new Exception(); } set { throw new Exception(); } } public virtual event EventHandler<string> Event { add { } remove { } } } public class C9<T> : C8 { public override void M(IEnumerable<C1<string[], bool>> x) { } public void M3(params T[] x) { } public override string Prop1 { get; set; } public string Prop3 { get; set; } public override string this[int x] { get { throw new Exception(); } set { throw new Exception(); } } public override event EventHandler<string> Event { add { } remove { } } } public class C10 { public void M3(params double[] x) { } public static C10 operator +(C10 x, C10 y) { return x; } public bool Prop1 { get; set; } public static string Prop3 { get; set; } public bool this[int x] { get { return false; } set { return; } } public event EventHandler<bool> Event { add { } remove { } } } public class C11 { void M(dynamic d) { } public void Run() { dynamic d = this; int x = 0; x += 42; // Viable callables: C11.M() d.M(x); // Viable callables: C11.C11() new C11(d); d = 0; // Viable callables: (none) new C11(d); } C11(C11 x) { } } public class C12 { interface I { void M(); } class C13 : I { public void M() { } } class C14 : I { public void M() { } } void Run<T1>(T1 x) where T1 : I { // Viable callables: C13.M() x.M(); } void Run2<T2>(T2 x) where T2 : I { Run(x); } void Run3() { Run2(new C13()); } } public class C15 { interface I<T1> { void M<T2>(); } class A1 { public virtual void M<T1>() { } } class A2 : A1, I<int> { } class A3 : A2 { new public void M<T1>() { } } class A4 : A2, I<int> { new public virtual void M<T1>() { } } class A5 : A4 { public override void M<T1>() { } } class A6 : A1 { public override void M<T1>() { } } void Run(I<int> i) { // Viable callables: {A1,A4,A5}.M() i.M<int>(); i = new A3(); // Viable callables: A1.M() i.M<bool>(); i = new A4(); // Viable callables: A4.M() i.M<string>(); i = ViableCallable.Mock<A4>(); // Viable callables: {A4,A5}.M() i.M<string>(); } } abstract class C16<T1, T2> { public virtual T2 M1(T1 x) => throw null; public virtual T M2<T>(Func<T> x) => x(); } class C17 : C16<string, int> { void M1(int i) { // Viable callables: C16<string, int>.M1() this.M1(""); // Viable callables: C17.M2<int>() this.M2(() => i); } public override T M2<T>(Func<T> x) => x(); void M3<T>(T t, string s) where T : C17 { // Viable callable: C17.M2() t.M2(() => s); } void M4<T>(C16<T, int> c) where T : struct { // Viable callable: C16.M2() [also reports C17.M2(); false positive] c.M2(() => default(T)); } void M5<T>(C16<T, int> c) where T : class { // Viable callables: {C16,C17}.M1() c.M2(() => default(T)); } } interface I2 { void M1(); void M2() => throw null; } class C18 : I2 { public void M1() { } void Run(I2 i) { // Viable callables: C18.M1() i.M1(); // Viable callables: I2.M2() i.M2(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml.Linq; namespace DocumentFormat.OpenXml.Linq { /// <summary> /// Declares XNamespace and XName fields for the xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" namespace. /// </summary> public static class WNE { /// <summary> /// Defines the XML namespace associated with the wne prefix. /// </summary> public static readonly XNamespace wne = "http://schemas.microsoft.com/office/word/2006/wordml"; /// <summary> /// Represents the wne:acd XML elements. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="acds" />, <see cref="keymap" />.</description></item> /// <item><description>has the following XML attributes: <see cref="acdName" />, <see cref="argValue" />, <see cref="fciBasedOn" />, <see cref="fciIndexBasedOn" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: AllocatedCommand, AllocatedCommandKeyboardCustomization.</description></item> /// </list> /// </remarks> public static readonly XName acd = wne + "acd"; /// <summary> /// Represents the wne:acdEntry XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="acdManifest" />.</description></item> /// <item><description>has the following XML attributes: <see cref="acdName" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: AllocatedCommandManifestEntry.</description></item> /// </list> /// </remarks> public static readonly XName acdEntry = wne + "acdEntry"; /// <summary> /// Represents the wne:acdManifest XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="toolbars" />.</description></item> /// <item><description>has the following child XML elements: <see cref="acdEntry" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: AllocatedCommandManifest.</description></item> /// </list> /// </remarks> public static readonly XName acdManifest = wne + "acdManifest"; /// <summary> /// Represents the wne:acdName XML attributes. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="acd" />, <see cref="acdEntry" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: AllocatedCommand.AcceleratorName, AllocatedCommandKeyboardCustomization.AcceleratorName, AllocatedCommandManifestEntry.AcceleratorName.</description></item> /// </list> /// </remarks> public static readonly XName acdName = wne + "acdName"; /// <summary> /// Represents the wne:acds XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="tcg" />.</description></item> /// <item><description>has the following child XML elements: <see cref="acd" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: AllocatedCommands.</description></item> /// </list> /// </remarks> public static readonly XName acds = wne + "acds"; /// <summary> /// Represents the wne:active XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="recipientData" />.</description></item> /// <item><description>has the following XML attributes: <see cref="val" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: RecordIncluded.</description></item> /// </list> /// </remarks> public static readonly XName active = wne + "active"; /// <summary> /// Represents the wne:argValue XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="acd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: AllocatedCommand.ArgumentValue.</description></item> /// </list> /// </remarks> public static readonly XName argValue = wne + "argValue"; /// <summary> /// Represents the wne:bEncrypt XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="mcd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: Mcd.BEncrypt.</description></item> /// </list> /// </remarks> public static readonly XName bEncrypt = wne + "bEncrypt"; /// <summary> /// Represents the wne:chmPrimary XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: KeyMapEntry.CharacterMapPrimary.</description></item> /// </list> /// </remarks> public static readonly XName chmPrimary = wne + "chmPrimary"; /// <summary> /// Represents the wne:chmSecondary XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: KeyMapEntry.CharacterMapSecondary.</description></item> /// </list> /// </remarks> public static readonly XName chmSecondary = wne + "chmSecondary"; /// <summary> /// Represents the wne:cmg XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="mcd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: Mcd.Cmg.</description></item> /// </list> /// </remarks> public static readonly XName cmg = wne + "cmg"; /// <summary> /// Represents the wne:docEvents XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="vbaSuppData" />.</description></item> /// <item><description>has the following child XML elements: <see cref="eventDocBuildingBlockAfterInsert" />, <see cref="eventDocClose" />, <see cref="eventDocContentControlAfterInsert" />, <see cref="eventDocContentControlBeforeDelete" />, <see cref="eventDocContentControlContentUpdate" />, <see cref="eventDocContentControlOnEnter" />, <see cref="eventDocContentControlOnExit" />, <see cref="eventDocNew" />, <see cref="eventDocOpen" />, <see cref="eventDocStoreUpdate" />, <see cref="eventDocSync" />, <see cref="eventDocXmlAfterInsert" />, <see cref="eventDocXmlBeforeDelete" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: DocEvents.</description></item> /// </list> /// </remarks> public static readonly XName docEvents = wne + "docEvents"; /// <summary> /// Represents the wne:eventDocBuildingBlockAfterInsert XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocBuildingBlockAfterInsertXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocBuildingBlockAfterInsert = wne + "eventDocBuildingBlockAfterInsert"; /// <summary> /// Represents the wne:eventDocClose XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocCloseXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocClose = wne + "eventDocClose"; /// <summary> /// Represents the wne:eventDocContentControlAfterInsert XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocContentControlAfterInsertXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocContentControlAfterInsert = wne + "eventDocContentControlAfterInsert"; /// <summary> /// Represents the wne:eventDocContentControlBeforeDelete XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocContentControlBeforeDeleteXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocContentControlBeforeDelete = wne + "eventDocContentControlBeforeDelete"; /// <summary> /// Represents the wne:eventDocContentControlContentUpdate XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocContentControlUpdateXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocContentControlContentUpdate = wne + "eventDocContentControlContentUpdate"; /// <summary> /// Represents the wne:eventDocContentControlOnEnter XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocContentControlOnEnterXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocContentControlOnEnter = wne + "eventDocContentControlOnEnter"; /// <summary> /// Represents the wne:eventDocContentControlOnExit XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocContentControlOnExistXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocContentControlOnExit = wne + "eventDocContentControlOnExit"; /// <summary> /// Represents the wne:eventDocNew XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocNewXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocNew = wne + "eventDocNew"; /// <summary> /// Represents the wne:eventDocOpen XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocOpenXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocOpen = wne + "eventDocOpen"; /// <summary> /// Represents the wne:eventDocStoreUpdate XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocStoreUpdateXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocStoreUpdate = wne + "eventDocStoreUpdate"; /// <summary> /// Represents the wne:eventDocSync XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocSyncXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocSync = wne + "eventDocSync"; /// <summary> /// Represents the wne:eventDocXmlAfterInsert XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocXmlAfterInsertXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocXmlAfterInsert = wne + "eventDocXmlAfterInsert"; /// <summary> /// Represents the wne:eventDocXmlBeforeDelete XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="docEvents" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: EventDocXmlBeforeDeleteXsdString.</description></item> /// </list> /// </remarks> public static readonly XName eventDocXmlBeforeDelete = wne + "eventDocXmlBeforeDelete"; /// <summary> /// Represents the wne:fci XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="keymap" />.</description></item> /// <item><description>has the following XML attributes: <see cref="fciIndex" />, <see cref="fciName" />, <see cref="swArg" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: FixedCommandKeyboardCustomization.</description></item> /// </list> /// </remarks> public static readonly XName fci = wne + "fci"; /// <summary> /// Represents the wne:fciBasedOn XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="acd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: AllocatedCommand.CommandBasedOn.</description></item> /// </list> /// </remarks> public static readonly XName fciBasedOn = wne + "fciBasedOn"; /// <summary> /// Represents the wne:fciIndex XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="fci" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: FixedCommandKeyboardCustomization.CommandIndex.</description></item> /// </list> /// </remarks> public static readonly XName fciIndex = wne + "fciIndex"; /// <summary> /// Represents the wne:fciIndexBasedOn XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="acd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: AllocatedCommand.CommandIndexBasedOn.</description></item> /// </list> /// </remarks> public static readonly XName fciIndexBasedOn = wne + "fciIndexBasedOn"; /// <summary> /// Represents the wne:fciName XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="fci" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: FixedCommandKeyboardCustomization.CommandName.</description></item> /// </list> /// </remarks> public static readonly XName fciName = wne + "fciName"; /// <summary> /// Represents the wne:hash XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="recipientData" />.</description></item> /// <item><description>has the following XML attributes: <see cref="val" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: RecordHashCode.</description></item> /// </list> /// </remarks> public static readonly XName hash = wne + "hash"; /// <summary> /// Represents the wne:kcmPrimary XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: KeyMapEntry.KeyCodePrimary.</description></item> /// </list> /// </remarks> public static readonly XName kcmPrimary = wne + "kcmPrimary"; /// <summary> /// Represents the wne:kcmSecondary XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: KeyMapEntry.KeyCodeSecondary.</description></item> /// </list> /// </remarks> public static readonly XName kcmSecondary = wne + "kcmSecondary"; /// <summary> /// Represents the wne:keymap XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="keymaps" />, <see cref="keymapsBad" />.</description></item> /// <item><description>has the following child XML elements: <see cref="acd" />, <see cref="fci" />, <see cref="macro" />, <see cref="wch" />, <see cref="wll" />.</description></item> /// <item><description>has the following XML attributes: <see cref="chmPrimary" />, <see cref="chmSecondary" />, <see cref="kcmPrimary" />, <see cref="kcmSecondary" />, <see cref="mask" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: KeyMapEntry.</description></item> /// </list> /// </remarks> public static readonly XName keymap = wne + "keymap"; /// <summary> /// Represents the wne:keymaps XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="tcg" />.</description></item> /// <item><description>has the following child XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: KeyMapCustomizations.</description></item> /// </list> /// </remarks> public static readonly XName keymaps = wne + "keymaps"; /// <summary> /// Represents the wne:keymapsBad XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="tcg" />.</description></item> /// <item><description>has the following child XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: MismatchedKeyMapCustomization.</description></item> /// </list> /// </remarks> public static readonly XName keymapsBad = wne + "keymapsBad"; /// <summary> /// Represents the wne:macro XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="keymap" />.</description></item> /// <item><description>has the following XML attributes: <see cref="macroName" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: MacroKeyboardCustomization.</description></item> /// </list> /// </remarks> public static readonly XName macro = wne + "macro"; /// <summary> /// Represents the wne:macroName XML attributes. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="macro" />, <see cref="mcd" />, <see cref="wll" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: MacroKeyboardCustomization.MacroName, Mcd.MacroName, WllMacroKeyboardCustomization.MacroName.</description></item> /// </list> /// </remarks> public static readonly XName macroName = wne + "macroName"; /// <summary> /// Represents the wne:mask XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="keymap" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: KeyMapEntry.Mask.</description></item> /// </list> /// </remarks> public static readonly XName mask = wne + "mask"; /// <summary> /// Represents the wne:mcd XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="mcds" />.</description></item> /// <item><description>has the following XML attributes: <see cref="bEncrypt" />, <see cref="cmg" />, <see cref="macroName" />, <see cref="menuHelp" />, <see cref="name" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: Mcd.</description></item> /// </list> /// </remarks> public static readonly XName mcd = wne + "mcd"; /// <summary> /// Represents the wne:mcds XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="vbaSuppData" />.</description></item> /// <item><description>has the following child XML elements: <see cref="mcd" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: Mcds.</description></item> /// </list> /// </remarks> public static readonly XName mcds = wne + "mcds"; /// <summary> /// Represents the wne:menuHelp XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="mcd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: Mcd.MenuHelp.</description></item> /// </list> /// </remarks> public static readonly XName menuHelp = wne + "menuHelp"; /// <summary> /// Represents the wne:name XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="mcd" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: Mcd.Name.</description></item> /// </list> /// </remarks> public static readonly XName name = wne + "name"; /// <summary> /// Represents the wne:recipientData XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="recipients" />.</description></item> /// <item><description>has the following child XML elements: <see cref="active" />, <see cref="hash" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: SingleDataSourceRecord.</description></item> /// </list> /// </remarks> public static readonly XName recipientData = wne + "recipientData"; /// <summary> /// Represents the wne:recipients XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following child XML elements: <see cref="recipientData" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: MailMergeRecipients.</description></item> /// </list> /// </remarks> public static readonly XName recipients = wne + "recipients"; /// <summary> /// Represents the wne:swArg XML attribute. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="fci" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: FixedCommandKeyboardCustomization.Argument.</description></item> /// </list> /// </remarks> public static readonly XName swArg = wne + "swArg"; /// <summary> /// Represents the wne:tcg XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following child XML elements: <see cref="acds" />, <see cref="keymaps" />, <see cref="keymapsBad" />, <see cref="toolbars" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: TemplateCommandGroup.</description></item> /// </list> /// </remarks> public static readonly XName tcg = wne + "tcg"; /// <summary> /// Represents the wne:toolbarData XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="toolbars" />.</description></item> /// <item><description>has the following XML attributes: <see cref="R.id" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: ToolbarData.</description></item> /// </list> /// </remarks> public static readonly XName toolbarData = wne + "toolbarData"; /// <summary> /// Represents the wne:toolbars XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="tcg" />.</description></item> /// <item><description>has the following child XML elements: <see cref="acdManifest" />, <see cref="toolbarData" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: Toolbars.</description></item> /// </list> /// </remarks> public static readonly XName toolbars = wne + "toolbars"; /// <summary> /// Represents the wne:val XML attributes. /// </summary> /// <remarks> /// <para>As an XML attribute, it:</para> /// <list type="bullet"> /// <item><description>is contained in the following XML elements: <see cref="active" />, <see cref="hash" />, <see cref="wch" />.</description></item> /// <item><description>corresponds to the following strongly-typed properties: CharacterInsertion.Val, RecordHashCode.Val, RecordIncluded.Val.</description></item> /// </list> /// </remarks> public static readonly XName val = wne + "val"; /// <summary> /// Represents the wne:vbaSuppData XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following child XML elements: <see cref="docEvents" />, <see cref="mcds" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VbaSuppData.</description></item> /// </list> /// </remarks> public static readonly XName vbaSuppData = wne + "vbaSuppData"; /// <summary> /// Represents the wne:wch XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="keymap" />.</description></item> /// <item><description>has the following XML attributes: <see cref="val" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: CharacterInsertion.</description></item> /// </list> /// </remarks> public static readonly XName wch = wne + "wch"; /// <summary> /// Represents the wne:wll XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="keymap" />.</description></item> /// <item><description>has the following XML attributes: <see cref="macroName" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: WllMacroKeyboardCustomization.</description></item> /// </list> /// </remarks> public static readonly XName wll = wne + "wll"; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.DateTimeOffset { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// A sample API that tests datetimeoffset usage for date-time /// </summary> public partial class SwaggerDateTimeOffsetClient : ServiceClient<SwaggerDateTimeOffsetClient>, ISwaggerDateTimeOffsetClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost:3000/api"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//----------------------------------------------------------------------------- // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Cci.Pdb { internal class PdbFunction { static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25, 0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60); static internal readonly IComparer byAddress = new PdbFunctionsByAddress(); static internal readonly IComparer byAddressAndToken = new PdbFunctionsByAddressAndToken(); //static internal readonly IComparer byToken = new PdbFunctionsByToken(); internal uint token; internal uint slotToken; //internal string name; //internal string module; //internal ushort flags; internal uint segment; internal uint address; //internal uint length; //internal byte[] metadata; internal PdbScope[] scopes; internal PdbSlot[] slots; internal PdbConstant[] constants; internal string[] usedNamespaces; internal PdbLines[] lines; internal ushort[]/*?*/ usingCounts; internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes; internal string/*?*/ iteratorClass; internal List<ILocalScope>/*?*/ iteratorScopes; private static string StripNamespace(string module) { int li = module.LastIndexOf('.'); if (li > 0) { return module.Substring(li + 1); } return module; } internal static PdbFunction[] LoadManagedFunctions(/*string module,*/ BitAccess bits, uint limit, bool readStrings) { //string mod = StripNamespace(module); int begin = bits.Position; int count = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_GMANPROC: case SYM.S_LMANPROC: ManProcSym proc; bits.ReadUInt32(out proc.parent); bits.ReadUInt32(out proc.end); bits.Position = (int)proc.end; count++; break; case SYM.S_END: bits.Position = stop; break; default: //Console.WriteLine("{0,6}: {1:x2} {2}", // bits.Position, rec, (SYM)rec); bits.Position = stop; break; } } if (count == 0) { return null; } bits.Position = begin; PdbFunction[] funcs = new PdbFunction[count]; int func = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_GMANPROC: case SYM.S_LMANPROC: ManProcSym proc; //int offset = bits.Position; bits.ReadUInt32(out proc.parent); bits.ReadUInt32(out proc.end); bits.ReadUInt32(out proc.next); bits.ReadUInt32(out proc.len); bits.ReadUInt32(out proc.dbgStart); bits.ReadUInt32(out proc.dbgEnd); bits.ReadUInt32(out proc.token); bits.ReadUInt32(out proc.off); bits.ReadUInt16(out proc.seg); bits.ReadUInt8(out proc.flags); bits.ReadUInt16(out proc.retReg); if (readStrings) { bits.ReadCString(out proc.name); } else { bits.SkipCString(out proc.name); } //Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name); bits.Position = stop; funcs[func++] = new PdbFunction(/*module,*/ proc, bits); break; default: { //throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec); bits.Position = stop; break; } } } return funcs; } internal static void CountScopesAndSlots(BitAccess bits, uint limit, out int constants, out int scopes, out int slots, out int usedNamespaces) { int pos = bits.Position; BlockSym32 block; constants = 0; slots = 0; scopes = 0; usedNamespaces = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_BLOCK32: { bits.ReadUInt32(out block.parent); bits.ReadUInt32(out block.end); scopes++; bits.Position = (int)block.end; break; } case SYM.S_MANSLOT: slots++; bits.Position = stop; break; case SYM.S_UNAMESPACE: usedNamespaces++; bits.Position = stop; break; case SYM.S_MANCONSTANT: constants++; bits.Position = stop; break; default: bits.Position = stop; break; } } bits.Position = pos; } internal PdbFunction() { } internal PdbFunction(/*string module, */ManProcSym proc, BitAccess bits) { this.token = proc.token; //this.module = module; //this.name = proc.name; //this.flags = proc.flags; this.segment = proc.seg; this.address = proc.off; //this.length = proc.len; if (proc.seg != 1) { throw new PdbDebugException("Segment is {0}, not 1.", proc.seg); } if (proc.parent != 0 || proc.next != 0) { throw new PdbDebugException("Warning parent={0}, next={1}", proc.parent, proc.next); } //if (proc.dbgStart != 0 || proc.dbgEnd != 0) { // throw new PdbDebugException("Warning DBG start={0}, end={1}", // proc.dbgStart, proc.dbgEnd); //} int constantCount; int scopeCount; int slotCount; int usedNamespacesCount; CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount); int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0; int slot = 0; int constant = 0; int usedNs = 0; scopes = new PdbScope[scopeCount + scope]; slots = new PdbSlot[slotCount]; constants = new PdbConstant[constantCount]; usedNamespaces = new string[usedNamespacesCount]; if (scope > 0) scopes[0] = new PdbScope(this.address, proc.len, slots, constants, usedNamespaces); while (bits.Position < proc.end) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_OEM: { // 0x0404 OemSymbol oem; bits.ReadGuid(out oem.idOem); bits.ReadUInt32(out oem.typind); // internal byte[] rgl; // user data, force 4-byte alignment if (oem.idOem == msilMetaData) { string name = bits.ReadString(); if (name == "MD2") { byte version; bits.ReadUInt8(out version); if (version == 4) { byte count; bits.ReadUInt8(out count); bits.Align(4); while (count-- > 0) this.ReadCustomMetadata(bits); } } bits.Position = stop; break; } else { throw new PdbDebugException("OEM section: guid={0} ti={1}", oem.idOem, oem.typind); // bits.Position = stop; } } case SYM.S_BLOCK32: { BlockSym32 block = new BlockSym32(); bits.ReadUInt32(out block.parent); bits.ReadUInt32(out block.end); bits.ReadUInt32(out block.len); bits.ReadUInt32(out block.off); bits.ReadUInt16(out block.seg); bits.SkipCString(out block.name); bits.Position = stop; scopes[scope++] = new PdbScope(this.address, block, bits, out slotToken); bits.Position = (int)block.end; break; } case SYM.S_MANSLOT: uint typind; slots[slot++] = new PdbSlot(bits, out typind); bits.Position = stop; break; case SYM.S_MANCONSTANT: constants[constant++] = new PdbConstant(bits); bits.Position = stop; break; case SYM.S_UNAMESPACE: bits.ReadCString(out usedNamespaces[usedNs++]); bits.Position = stop; break; case SYM.S_END: bits.Position = stop; break; default: { //throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec); bits.Position = stop; break; } } } if (bits.Position != proc.end) { throw new PdbDebugException("Not at S_END"); } ushort esiz; ushort erec; bits.ReadUInt16(out esiz); bits.ReadUInt16(out erec); if (erec != (ushort)SYM.S_END) { throw new PdbDebugException("Missing S_END"); } } private void ReadCustomMetadata(BitAccess bits) { int savedPosition = bits.Position; byte version; bits.ReadUInt8(out version); if (version != 4) { throw new PdbDebugException("Unknown custom metadata item version: {0}", version); } byte kind; bits.ReadUInt8(out kind); bits.Align(4); uint numberOfBytesInItem; bits.ReadUInt32(out numberOfBytesInItem); switch (kind) { case 0: this.ReadUsingInfo(bits); break; case 1: break; // this.ReadForwardInfo(bits); break; case 2: break; // this.ReadForwardedToModuleInfo(bits); break; case 3: this.ReadIteratorLocals(bits); break; case 4: this.ReadForwardIterator(bits); break; case 6: break; //vs2015 thing case 7: break; //vs2015 thing default: throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind); } bits.Position = savedPosition + (int)numberOfBytesInItem; } private void ReadForwardIterator(BitAccess bits) { this.iteratorClass = bits.ReadString(); } private void ReadIteratorLocals(BitAccess bits) { uint numberOfLocals; bits.ReadUInt32(out numberOfLocals); this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals); while (numberOfLocals-- > 0) { uint ilStartOffset; uint ilEndOffset; bits.ReadUInt32(out ilStartOffset); bits.ReadUInt32(out ilEndOffset); this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset - ilStartOffset)); } } //private void ReadForwardedToModuleInfo(BitAccess bits) { //} //private void ReadForwardInfo(BitAccess bits) { //} private void ReadUsingInfo(BitAccess bits) { ushort numberOfNamespaces; bits.ReadUInt16(out numberOfNamespaces); this.usingCounts = new ushort[numberOfNamespaces]; for (ushort i = 0; i < numberOfNamespaces; i++) { bits.ReadUInt16(out this.usingCounts[i]); } } internal class PdbFunctionsByAddress : IComparer { public int Compare(Object x, Object y) { PdbFunction fx = (PdbFunction)x; PdbFunction fy = (PdbFunction)y; if (fx.segment < fy.segment) { return -1; } else if (fx.segment > fy.segment) { return 1; } else if (fx.address < fy.address) { return -1; } else if (fx.address > fy.address) { return 1; } else { return 0; } } } internal class PdbFunctionsByAddressAndToken : IComparer { public int Compare(Object x, Object y) { PdbFunction fx = (PdbFunction)x; PdbFunction fy = (PdbFunction)y; if (fx.segment < fy.segment) { return -1; } else if (fx.segment > fy.segment) { return 1; } else if (fx.address < fy.address) { return -1; } else if (fx.address > fy.address) { return 1; } else { if (fx.token < fy.token) return -1; else if (fx.token > fy.token) return 1; else return 0; } } } //internal class PdbFunctionsByToken : IComparer { // public int Compare(Object x, Object y) { // PdbFunction fx = (PdbFunction)x; // PdbFunction fy = (PdbFunction)y; // if (fx.token < fy.token) { // return -1; // } else if (fx.token > fy.token) { // return 1; // } else { // return 0; // } // } //} } }